github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/utils/ratelimiter/rate_limiter_test.go (about) 1 package ratelimiter 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 "golang.org/x/time/rate" 9 10 "github.com/onflow/flow-go/utils/unittest" 11 ) 12 13 // TestRateLimiter_Allow ensures rate limiter allows messages as expected 14 func TestRateLimiter_Allow(t *testing.T) { 15 // limiter limit will be set to 5 events/sec the 6th event per interval will be rate limited 16 limit := rate.Limit(1) 17 18 // burst per interval 19 burst := 1 20 21 id, _ := unittest.IdentityWithNetworkingKeyFixture() 22 peerID, err := unittest.PeerIDFromFlowID(id) 23 require.NoError(t, err) 24 25 // setup rate limiter 26 rateLimiter := NewRateLimiter(limit, burst, time.Second) 27 28 require.True(t, rateLimiter.Allow(peerID, 0)) 29 30 // second message should be rate limited 31 require.False(t, rateLimiter.Allow(peerID, 0)) 32 33 // wait for the next interval, the rate limiter should allow the next message. 34 time.Sleep(1 * time.Second) 35 36 require.True(t, rateLimiter.Allow(peerID, 0)) 37 } 38 39 // TestRateLimiter_IsRateLimited ensures IsRateLimited returns true for peers that are rate limited. 40 func TestRateLimiter_IsRateLimited(t *testing.T) { 41 // limiter limit will be set to 5 events/sec the 6th event per interval will be rate limited 42 limit := rate.Limit(1) 43 44 // burst per interval 45 burst := 1 46 47 id, _ := unittest.IdentityWithNetworkingKeyFixture() 48 peerID, err := unittest.PeerIDFromFlowID(id) 49 require.NoError(t, err) 50 51 // setup rate limiter 52 rateLimiter := NewRateLimiter(limit, burst, time.Second) 53 54 require.False(t, rateLimiter.IsRateLimited(peerID)) 55 require.True(t, rateLimiter.Allow(peerID, 0)) 56 57 // second message should be rate limited 58 require.False(t, rateLimiter.Allow(peerID, 0)) 59 require.True(t, rateLimiter.IsRateLimited(peerID)) 60 61 // wait for the next interval, the rate limiter should allow the next message. 62 time.Sleep(1 * time.Second) 63 require.True(t, rateLimiter.Allow(peerID, 0)) 64 require.False(t, rateLimiter.IsRateLimited(peerID)) 65 }