limiter_test.go 921 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package mathutil
  2. import (
  3. . "github.com/smartystreets/goconvey/convey"
  4. "math"
  5. "testing"
  6. "time"
  7. )
  8. func Test_limiter(t *testing.T) {
  9. Convey("limit interval", t, func() {
  10. var rate = 100.0
  11. var limit = NewLimiter(rate)
  12. var interval = 1.0 / rate
  13. var last time.Time
  14. for i := 0; i < 100; i++ {
  15. var t = <-limit.Token()
  16. if !last.IsZero() {
  17. var diff = t.Sub(last)
  18. So(math.Abs(diff.Seconds()-interval), ShouldBeLessThanOrEqualTo, 0.002)
  19. }
  20. last = t
  21. }
  22. })
  23. Convey("limit count", t, func() {
  24. var rate = 100.0
  25. var seconds = 10.0
  26. var limit = NewLimiter(rate)
  27. var expect = rate * seconds
  28. var timer = time.NewTimer(time.Duration(float64(time.Second) * seconds))
  29. var total = 0
  30. var run = true
  31. for run {
  32. select {
  33. case <-timer.C:
  34. run = false
  35. default:
  36. <-limit.Token()
  37. total++
  38. }
  39. }
  40. So(math.Abs(float64(total)-expect), ShouldBeLessThanOrEqualTo, rate*0.01)
  41. })
  42. }