-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_limiter_test.go
83 lines (70 loc) · 1.52 KB
/
key_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
package ratelimiter
import (
"fmt"
"testing"
"time"
)
func TestKeyLimiterGetSetDelete(t *testing.T) {
key := "test"
l := NewKeyLimiter()
l.RegisterKey(key, 5, time.Second)
if !l.HasKey(key) {
t.Fatal("expected existing key:", key)
}
l.DeleteKeys("test")
if l.HasKey(key) {
t.Fatal("expected nonexistent key:", key)
}
}
func testKeyLimiterAccuracy(t *testing.T) {
limit := 8
window := 5 * time.Second
l := NewKeyLimiter()
defer l.DeleteKeys()
l.RegisterKey("test", uint32(limit), window)
attempts := 10
elapsedChan := make(chan time.Duration, 1)
go func(elCh chan time.Duration) {
started := time.Now()
for i := 0; i < attempts; i++ {
l.LimitKey("test", 1, func() {
elCh <- time.Now().Sub(started)
})
}
}(elapsedChan)
for i := 0; i < attempts; i++ {
select {
case dur := <-elapsedChan:
if i == limit {
fmt.Println(dur.Round(time.Second), window)
if dur.Round(time.Second) == window {
return
}
}
}
}
t.Fatal("limiter is inaccurate")
}
func TestConcurrentKeyLimiterAccuracy(t *testing.T) {
limit := 8
window := 5 * time.Second
l := NewKeyLimiter()
defer l.DeleteKeys()
l.RegisterKey("test", uint32(limit), window)
attempts := 10
elapsedChan := make(chan time.Duration, attempts)
started := time.Now()
for i := 0; i < attempts; i++ {
go func() {
l.LimitKey("test", 1, func() {
elapsedChan <- time.Now().Sub(started)
})
}()
}
for dur := range elapsedChan {
if dur.Round(time.Second) == window {
return
}
}
t.Fatal("limiter is inaccurate")
}