github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/throttler_test.go (about)

     1  package actor
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestThrottler(t *testing.T) {
    12  	wg := &sync.WaitGroup{}
    13  	wg.Add(1)
    14  
    15  	// create a throttler that triggers after 10 invocations within 1 second
    16  	throttler := NewThrottle(10, 1*time.Second, func(i int32) {
    17  		wg.Done()
    18  	})
    19  
    20  	throttler()
    21  	v := throttler()
    22  
    23  	assert.Equal(t, Open, v)
    24  
    25  	for i := 0; i < 8; i++ {
    26  		v = throttler()
    27  	}
    28  
    29  	// should be closing now when we have invoked 10 times
    30  	assert.Equal(t, Closing, v)
    31  
    32  	// invoke once more
    33  	v = throttler()
    34  	// should bee closed, 11 invokes
    35  	assert.Equal(t, Closed, v)
    36  
    37  	// wait for callback to be invoked
    38  	wg.Wait()
    39  
    40  	// valve should be open now that time has elapsed
    41  	v = throttler()
    42  	assert.Equal(t, Open, v)
    43  }