// SPDX-License-Identifier: AGPL-3.0-or-later package httpapi import ( "io" "log/slog" "net/http" "os" "slices" "strings" "testing" "gopkg.in/yaml.v3" ) // notInSpec are routes that OpenAPI does not describe: the catch-all 404, the // admin SPA and the collaboration WebSocket. var notInSpec = []string{"/api/", "GET /admin/", "GET /admin", "GET /collab"} // TestRoutesMatchContract checks that the router and api/openapi.yaml list the // same operations, so neither can change without the other. func TestRoutesMatchContract(t *testing.T) { raw, err := os.ReadFile("../../../api/openapi.yaml") if err != nil { t.Fatal(err) } var spec struct { Paths map[string]map[string]any `yaml:"paths"` } if err := yaml.Unmarshal(raw, &spec); err != nil { t.Fatal(err) } var want []string for path, ops := range spec.Paths { for method := range ops { switch method { case "get", "put", "post", "patch", "delete": want = append(want, strings.ToUpper(method)+" "+path) } } } mux := newMux(Deps{ DB: fakeDB{}, Admin: http.NotFoundHandler(), Log: slog.New(slog.NewTextHandler(io.Discard, nil)), }) var got []string for _, p := range mux.patterns { if !slices.Contains(notInSpec, p) { got = append(got, p) } } for _, op := range want { if !slices.Contains(got, op) { t.Errorf("%s is in api/openapi.yaml but not routed", op) } } for _, p := range got { if !slices.Contains(want, p) { t.Errorf("%s is routed but missing from api/openapi.yaml", p) } } }