package testutil import ( "context" "fmt" "math/rand" "time" "perms-system-server/internal/config" "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/redis" "github.com/zeromicro/go-zero/core/stores/sqlx" "golang.org/x/crypto/bcrypt" ) var testConfig = config.Config{ MySQL: struct{ DataSource string }{ DataSource: "root:NsDmWyM@312@tcp(127.0.0.1:3306)/perms_system?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai", }, CacheRedis: config.CacheRedisConf{ Nodes: cache.CacheConf{ { RedisConf: redis.RedisConf{ Host: "127.0.0.1:6379", Pass: "NsDmWyM@312", Type: "node", }, Weight: 100, }, }, KeyPrefix: "test_perms", }, Auth: struct { AccessSecret string AccessExpire int64 RefreshSecret string RefreshExpire int64 ManagementKey string }{ AccessSecret: "test-access-secret", AccessExpire: 7200, RefreshSecret: "test-refresh-secret", RefreshExpire: 604800, ManagementKey: "test-management-key", }, } func GetTestConfig() config.Config { return testConfig } func GetTestSqlConn() sqlx.SqlConn { return sqlx.NewMysql(testConfig.MySQL.DataSource) } func GetTestCacheConf() cache.CacheConf { return testConfig.CacheRedis.Nodes } func GetTestCachePrefix() string { return testConfig.CacheRedis.KeyPrefix } func UniqueId() string { return fmt.Sprintf("t_%d_%d", time.Now().UnixNano(), rand.Intn(100000)) } func HashPassword(pwd string) string { h, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost) return string(h) } func CleanTable(ctx context.Context, conn sqlx.SqlConn, table string, ids ...int64) { for _, id := range ids { query := fmt.Sprintf("DELETE FROM %s WHERE `id` = ?", table) conn.ExecCtx(ctx, query, id) } } func CleanTableByField(ctx context.Context, conn sqlx.SqlConn, table, field string, value interface{}) { query := fmt.Sprintf("DELETE FROM %s WHERE `%s` = ?", table, field) conn.ExecCtx(ctx, query, value) } // EnsureProduct guarantees that an enabled product with the given code exists in DB. // 幂等:不存在则插入为 Enabled,存在则强制刷回 Enabled 状态。返回产品 id。 // 通过 INSERT ... ON DUPLICATE KEY UPDATE 避免并发竞争。 func EnsureProduct(ctx context.Context, conn sqlx.SqlConn, code string) int64 { now := time.Now().Unix() _, err := conn.ExecCtx(ctx, "INSERT INTO `sys_product` (`code`,`name`,`appKey`,`appSecret`,`remark`,`status`,`createTime`,`updateTime`) VALUES (?,?,?,?,?,?,?,?) "+ "ON DUPLICATE KEY UPDATE `status` = 1, `updateTime` = VALUES(`updateTime`)", code, code, code+"_k", "s", "", int64(1), now, now) if err != nil { return 0 } var id int64 _ = conn.QueryRowCtx(ctx, &id, "SELECT `id` FROM `sys_product` WHERE `code` = ? LIMIT 1", code) return id }