You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.5 KiB

  1. package timer
  2. import (
  3. "testing"
  4. "time"
  5. // make govet noshadow happy...
  6. asrt "github.com/stretchr/testify/assert"
  7. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  8. )
  9. type thCounter struct {
  10. input chan struct{}
  11. mtx tmsync.Mutex
  12. count int
  13. }
  14. func (c *thCounter) Increment() {
  15. c.mtx.Lock()
  16. c.count++
  17. c.mtx.Unlock()
  18. }
  19. func (c *thCounter) Count() int {
  20. c.mtx.Lock()
  21. val := c.count
  22. c.mtx.Unlock()
  23. return val
  24. }
  25. // Read should run in a go-routine and
  26. // updates count by one every time a packet comes in
  27. func (c *thCounter) Read() {
  28. for range c.input {
  29. c.Increment()
  30. }
  31. }
  32. func TestThrottle(test *testing.T) {
  33. assert := asrt.New(test)
  34. ms := 50
  35. delay := time.Duration(ms) * time.Millisecond
  36. longwait := time.Duration(2) * delay
  37. t := NewThrottleTimer("foo", delay)
  38. // start at 0
  39. c := &thCounter{input: t.Ch}
  40. assert.Equal(0, c.Count())
  41. go c.Read()
  42. // waiting does nothing
  43. time.Sleep(longwait)
  44. assert.Equal(0, c.Count())
  45. // send one event adds one
  46. t.Set()
  47. time.Sleep(longwait)
  48. assert.Equal(1, c.Count())
  49. // send a burst adds one
  50. for i := 0; i < 5; i++ {
  51. t.Set()
  52. }
  53. time.Sleep(longwait)
  54. assert.Equal(2, c.Count())
  55. // send 12, over 2 delay sections, adds 3 or more. It
  56. // is possible for more to be added if the overhead
  57. // in executing the loop is large
  58. short := time.Duration(ms/5) * time.Millisecond
  59. for i := 0; i < 13; i++ {
  60. t.Set()
  61. time.Sleep(short)
  62. }
  63. time.Sleep(longwait)
  64. assert.LessOrEqual(5, c.Count())
  65. close(t.Ch)
  66. }