forked from Patrolavia/ratelimit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_test.go
66 lines (61 loc) · 1.2 KB
/
reader_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
package ratelimit
import (
"bytes"
"testing"
"time"
)
func TestReader(t *testing.T) {
cases := []struct {
name string
rate int64
burst int64
prefill bool // whether to enable burst
expect time.Duration
}{
{
name: "R1K-B1K",
rate: 1 * KB,
burst: 1 * KB,
expect: 2 * time.Second,
},
{
name: "R1K-B5K",
rate: 1 * KB,
burst: 5 * KB,
expect: 2 * time.Second,
},
{
name: "R1K-B5K*burst",
rate: 1 * KB,
burst: 5 * KB,
expect: 0 * time.Second,
prefill: true,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
b := NewFromRate(c.rate, c.burst, 0)
buf := bytes.NewBuffer(make([]byte, c.rate*2))
r := b.NewReader(buf)
if c.prefill {
b.Return(c.burst)
}
begin := time.Now().UnixNano()
data := make([]byte, c.rate)
for _ = range []int{1, 2} {
n, err := r.Read(data)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if int64(n) != c.rate {
t.Fatalf("written != rate: %d", n)
}
}
end := time.Now().UnixNano()
dur := time.Duration(end - begin)
if dur < c.expect || dur > c.expect+time.Second {
t.Errorf("unexpected time: %d", dur)
}
})
}
}