forked from momokatte/go-limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathburst_test.go
75 lines (60 loc) · 1.76 KB
/
burst_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
package limiter
import (
"errors"
"testing"
"time"
)
func TestBurstRateLimiter(t *testing.T) {
l := NewBurstRateLimiter(NewRate(1, time.Millisecond))
start := time.Now()
for i := 0; i < 40; i += 1 {
l.CheckWait()
}
duration := time.Now().Sub(start)
expectedMin := time.Duration(30) * time.Millisecond
if duration < expectedMin {
t.Errorf("Expected duration greater than %d, got %d", expectedMin, duration)
t.FailNow()
}
expectedMax := time.Duration(50) * time.Millisecond
if expectedMax < duration {
t.Errorf("Expected duration less than %d, got %d", expectedMax, duration)
t.FailNow()
}
}
func TestBurstRateLimiter_Invoke(t *testing.T) {
l := NewBurstRateLimiter(NewRate(1, time.Millisecond))
if err := l.Invoke(func() error { return errors.New("error") }); err == nil {
t.Error("Expected error, got nil")
}
if err := l.Invoke(func() error { return nil }); err != nil {
t.Errorf("Unexpected error, got: %s", err.Error())
}
start := time.Now()
for i := 0; i < 40; i += 1 {
l.Invoke(func() error { return nil })
}
duration := time.Now().Sub(start)
expectedMin := time.Duration(30) * time.Millisecond
if duration < expectedMin {
t.Errorf("Expected duration greater than %d, got %d", expectedMin, duration)
t.FailNow()
}
expectedMax := time.Duration(50) * time.Millisecond
if expectedMax < duration {
t.Errorf("Expected duration less than %d, got %d", expectedMax, duration)
t.FailNow()
}
}
func BenchmarkBurstRateLimiter(b *testing.B) {
l := NewBurstRateLimiter(NewRate(2000000, time.Millisecond))
for i := 0; i < b.N; i++ {
l.CheckWait()
}
}
func BenchmarkBurstRateLimiter_Invoke(b *testing.B) {
l := NewBurstRateLimiter(NewRate(2000000, time.Millisecond))
for i := 0; i < b.N; i++ {
l.Invoke(func() error { return nil })
}
}