github.com/decred/dcrlnd@v0.7.6/chanfitness/rate_limit_test.go (about) 1 package chanfitness 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 // TestGetRateLimit tests getting of our rate limit using the current constants. 11 // It creates test cases that are relative to our constants so that they 12 // can be adjusted without breaking the unit test. 13 func TestGetRateLimit(t *testing.T) { 14 tests := []struct { 15 name string 16 flapCount int 17 rateLimit time.Duration 18 }{ 19 { 20 name: "zero flaps", 21 flapCount: 0, 22 rateLimit: rateLimits[0], 23 }, 24 { 25 name: "middle tier", 26 flapCount: rateLimitScale * (len(rateLimits) / 2), 27 rateLimit: rateLimits[len(rateLimits)/2], 28 }, 29 { 30 name: "last tier", 31 flapCount: rateLimitScale * (len(rateLimits) - 1), 32 rateLimit: rateLimits[len(rateLimits)-1], 33 }, 34 { 35 name: "beyond last tier", 36 flapCount: rateLimitScale * (len(rateLimits) * 2), 37 rateLimit: rateLimits[len(rateLimits)-1], 38 }, 39 } 40 41 for _, test := range tests { 42 test := test 43 44 t.Run(test.name, func(t *testing.T) { 45 t.Parallel() 46 47 limit := getRateLimit(test.flapCount) 48 require.Equal(t, test.rateLimit, limit) 49 }) 50 } 51 } 52 53 // TestCooldownFlapCount tests cooldown of all time flap counts. 54 func TestCooldownFlapCount(t *testing.T) { 55 tests := []struct { 56 name string 57 flapCount int 58 lastFlap time.Time 59 expected int 60 }{ 61 { 62 name: "just flapped, do not cooldown", 63 flapCount: 1, 64 lastFlap: testNow, 65 expected: 1, 66 }, 67 { 68 name: "period not elapsed, do not cooldown", 69 flapCount: 1, 70 lastFlap: testNow.Add(flapCountCooldownPeriod / 2 * -1), 71 expected: 1, 72 }, 73 { 74 name: "rounded to 0", 75 flapCount: 1, 76 lastFlap: testNow.Add(flapCountCooldownPeriod * -1), 77 expected: 0, 78 }, 79 { 80 name: "decreased to integer value", 81 flapCount: 10, 82 lastFlap: testNow.Add(flapCountCooldownPeriod * -1), 83 expected: 9, 84 }, 85 { 86 name: "multiple cooldown periods", 87 flapCount: 10, 88 lastFlap: testNow.Add(flapCountCooldownPeriod * -3), 89 expected: 8, 90 }, 91 } 92 93 for _, test := range tests { 94 test := test 95 96 t.Run(test.name, func(t *testing.T) { 97 t.Parallel() 98 99 flapCount := cooldownFlapCount( 100 testNow, test.flapCount, test.lastFlap, 101 ) 102 require.Equal(t, test.expected, flapCount) 103 }) 104 } 105 }