-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware_test.go
55 lines (37 loc) · 1.22 KB
/
middleware_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
package goralim
import (
"testing"
"net/http"
"net/http/httptest"
"github.com/go-redis/redis"
"github.com/stretchr/testify/assert"
)
func TestRateLimiter(t *testing.T){
redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer redisClient.Close()
key := "test_key"
capacity := 10
refillRate := 5
tb := NewTokenBucket(key, redisClient, capacity, refillRate)
handler := http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){
w.WriteHeader(http.StatusOK)
})
rateLimiter := RateLimiter(tb, handler)
req, err := http.NewRequest("GET", "/", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
rateLimiter.ServeHTTP(rr, req)
// Test tokens exhaustion
for i := 0; i < capacity; i++ {
req, err := http.NewRequest("GET", "/", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
rateLimiter.ServeHTTP(rr, req)
}
req, err = http.NewRequest("GET", "/", nil)
assert.NoError(t, err)
rr = httptest.NewRecorder()
rateLimiter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusTooManyRequests, rr.Code)
assert.Contains(t, rr.Body.String(), "Too Many Requests")
}