Files
admin_gitea 6f07849a53
Build Packages / Test (push) Has been cancelled
Build Packages / Build macOS package (push) Has been cancelled
Build Packages / Build Linux package (push) Has been cancelled
Build Packages / Build Windows package (push) Has been cancelled
Build Packages / Publish GitHub Release (push) Has been cancelled
feat: unify service port and add GitHub packages workflow
2026-08-05 15:13:29 +08:00

60 lines
1.9 KiB
Go

package main
import (
"net/http"
"net/http/httptest"
"testing"
"testing/fstest"
"github.com/gin-gonic/gin"
)
func TestAPIAndFrontendShareRouter(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.GET("/api/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
router.NoRoute(serveFrontend(fstest.MapFS{
"index.html": {Data: []byte("<html>app</html>")},
"assets/app.js": {Data: []byte("console.log('app')")},
}))
tests := []struct {
path string
statusCode int
body string
}{
{path: "/api/ping", statusCode: http.StatusOK, body: `{"status":"ok"}`},
{path: "/admin", statusCode: http.StatusOK, body: "<html>app</html>"},
{path: "/assets/app.js", statusCode: http.StatusOK, body: "console.log('app')"},
{path: "/api/missing", statusCode: http.StatusNotFound, body: "404 page not found"},
{path: "/uploads/missing.png", statusCode: http.StatusNotFound, body: "404 page not found"},
}
for _, test := range tests {
t.Run(test.path, func(t *testing.T) {
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
if recorder.Code != test.statusCode || recorder.Body.String() != test.body {
t.Fatalf("unexpected response: status=%d body=%q", recorder.Code, recorder.Body.String())
}
})
}
}
func TestCORSMiddlewareUsesServicePort(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(corsMiddleware("8080"))
router.GET("/api/ping", func(c *gin.Context) { c.Status(http.StatusNoContent) })
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
request.Header.Set("Origin", "http://localhost:8080")
router.ServeHTTP(recorder, request)
if origin := recorder.Header().Get("Access-Control-Allow-Origin"); origin != "http://localhost:8080" {
t.Fatalf("unexpected allowed origin: %q", origin)
}
}