Files
user-system/internal/repository/testdb_helper_test.go

49 lines
1.1 KiB
Go
Raw Permalink 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"
_ "modernc.org/sqlite" // 纯 Go SQLite注册 "sqlite" 驱动
gormsqlite "gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"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
}