Files
ai_job_chat_agent/internal/api/middleware/ratelimit_test.go
2026-01-12 11:33:43 +08:00

36 lines
713 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"testing"
"time"
)
func TestRateLimiter_AllowAndRefill(t *testing.T) {
rl := NewRateLimiter(2, 1) // 容量2每秒补充1
// 注入可控时间
now := time.Unix(0, 0).UnixNano()
rl.now = func() int64 { return now }
rl.lastRefill = now
rl.tokens = 2
if !rl.Allow() {
t.Fatalf("expected first Allow() true")
}
if !rl.Allow() {
t.Fatalf("expected second Allow() true")
}
if rl.Allow() {
t.Fatalf("expected third Allow() false (no tokens)")
}
// 过 1 秒应补充 1 个令牌
now += int64(time.Second)
if !rl.Allow() {
t.Fatalf("expected Allow() true after refill")
}
if rl.Allow() {
t.Fatalf("expected Allow() false again (tokens should be 0)")
}
}