-
Notifications
You must be signed in to change notification settings - Fork 59
/
ratelimit_test.go
96 lines (75 loc) · 1.77 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package twitch
import (
"sync"
"testing"
"time"
)
func TestUnlimitedRateLimiter(t *testing.T) {
limiter := CreateUnlimitedRateLimiter()
if !limiter.IsUnlimited() {
t.Fatal("Limited must be unlimited")
}
for i := 0; i < 5000; i++ {
before := time.Now()
limiter.Throttle(1)
after := time.Now()
diff := after.Sub(before)
if diff >= windowRateLimiterSleepDuration {
t.Fatal("No sleeping allowed in unlimited rate limiter")
}
}
}
func TestDefaultRateLimiter(t *testing.T) {
limiter := CreateDefaultRateLimiter()
if limiter.IsUnlimited() {
t.Fatal("Limited must not be unlimited")
}
for i := 0; i < 20; i++ {
before := time.Now()
limiter.Throttle(1)
after := time.Now()
diff := after.Sub(before)
if diff >= windowRateLimiterSleepDuration {
t.Fatal("No sleeping should take place while we're within the rate limit")
}
}
}
func TestDefaultRateLimiterBigChunks(t *testing.T) {
limiter := CreateDefaultRateLimiter()
if limiter.IsUnlimited() {
t.Fatal("Limited must not be unlimited")
}
for i := 0; i < 2; i++ {
before := time.Now()
limiter.Throttle(10)
after := time.Now()
diff := after.Sub(before)
if diff >= windowRateLimiterSleepDuration {
t.Fatal("No sleeping should take place while we're within the rate limit")
}
}
}
func TestDefaultRateLimiterMultiThread(t *testing.T) {
limiter := CreateDefaultRateLimiter()
wg := sync.WaitGroup{}
sender := func(n int) {
for i := 0; i < n; i++ {
limiter.Throttle(1)
}
}
before := time.Now()
numWorkers := 2
wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go func() {
sender(10)
wg.Done()
}()
}
wg.Wait()
after := time.Now()
diff := after.Sub(before)
if diff >= windowRateLimiterSleepDuration {
t.Fatal("No sleeping allowed in unlimited rate limiter")
}
}