Files
archie/modules/dashboard/dashboard_test.go
T
sam 18d1e07a21 fix(dashboard): one pattern serves the page and the API catch-all (archie #2005)
The dashboard registered "/api/" and then "GET /", which ServeMux refuses:
"GET /" names fewer methods than "/api/" but a more general path, so a binary
with the dashboard built in panicked on start. Staging went down on the deploy
that first shipped both.

One handler behind one pattern decides instead: an unclaimed /api/ path is a
JSON 404, the page is read-only, and everything else is a route inside the SPA.

The test reproduces the panic against the old routing, and pins what each path
answers.
2026-11-16 00:05:02 +11:00

52 lines
2.3 KiB
Go

package dashboard
import (
"io/fs"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
// TestRoutesServeThePageBesideTheAPICatchAll guards a boot-time panic: a
// method-scoped "GET /" fallback cannot sit beside the "/api/" catch-all on one
// ServeMux, so the binary crashed on start with the dashboard built in. It also
// pins what each path answers: an unclaimed API path is a JSON 404 rather than
// the page, and the page is read-only.
func TestRoutesServeThePageBesideTheAPICatchAll(t *testing.T) {
dist := fstest.MapFS{
page: &fstest.MapFile{Data: []byte("<html>archie</html>")},
"assets/app-1.js": &fstest.MapFile{Data: []byte("console.log(1)")},
}
tests := []struct {
name string
dist fs.FS
method string
path string
wantStatus int
wantContent string
}{
{name: "the page serves a client route", dist: dist, method: http.MethodGet, path: "/runs/42", wantStatus: http.StatusOK, wantContent: "<html>archie</html>"},
{name: "an asset serves as itself", dist: dist, method: http.MethodGet, path: "/assets/app-1.js", wantStatus: http.StatusOK, wantContent: "console.log(1)"},
{name: "an unclaimed API path is JSON", dist: dist, method: http.MethodGet, path: "/api/nope", wantStatus: http.StatusNotFound, wantContent: "no such route"},
{name: "an API path denies every method", dist: dist, method: http.MethodPost, path: "/api/nope", wantStatus: http.StatusNotFound, wantContent: "no such route"},
{name: "the page is read-only", dist: dist, method: http.MethodPost, path: "/runs", wantStatus: http.StatusMethodNotAllowed, wantContent: "read-only"},
{name: "a build without the dashboard says how to make it", method: http.MethodGet, path: "/runs", wantStatus: http.StatusNotFound, wantContent: "task ui"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mux := http.NewServeMux()
Routes(mux, tt.dist)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
if w.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d", w.Code, tt.wantStatus)
}
if body := w.Body.String(); !strings.Contains(body, tt.wantContent) {
t.Fatalf("body = %q, want it to contain %q", body, tt.wantContent)
}
})
}
}