tendermint/common/throttle_timer_test.go

101 lines
1.8 KiB
Go
Raw Normal View History

2017-12-05 11:25:17 +01:00
package common
import (
"sync"
"testing"
"time"
// make govet noshadow happy...
asrt "github.com/stretchr/testify/assert"
)
2017-12-05 15:01:07 +01:00
type thCounter struct {
2017-12-06 21:08:55 +01:00
input <-chan struct{}
2017-12-05 11:25:17 +01:00
mtx sync.Mutex
count int
}
2017-12-05 15:01:07 +01:00
func (c *thCounter) Increment() {
2017-12-05 11:25:17 +01:00
c.mtx.Lock()
c.count++
c.mtx.Unlock()
}
2017-12-05 15:01:07 +01:00
func (c *thCounter) Count() int {
2017-12-05 11:25:17 +01:00
c.mtx.Lock()
val := c.count
c.mtx.Unlock()
return val
}
// Read should run in a go-routine and
// updates count by one every time a packet comes in
2017-12-05 15:01:07 +01:00
func (c *thCounter) Read() {
// note, since this channel never closes, this will never end
// if thCounter was used in anything beyond trivial test cases.
// it would have to be smarter.
2017-12-05 11:25:17 +01:00
for range c.input {
c.Increment()
}
}
func TestThrottle(test *testing.T) {
assert := asrt.New(test)
ms := 50
delay := time.Duration(ms) * time.Millisecond
2017-12-06 11:17:50 +01:00
shortwait := time.Duration(ms/2) * time.Millisecond
2017-12-05 11:25:17 +01:00
longwait := time.Duration(2) * delay
t := NewThrottleTimer("foo", delay)
// start at 0
c := &thCounter{input: t.Ch}
2017-12-05 11:25:17 +01:00
assert.Equal(0, c.Count())
go c.Read()
// waiting does nothing
time.Sleep(longwait)
assert.Equal(0, c.Count())
// send one event adds one
t.Set()
time.Sleep(longwait)
assert.Equal(1, c.Count())
// send a burst adds one
for i := 0; i < 5; i++ {
t.Set()
}
time.Sleep(longwait)
assert.Equal(2, c.Count())
2017-12-06 11:17:50 +01:00
// keep cancelling before it is ready
for i := 0; i < 10; i++ {
t.Set()
time.Sleep(shortwait)
t.Unset()
}
time.Sleep(longwait)
assert.Equal(2, c.Count())
// a few unsets do nothing...
for i := 0; i < 5; i++ {
t.Unset()
}
assert.Equal(2, c.Count())
2017-12-05 11:25:17 +01:00
// send 12, over 2 delay sections, adds 3
short := time.Duration(ms/5) * time.Millisecond
for i := 0; i < 13; i++ {
t.Set()
time.Sleep(short)
}
time.Sleep(longwait)
assert.Equal(5, c.Count())
2017-12-06 11:17:50 +01:00
stopped := t.Stop()
assert.True(stopped)
2017-12-07 10:36:03 +01:00
// extra calls to stop don't block
t.Stop()
2017-12-05 11:25:17 +01:00
}