tendermint/common/repeat_timer_test.go

89 lines
1.7 KiB
Go
Raw Normal View History

2017-12-05 06:01:07 -08:00
package common
import (
"testing"
"time"
2017-12-23 04:18:50 -08:00
"github.com/stretchr/testify/assert"
2017-12-05 06:01:07 -08:00
)
2017-12-23 04:18:50 -08:00
// NOTE: this only tests with the LogicalTicker.
// How do you test a real-clock ticker properly?
2017-12-23 04:18:50 -08:00
func TestRepeat(t *testing.T) {
2017-12-05 06:01:07 -08:00
ch := make(chan time.Time, 100)
2017-12-23 04:18:50 -08:00
lt := time.Time{} // zero time is year 1
// tick fires `cnt` times for each second.
tick := func(cnt int) {
for i := 0; i < cnt; i++ {
2017-12-23 04:18:50 -08:00
lt = lt.Add(time.Second)
ch <- lt
}
2017-12-05 06:01:07 -08:00
}
2017-12-23 04:18:50 -08:00
// tock consumes Ticker.Chan() events `cnt` times.
tock := func(t *testing.T, rt *RepeatTimer, cnt int) {
for i := 0; i < cnt; i++ {
2017-12-23 04:18:50 -08:00
timeout := time.After(time.Second * 2)
select {
2017-12-23 04:18:50 -08:00
case _ = <-rt.Chan():
case <-timeout:
t.Fatal("expected RepeatTimer to fire")
}
}
done := true
select {
2017-12-23 04:18:50 -08:00
case <-rt.Chan():
done = false
default:
}
2017-12-23 04:18:50 -08:00
assert.True(t, done)
}
2017-12-23 04:18:50 -08:00
tm := NewLogicalTickerMaker(ch)
2017-12-25 07:13:37 -08:00
dur := time.Duration(10 * time.Millisecond) // less than a second
2017-12-23 04:18:50 -08:00
rt := NewRepeatTimerWithTickerMaker("bar", dur, tm)
2017-12-05 06:01:07 -08:00
2017-12-23 04:18:50 -08:00
// Start at 0.
tock(t, rt, 0)
tick(1) // init time
2017-12-05 06:01:07 -08:00
2017-12-23 04:18:50 -08:00
tock(t, rt, 0)
tick(1) // wait 1 periods
tock(t, rt, 1)
tick(2) // wait 2 periods
tock(t, rt, 2)
tick(3) // wait 3 periods
tock(t, rt, 3)
tick(4) // wait 4 periods
tock(t, rt, 4)
2017-12-05 06:01:07 -08:00
2017-12-23 04:18:50 -08:00
// Multiple resets leads to no firing.
2017-12-05 06:01:07 -08:00
for i := 0; i < 20; i++ {
time.Sleep(time.Millisecond)
2017-12-23 04:18:50 -08:00
rt.Reset()
2017-12-05 06:01:07 -08:00
}
2017-12-23 04:18:50 -08:00
// After this, it works as new.
tock(t, rt, 0)
tick(1) // init time
tock(t, rt, 0)
tick(1) // wait 1 periods
tock(t, rt, 1)
tick(2) // wait 2 periods
tock(t, rt, 2)
tick(3) // wait 3 periods
tock(t, rt, 3)
tick(4) // wait 4 periods
tock(t, rt, 4)
2017-12-05 06:01:07 -08:00
2017-12-23 04:18:50 -08:00
// After a stop, nothing more is sent.
rt.Stop()
tock(t, rt, 0)
2017-12-05 06:01:07 -08:00
2017-12-23 04:18:50 -08:00
// Another stop panics.
assert.Panics(t, func() { rt.Stop() })
2017-12-05 06:01:07 -08:00
}