package main import ( "bytes" "encoding/json" "os" "path/filepath" "slices" "strings" "testing" "uberbringer/internal/app/uberbringer/server" ) // repoRoot finds the repository root above the package directory, which go // test runs in. func repoRoot(t *testing.T) string { t.Helper() cwd, err := os.Getwd() if err != nil { t.Fatal(err) } root, err := findRepoRoot(cwd) if err != nil { t.Fatal(err) } return root } func generated(t *testing.T) map[string]any { t.Helper() out, err := Generate(repoRoot(t)) if err != nil { t.Fatalf("Generate: %v", err) } var doc map[string]any if err := json.Unmarshal(out, &doc); err != nil { t.Fatalf("generated document is not JSON: %v", err) } return doc } func schema(t *testing.T, doc map[string]any, name string) map[string]any { t.Helper() s, ok := doc["components"].(map[string]any)["schemas"].(map[string]any)[name].(map[string]any) if !ok { t.Fatalf("no schema %s", name) } return s } func property(t *testing.T, doc map[string]any, schemaName, prop string) map[string]any { t.Helper() p, ok := schema(t, doc, schemaName)["properties"].(map[string]any)[prop].(map[string]any) if !ok { t.Fatalf("%s has no property %s", schemaName, prop) } return p } // TestSwaggerJSONUpToDate fails when docs/swagger.json differs from what the // route table and its types produce: regenerate with `go generate ./...`. func TestSwaggerJSONUpToDate(t *testing.T) { root := repoRoot(t) committed, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(swaggerPath))) if err != nil { t.Fatal(err) } out, err := Generate(root) if err != nil { t.Fatal(err) } if !bytes.Equal(committed, out) { t.Fatal("docs/swagger.json is out of date; run: go generate ./...") } } func TestGenerateIsStable(t *testing.T) { a, err := Generate(repoRoot(t)) if err != nil { t.Fatal(err) } b, err := Generate(repoRoot(t)) if err != nil { t.Fatal(err) } if !bytes.Equal(a, b) { t.Fatal("two runs produced different documents") } } func TestEveryRouteIsDocumented(t *testing.T) { doc := generated(t) if doc["openapi"] != "3.1.0" { t.Fatalf("openapi = %v", doc["openapi"]) } paths := doc["paths"].(map[string]any) for _, r := range server.Routes() { op, ok := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any) if !ok { t.Errorf("%s %s is not documented", r.Method, r.Path) continue } if op["operationId"] != r.OperationID { t.Errorf("%s %s: operationId %v", r.Method, r.Path, op["operationId"]) } responses := op["responses"].(map[string]any) if _, ok := responses["500"]; !ok { t.Errorf("%s %s: no 500 response", r.Method, r.Path) } security, _ := op["security"].([]any) if r.Auth != (len(security) == 1) { t.Errorf("%s %s: Auth %v, security %v", r.Method, r.Path, r.Auth, op["security"]) } if !r.Auth { continue } for status, header := range map[string]string{"401": "WWW-Authenticate", "429": "Retry-After"} { resp, ok := responses[status].(map[string]any) if !ok { t.Errorf("%s %s: no %s response", r.Method, r.Path, status) continue } if headers, _ := resp["headers"].(map[string]any); headers[header] == nil { t.Errorf("%s %s: %s without %s", r.Method, r.Path, status, header) } } } } // Every {name} in a path has its path parameter. func TestPathParametersDocumented(t *testing.T) { doc := generated(t) paths := doc["paths"].(map[string]any) for _, r := range server.Routes() { op := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any) params, _ := op["parameters"].([]any) for _, name := range pathParams(r.Path) { found := slices.ContainsFunc(params, func(p any) bool { m := p.(map[string]any) return m["name"] == name && m["in"] == "path" && m["required"] == true }) if !found { t.Errorf("%s %s: path parameter %s is not documented", r.Method, r.Path, name) } } } } func pathParams(path string) []string { var names []string for part := range strings.SplitSeq(path, "/") { if name, ok := strings.CutPrefix(part, "{"); ok { names = append(names, strings.TrimSuffix(name, "}")) } } return names } func TestReferencesResolve(t *testing.T) { doc := generated(t) schemas := doc["components"].(map[string]any)["schemas"].(map[string]any) var walk func(node any) walk = func(node any) { switch n := node.(type) { case map[string]any: for k, v := range n { if s, ok := v.(string); ok && k == "$ref" { name, found := strings.CutPrefix(s, componentsPrefix) if !found { t.Errorf("$ref %q does not point at the components", s) } else if _, ok := schemas[name]; !ok { t.Errorf("$ref %q names no schema", s) } continue } walk(v) } case []any: for _, v := range n { walk(v) } } } walk(doc) } // A request schema refuses unknown fields and requires only what its // jsonschema tags mark, as the server's strict decoder does. A response // schema allows fields a later version adds. func TestRequestSchemasAreStrict(t *testing.T) { doc := generated(t) for name, required := range map[string][]any{"Job": {"elements"}, "Element": {"type"}, "Pair": {"key"}} { s := schema(t, doc, name) if s["additionalProperties"] != false { t.Errorf("%s allows additional properties", name) } if got, _ := s["required"].([]any); !slices.Equal(got, required) { t.Errorf("%s requires %v, want %v", name, got, required) } } for _, name := range []string{"JobStatus", "HealthResponse", "PreviewResponse", "ErrorResponse"} { if _, ok := schema(t, doc, name)["additionalProperties"]; ok { t.Errorf("%s restricts additional properties", name) } } } // Descriptions come from the doc comments, with the JSON name in place of // the Go name; enums and the job ID's pattern from the tags and the mapper. func TestSchemasCarryComments(t *testing.T) { doc := generated(t) if d, _ := schema(t, doc, "Element")["description"].(string); !strings.HasPrefix(d, "Element is one item on a receipt") { t.Errorf("Element description = %q", d) } // A type's description starts with the schema's name and stops at the // first blank line of its doc comment. if d, _ := schema(t, doc, "ErrorResponse")["description"].(string); !strings.HasPrefix(d, "ErrorResponse is ") { t.Errorf("ErrorResponse description = %q", d) } if d, _ := schema(t, doc, "Job")["description"].(string); d != "Job is a receipt to print." { t.Errorf("Job description = %q", d) } status := property(t, doc, "JobStatus", "status") if d, _ := status["description"].(string); !strings.HasPrefix(d, "status is ") { t.Errorf("JobStatus.status description = %q", d) } if enum, _ := status["enum"].([]any); len(enum) != 4 { t.Errorf("JobStatus.status enum = %v", status["enum"]) } id := property(t, doc, "JobStatus", "id") if id["type"] != "string" || id["pattern"] != jobIDPattern { t.Errorf("JobStatus.id = %v", id) } for _, prop := range []string{"text", "size", "pairs", "leader"} { if d, _ := property(t, doc, "Element", prop)["description"].(string); d == "" { t.Errorf("Element.%s has no description", prop) } } } // Preview answers plain text or JSON, and the print route's 202 carries // the job's URL. func TestResponseContent(t *testing.T) { doc := generated(t) paths := doc["paths"].(map[string]any) preview := paths["/api/v1/preview"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any) content := preview["content"].(map[string]any) if len(content) != 2 || content["application/json"] == nil { t.Errorf("preview 200 content = %v", content) } accepted := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["202"].(map[string]any) if headers, _ := accepted["headers"].(map[string]any); headers["Location"] == nil { t.Errorf("print 202 headers = %v", accepted["headers"]) } queueFull := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["503"].(map[string]any) if codes, _ := queueFull[codesExtension].([]any); !slices.Contains(codes, any("queue_full")) { t.Errorf("print 503 codes = %v", queueFull[codesExtension]) } }