-
Notifications
You must be signed in to change notification settings - Fork 1
/
limitless_test.go
97 lines (83 loc) · 1.86 KB
/
limitless_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
package limitless
import (
"context"
"fmt"
"testing"
"time"
"github.com/go-redis/redis/v8"
)
func TestInMemoryImpl(t *testing.T) {
limiter := NewInMemoryTokenBucket(5, 2)
doExample(t, limiter, 5, 2)
}
func TestRedisImpl(t *testing.T) {
ctx := context.Background()
client, err := newRedisClient(ctx)
if err != nil {
fmt.Println(err)
return
}
defer client.Close()
// environment.InitializeEnvs(environment.VARIANT_TEST)
// logger.InitializeLogger()
// piceredis.InitializeRedisMap([]piceredis.EnumRedisDb{piceredis.REDIS_CREDIT_DB})
limiter, err := NewRedisTokenBucket(ctx, client, "myTokenBucket", 5, 2)
// limiter, err := NewRedisTokenBucket(ctx, piceredis.DefaultClient(&ctx), "myTokenBucket", 5, 2)
if err != nil {
fmt.Println(err)
return
}
doExample(t, limiter, 5, 2)
}
func doExample(t *testing.T, limiter RateLimiter, capacity int64, rate int) {
// rate limit does not exceed
failed := false
for i := 0; i < 10; i++ {
allow, err := Allow(limiter)
if err != nil {
fmt.Println(err)
return
}
if allow != nil && *allow {
fmt.Printf("Operation allowed")
} else {
fmt.Printf("Rate limit exceeded")
failed = true
}
time.Sleep(time.Duration(rate) * time.Second)
}
if failed {
t.Fail()
}
// rate limit exceeds
failed = false
for i := 0; i < 10; i++ {
allow, err := Allow(limiter)
if err != nil {
fmt.Println(err)
return
}
if allow != nil && *allow {
fmt.Printf("Operation allowed")
} else {
failed = true
fmt.Printf("Rate limit exceeded")
}
time.Sleep(time.Duration(rate-1) * time.Second)
}
if !failed {
t.Fail()
}
}
func newRedisClient(ctx context.Context) (*redis.Client, error) {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "XXXX",
DB: 0,
})
_, err := client.Ping(ctx).Result()
if err != nil {
return nil, err
}
return client, nil
}