testutil.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }{
  36. AccessSecret: "test-access-secret",
  37. AccessExpire: 7200,
  38. RefreshSecret: "test-refresh-secret",
  39. RefreshExpire: 604800,
  40. },
  41. }
  42. func GetTestConfig() config.Config {
  43. return testConfig
  44. }
  45. func GetTestSqlConn() sqlx.SqlConn {
  46. return sqlx.NewMysql(testConfig.MySQL.DataSource)
  47. }
  48. func GetTestCacheConf() cache.CacheConf {
  49. return testConfig.CacheRedis.Nodes
  50. }
  51. func GetTestCachePrefix() string {
  52. return testConfig.CacheRedis.KeyPrefix
  53. }
  54. func UniqueId() string {
  55. return fmt.Sprintf("t_%d_%d", time.Now().UnixNano(), rand.Intn(100000))
  56. }
  57. func HashPassword(pwd string) string {
  58. h, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)
  59. return string(h)
  60. }
  61. func CleanTable(ctx context.Context, conn sqlx.SqlConn, table string, ids ...int64) {
  62. for _, id := range ids {
  63. query := fmt.Sprintf("DELETE FROM %s WHERE `id` = ?", table)
  64. conn.ExecCtx(ctx, query, id)
  65. }
  66. }
  67. func CleanTableByField(ctx context.Context, conn sqlx.SqlConn, table, field string, value interface{}) {
  68. query := fmt.Sprintf("DELETE FROM %s WHERE `%s` = ?", table, field)
  69. conn.ExecCtx(ctx, query, value)
  70. }