Files
junhong_cmp_fiber/internal/testutil/database.go
break 147f3eb775 修复 UR#55 代码审查问题:事务隔离、错误包装、重复辅助函数
- resolvePackageTerms 接受 tx 参数并使用事务绑定的 Store,确保快照与写入同库
- auto_purchase.go 错误包装改用 pkgerrors.Wrap 而非标准库 errors
- shop_package_batch_allocation 去除 fmt 依赖改用 strconv 拼接
- shop_series_grant 提取 effectiveBase 局部变量避免重复调用
- 测试辅助函数统一迁移至 testutil.StringPointer,删除各文件本地重复定义
- 新增 testutil.NewRedisClient 和 testutil.StringPointer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 11:09:08 +09:00

67 lines
2.0 KiB
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"
"strconv"
"testing"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/break/junhong_cmp_fiber/pkg/database"
"github.com/redis/go-redis/v9"
"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
}
// NewRedisClient 创建真实 Redis 测试客户端并在测试结束时关闭。
func NewRedisClient(t *testing.T) *redis.Client {
t.Helper()
if os.Getenv("JUNHONG_REDIS_ADDRESS") == "" {
t.Skip("未加载 .env.local跳过依赖真实 Redis 的集成测试")
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("加载测试配置失败:%v", err)
}
client, err := database.NewRedisClient(database.RedisConfig{
Address: cfg.Redis.Address + ":" + strconv.Itoa(cfg.Redis.Port), Password: cfg.Redis.Password,
DB: cfg.Redis.DB, PoolSize: cfg.Redis.PoolSize, MinIdleConns: cfg.Redis.MinIdleConns,
DialTimeout: cfg.Redis.DialTimeout, ReadTimeout: cfg.Redis.ReadTimeout, WriteTimeout: cfg.Redis.WriteTimeout,
}, zap.NewNop())
if err != nil {
t.Fatalf("连接 Redis 失败:%v", err)
}
t.Cleanup(func() { _ = client.Close() })
return client
}
// StringPointer 返回字符串值的指针,供测试用例构造 nullable string 参数。
func StringPointer(s string) *string { return &s }