tendermint/common/repeat_timer_test.go

70 lines
1.2 KiB
Go
Raw Normal View History

2017-12-05 06:01:07 -08:00
package common
import (
"testing"
"time"
// make govet noshadow happy...
asrt "github.com/stretchr/testify/assert"
)
// 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)
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
}
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
tock(test, t, 0)
2017-12-05 06:01:07 -08:00
// wait for 4 periods
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++ {
time.Sleep(time.Millisecond)
2017-12-05 06:01:07 -08:00
t.Reset()
}
tock(test, t, 0)
2017-12-05 06:01:07 -08:00
// after this, it still works normal
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)
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
}