2017-12-05 06:01:07 -08:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
// make govet noshadow happy...
|
|
|
|
asrt "github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
2017-12-21 08:15:17 -08:00
|
|
|
// NOTE: this only tests with the ManualTicker.
|
|
|
|
// How do you test a real-clock ticker properly?
|
2017-12-05 06:01:07 -08:00
|
|
|
func TestRepeat(test *testing.T) {
|
|
|
|
assert := asrt.New(test)
|
|
|
|
|
2017-12-21 08:15:17 -08: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 06:01:07 -08:00
|
|
|
}
|
2017-12-21 08:15:17 -08: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 06:01:07 -08:00
|
|
|
|
|
|
|
// start at 0
|
2017-12-21 08:15:17 -08:00
|
|
|
tock(test, t, 0)
|
2017-12-05 06:01:07 -08:00
|
|
|
|
|
|
|
// wait for 4 periods
|
2017-12-21 08:15:17 -08:00
|
|
|
tick(4)
|
|
|
|
tock(test, t, 4)
|
2017-12-05 06:01:07 -08:00
|
|
|
|
|
|
|
// keep reseting leads to no firing
|
|
|
|
for i := 0; i < 20; i++ {
|
2017-12-21 08:15:17 -08:00
|
|
|
time.Sleep(time.Millisecond)
|
2017-12-05 06:01:07 -08:00
|
|
|
t.Reset()
|
|
|
|
}
|
2017-12-21 08:15:17 -08:00
|
|
|
tock(test, t, 0)
|
2017-12-05 06:01:07 -08:00
|
|
|
|
|
|
|
// after this, it still works normal
|
2017-12-21 08:15:17 -08:00
|
|
|
tick(2)
|
|
|
|
tock(test, t, 2)
|
2017-12-05 06:01:07 -08:00
|
|
|
|
|
|
|
// after a stop, nothing more is sent
|
|
|
|
stopped := t.Stop()
|
|
|
|
assert.True(stopped)
|
2017-12-21 08:15:17 -08:00
|
|
|
tock(test, t, 0)
|
2017-12-05 06:01:07 -08:00
|
|
|
|
2017-12-19 14:16:16 -08:00
|
|
|
// close channel to stop counter
|
|
|
|
close(t.Ch)
|
2017-12-05 06:01:07 -08:00
|
|
|
}
|