forked from go-redis/redis_rate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrate_test.go
66 lines (56 loc) · 1.42 KB
/
rate_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
package rate_test
import (
"testing"
"time"
timerate "golang.org/x/time/rate"
"gopkg.in/redis.v3"
"github.com/go-redis/rate"
)
func rateLimiter() *rate.Limiter {
ring := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{"0": ":6379"},
})
ring.FlushDb()
limiter := timerate.NewLimiter(timerate.Every(time.Millisecond), 100)
return rate.NewLimiter(ring, limiter)
}
func TestLimit(t *testing.T) {
l := rateLimiter()
rate, reset, allow := l.Allow("test_id", 1, time.Minute)
if !allow {
t.Fatalf("rate limited with rate %d", rate)
}
if rate != 1 {
t.Fatalf("got %d, wanted 1", rate)
}
dur := time.Duration(reset-time.Now().Unix()) * time.Second
if dur > time.Minute {
t.Fatalf("got %s, wanted <= %s", dur, time.Minute)
}
rate, _, allow = l.Allow("test_id", 1, time.Minute)
if allow {
t.Fatalf("not rate limited with rate %d", rate)
}
if rate != 2 {
t.Fatalf("got %d, wanted 2", rate)
}
}
func TestRedisIsDown(t *testing.T) {
ring := redis.NewRing(&redis.RingOptions{})
limiter := timerate.NewLimiter(timerate.Every(time.Second), 1)
l := rate.NewLimiter(ring, limiter)
rate, _, allow := l.AllowMinute("test_id", 1)
if !allow {
t.Fatalf("rate limited with rate %d", rate)
}
if rate != 0 {
t.Fatalf("got %d, wanted 0", rate)
}
rate, _, allow = l.AllowMinute("test_id", 1)
if allow {
t.Fatalf("not rate limited with rate %d", rate)
}
if rate != 0 {
t.Fatalf("got %d, wanted 0", rate)
}
}