billing_cache_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. //go:build unit
  2. package repository
  3. import (
  4. "math"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/require"
  8. )
  9. func TestBillingBalanceKey(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. userID int64
  13. expected string
  14. }{
  15. {
  16. name: "normal_user_id",
  17. userID: 123,
  18. expected: "billing:balance:123",
  19. },
  20. {
  21. name: "zero_user_id",
  22. userID: 0,
  23. expected: "billing:balance:0",
  24. },
  25. {
  26. name: "negative_user_id",
  27. userID: -1,
  28. expected: "billing:balance:-1",
  29. },
  30. {
  31. name: "max_int64",
  32. userID: math.MaxInt64,
  33. expected: "billing:balance:9223372036854775807",
  34. },
  35. }
  36. for _, tc := range tests {
  37. t.Run(tc.name, func(t *testing.T) {
  38. got := billingBalanceKey(tc.userID)
  39. require.Equal(t, tc.expected, got)
  40. })
  41. }
  42. }
  43. func TestBillingSubKey(t *testing.T) {
  44. tests := []struct {
  45. name string
  46. userID int64
  47. groupID int64
  48. expected string
  49. }{
  50. {
  51. name: "normal_ids",
  52. userID: 123,
  53. groupID: 456,
  54. expected: "billing:sub:123:456",
  55. },
  56. {
  57. name: "zero_ids",
  58. userID: 0,
  59. groupID: 0,
  60. expected: "billing:sub:0:0",
  61. },
  62. {
  63. name: "negative_ids",
  64. userID: -1,
  65. groupID: -2,
  66. expected: "billing:sub:-1:-2",
  67. },
  68. {
  69. name: "max_int64_ids",
  70. userID: math.MaxInt64,
  71. groupID: math.MaxInt64,
  72. expected: "billing:sub:9223372036854775807:9223372036854775807",
  73. },
  74. }
  75. for _, tc := range tests {
  76. t.Run(tc.name, func(t *testing.T) {
  77. got := billingSubKey(tc.userID, tc.groupID)
  78. require.Equal(t, tc.expected, got)
  79. })
  80. }
  81. }
  82. func TestJitteredTTL(t *testing.T) {
  83. const (
  84. minTTL = 4*time.Minute + 30*time.Second // 270s = 5min - 30s
  85. maxTTL = 5*time.Minute + 30*time.Second // 330s = 5min + 30s
  86. )
  87. for i := 0; i < 200; i++ {
  88. ttl := jitteredTTL()
  89. require.GreaterOrEqual(t, ttl, minTTL, "jitteredTTL() 返回值低于下限: %v", ttl)
  90. require.LessOrEqual(t, ttl, maxTTL, "jitteredTTL() 返回值超过上限: %v", ttl)
  91. }
  92. }
  93. func TestJitteredTTL_HasVariation(t *testing.T) {
  94. // 多次调用应该产生不同的值(验证抖动存在)
  95. seen := make(map[time.Duration]struct{}, 50)
  96. for i := 0; i < 50; i++ {
  97. seen[jitteredTTL()] = struct{}{}
  98. }
  99. // 50 次调用中应该至少有 2 个不同的值
  100. require.Greater(t, len(seen), 1, "jitteredTTL() 应产生不同的 TTL 值")
  101. }