github.com/supragya/TendermintConnector@v0.0.0-20210619045051-113e32b84fb1/_deprecated_chains/cosmos/libs/common/throttle_timer_test.go (about) 1 package common 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 8 // make govet noshadow happy... 9 asrt "github.com/stretchr/testify/assert" 10 ) 11 12 type thCounter struct { 13 input chan struct{} 14 mtx sync.Mutex 15 count int 16 } 17 18 func (c *thCounter) Increment() { 19 c.mtx.Lock() 20 c.count++ 21 c.mtx.Unlock() 22 } 23 24 func (c *thCounter) Count() int { 25 c.mtx.Lock() 26 val := c.count 27 c.mtx.Unlock() 28 return val 29 } 30 31 // Read should run in a go-routine and 32 // updates count by one every time a packet comes in 33 func (c *thCounter) Read() { 34 for range c.input { 35 c.Increment() 36 } 37 } 38 39 func TestThrottle(test *testing.T) { 40 assert := asrt.New(test) 41 42 ms := 50 43 delay := time.Duration(ms) * time.Millisecond 44 longwait := time.Duration(2) * delay 45 t := NewThrottleTimer("foo", delay) 46 47 // start at 0 48 c := &thCounter{input: t.Ch} 49 assert.Equal(0, c.Count()) 50 go c.Read() 51 52 // waiting does nothing 53 time.Sleep(longwait) 54 assert.Equal(0, c.Count()) 55 56 // send one event adds one 57 t.Set() 58 time.Sleep(longwait) 59 assert.Equal(1, c.Count()) 60 61 // send a burst adds one 62 for i := 0; i < 5; i++ { 63 t.Set() 64 } 65 time.Sleep(longwait) 66 assert.Equal(2, c.Count()) 67 68 // send 12, over 2 delay sections, adds 3 69 short := time.Duration(ms/5) * time.Millisecond 70 for i := 0; i < 13; i++ { 71 t.Set() 72 time.Sleep(short) 73 } 74 time.Sleep(longwait) 75 assert.Equal(5, c.Count()) 76 77 close(t.Ch) 78 }