1 package connmgr
2 3 import (
4 "math"
5 "testing"
6 "time"
7 )
8 9 // TestDynamicBanScoreDecay tests the exponential decay implemented in DynamicBanScore.
10 func TestDynamicBanScoreDecay(t *testing.T) {
11 var bs DynamicBanScore
12 base := time.Now()
13 r := bs.increase(100, 50, base)
14 if r != 150 {
15 t.Errorf("Unexpected result %d after ban score increase.", r)
16 }
17 r = bs.int(base.Add(time.Minute))
18 if r != 125 {
19 t.Errorf("Halflife check failed - %d instead of 125", r)
20 }
21 r = bs.int(base.Add(7 * time.Minute))
22 if r != 100 {
23 t.Errorf("Decay after 7m - %d instead of 100", r)
24 }
25 }
26 27 // TestDynamicBanScoreLifetime tests that DynamicBanScore properly yields zero once the maximum age is reached.
28 func TestDynamicBanScoreLifetime(t *testing.T) {
29 var bs DynamicBanScore
30 base := time.Now()
31 _ = bs.increase(0, math.MaxUint32, base)
32 r := bs.int(base.Add(Lifetime * time.Second))
33 if r != 3 { // 3, not 4 due to precision loss and truncating 3.999...
34 t.Errorf("Pre max age check with MaxUint32 failed - %d", r)
35 }
36 r = bs.int(base.Add((Lifetime + 1) * time.Second))
37 if r != 0 {
38 t.Errorf("Zero after max age check failed - %d instead of 0", r)
39 }
40 }
41 42 // TestDynamicBanScore tests exported functions of DynamicBanScore. Exponential decay or other time based behavior is
43 // tested by other functions.
44 func TestDynamicBanScoreReset(t *testing.T) {
45 var bs DynamicBanScore
46 if bs.Int() != 0 {
47 t.Errorf("Initial state is not zero.")
48 }
49 bs.Increase(100, 0)
50 r := bs.Int()
51 if r != 100 {
52 t.Errorf("Unexpected result %d after ban score increase.", r)
53 }
54 bs.Reset()
55 if bs.Int() != 0 {
56 t.Errorf("Failed to reset ban score.")
57 }
58 }
59