-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimiter_test.go
62 lines (46 loc) · 1.79 KB
/
ratelimiter_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
package resilience4go_ratelimiter
import (
"fmt"
"github.com/stretchr/testify/require"
"testing"
"time"
)
func Test_AcquireBigNumberOfPermitsAtStartOfCycleTest(t *testing.T) {
config, _ := NewRateLimiterConfig(time.Duration(0), time.Duration(250_000_000)*time.Nanosecond, 10, false)
limiter := NewAtomicRateLimiter("atomic", config)
waitForRefresh(limiter, config, ".")
firstPermission := limiter.AcquirePermission(5)
require.True(t, firstPermission)
secondPermission := limiter.AcquirePermission(5)
require.True(t, secondPermission)
firstNoPermission := limiter.AcquirePermission(1)
require.False(t, firstNoPermission)
waitForRefresh(limiter, config, "*")
retryInNewCyclePermission := limiter.AcquirePermission(1)
require.True(t, retryInNewCyclePermission)
}
func Test_TryToAcquireBigNumberOfPermitsAtEndOfCycleTest(t *testing.T) {
config, _ := NewRateLimiterConfig(time.Duration(0), time.Duration(250_000_000)*time.Nanosecond, 10, false)
limiter := NewAtomicRateLimiter("atomic", config)
waitForRefresh(limiter, config, ".")
firstPermission := limiter.AcquirePermission(1)
require.True(t, firstPermission)
secondPermission := limiter.AcquirePermission(5)
require.True(t, secondPermission)
firstNoPermission := limiter.AcquirePermission(5)
require.False(t, firstNoPermission)
waitForRefresh(limiter, config, "*")
retryInSecondCyclePermission := limiter.AcquirePermission(5)
require.True(t, retryInSecondCyclePermission)
}
func waitForRefresh(limiter RateLimiter, config *RateLimiterConfig, printedWhileWaiting string) {
start := time.Now()
for ok := true; ok; ok = time.Now().Before(start.Add(config.limitRefreshPeriod)) {
if limiter.GetAvailablePermissions() == config.limitForPeriod {
break
}
fmt.Print(printedWhileWaiting)
time.Sleep(10 * time.Millisecond)
}
fmt.Println()
}