Files
full/pkgs/all/internal/server/server_test.go
2026-09-22 21:15:34 +08:00

61 lines
2.1 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 server
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestHTTPRouterIsAvailable(t *testing.T) {
srv, err := New("0123456789abcdef0123456789abcdef", 3600, []string{"/healthz"})
if err != nil {
t.Fatal(err)
}
srv.HTTP.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
response := httptest.NewRecorder()
srv.HTTP.ServeHTTP(response, request)
if response.Code != http.StatusNoContent {
t.Fatalf("unexpected status: %d", response.Code)
}
}
// TestGatewayDispatchKeepsBusinessNotFound 守住 404 分流:网关未命中路由才回退 Gin
// 业务 handler 返回的 404 必须原样透出,不能被 Gin 的纯文本 404 覆盖。
func TestGatewayDispatchKeepsBusinessNotFound(t *testing.T) {
srv, err := New("0123456789abcdef0123456789abcdef", 3600, nil)
if err != nil {
t.Fatal(err)
}
if err := srv.Gateway.HandlePath(http.MethodPost, "/demo.Thing/Get", func(w http.ResponseWriter, _ *http.Request, _ map[string]string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"code":5,"message":"record not found"}`))
}); err != nil {
t.Fatal(err)
}
srv.HTTP.POST("/rest/demo/ping", func(c *gin.Context) { c.String(http.StatusOK, "gin") })
handler := srv.handler()
t.Run("business not found", func(t *testing.T) {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/demo.Thing/Get", nil))
if response.Code != http.StatusNotFound || !strings.Contains(response.Body.String(), "record not found") {
t.Fatalf("business 404 was overwritten: status=%d body=%s", response.Code, response.Body.String())
}
})
t.Run("gateway route miss", func(t *testing.T) {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/rest/demo/ping", nil))
if response.Code != http.StatusOK || response.Body.String() != "gin" {
t.Fatalf("gin fallback failed: status=%d body=%s", response.Code, response.Body.String())
}
})
}