Files
alterminal/internal/auth/notfound_test.go
T
2026-10-03 10:44:29 +08:00

52 lines
1.7 KiB
Go

package auth
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
)
func TestNotFoundHandlerRendersPage(t *testing.T) {
rec := httptest.NewRecorder()
NotFoundHandler(rec, httptest.NewRequest(http.MethodGet, "/no-such-page", nil))
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
t.Fatalf("Content-Type = %q, want text/html", ct)
}
if csp := rec.Header().Get("Content-Security-Policy"); !strings.Contains(csp, "default-src 'none'") || !strings.Contains(csp, "style-src 'self'") {
t.Fatalf("Content-Security-Policy = %q, 應停用外部資源載入且樣式僅允許本站", csp)
}
body := rec.Body.String()
for _, want := range []string{"404", "找不到頁面", `href="/login"`, `/static/css/main.css`} {
if !strings.Contains(body, want) {
t.Errorf("404 頁缺少 %s", want)
}
}
if strings.Contains(body, "<aside") {
t.Fatal("404 頁應為獨立版面,不含側邊導覽欄")
}
}
func TestRouterNotFoundUsesCustomPage(t *testing.T) {
// chi 的 NotFound 不分方法:GET 與 POST 到未匹配路徑都應輸出自訂頁。
r := chi.NewRouter()
r.Get("/login", func(w http.ResponseWriter, r *http.Request) {})
r.NotFound(NotFoundHandler)
for _, method := range []string{http.MethodGet, http.MethodPost} {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(method, "/definitely-not-a-route", nil))
if rec.Code != http.StatusNotFound {
t.Fatalf("%s status = %d, want 404", method, rec.Code)
}
if !strings.Contains(rec.Body.String(), "找不到頁面") {
t.Fatalf("%s 應輸出自訂 404 頁,body = %s", method, rec.Body.String())
}
}
}