2017-12-05 15:01:07 +01:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
// make govet noshadow happy...
|
|
|
|
asrt "github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
2017-12-21 11:15:17 -05:00
|
|
|
// NOTE: this only tests with the ManualTicker.
|
|
|
|
// How do you test a real-clock ticker properly?
|
2017-12-05 15:01:07 +01:00
|
|
|
func TestRepeat(test *testing.T) {
|
|
|
|
assert := asrt.New(test)
|
|
|
|
|
2017-12-21 11:15:17 -05:00
|
|
|
ch := make(chan time.Time, 100)
|
|
|
|
// tick fires cnt times on ch
|
|
|
|
tick := func(cnt int) {
|
|
|
|
for i := 0; i < cnt; i++ {
|
|
|
|
ch <- time.Now()
|
|
|
|
}
|
2017-12-05 15:01:07 +01:00
|
|
|
}
|
2017-12-21 11:15:17 -05:00
|
|
|
tock := func(test *testing.T, t *RepeatTimer, cnt int) {
|
|
|
|
for i := 0; i < cnt; i++ {
|
|
|
|
after := time.After(time.Second * 2)
|
|
|
|
select {
|
|
|
|
case <-t.Ch:
|
|
|
|
case <-after:
|
|
|
|
test.Fatal("expected ticker to fire")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
done := true
|
|
|
|
select {
|
|
|
|
case <-t.Ch:
|
|
|
|
done = false
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
assert.True(done)
|
|
|
|
}
|
|
|
|
|
|
|
|
ticker := NewManualTicker(ch)
|
|
|
|
t := NewRepeatTimerWithTicker("bar", ticker)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
|
|
|
// start at 0
|
2017-12-21 11:15:17 -05:00
|
|
|
tock(test, t, 0)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
|
|
|
// wait for 4 periods
|
2017-12-21 11:15:17 -05:00
|
|
|
tick(4)
|
|
|
|
tock(test, t, 4)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
|
|
|
// keep reseting leads to no firing
|
|
|
|
for i := 0; i < 20; i++ {
|
2017-12-21 11:15:17 -05:00
|
|
|
time.Sleep(time.Millisecond)
|
2017-12-05 15:01:07 +01:00
|
|
|
t.Reset()
|
|
|
|
}
|
2017-12-21 11:15:17 -05:00
|
|
|
tock(test, t, 0)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
|
|
|
// after this, it still works normal
|
2017-12-21 11:15:17 -05:00
|
|
|
tick(2)
|
|
|
|
tock(test, t, 2)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
|
|
|
// after a stop, nothing more is sent
|
|
|
|
stopped := t.Stop()
|
|
|
|
assert.True(stopped)
|
2017-12-21 11:15:17 -05:00
|
|
|
tock(test, t, 0)
|
2017-12-05 15:01:07 +01:00
|
|
|
|
2017-12-19 16:16:16 -06:00
|
|
|
// close channel to stop counter
|
|
|
|
close(t.Ch)
|
2017-12-05 15:01:07 +01:00
|
|
|
}
|