-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoken_bucket_test.go
46 lines (36 loc) · 1.11 KB
/
token_bucket_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 equalizer
import (
"context"
"testing"
"time"
"github.com/reugn/equalizer/internal/assert"
)
func TestTokenBucket(t *testing.T) {
tokenBucket, err := NewTokenBucket(32, 100*time.Millisecond)
assert.IsNil(t, err)
var quota bool
for i := 0; i < 32; i++ {
quota = tokenBucket.TryAcquire()
}
assert.Equal(t, quota, true)
quota = tokenBucket.TryAcquire()
assert.Equal(t, quota, false)
time.Sleep(110 * time.Millisecond)
quota = tokenBucket.TryAcquire()
assert.Equal(t, quota, true)
assert.IsNil(t, tokenBucket.Acquire(context.Background()))
}
func TestTokenBucket_Context(t *testing.T) {
tokenBucket, err := NewTokenBucket(1, time.Second)
assert.IsNil(t, err)
assert.IsNil(t, tokenBucket.Acquire(context.Background()))
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
defer cancel()
err = tokenBucket.Acquire(ctx)
assert.ErrorIs(t, err, context.DeadlineExceeded)
}
func TestTokenBucket_Errors(t *testing.T) {
tokenBucket, err := NewTokenBucket(-1, time.Second)
assert.ErrorContains(t, err, "nonpositive capacity")
assert.IsNil(t, tokenBucket)
}