12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package limit
- import (
- "testing"
- "time"
- "git.i2edu.net/i2/go-zero/core/logx"
- "git.i2edu.net/i2/go-zero/core/stores/redis"
- "git.i2edu.net/i2/go-zero/core/stores/redis/redistest"
- "github.com/alicebob/miniredis/v2"
- "github.com/stretchr/testify/assert"
- )
- 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.NewRedis(s.Addr(), redis.NodeType), "tokenlimit")
- 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) {
- store, clean, err := redistest.CreateRedis()
- assert.Nil(t, err)
- defer clean()
- const (
- total = 100
- rate = 5
- burst = 10
- )
- l := NewTokenLimiter(rate, burst, store, "tokenlimit")
- 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) {
- store, clean, err := redistest.CreateRedis()
- assert.Nil(t, err)
- defer clean()
- const (
- total = 100
- rate = 5
- burst = 10
- )
- l := NewTokenLimiter(rate, burst, store, "tokenlimit")
- var allowed int
- for i := 0; i < total; i++ {
- if l.Allow() {
- allowed++
- }
- }
- assert.True(t, allowed >= burst)
- }
|