// send_precheck_test.go(原 Day42):/send/precheck 预检端点——拦截器链真入口(D18 提交前预检)。 package v1 import ( "net/http" "strings" "testing" "github.com/gin-gonic/gin" "github.com/glebarez/sqlite" "gorm.io/gorm" "go-sms/internal/middleware" "go-sms/internal/model/entity" "go-sms/internal/pkg/casbin" "go-sms/internal/service/account" "go-sms/internal/service/audit" "go-sms/internal/service/channel" "go-sms/internal/service/interceptor" "go-sms/internal/service/template" ) // newD42Router Day 42 路由:模板+拦截链(sqlite,黑名单/频次策略/拦截日志表)。 func newD42Router(t *testing.T) (*gin.Engine, *gorm.DB) { t.Helper() gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) if err != nil { t.Fatal(err) } if sqlDB, e := db.DB(); e == nil { sqlDB.SetMaxOpenConns(1) } if err := db.AutoMigrate(&entity.AccountUser{}, &entity.TemplateSMS{}, &entity.SendBlockLog{}); err != nil { t.Fatal(err) } // 策略表与账号/消息系实体共用索引名(idx_account_status/uk_mobile_account), // glebarez sqlite 索引名为库级作用域,建索引报错但表已建好,忽略(见 interceptor 测试同注)。 _ = db.AutoMigrate(&entity.PolicyFrequency{}) _ = db.AutoMigrate(&entity.PolicyBlacklist{}) _ = db.AutoMigrate(&entity.PolicyWhitelist{}) e, err := casbin.New(db) if err != nil { t.Fatal(err) } for _, p := range [][]string{{"admin", "*", "*"}, {"customer", "message", "write"}} { if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { t.Fatal(err) } } users := []entity.AccountUser{ {Username: "d42-admin", Role: "admin", Status: 1}, {Username: "d42-cust", Role: "customer", Status: 1}, } for i := range users { if err := db.Create(&users[i]).Error; err != nil { t.Fatal(err) } if _, err := e.BindRole(users[i].ID, users[i].Role); err != nil { t.Fatal(err) } } acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) chain := interceptor.NewDefaultChain(db, nil, interceptor.NewDBRecorder(db), interceptor.Options{FreqStore: interceptor.NewMemoryFreqStore()}) r := gin.New() Register(r.Group("/api/v1"), Deps{ Account: acctSvc, Audit: audit.NewService(db), Channel: channel.NewService(db), Template: template.NewService(db), Interceptor: chain, Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), Perm: middleware.CasbinChecker(e), }) return r, db } // TestAPI_SendPrecheck 验收:黑名单/频次/签名逐号预检(DryRun);全过 passed=total。 func TestAPI_SendPrecheck(t *testing.T) { r, db := newD42Router(t) tok := d25Token(t, 2, "customer") // customer:message:write(ID=2 d42-cust) // 造数:黑名单 1 号 + 频次策略(同号码自然日 max=1)。 if err := db.Create(&entity.PolicyBlacklist{Mobile: "13800138000", AccountID: 0}).Error; err != nil { t.Fatal(err) } if err := db.Create(&entity.PolicyFrequency{ AccountID: 2, Dim: 1, WindowUnit: 1, MaxCount: 1, Status: 1}).Error; err != nil { t.Fatal(err) } // ① 黑名单拦截:1 黑 + 1 干净号 → blocked 1 / passed 1。 body := `{"account_id":2,"mobiles":["13800138000","13800138001"],"content":"【云】双 11 大促"}` w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"passed":1`) || !strings.Contains(w.Body.String(), `"interceptor":"blacklist"`) { t.Fatalf("黑名单预检 = %d: %s", w.Code, w.Body.String()) } // 拦截原因落库(DryRun 不落库——预检无副作用;仅提交主链落库,这里应 0 行)。 var n int64 db.Model(&entity.SendBlockLog{}).Count(&n) if n != 0 { t.Fatalf("DryRun 预检不应落库: %d", n) } // ② 签名拦截:无【】签名。 body = `{"account_id":2,"mobiles":["13800138002"],"content":"无签名内容"}` w = doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"interceptor":"sign"`) { t.Fatalf("签名预检 = %d: %s", w.Code, w.Body.String()) } // ③ 模板短信预检:未过审 400 → 审核过后渲染逐号预检通过。 w = doReqBody(r, http.MethodPost, "/api/v1/templates", tok, "application/json", []byte(`{"account_id":2,"name":"会员日","content":"【云】{name}您好,会员日 5 折"}`)) if w.Code != http.StatusOK { t.Fatalf("建模板 = %d: %s", w.Code, w.Body.String()) } adminTok := d25Token(t, 1, "admin") body = `{"account_id":2,"template_id":1,"mobiles":["13800138003"],"variables":{"name":"张三"}}` if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusBadRequest { t.Fatalf("模板未过审预检应 400: %d %s", w.Code, w.Body.String()) } doReqBody(r, http.MethodPut, "/api/v1/templates/1/review", adminTok, "application/json", []byte(`{"pass":true}`)) if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"passed":1`) { t.Fatalf("过审模板预检应通过: %d %s", w.Code, w.Body.String()) } // 缺参拒绝。 body = `{"account_id":2,"template_id":1,"mobiles":["13800138003"]}` if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusBadRequest { t.Fatalf("模板缺参预检应 400: %d %s", w.Code, w.Body.String()) } // ④ 非法号码(基础校验拒绝路径)。 body = `{"account_id":2,"mobiles":["123"],"content":"【云】x"}` w = doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) if w.Code != http.StatusBadRequest { t.Fatalf("非法号码应 400: %d %s", w.Code, w.Body.String()) } }