github.com/vipernet-xyz/tm@v0.34.24/libs/timer/throttle_timer_test.go (about)

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