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.

95 lines
1.6 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. 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. shortwait := time.Duration(ms/2) * time.Millisecond
  37. longwait := time.Duration(2) * delay
  38. t := NewThrottleTimer("foo", delay)
  39. // start at 0
  40. c := &thCounter{input: t.Ch}
  41. assert.Equal(0, c.Count())
  42. go c.Read()
  43. // waiting does nothing
  44. time.Sleep(longwait)
  45. assert.Equal(0, c.Count())
  46. // send one event adds one
  47. t.Set()
  48. time.Sleep(longwait)
  49. assert.Equal(1, c.Count())
  50. // send a burst adds one
  51. for i := 0; i < 5; i++ {
  52. t.Set()
  53. }
  54. time.Sleep(longwait)
  55. assert.Equal(2, c.Count())
  56. // keep cancelling before it is ready
  57. for i := 0; i < 10; i++ {
  58. t.Set()
  59. time.Sleep(shortwait)
  60. t.Unset()
  61. }
  62. time.Sleep(longwait)
  63. assert.Equal(2, c.Count())
  64. // a few unsets do nothing...
  65. for i := 0; i < 5; i++ {
  66. t.Unset()
  67. }
  68. assert.Equal(2, c.Count())
  69. // send 12, over 2 delay sections, adds 3
  70. short := time.Duration(ms/5) * time.Millisecond
  71. for i := 0; i < 13; i++ {
  72. t.Set()
  73. time.Sleep(short)
  74. }
  75. time.Sleep(longwait)
  76. assert.Equal(5, c.Count())
  77. stopped := t.Stop()
  78. assert.True(stopped)
  79. }