// auth_jwt_revocation_test.go(原 Day24):黑名单鉴权中间件测试。 package middleware import ( "context" "net/http" "net/http/httptest" "testing" "time" "github.com/gin-gonic/gin" ) // runRevocation 用给定 revoked/checker 构造中间件并执行一次请求。 func runRevocation(t *testing.T, token string, revoked func(context.Context, string) bool, checker func(context.Context, int64) (bool, error)) int { t.Helper() gin.SetMode(gin.TestMode) r := gin.New() r.GET("/p", AuthJWTWithRevocation("sec", revoked, checker), func(c *gin.Context) { c.Status(http.StatusOK) }) w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/p", nil) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } r.ServeHTTP(w, req) return w.Code } // TestAuthJWTWithRevocation 黑名单/禁用/放行三分支。 func TestAuthJWTWithRevocation(t *testing.T) { tok, err := SignAccessToken("sec", 42, "d24", "ops", time.Hour) if err != nil { t.Fatal(err) } notRevoked := func(context.Context, string) bool { return false } enabled := func(context.Context, int64) (bool, error) { return true, nil } disabled := func(context.Context, int64) (bool, error) { return false, nil } // 已注销令牌 → 401 if code := runRevocation(t, tok, func(context.Context, string) bool { return true }, enabled); code != http.StatusUnauthorized { t.Fatalf("已注销令牌 = %d, 期望 401", code) } // 未注销但账号禁用 → 401 if code := runRevocation(t, tok, notRevoked, disabled); code != http.StatusUnauthorized { t.Fatalf("禁用账号 = %d, 期望 401", code) } // 正常放行 → 200 if code := runRevocation(t, tok, notRevoked, enabled); code != http.StatusOK { t.Fatalf("正常令牌 = %d, 期望 200", code) } // 无令牌 → 401 if code := runRevocation(t, "", notRevoked, enabled); code != http.StatusUnauthorized { t.Fatalf("无令牌 = %d, 期望 401", code) } // nil 回调全部跳过(仅 JWT 校验)→ 200 if code := runRevocation(t, tok, nil, nil); code != http.StatusOK { t.Fatalf("nil 回调 = %d, 期望 200", code) } }