You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/limit/tokenlimit_test.go

89 lines
1.6 KiB
Go

4 years ago
package limit
import (
"testing"
"time"
"github.com/alicebob/miniredis/v2"
4 years ago
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redis/redistest"
4 years ago
)
func init() {
logx.Disable()
}
func TestTokenLimit_Rescue(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
const (
total = 100
rate = 5
burst = 10
)
l := NewTokenLimiter(rate, burst, redis.New(s.Addr()), "tokenlimit")
4 years ago
s.Close()
var allowed int
for i := 0; i < total; i++ {
time.Sleep(time.Second / time.Duration(total))
if i == total>>1 {
assert.Nil(t, s.Restart())
}
if l.Allow() {
allowed++
}
// make sure start monitor more than once doesn't matter
l.startMonitor()
}
assert.True(t, allowed >= burst+rate)
}
func TestTokenLimit_Take(t *testing.T) {
4 years ago
store, clean, err := redistest.CreateRedis()
4 years ago
assert.Nil(t, err)
4 years ago
defer clean()
4 years ago
const (
total = 100
rate = 5
burst = 10
)
4 years ago
l := NewTokenLimiter(rate, burst, store, "tokenlimit")
4 years ago
var allowed int
for i := 0; i < total; i++ {
time.Sleep(time.Second / time.Duration(total))
if l.Allow() {
allowed++
}
}
assert.True(t, allowed >= burst+rate)
}
func TestTokenLimit_TakeBurst(t *testing.T) {
4 years ago
store, clean, err := redistest.CreateRedis()
4 years ago
assert.Nil(t, err)
4 years ago
defer clean()
4 years ago
const (
total = 100
rate = 5
burst = 10
)
4 years ago
l := NewTokenLimiter(rate, burst, store, "tokenlimit")
4 years ago
var allowed int
for i := 0; i < total; i++ {
if l.Allow() {
allowed++
}
}
assert.True(t, allowed >= burst)
}