periodlimit_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package limit
  2. import (
  3. "testing"
  4. "github.com/alicebob/miniredis/v2"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/zeromicro/go-zero/core/stores/redis"
  7. "github.com/zeromicro/go-zero/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, clean, err := redistest.CreateRedis()
  30. assert.Nil(t, err)
  31. defer clean()
  32. const (
  33. seconds = 1
  34. total = 100
  35. quota = 5
  36. )
  37. l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
  38. var allowed, hitQuota, overQuota int
  39. for i := 0; i < total; i++ {
  40. val, err := l.Take("first")
  41. if err != nil {
  42. t.Error(err)
  43. }
  44. switch val {
  45. case Allowed:
  46. allowed++
  47. case HitQuota:
  48. hitQuota++
  49. case OverQuota:
  50. overQuota++
  51. default:
  52. t.Error("unknown status")
  53. }
  54. }
  55. assert.Equal(t, quota-1, allowed)
  56. assert.Equal(t, 1, hitQuota)
  57. assert.Equal(t, total-quota, overQuota)
  58. }
  59. func TestQuotaFull(t *testing.T) {
  60. s, err := miniredis.Run()
  61. assert.Nil(t, err)
  62. l := NewPeriodLimit(1, 1, redis.New(s.Addr()), "periodlimit")
  63. val, err := l.Take("first")
  64. assert.Nil(t, err)
  65. assert.Equal(t, HitQuota, val)
  66. }