periodlimit_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package limit
  2. import (
  3. "testing"
  4. "github.com/alicebob/miniredis"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/tal-tech/go-zero/core/stores/redis"
  7. )
  8. func TestPeriodLimit_Take(t *testing.T) {
  9. testPeriodLimit(t)
  10. }
  11. func TestPeriodLimit_TakeWithAlign(t *testing.T) {
  12. testPeriodLimit(t, Align())
  13. }
  14. func TestPeriodLimit_RedisUnavailable(t *testing.T) {
  15. s, err := miniredis.Run()
  16. assert.Nil(t, err)
  17. const (
  18. seconds = 1
  19. total = 100
  20. quota = 5
  21. )
  22. l := NewPeriodLimit(seconds, quota, redis.NewRedis(s.Addr(), redis.NodeType), "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 ...LimitOption) {
  29. s, err := miniredis.Run()
  30. assert.Nil(t, err)
  31. defer s.Close()
  32. const (
  33. seconds = 1
  34. total = 100
  35. quota = 5
  36. )
  37. l := NewPeriodLimit(seconds, quota, redis.NewRedis(s.Addr(), redis.NodeType), "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. }