package app import ( "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestAdminRequiresLogin(t *testing.T) { srv := newTestServer(t) for _, path := range []string{"/admin", "/admin/main", "/admin/projects", "/admin/contact-details"} { req := httptest.NewRequest(http.MethodGet, path, nil) rec := httptest.NewRecorder() srv.Routes().ServeHTTP(rec, req) if rec.Code != http.StatusSeeOther { t.Fatalf("%s expected redirect, got %d", path, rec.Code) } if location := rec.Header().Get("Location"); location != "/admin/login" { t.Fatalf("%s expected login redirect, got %q", path, location) } } } func TestAdminLogin(t *testing.T) { srv := newTestServer(t) form := url.Values{"username": {"admin"}, "password": {"changeme"}} req := httptest.NewRequest(http.MethodPost, "/admin/login", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec := httptest.NewRecorder() srv.Routes().ServeHTTP(rec, req) if rec.Code != http.StatusSeeOther { t.Fatalf("expected redirect, got %d", rec.Code) } if location := rec.Header().Get("Location"); location != "/admin/main" { t.Fatalf("expected admin main redirect, got %q", location) } if len(rec.Result().Cookies()) == 0 { t.Fatal("expected session cookie") } }