Files
junhong_cmp_fiber/internal/testutil/database.go

40 lines
995 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package testutil 提供项目集成测试共用的真实基础设施连接。
package testutil
import (
"os"
"testing"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/break/junhong_cmp_fiber/pkg/database"
"go.uber.org/zap"
"gorm.io/gorm"
)
// NewPostgresTransaction 创建自动回滚的 PostgreSQL 测试事务。
func NewPostgresTransaction(t *testing.T) *gorm.DB {
t.Helper()
if os.Getenv("JUNHONG_DATABASE_HOST") == "" {
t.Skip("未加载 .env.local跳过依赖真实 PostgreSQL 的集成测试")
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("加载测试配置失败:%v", err)
}
db, err := database.InitPostgreSQL(&cfg.Database, zap.NewNop())
if err != nil {
t.Fatalf("连接 PostgreSQL 失败:%v", err)
}
tx := db.Begin()
if tx.Error != nil {
t.Fatalf("开启测试事务失败:%v", tx.Error)
}
t.Cleanup(func() {
_ = tx.Rollback().Error
if sqlDB, dbErr := db.DB(); dbErr == nil {
_ = sqlDB.Close()
}
})
return tx
}