package httpx import ( "net/http/httptest" "strings" "testing" "github.com/gin-gonic/gin" ) func TestResponseHelpers(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New() r.GET("/ok", OK) r.GET("/fail", func(c *gin.Context) { Fail(c, "bad") }) r.GET("/auth", func(c *gin.Context) { NoAuth(c, "login") }) for _, tc := range []struct { path string statusCode int body string }{ {"/ok", 200, `{"code":0,"data":{},"msg":"操作成功"}`}, {"/fail", 200, `{"code":7,"data":{},"msg":"bad"}`}, {"/auth", 401, `{"code":7,"data":null,"msg":"login"}`}, } { req := httptest.NewRequest("GET", tc.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) if w.Code != tc.statusCode || w.Body.String() != tc.body { t.Fatalf("%s: status=%d body=%q", tc.path, w.Code, w.Body.String()) } } } func TestSanitizeFailureMessageKeepsSafeConnectionSummary(t *testing.T) { for _, message := range []string{"Kafka 连接测试失败", "EMQX 连接测试失败", "RabbitMQ 连接测试失败"} { if got := sanitizeFailureMessage(message); got != message { t.Fatalf("sanitizeFailureMessage(%q) = %q", message, got) } } } func TestSetCookieUsesRequestedName(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New() r.GET("/cookie", func(c *gin.Context) { SetCookie(c, "example", "value", 60) }) req := httptest.NewRequest("GET", "/cookie", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) if got := w.Header().Get("Set-Cookie"); !strings.HasPrefix(got, "example=") { t.Fatalf("Set-Cookie = %q", got) } }