limit_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package limit
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "go-common/library/rate"
  7. )
  8. func worker(qps int64, ch chan struct{}) {
  9. for {
  10. <-ch
  11. time.Sleep(time.Duration(int64(time.Second) / qps))
  12. }
  13. }
  14. func TestRateSuccess(t *testing.T) {
  15. ch := make(chan struct{})
  16. go worker(100, ch)
  17. failed := producer(New(nil), 100, ch)
  18. if failed > 0 {
  19. t.Fatalf("Should be rejected 0 time,but (%d)", failed)
  20. }
  21. }
  22. func TestRateFail(t *testing.T) {
  23. ch := make(chan struct{})
  24. go worker(100, ch)
  25. failed := producer(New(nil), 200, ch)
  26. if failed < 900 {
  27. t.Fatalf("Should be rejected more than 900 times,but (%d)", failed)
  28. }
  29. }
  30. func TestRateFailMuch(t *testing.T) {
  31. ch := make(chan struct{})
  32. go worker(10, ch)
  33. failed := producer(New(nil), 200, ch)
  34. if failed < 1600 {
  35. t.Fatalf("Should be rejected more than 1600 times,but (%d)", failed)
  36. }
  37. }
  38. func producer(l *Limiter, qps int64, ch chan struct{}) (failed int) {
  39. for i := 0; i < int(qps)*10; i++ {
  40. go func() {
  41. done, err := l.Allow(context.Background())
  42. defer done(rate.Success)
  43. if err == nil {
  44. ch <- struct{}{}
  45. } else {
  46. failed++
  47. }
  48. }()
  49. time.Sleep(time.Duration(int64(time.Second) / qps))
  50. }
  51. return
  52. }