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/periodlimit_test.go

76 lines
1.5 KiB
Go

4 years ago
package limit
import (
"testing"
"github.com/alicebob/miniredis/v2"
4 years ago
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
4 years ago
)
func TestPeriodLimit_Take(t *testing.T) {
testPeriodLimit(t)
}
func TestPeriodLimit_TakeWithAlign(t *testing.T) {
testPeriodLimit(t, Align())
}
func TestPeriodLimit_RedisUnavailable(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
const (
seconds = 1
quota = 5
)
l := NewPeriodLimit(seconds, quota, redis.New(s.Addr()), "periodlimit")
4 years ago
s.Close()
val, err := l.Take("first")
assert.NotNil(t, err)
assert.Equal(t, 0, val)
}
func testPeriodLimit(t *testing.T, opts ...PeriodOption) {
store := redistest.CreateRedis(t)
4 years ago
const (
seconds = 1
total = 100
quota = 5
)
4 years ago
l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
4 years ago
var allowed, hitQuota, overQuota int
for i := 0; i < total; i++ {
val, err := l.Take("first")
if err != nil {
t.Error(err)
}
switch val {
case Allowed:
allowed++
case HitQuota:
hitQuota++
case OverQuota:
overQuota++
default:
t.Error("unknown status")
}
}
assert.Equal(t, quota-1, allowed)
assert.Equal(t, 1, hitQuota)
assert.Equal(t, total-quota, overQuota)
}
func TestQuotaFull(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
l := NewPeriodLimit(1, 1, redis.New(s.Addr()), "periodlimit")
val, err := l.Take("first")
assert.Nil(t, err)
assert.Equal(t, HitQuota, val)
}