github.com/pokt-network/tendermint@v0.32.11-0.20230426215212-59310158d3e9/libs/timer/throttle_timer_test.go (about)

     1  package timer
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	// make govet noshadow happy...
     9  
    10  	asrt "github.com/stretchr/testify/assert"
    11  )
    12  
    13  type thCounter struct {
    14  	input chan struct{}
    15  	mtx   sync.Mutex
    16  	count int
    17  }
    18  
    19  func (c *thCounter) Increment() {
    20  	c.mtx.Lock()
    21  	c.count++
    22  	c.mtx.Unlock()
    23  }
    24  
    25  func (c *thCounter) Count() int {
    26  	c.mtx.Lock()
    27  	val := c.count
    28  	c.mtx.Unlock()
    29  	return val
    30  }
    31  
    32  // Read should run in a go-routine and
    33  // updates count by one every time a packet comes in
    34  func (c *thCounter) Read() {
    35  	for range c.input {
    36  		c.Increment()
    37  	}
    38  }
    39  
    40  func TestThrottle(test *testing.T) {
    41  	assert := asrt.New(test)
    42  
    43  	ms := 50
    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 12, over 2 delay sections, adds 3
    70  	short := time.Duration(ms/5) * time.Millisecond
    71  	for i := 0; i < 13; 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  }