-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
rate_test.go
46 lines (42 loc) · 979 Bytes
/
rate_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
package rate
import (
"testing"
"time"
)
func TestRateLimiter_Wait_noblock(t *testing.T) {
start := time.Now()
limit := 5
interval := time.Second * 3
limiter := New(limit, interval)
for i := 0; i < limit; i++ {
limiter.Wait()
}
if time.Now().Sub(start) >= interval {
t.Error("The limiter blocked when it shouldn't have")
}
}
func TestRateLimiter_Wait_block(t *testing.T) {
start := time.Now()
limit := 5
interval := time.Second * 3
limiter := New(limit, interval)
for i := 0; i < limit+1; i++ {
limiter.Wait()
}
if time.Now().Sub(start) < interval {
t.Error("The limiter didn't block when it should have")
}
}
func TestRateLimiter_Try(t *testing.T) {
limit := 5
interval := time.Second * 3
limiter := New(limit, interval)
for i := 0; i < limit; i++ {
if ok, _ := limiter.Try(); !ok {
t.Fatalf("Should have allowed try on attempt %d", i)
}
}
if ok, _ := limiter.Try(); ok {
t.Fatal("Should have not allowed try on final attempt")
}
}