-
Notifications
You must be signed in to change notification settings - Fork 8
/
keyratelimit_test.go
83 lines (70 loc) · 1.92 KB
/
keyratelimit_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package ratelimit_test
import (
"context"
"sync"
"testing"
"time"
"github.com/projectdiscovery/ratelimit"
"github.com/stretchr/testify/require"
)
func TestMultiLimiter(t *testing.T) {
limiter, err := ratelimit.NewMultiLimiter(context.Background(), &ratelimit.Options{
Key: "default",
IsUnlimited: false,
MaxCount: 100,
Duration: time.Duration(3) * time.Second,
})
require.Nil(t, err)
wg := &sync.WaitGroup{}
expectedTime := (time.Duration(6) * time.Second).Round(time.Millisecond)
wg.Add(1)
go func() {
defer wg.Done()
defaultStart := time.Now()
for i := 0; i < 201; i++ {
errx := limiter.Take("default")
require.Nil(t, errx, "failed to take")
}
timeTaken := time.Since(defaultStart).Round(time.Millisecond)
require.GreaterOrEqualf(t, timeTaken.Nanoseconds(), expectedTime.Nanoseconds(), "more token sent than requested in given timeframe")
}()
err = limiter.Add(&ratelimit.Options{
Key: "one",
IsUnlimited: false,
MaxCount: 100,
Duration: time.Duration(3) * time.Second,
})
require.Nil(t, err)
wg.Add(1)
go func() {
defer wg.Done()
oneStart := time.Now()
for i := 0; i < 201; i++ {
errx := limiter.Take("one")
require.Nil(t, errx)
}
timeTaken := time.Since(oneStart).Round(time.Millisecond)
require.GreaterOrEqualf(t, timeTaken.Nanoseconds(), expectedTime.Nanoseconds(), "more token sent than requested in given timeframe")
}()
wg.Wait()
}
func TestAdaptiveLimit(t *testing.T) {
limiter := ratelimit.New(context.TODO(), 1, time.Second)
require.NotNil(t, limiter)
start := time.Now()
expectedDuration := (time.Duration(3) * time.Second).Round(time.Millisecond)
go func() {
time.Sleep(2 * time.Second)
limiter.SetLimit(100)
}()
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
limiter.Take()
}()
}
wg.Wait()
require.WithinDuration(t, start.Add(expectedDuration), time.Now(), time.Second)
}