forked from vearne/ratelimit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimit_test.go
72 lines (64 loc) · 1.7 KB
/
ratelimit_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
package ratelimit
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"testing"
"time"
)
const (
key = "key:token"
)
func TestCantGetTokenBefore(t *testing.T) {
ctrl := gomock.NewController(t)
// Assert that Bar() is invoked.
defer ctrl.Finish()
client := NewMockCmdable(ctrl)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
var sc redis.StatusCmd
sc.SetVal("PONG")
client.EXPECT().Ping(ctx).Return(&sc)
var c redis.Cmd
c.SetVal(int64(0))
client.EXPECT().EvalSha(ctx, gomock.Any(), []string{key}, gomock.Any()).Return(&c).AnyTimes()
var bsc redis.BoolSliceCmd
bsc.SetVal([]bool{true})
client.EXPECT().ScriptExists(ctx, gomock.Any()).Return(&bsc)
limiter, _ := NewTokenBucketRateLimiter(ctx, client, key,
time.Second,
3,
1,
2)
for i := 0; i < 3; i++ {
err := limiter.Wait(ctx)
if i == 2 {
assert.Contains(t, err.Error(), "can't get token")
}
}
}
func TestContextTimeOut(t *testing.T) {
ctrl := gomock.NewController(t)
// Assert that Bar() is invoked.
defer ctrl.Finish()
client := NewMockCmdable(ctrl)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
var sc redis.StatusCmd
sc.SetVal("PONG")
client.EXPECT().Ping(ctx).Return(&sc)
var c redis.Cmd
c.SetVal(int64(0))
client.EXPECT().EvalSha(ctx, gomock.Any(), []string{key}, gomock.Any()).Return(&c).AnyTimes()
var bsc redis.BoolSliceCmd
bsc.SetVal([]bool{true})
client.EXPECT().ScriptExists(ctx, gomock.Any()).Return(&bsc)
limiter, _ := NewTokenBucketRateLimiter(ctx, client, key,
time.Second,
20,
1,
2)
err := limiter.Wait(ctx)
assert.Contains(t, err.Error(), "timeout")
}