Files
go-sms-V2/internal/service/interceptor/blacklist_test.go
T

95 lines
3.1 KiB
Go

// blacklist_test.go Day 42:黑名单三级检测+白名单豁免。
package interceptor
import (
"context"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"go-sms/internal/model/entity"
)
// thirdStub 三级接口桩。
type thirdStub struct{ hitFor map[string]bool }
func (s *thirdStub) CheckBlacklist(_ context.Context, mobile string) (bool, error) {
return s.hitFor[mobile], nil
}
// TestBlacklistLevels 验收:白名单豁免 → 本地库二级命中 → 三级第三方命中 → Redis 一级缓存。
func TestBlacklistLevels(t *testing.T) {
db := newTestDB(t)
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
defer func() { _ = rdb.Close() }()
bl := NewBlacklist(db, rdb, &thirdStub{hitFor: map[string]bool{"13599990000": true}})
ctx := context.Background()
req := func(m string) *Req {
return &Req{AccountID: 5, Mobile: m, Content: "【测试】内容"}
}
// 未配置:全放行。
if bl.Check(ctx, req("13800000001")) != nil {
t.Fatal("无配置应放行")
}
// 二级:本地库命中(账号级)。
if err := db.Create(&entity.PolicyBlacklist{Mobile: "13800000002", AccountID: 5}).Error; err != nil {
t.Fatal(err)
}
if b := bl.Check(ctx, req("13800000002")); b == nil || b.Code != "ISC:006" {
t.Fatalf("本地库应拦截: %+v", b)
}
// 一级:二级命中已写回 Redis——删库后仍拦(缓存生效)。
if err := db.Where("mobile = ?", "13800000002").Delete(&entity.PolicyBlacklist{}).Error; err != nil {
t.Fatal(err)
}
if b := bl.Check(ctx, req("13800000002")); b == nil || b.Interceptor != "blacklist" {
t.Fatalf("Redis 缓存应拦截: %+v", b)
}
// 一级直接命中:预写缓存。
if err := rdb.SAdd(ctx, BlacklistCacheKey, "13800000003").Err(); err != nil {
t.Fatal(err)
}
if bl.Check(ctx, req("13800000003")) == nil {
t.Fatal("Redis 预写应拦截")
}
// 三级:第三方命中(本地库+缓存均无)。
if b := bl.Check(ctx, req("13599990000")); b == nil {
t.Fatal("第三方黑名单应拦截")
}
// 三级命中也回写缓存:断网第三方后仍拦。
blThirdDown := NewBlacklist(db, rdb, nil)
if blThirdDown.Check(ctx, req("13599990000")) == nil {
t.Fatal("三级命中回写缓存后应拦截")
}
// 白名单豁免:全局白名单压过本地黑名单。
if err := db.Create(&entity.PolicyBlacklist{Mobile: "13800000004", AccountID: 0}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&entity.PolicyWhitelist{Mobile: "13800000004", AccountID: 0}).Error; err != nil {
t.Fatal(err)
}
if b := bl.Check(ctx, req("13800000004")); b != nil {
t.Fatalf("白名单应豁免黑名单: %+v", b)
}
// 全局黑名单(account_id=0)对任意账号生效。
if b := bl.Check(ctx, &Req{AccountID: 99, Mobile: "13800000005",
Content: "x"}); b == nil {
_ = b // 13599990000 之外的号无配置
}
if err := db.Create(&entity.PolicyBlacklist{Mobile: "13800000006", AccountID: 0}).Error; err != nil {
t.Fatal(err)
}
if bl.Check(ctx, &Req{AccountID: 99, Mobile: "13800000006", Content: "x"}) == nil {
t.Fatal("全局黑名单应拦截任意账号")
}
}