diff --git a/internal/api/access_test.go b/internal/api/access_test.go index c661885f..d8b6dbb1 100644 --- a/internal/api/access_test.go +++ b/internal/api/access_test.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -92,6 +93,31 @@ func sessionCookie(t *testing.T, pool *pgxpool.Pool, user dbq.User) *http.Cookie return &http.Cookie{Name: auth.SessionCookieName, Value: token} } +// reachedHandler stands for a request that got past the access checks into a +// handler, which then panicked on the walk's bare wiring. +const reachedHandler = -1 + +// serveGuarded serves one request and returns its status, or reachedHandler +// when a handler panicked. Without the recover, one route mounted outside its +// group would take down the whole test binary and hide every other failure. +func serveGuarded(r http.Handler, req *http.Request) (code int) { + defer func() { + if recover() != nil { + code = reachedHandler + } + }() + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w.Code +} + +func describeCode(code int) string { + if code == reachedHandler { + return "from inside its handler (it ran, and panicked)" + } + return strconv.Itoa(code) +} + // Every API route but the public ones answers 401 without a session, and // every admin route answers 403 to a signed-in user who is not an admin. // The routes come from the production router, so a route registered outside @@ -109,10 +135,8 @@ func TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin(t *testing.T) { public[key] = true continue } - anon := httptest.NewRecorder() - r.ServeHTTP(anon, httptest.NewRequest(rt.method, rt.path, nil)) - if anon.Code != http.StatusUnauthorized { - t.Errorf("%s answered %d without a session, want 401", key, anon.Code) + if code := serveGuarded(r, httptest.NewRequest(rt.method, rt.path, nil)); code != http.StatusUnauthorized { + t.Errorf("%s answered %s without a session, want 401", key, describeCode(code)) } if !strings.HasPrefix(rt.pattern, "/api/admin/") { continue @@ -120,10 +144,8 @@ func TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin(t *testing.T) { admin++ req := httptest.NewRequest(rt.method, rt.path, nil) req.AddCookie(cookie) - signedIn := httptest.NewRecorder() - r.ServeHTTP(signedIn, req) - if signedIn.Code != http.StatusForbidden { - t.Errorf("%s answered %d to a non-admin, want 403", key, signedIn.Code) + if code := serveGuarded(r, req); code != http.StatusForbidden { + t.Errorf("%s answered %s to a non-admin, want 403", key, describeCode(code)) } } if admin < 50 {