vegas_test.go 1.1 KB

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