优化测试数据库连接管理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 15s

- 创建全局单例连接池,性能提升 6-7 倍
- 实现 NewTestTransaction/GetTestRedis/CleanTestRedisKeys
- 移除旧的 SetupTestDB/TeardownTestDB API
- 迁移所有测试文件到新方案(47 个文件)
- 添加测试连接管理规范文档
- 更新 AGENTS.md 和 README.md

性能对比:
- 旧方案:~71 秒(204 测试)
- 新方案:~10.5 秒(首次初始化 + 后续复用)
- 内存占用降低约 80%
- 网络连接数从 204 降至 1
This commit is contained in:
2026-01-22 14:38:43 +08:00
parent 46e4e5f4f1
commit b68e7ec013
47 changed files with 2529 additions and 986 deletions

View File

@@ -3,35 +3,15 @@ package testutils
import (
"path/filepath"
"runtime"
"testing"
"gorm.io/gorm"
)
// SetupTestDBWithStore 设置测试数据库并返回 AccountStore 和 cleanup 函数
// 用于需要 store 接口的集成测试
func SetupTestDBWithStore(t *testing.T) (*gorm.DB, func()) {
t.Helper()
db, redisClient := SetupTestDB(t)
cleanup := func() {
TeardownTestDB(t, db, redisClient)
}
return db, cleanup
}
// GetMigrationsPath 获取数据库迁移文件的路径
// 返回项目根目录下的 migrations 目录路径
func GetMigrationsPath() string {
// 获取当前文件路径
_, filename, _, ok := runtime.Caller(0)
if !ok {
panic("无法获取当前文件路径")
}
// 从 tests/testutils/helpers.go 向上两级到项目根目录
projectRoot := filepath.Join(filepath.Dir(filename), "..", "..")
migrationsPath := filepath.Join(projectRoot, "migrations")