Files
user-system/internal/repository/testdb_helper_test.go
long-agent 582ad7a069 test: add comprehensive test coverage and improve code quality
- Add new test files for auth, service, and handler modules
- Improve test organization and coverage
- Refactor code for better maintainability
- Add captcha, settings, stats, and theme handler tests
- Add auth module tests (CAS, OAuth, password, SSO, state)
- Add service layer tests for auth, export, permissions, roles
- All Go tests pass (exit code 0)
- All frontend tests pass (325 tests in 59 files)
2026-04-17 20:43:50 +08:00

49 lines
1.1 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 repository
import (
"fmt"
"sync/atomic"
"testing"
gormsqlite "gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
_ "modernc.org/sqlite" // 纯 Go SQLite注册 "sqlite" 驱动
"github.com/user-management-system/internal/domain"
)
var repoDBCounter int64
// openTestDB 为每个测试打开独立的内存数据库(使用 modernc.org/sqlite无需 CGO
// 每次调用都生成唯一的 DSN避免多个测试共用同一内存 DB 导致 index 重复错误
func openTestDB(t *testing.T) *gorm.DB {
t.Helper()
id := atomic.AddInt64(&repoDBCounter, 1)
dsn := fmt.Sprintf("file:repotestdb%d?mode=memory&cache=private", id)
db, err := gorm.Open(gormsqlite.New(gormsqlite.Config{
DriverName: "sqlite",
DSN: dsn,
}), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("打开测试数据库失败: %v", err)
}
tables := []interface{}{
&domain.User{},
&domain.Role{},
&domain.Permission{},
&domain.UserRole{},
&domain.RolePermission{},
}
if err := db.AutoMigrate(tables...); err != nil {
t.Fatalf("数据库迁移失败: %v", err)
}
return db
}