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.

98 lines
1.8 KiB

  1. package common
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. // make govet noshadow happy...
  7. asrt "github.com/stretchr/testify/assert"
  8. )
  9. type thCounter struct {
  10. input <-chan struct{}
  11. mtx sync.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. // note, since this channel never closes, this will never end
  29. // if thCounter was used in anything beyond trivial test cases.
  30. // it would have to be smarter.
  31. for range c.input {
  32. c.Increment()
  33. }
  34. }
  35. func TestThrottle(test *testing.T) {
  36. assert := asrt.New(test)
  37. ms := 50
  38. delay := time.Duration(ms) * time.Millisecond
  39. shortwait := time.Duration(ms/2) * time.Millisecond
  40. longwait := time.Duration(2) * delay
  41. t := NewThrottleTimer("foo", delay)
  42. // start at 0
  43. c := &thCounter{input: t.Ch}
  44. assert.Equal(0, c.Count())
  45. go c.Read()
  46. // waiting does nothing
  47. time.Sleep(longwait)
  48. assert.Equal(0, c.Count())
  49. // send one event adds one
  50. t.Set()
  51. time.Sleep(longwait)
  52. assert.Equal(1, c.Count())
  53. // send a burst adds one
  54. for i := 0; i < 5; i++ {
  55. t.Set()
  56. }
  57. time.Sleep(longwait)
  58. assert.Equal(2, c.Count())
  59. // keep cancelling before it is ready
  60. for i := 0; i < 10; i++ {
  61. t.Set()
  62. time.Sleep(shortwait)
  63. t.Unset()
  64. }
  65. time.Sleep(longwait)
  66. assert.Equal(2, c.Count())
  67. // a few unsets do nothing...
  68. for i := 0; i < 5; i++ {
  69. t.Unset()
  70. }
  71. assert.Equal(2, c.Count())
  72. // send 12, over 2 delay sections, adds 3
  73. short := time.Duration(ms/5) * time.Millisecond
  74. for i := 0; i < 13; i++ {
  75. t.Set()
  76. time.Sleep(short)
  77. }
  78. time.Sleep(longwait)
  79. assert.Equal(5, c.Count())
  80. stopped := t.Stop()
  81. assert.True(stopped)
  82. }