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