package api import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/go-chi/chi/v5" ) func newSchemaRouter(s *Server) http.Handler { r := chi.NewRouter() r.Get("/api/schemas", s.HandleListSchemas) r.Get("/api/schemas/{name}", s.HandleGetSchema) r.Get("/api/schemas/{name}/form", s.HandleGetFormDescriptor) return r } func TestHandleListSchemas(t *testing.T) { s := newTestServerWithSchemas(t) router := newSchemaRouter(s) req := httptest.NewRequest("GET", "/api/schemas", nil) w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("status: got %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String()) } var schemas []map[string]any if err := json.Unmarshal(w.Body.Bytes(), &schemas); err != nil { t.Fatalf("decoding response: %v", err) } if len(schemas) == 0 { t.Error("expected at least 1 schema") } } func TestHandleGetSchema(t *testing.T) { s := newTestServerWithSchemas(t) router := newSchemaRouter(s) req := httptest.NewRequest("GET", "/api/schemas/kindred-rd", nil) w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("status: got %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String()) } var schema map[string]any if err := json.Unmarshal(w.Body.Bytes(), &schema); err != nil { t.Fatalf("decoding response: %v", err) } if schema["name"] != "kindred-rd" { t.Errorf("name: got %v, want %q", schema["name"], "kindred-rd") } } func TestHandleGetSchemaNotFound(t *testing.T) { s := newTestServerWithSchemas(t) router := newSchemaRouter(s) req := httptest.NewRequest("GET", "/api/schemas/nonexistent", nil) w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("status: got %d, want %d", w.Code, http.StatusNotFound) } } func TestHandleGetFormDescriptor(t *testing.T) { s := newTestServerWithSchemas(t) router := newSchemaRouter(s) req := httptest.NewRequest("GET", "/api/schemas/kindred-rd/form", nil) w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("status: got %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String()) } var form map[string]any if err := json.Unmarshal(w.Body.Bytes(), &form); err != nil { t.Fatalf("decoding response: %v", err) } // Form descriptor should have fields if _, ok := form["fields"]; !ok { // Some schemas may use "categories" or "segments" instead if _, ok := form["categories"]; !ok { if _, ok := form["segments"]; !ok { t.Error("form descriptor missing fields/categories/segments key") } } } }