-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrate_limit_test.go
137 lines (115 loc) · 4.08 KB
/
rate_limit_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package gomw
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestRateLimitPassRequest(t *testing.T) {
cfg := RateLimitConfig{MaxRequests: 2, TimeWindowReset: 1 * time.Second}
next := newMockNextHandler()
rl := Ratelimit(InMemoryStore(), cfg)(next)
calls := 2
for i := 0; i < calls; i++ {
r, _ := http.NewRequest("GET", "/url", nil)
w := httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, 200, w.Code)
assert.Empty(t, w.Header().Get("X-RateLimit-Reset"))
}
assert.Equal(t, calls, next.totalCalls)
assert.True(t, next.Success())
assert.True(t, next.Called())
}
func TestRateLimitPassWhenConfigIsNotProper(t *testing.T) {
ms := new(mockStore)
next := newMockNextHandler()
ms.On("Get", mock.AnythingOfType("string")).Return(5)
ms.On("Incr", mock.AnythingOfType("string"))
ms.On("Reset", mock.AnythingOfType("string"))
testcases := []struct {
description string
cfg RateLimitConfig
store Store
}{
{
"store is empty",
RateLimitConfig{MaxRequests: 1, TimeWindowReset: 1, RequestKey: func(*http.Request) string { return "" }},
Store(nil),
},
{
"reset timer config is empty",
RateLimitConfig{MaxRequests: 1, RequestKey: func(*http.Request) string { return "" }},
ms,
},
{
"function fetch key from request config is empty",
RateLimitConfig{MaxRequests: 1, TimeWindowReset: 2},
ms,
},
{
"RateLimit max requests config is 0",
RateLimitConfig{TimeWindowReset: 1, RequestKey: func(*http.Request) string { return "" }},
ms,
},
}
for _, tc := range testcases {
rl := Ratelimit(tc.store, tc.cfg)(next)
r, _ := http.NewRequest("GET", "/url", nil)
w := httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, 200, w.Code, tc.description)
assert.Empty(t, w.Header().Get("X-RateLimit-Reset"), tc.description)
}
assert.Equal(t, len(testcases), next.totalCalls)
assert.True(t, next.Success())
assert.True(t, next.Called())
}
func TestRateLimitFailure(t *testing.T) {
cfg := RateLimitConfig{MaxRequests: 1, TimeWindowReset: 2000 * time.Millisecond, RequestKey: func(r *http.Request) string { return "request_key" }}
next, ms := newMockNextHandler(), new(mockStore)
rl := Ratelimit(ms, cfg)(next)
ms.On("Get", "request_key").Return(2).Once()
ms.On("Incr", "request_key").Once()
r, _ := http.NewRequest("GET", "/url", nil)
w := httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, http.StatusTooManyRequests, w.Code)
assert.Equal(t, "2.00", w.Header().Get("X-RateLimit-Reset"))
assert.Empty(t, next.totalCalls)
assert.False(t, next.Success())
assert.False(t, next.Called())
ms.AssertExpectations(t)
}
func TestRateLimitAfterExpiry(t *testing.T) {
cfg := RateLimitConfig{MaxRequests: 1, TimeWindowReset: 50 * time.Millisecond, RequestKey: func(r *http.Request) string { return r.URL.Path }}
next, s := newMockNextHandler(), &mapStore{Mutex: sync.Mutex{}, record: make(map[string]int)}
rl := Ratelimit(s, cfg)(next)
r, _ := http.NewRequest("GET", "/url", nil)
w := httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, 200, w.Code)
assert.Empty(t, w.Header().Get("X-RateLimit-Reset"))
assert.Equal(t, 1, s.Get(r.URL.Path), "Store should have the record of request")
w = httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, 429, w.Code, "Should fail the second immediate request")
assert.Equal(t, "0.05", w.Header().Get("X-RateLimit-Reset"))
assert.Equal(t, 2, s.Get(r.URL.Path), "Store should have the record of request")
time.Sleep(70 * time.Millisecond)
w = httptest.NewRecorder()
rl.ServeHTTP(w, r)
assert.Equal(t, 200, w.Code, "Should succeed after the timeout")
assert.Empty(t, w.Header().Get("X-RateLimit-Reset"))
assert.Equal(t, 1, s.Get(r.URL.Path), "Store should have the record of request")
assert.Equal(t, 2, next.totalCalls)
assert.True(t, next.Success())
assert.True(t, next.Called())
}
type mockStore struct{ mock.Mock }
func (m *mockStore) Reset(s string) { m.Called(s) }
func (m *mockStore) Incr(s string) { m.Called(s) }
func (m *mockStore) Get(s string) int { return m.Called(s).Int(0) }