github.com/koko1123/flow-go-1@v0.29.6/network/p2p/unicast/ratelimit/message_rate_limiter_test.go (about) 1 package ratelimit 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 "golang.org/x/time/rate" 9 10 "github.com/koko1123/flow-go-1/utils/unittest" 11 ) 12 13 // TestMessageRateLimiter_Allow ensures rate limiter allows messages as expected 14 func TestMessageRateLimiter_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 message rate limiter 26 messageRateLimiter := NewMessageRateLimiter(limit, burst, 1) 27 28 require.True(t, messageRateLimiter.Allow(peerID, 0)) 29 30 // second message should be rate limited 31 require.False(t, messageRateLimiter.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, messageRateLimiter.Allow(peerID, 0)) 37 } 38 39 // TestMessageRateLimiter_IsRateLimited ensures IsRateLimited returns true for peers that are rate limited. 40 func TestMessageRateLimiter_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 message rate limiter 52 messageRateLimiter := NewMessageRateLimiter(limit, burst, 1) 53 54 require.False(t, messageRateLimiter.IsRateLimited(peerID)) 55 require.True(t, messageRateLimiter.Allow(peerID, 0)) 56 57 // second message should be rate limited 58 require.False(t, messageRateLimiter.Allow(peerID, 0)) 59 require.True(t, messageRateLimiter.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, messageRateLimiter.Allow(peerID, 0)) 64 require.False(t, messageRateLimiter.IsRateLimited(peerID)) 65 }