Files
VLoop/backend/internal/middleware/redis/setnx_test.go
huanghaosheng 91c13ee022 test(redis): 把 SetNX 用例改为通用锁语义
删除 hot:applied 占位后,SetNX 只剩分布式锁一个调用方。
用例的注释与键名改为 lock:feed:hot: 前缀,避免再指向已不存在的占位键。
验证:go test -buildvcs=false -count=1 ./internal/middleware/redis/ 通过。
2026-11-01 15:15:39 +08:00

61 lines
1.6 KiB
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 redis
import (
"context"
"testing"
"time"
miniredis "github.com/alicebob/miniredis/v2"
goredis "github.com/redis/go-redis/v9"
)
// SetNX 是"同一把锁最多被一个持有者拿到"这个互斥的原语。
// 两个性质必须钉住:只有第一次能拿到占位;后到的调用不得刷新 TTL,
// 否则反复重试的调用方会让占位永不过期。
func TestSetNX_ClaimsOnlyOnce(t *testing.T) {
mr, err := miniredis.Run()
if err != nil {
t.Fatalf("start miniredis: %v", err)
}
defer mr.Close()
client := &Client{rdb: goredis.NewClient(&goredis.Options{Addr: mr.Addr()})}
defer client.Close()
ctx := context.Background()
key := "lock:feed:hot:abc123"
ttl := time.Hour
ok, err := client.SetNX(ctx, key, []byte("1"), ttl)
if err != nil {
t.Fatalf("first SetNX: %v", err)
}
if !ok {
t.Fatal("第一次 SetNX 应拿到占位(返回 true)")
}
mr.FastForward(10 * time.Minute)
ttlBefore := mr.TTL(key)
ok, err = client.SetNX(ctx, key, []byte("2"), ttl)
if err != nil {
t.Fatalf("second SetNX: %v", err)
}
if ok {
t.Fatal("第二次 SetNX 不应拿到占位(返回 false)")
}
if got, _ := mr.Get(key); got != "1" {
t.Fatalf("第二次 SetNX 不应覆盖已有值,得到 %q", got)
}
if ttlAfter := mr.TTL(key); ttlAfter != ttlBefore {
t.Fatalf("第二次 SetNX 不应刷新 TTL:%s → %s", ttlBefore, ttlAfter)
}
}
func TestSetNX_NilClientReturnsError(t *testing.T) {
var client *Client
if _, err := client.SetNX(context.Background(), "k", []byte("1"), time.Second); err == nil {
t.Fatal("nil client 应返回错误,而不是静默成功")
}
}