-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimiter_test.go
96 lines (89 loc) · 1.83 KB
/
limiter_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package buttonoff
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestAcceptPeriod(t *testing.T) {
type testTrial struct {
message string
delay time.Duration
expected bool
}
type testCase struct {
name string
period time.Duration
trials []testTrial
}
tcs := []testCase{
{
name: "100ms-period",
period: duration("100ms"),
trials: []testTrial{
{
message: "should accept first",
delay: duration("1ms"),
expected: true,
},
{
message: "should deny second within 10ms",
delay: duration("10ms"),
expected: false,
},
{
message: "should allow after period (91+10>100)",
delay: duration("91ms"),
expected: true,
},
},
},
{
name: "100ms-period-repeats",
period: duration("100ms"),
trials: []testTrial{
{
message: "should accept first",
delay: duration("1ms"),
expected: true,
},
{
message: "should deny second within 10ms",
delay: duration("10ms"),
expected: false,
},
{
message: "should allow after period (91+10>100)",
delay: duration("91ms"),
expected: true,
},
{
message: "let fill, should accept",
delay: duration("201ms"),
expected: true,
},
{
message: "shouldn't burst",
delay: duration("10ms"),
expected: false,
},
},
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
limiter := NewPressRateLimiter(tc.period)
for _, trial := range tc.trials {
// t.Logf("Delaying %s for test behavior.", trial.delay)
time.Sleep(trial.delay)
assert.Equal(t, trial.expected, limiter.Accept("key"), trial.message)
}
})
}
}
func duration(s string) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
panic(err)
}
return d
}