github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/vent/chain/ethereum/throttler_test.go (about) 1 package ethereum 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/hyperledger/burrow/logging/logconfig" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 var logger = logconfig.Sink().Terminal().LoggingConfig().WithTrace().MustLogger() 13 14 const delta = float64(time.Millisecond) 15 16 func TestThrottler_Overage(t *testing.T) { 17 throttler := NewThrottler(100, time.Second, time.Minute, logger) 18 19 now := doRequests(throttler, 100, time.Now(), time.Second) 20 assert.InDelta(t, time.Duration(0), throttler.calculateWait(), delta) 21 22 doRequests(throttler, 200, now, time.Second) 23 assert.InDelta(t, time.Second, throttler.calculateWait(), delta) 24 } 25 26 func TestThrottler_Expiry(t *testing.T) { 27 throttler := NewThrottler(100, time.Second, 2*time.Second, logger) 28 29 now := doRequests(throttler, 200, time.Now(), time.Second) 30 assert.InDelta(t, time.Second, throttler.calculateWait(), delta) 31 32 now = doRequests(throttler, 100, now, time.Second) 33 assert.InDelta(t, time.Second, throttler.calculateWait(), delta) 34 35 now = doRequests(throttler, 100, now, time.Second) 36 assert.InDelta(t, time.Duration(0), throttler.calculateWait(), delta) 37 } 38 39 func TestThrottler_Bursts(t *testing.T) { 40 throttler := NewThrottler(10_000, time.Hour, 2*time.Hour, logger) 41 42 now := doRequests(throttler, 200, time.Now(), time.Millisecond) 43 assert.InDelta(t, time.Minute+12*time.Second, throttler.calculateWait(), delta) 44 45 now = doRequests(throttler, 100, now, time.Second) 46 assert.InDelta(t, time.Minute+47*time.Second, throttler.calculateWait(), delta) 47 } 48 49 // Do numRequests many requests from start within interval 50 func doRequests(throttler *Throttler, numRequests int, start time.Time, interval time.Duration) time.Time { 51 period := interval / time.Duration(numRequests-1) 52 for i := 0; i < numRequests; i++ { 53 throttler.add(start.Add(period * time.Duration(i))) 54 } 55 return start.Add(interval) 56 }