/
tests.go
86 lines (66 loc) · 1.67 KB
/
tests.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
76
77
78
79
80
81
82
83
84
85
86
package tests
import (
"context"
"math"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/ulule/limiter"
)
// TestStoreSequentialAccess verify that store works as expected with a sequential access.
func TestStoreSequentialAccess(t *testing.T, store limiter.Store) {
is := require.New(t)
ctx := context.Background()
limiter := limiter.New(store, limiter.Rate{
Limit: 3,
Period: time.Minute,
})
for i := 1; i <= 6; i++ {
if i <= 3 {
lctx, err := limiter.Peek(ctx, "foo")
is.NoError(err)
is.NotZero(lctx)
is.Equal(int64(3-(i-1)), lctx.Remaining)
}
lctx, err := limiter.Get(ctx, "foo")
is.NoError(err)
is.NotZero(lctx)
if i <= 3 {
is.Equal(int64(3), lctx.Limit)
is.Equal(int64(3-i), lctx.Remaining)
is.True(math.Ceil(time.Since(time.Unix(lctx.Reset, 0)).Seconds()) <= 60)
lctx, err = limiter.Peek(ctx, "foo")
is.NoError(err)
is.Equal(int64(3-i), lctx.Remaining)
} else {
is.Equal(int64(3), lctx.Limit)
is.True(lctx.Remaining == 0)
is.True(math.Ceil(time.Since(time.Unix(lctx.Reset, 0)).Seconds()) <= 60)
}
}
}
// TestStoreConcurrentAccess verify that store works as expected with a concurrent access.
func TestStoreConcurrentAccess(t *testing.T, store limiter.Store) {
is := require.New(t)
ctx := context.Background()
limiter := limiter.New(store, limiter.Rate{
Limit: 100000,
Period: 10 * time.Second,
})
goroutines := 500
ops := 500
wg := &sync.WaitGroup{}
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
go func(i int) {
for j := 0; j < ops; j++ {
lctx, err := limiter.Get(ctx, "foo")
is.NoError(err)
is.NotZero(lctx)
}
wg.Done()
}(i)
}
wg.Wait()
}