testutil.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package testutil
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "perms-system-server/internal/config"
  8. "github.com/zeromicro/go-zero/core/stores/cache"
  9. "github.com/zeromicro/go-zero/core/stores/redis"
  10. "github.com/zeromicro/go-zero/core/stores/sqlx"
  11. "golang.org/x/crypto/bcrypt"
  12. )
  13. var testConfig = config.Config{
  14. MySQL: struct{ DataSource string }{
  15. DataSource: "root:NsDmWyM@312@tcp(127.0.0.1:3306)/perms_system?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai",
  16. },
  17. CacheRedis: config.CacheRedisConf{
  18. Nodes: cache.CacheConf{
  19. {
  20. RedisConf: redis.RedisConf{
  21. Host: "127.0.0.1:6379",
  22. Pass: "NsDmWyM@312",
  23. Type: "node",
  24. },
  25. Weight: 100,
  26. },
  27. },
  28. KeyPrefix: "test_perms",
  29. },
  30. Auth: struct {
  31. AccessSecret string
  32. AccessExpire int64
  33. RefreshSecret string
  34. RefreshExpire int64
  35. ManagementKey string
  36. }{
  37. AccessSecret: "test-access-secret",
  38. AccessExpire: 7200,
  39. RefreshSecret: "test-refresh-secret",
  40. RefreshExpire: 604800,
  41. ManagementKey: "test-management-key",
  42. },
  43. }
  44. func GetTestConfig() config.Config {
  45. return testConfig
  46. }
  47. func GetTestSqlConn() sqlx.SqlConn {
  48. return sqlx.NewMysql(testConfig.MySQL.DataSource)
  49. }
  50. func GetTestCacheConf() cache.CacheConf {
  51. return testConfig.CacheRedis.Nodes
  52. }
  53. func GetTestCachePrefix() string {
  54. return testConfig.CacheRedis.KeyPrefix
  55. }
  56. func UniqueId() string {
  57. return fmt.Sprintf("t_%d_%d", time.Now().UnixNano(), rand.Intn(100000))
  58. }
  59. func HashPassword(pwd string) string {
  60. h, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)
  61. return string(h)
  62. }
  63. func CleanTable(ctx context.Context, conn sqlx.SqlConn, table string, ids ...int64) {
  64. for _, id := range ids {
  65. query := fmt.Sprintf("DELETE FROM %s WHERE `id` = ?", table)
  66. conn.ExecCtx(ctx, query, id)
  67. }
  68. }
  69. func CleanTableByField(ctx context.Context, conn sqlx.SqlConn, table, field string, value interface{}) {
  70. query := fmt.Sprintf("DELETE FROM %s WHERE `%s` = ?", table, field)
  71. conn.ExecCtx(ctx, query, value)
  72. }