-
Notifications
You must be signed in to change notification settings - Fork 0
/
leakybucket_test.go
60 lines (54 loc) · 1.18 KB
/
leakybucket_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
package ratelimiter
import (
"testing"
"time"
)
func TestLeakyBucket(t *testing.T) {
tests := []struct {
name string
capacity int
leakRate int
initRequests int
sleepDuration time.Duration
expectedResult bool
}{
{
name: "Allow request when bucket is not full",
capacity: 5,
leakRate: 1,
initRequests: 4,
sleepDuration: 0,
expectedResult: true,
},
{
name: "Deny request when bucket is full",
capacity: 5,
leakRate: 1,
initRequests: 5,
sleepDuration: 0,
expectedResult: false,
},
{
name: "Allow request after bucket leaks",
capacity: 5,
leakRate: 1,
initRequests: 5,
sleepDuration: 2 * time.Second,
expectedResult: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lb := NewLeakyBucket(tt.capacity, tt.leakRate)
for i := 0; i < tt.initRequests; i++ {
lb.AllowRequest()
}
if tt.sleepDuration > 0 {
time.Sleep(tt.sleepDuration)
}
if lb.AllowRequest() != tt.expectedResult {
t.Errorf("AllowRequest() = %v, want %v", lb.AllowRequest(), tt.expectedResult)
}
})
}
}