package main import ( "net/http" "net/http/httptest" "strings" "testing" "time" ) func formPost(body string, cookie *http.Cookie) *http.Request { req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") if cookie != nil { req.AddCookie(cookie) } return req } // 未帶 Session Cookie 時不會查詢資料庫,因此 handler 可以傳入 nil db。 func TestLoginPageRendersForm(t *testing.T) { h := loginPageHandler(nil) rec := httptest.NewRecorder() h(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200", 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) } for _, want := range []string{`alert(1)") if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", rec.Code) } body := rec.Body.String() if strings.Contains(body, "