Files
ginframework/ratelimit/limiter_test.go
T
2026-11-28 02:28:13 -08:00

55 lines
1.7 KiB
Go

package ratelimit
import (
"context"
"testing"
"git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver"
)
// TestRedisLimiterKeepsQuotaAndReset 验证原周期、桶容量和重置行为在原生连接上保持不变。
func TestRedisLimiterKeepsQuotaAndReset(t *testing.T) {
var (
client = redisserver.New(t, 3)
limiter = NewRedis(client)
cfg = &Config{Key: "owner", Total: 1, Rate: 1, TimeInterval: 3600}
ctx = context.Background()
)
if allowed, err := limiter.AllowN(ctx, cfg, 1); err != nil || !allowed {
t.Fatalf("first allowance: %v %v", allowed, err)
}
if allowed, err := limiter.AllowN(ctx, cfg, 1); err != nil || allowed {
t.Fatalf("quota exceeded: %v %v", allowed, err)
}
if err := limiter.Reset(ctx, cfg); err != nil {
t.Fatal(err)
}
if allowed, err := limiter.AllowN(ctx, cfg, 1); err != nil || !allowed {
t.Fatalf("reset failed: %v %v", allowed, err)
}
}
// TestMemoryLimitersRemainIndependent 验证独立入口不再共享可变额度,重置仍可重新获得令牌。
func TestMemoryLimitersRemainIndependent(t *testing.T) {
var (
first, second = NewMemory(), NewMemory()
cfg = &Config{Key: "same", Total: 1, Rate: 1, TimeInterval: 3600}
ctx = context.Background()
)
if allow, _ := first.AllowN(ctx, cfg, 1); !allow {
t.Fatal("initial quota missing")
}
if allow, _ := first.AllowN(ctx, cfg, 1); allow {
t.Fatal("quota was not consumed")
}
if allow, _ := second.AllowN(ctx, cfg, 1); !allow {
t.Fatal("independent entry shares quota")
}
if err := first.Reset(ctx, cfg); err != nil {
t.Fatal(err)
}
if allow, _ := first.AllowN(ctx, cfg, 1); !allow {
t.Fatal("reset failed")
}
}