periodlimit_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package limit
  2. import (
  3. "testing"
  4. "github.com/alicebob/miniredis/v2"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/wuntsong-org/go-zero-plus/core/stores/redis"
  7. "github.com/wuntsong-org/go-zero-plus/core/stores/redis/redistest"
  8. )
  9. func TestPeriodLimit_Take(t *testing.T) {
  10. testPeriodLimit(t)
  11. }
  12. func TestPeriodLimit_TakeWithAlign(t *testing.T) {
  13. testPeriodLimit(t, Align())
  14. }
  15. func TestPeriodLimit_RedisUnavailable(t *testing.T) {
  16. s, err := miniredis.Run()
  17. assert.Nil(t, err)
  18. const (
  19. seconds = 1
  20. quota = 5
  21. )
  22. l := NewPeriodLimit(seconds, quota, redis.New(s.Addr()), "periodlimit")
  23. s.Close()
  24. val, err := l.Take("first")
  25. assert.NotNil(t, err)
  26. assert.Equal(t, 0, val)
  27. }
  28. func testPeriodLimit(t *testing.T, opts ...PeriodOption) {
  29. store := redistest.CreateRedis(t)
  30. const (
  31. seconds = 1
  32. total = 100
  33. quota = 5
  34. )
  35. l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
  36. var allowed, hitQuota, overQuota int
  37. for i := 0; i < total; i++ {
  38. val, err := l.Take("first")
  39. if err != nil {
  40. t.Error(err)
  41. }
  42. switch val {
  43. case Allowed:
  44. allowed++
  45. case HitQuota:
  46. hitQuota++
  47. case OverQuota:
  48. overQuota++
  49. default:
  50. t.Error("unknown status")
  51. }
  52. }
  53. assert.Equal(t, quota-1, allowed)
  54. assert.Equal(t, 1, hitQuota)
  55. assert.Equal(t, total-quota, overQuota)
  56. }
  57. func TestQuotaFull(t *testing.T) {
  58. s, err := miniredis.Run()
  59. assert.Nil(t, err)
  60. l := NewPeriodLimit(1, 1, redis.New(s.Addr()), "periodlimit")
  61. val, err := l.Take("first")
  62. assert.Nil(t, err)
  63. assert.Equal(t, HitQuota, val)
  64. }