periodlimit_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package limit
  2. import (
  3. "testing"
  4. "github.com/alicebob/miniredis/v2"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/tal-tech/go-zero/core/stores/redis"
  7. "github.com/tal-tech/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. total = 100
  21. quota = 5
  22. )
  23. l := NewPeriodLimit(seconds, quota, redis.NewRedis(s.Addr(), redis.NodeType), "periodlimit")
  24. s.Close()
  25. val, err := l.Take("first")
  26. assert.NotNil(t, err)
  27. assert.Equal(t, 0, val)
  28. }
  29. func testPeriodLimit(t *testing.T, opts ...PeriodOption) {
  30. store, clean, err := redistest.CreateRedis()
  31. assert.Nil(t, err)
  32. defer clean()
  33. const (
  34. seconds = 1
  35. total = 100
  36. quota = 5
  37. )
  38. l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
  39. var allowed, hitQuota, overQuota int
  40. for i := 0; i < total; i++ {
  41. val, err := l.Take("first")
  42. if err != nil {
  43. t.Error(err)
  44. }
  45. switch val {
  46. case Allowed:
  47. allowed++
  48. case HitQuota:
  49. hitQuota++
  50. case OverQuota:
  51. overQuota++
  52. default:
  53. t.Error("unknown status")
  54. }
  55. }
  56. assert.Equal(t, quota-1, allowed)
  57. assert.Equal(t, 1, hitQuota)
  58. assert.Equal(t, total-quota, overQuota)
  59. }