go-zero/core/limit/periodlimit_test.go

69 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package limit
import (
"testing"
"github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/stores/redis"
2020-11-02 17:51:33 +08:00
"github.com/tal-tech/go-zero/core/stores/redistest"
2020-07-26 17:09:05 +08:00
)
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
total = 100
quota = 5
)
l := NewPeriodLimit(seconds, quota, redis.NewRedis(s.Addr(), redis.NodeType), "periodlimit")
s.Close()
val, err := l.Take("first")
assert.NotNil(t, err)
assert.Equal(t, 0, val)
}
func testPeriodLimit(t *testing.T, opts ...LimitOption) {
2020-11-02 17:51:33 +08:00
store, clean, err := redistest.CreateRedis()
2020-07-26 17:09:05 +08:00
assert.Nil(t, err)
2020-11-02 17:51:33 +08:00
defer clean()
2020-07-26 17:09:05 +08:00
const (
seconds = 1
total = 100
quota = 5
)
2020-11-02 17:51:33 +08:00
l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
2020-07-26 17:09:05 +08:00
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)
}