-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_limiter_test.go
59 lines (50 loc) · 1.24 KB
/
host_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
package rlutils
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestHostLimiter(t *testing.T) {
cases := []struct {
name string
host string
expectedToBeLimited bool
}{
{
name: "Host is limited",
host: "api.example.com",
expectedToBeLimited: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mockCounter := new(MockCounter)
mockCounter.On("Get", mock.Anything, mock.Anything).Return(1, nil)
mockCounter.On("Increment", mock.Anything, mock.Anything).Return(nil)
reqLimit := 5
windowLen := time.Minute
limiter := NewHostLimiter(
reqLimit,
windowLen,
nil,
nil,
)
// Using the mock counter instead of the real one.
limiter.Counter = mockCounter
req := httptest.NewRequest(http.MethodGet, "http://"+tc.host, nil)
rule, err := limiter.Rule(req)
assert.NoError(t, err)
if tc.expectedToBeLimited {
assert.NotNil(t, rule)
assert.Equal(t, tc.host, rule.Key)
assert.Equal(t, reqLimit, rule.ReqLimit)
assert.Equal(t, windowLen, rule.WindowLen)
} else {
assert.Nil(t, rule)
}
})
}
}