-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathburst_test.go
61 lines (55 loc) · 1.41 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
package rate
import (
"fmt"
"testing"
"time"
)
func TestNewBurstLimit(t *testing.T) {
var (
start = time.Now()
b1 = NewBurstLimit(1, 1, time.Second)
b2 = NewBurstLimit(2, 1, time.Second)
)
defer b1.Close()
defer b2.Close()
b1.Wait()
if time.Since(start) >= time.Second {
t.Errorf("NewLimitBurst was incorrect, should have run less than a second")
} else {
t.Logf("NewBurstLimit ran: %s", time.Since(start))
}
b2.Wait()
b2.Wait()
if time.Since(start) >= time.Second {
t.Errorf("NewLimitBurst was incorrect, should have run less than a second")
} else {
t.Logf("NewBurstLimit ran: %s", time.Since(start))
}
<-time.After(2 * time.Second)
start = time.Now()
b2.Wait()
b2.Wait()
if time.Since(start) >= time.Second {
t.Errorf("NewLimitBurst was incorrect, should have run less than a second")
} else {
t.Logf("NewBurstLimit ran: %s", time.Since(start))
}
}
func ExampleNewBurstLimit() {
// initialize a new burst-rate-limiter with a burst limit of 10 and a
// regeneration intervall of 1/s.
burst := NewBurstLimit(10, 1, time.Second)
// remember to free resources
defer burst.Close()
// burst through the first 10 tokens
for i := 0; i < 10; i++ {
// block until the next free token becomes available
burst.Wait()
}
// calling Try() now will not return an error, because there is no free
// token available in the bucket.
err := burst.Try()
fmt.Println(err)
// Output:
// too fast
}