forked from ulule/limiter
/
limiter_test.go
107 lines (85 loc) · 2.41 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
97
98
99
100
101
102
103
104
105
106
107
package limiter
import (
"math"
"testing"
"time"
"github.com/garyburd/redigo/redis"
"github.com/stretchr/testify/assert"
)
// TestLimiterMemory tests Limiter with memory store.
func TestLimiterMemory(t *testing.T) {
rate, err := NewRateFromFormatted("3-M")
assert.Nil(t, err)
store := NewMemoryStoreWithOptions(StoreOptions{
Prefix: "limitertests:memory",
CleanUpInterval: 30 * time.Second,
})
limiter := NewLimiter(store, rate)
i := 1
for i <= 5 {
ctx, err := limiter.Get("boo")
assert.Nil(t, err)
if i <= 3 {
assert.Equal(t, int64(3), ctx.Limit)
assert.Equal(t, int64(3-i), ctx.Remaining)
assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)
} else {
assert.Equal(t, int64(3), ctx.Limit)
assert.True(t, ctx.Remaining == 0)
assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)
}
i++
}
}
// TestLimiterRedis tests Limiter with Redis store.
func TestLimiterRedis(t *testing.T) {
rate, err := NewRateFromFormatted("3-M")
assert.Nil(t, err)
store, err := NewRedisStoreWithOptions(
newRedisPool(),
StoreOptions{Prefix: "limitertests:redis", MaxRetry: 3})
assert.Nil(t, err)
limiter := NewLimiter(store, rate)
i := 1
for i <= 5 {
ctx, err := limiter.Get("boo")
assert.Nil(t, err)
if i <= 3 {
assert.Equal(t, int64(3), ctx.Limit)
assert.Equal(t, int64(3-i), ctx.Remaining)
assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)
} else {
assert.Equal(t, int64(3), ctx.Limit)
assert.True(t, ctx.Remaining == 0)
assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)
}
i++
}
}
// -----------------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------------
// newRedisPool returns
func newRedisPool() *redis.Pool {
return redis.NewPool(func() (redis.Conn, error) {
c, err := redis.Dial("tcp", ":6379")
if err != nil {
return nil, err
}
return c, err
}, 100)
}
// newRedisLimiter returns an instance of limiter with redis backend.
func newRedisLimiter(formattedQuota string, prefix string) *Limiter {
rate, err := NewRateFromFormatted(formattedQuota)
if err != nil {
panic(err)
}
store, err := NewRedisStoreWithOptions(
newRedisPool(),
StoreOptions{Prefix: prefix, MaxRetry: 3})
if err != nil {
panic(err)
}
return NewLimiter(store, rate)
}