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.

78 lines
1.4 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 rCounter struct {
  10. input <-chan time.Time
  11. mtx sync.Mutex
  12. count int
  13. }
  14. func (c *rCounter) Increment() {
  15. c.mtx.Lock()
  16. c.count++
  17. c.mtx.Unlock()
  18. }
  19. func (c *rCounter) 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 *rCounter) Read() {
  28. for range c.input {
  29. c.Increment()
  30. }
  31. }
  32. func TestRepeat(test *testing.T) {
  33. assert := asrt.New(test)
  34. dur := time.Duration(100) * time.Millisecond
  35. short := time.Duration(20) * time.Millisecond
  36. // delay waits for cnt durations, an a little extra
  37. delay := func(cnt int) time.Duration {
  38. return time.Duration(cnt)*dur + time.Duration(10)*time.Millisecond
  39. }
  40. t := NewRepeatTimer("bar", dur)
  41. // start at 0
  42. c := &rCounter{input: t.Ch}
  43. go c.Read()
  44. assert.Equal(0, c.Count())
  45. // wait for 4 periods
  46. time.Sleep(delay(4))
  47. assert.Equal(4, c.Count())
  48. // keep reseting leads to no firing
  49. for i := 0; i < 20; i++ {
  50. time.Sleep(short)
  51. t.Reset()
  52. }
  53. assert.Equal(4, c.Count())
  54. // after this, it still works normal
  55. time.Sleep(delay(2))
  56. assert.Equal(6, c.Count())
  57. // after a stop, nothing more is sent
  58. stopped := t.Stop()
  59. assert.True(stopped)
  60. time.Sleep(delay(2))
  61. assert.Equal(6, c.Count())
  62. // extra calls to stop don't block
  63. t.Stop()
  64. }