"""Generated clients must accept the pitch-1.1 contract without changing hitting schemas.""" import copy import json from pathlib import Path import pytest from ai_coach.pitch_report.v1_1.schemas import PitchReport from ai_coach.swing_report.schemas import SwingAnalysisPayload, SwingReport from fastapi.openapi.utils import get_openapi from jsonschema import Draft202012Validator from pydantic.json_schema import models_json_schema from app.integrations.pitching_reports import report_for_read from app.main import create_app from tests.factories import make_account from tests.integration.test_pitching_flow import payload as current_pitch_payload from tests.integration.test_swing_reports import PAYLOAD, make_session def assert_valid(spec, schema, instance): validator = Draft202012Validator({**schema, "components": spec["components"]}) errors = list(validator.iter_errors(instance)) assert not errors, "\n".join(f"{list(error.path)}: {error.message}" for error in errors) def references(value): if isinstance(value, dict): if "$ref" in value: yield value["$ref"] for child in value.values(): yield from references(child) elif isinstance(value, list): for child in value: yield from references(child) async def test_openapi_pitching_unions_and_all_references_resolve(client): spec = (await client.get("/openapi.json")).json() for ref in references(spec): assert ref.startswith("#/"), ref target = spec for part in ref[2:].split("/"): target = target[part.replace("~1", "/").replace("~0", "~")] paths, schemas = spec["paths"], spec["components"]["schemas"] pitch = paths["/v1/sessions/{session_id}/pitch-report"]["post"] request = pitch["requestBody"]["content"]["application/json"]["schema"] assert request == {"$ref": "#/components/schemas/PitchPayload"} assert "PitchAnalysisPayload" not in schemas assert schemas["SessionOut"]["properties"]["report"]["anyOf"] == [ {"$ref": "#/components/schemas/SwingReport"}, {"$ref": "#/components/schemas/PitchReport"}, {"type": "null"}] assert paths["/v1/sessions"]["post"]["responses"]["201"]["content"]["application/json"]["schema"] == { "$ref": "#/components/schemas/SessionEnvelope"} assert paths["/v1/sessions/{session_id}"]["get"]["responses"]["200"]["content"]["application/json"]["schema"] == { "$ref": "#/components/schemas/SessionEnvelope"} retry = paths["/v1/sessions/{session_id}/pitch-report/retry-coaching"]["post"] assert "requestBody" not in retry assert retry["responses"]["200"]["content"]["application/json"]["schema"] == { "$ref": "#/components/schemas/PitchReport"} assert schemas["PitchPayload"]["properties"]["schema_version"]["const"] == "pitch-1.1" assert schemas["PitchPayload"]["properties"]["visual_evidence"]["type"] == "null" assert schemas["PitchReport"]["properties"]["visual_evidence"]["type"] == "null" def test_existing_schema_components_and_hitting_contract_remain_unchanged(): app = create_app() before = get_openapi(title=app.title, version=app.version, routes=app.routes) _, contracts = models_json_schema([ (SwingAnalysisPayload, "validation"), (SwingReport, "serialization"), ], ref_template="#/components/schemas/{model}") before["components"]["schemas"].update(contracts["$defs"]) after = app.openapi() for name, expected in before["components"]["schemas"].items(): if name not in {"HTTPValidationError", "ValidationError", "SessionOut"}: assert after["components"]["schemas"][name] == expected, name hitting = after["paths"]["/v1/sessions/{session_id}/swing-report"]["post"] assert hitting["requestBody"]["content"]["application/json"]["schema"] == { "$ref": "#/components/schemas/SwingAnalysisPayload"} assert hitting["responses"]["200"]["content"]["application/json"]["schema"] == { "$ref": "#/components/schemas/SwingReport"} @pytest.mark.parametrize("kind", ["current_pitch", "hitting"]) async def test_real_requests_reports_and_session_envelopes_validate_against_openapi(client, kind): spec = (await client.get("/openapi.json")).json() owner = await make_account() sid = await make_session(owner["id"], mode="h" if kind == "hitting" else "p") payload = copy.deepcopy(PAYLOAD if kind == "hitting" else current_pitch_payload(sid)) path = "/v1/sessions/{session_id}/" + ("swing-report" if kind == "hitting" else "pitch-report") operation = spec["paths"][path]["post"] assert_valid(spec, operation["requestBody"]["content"]["application/json"]["schema"], payload) response = await client.post(path.format(session_id=sid), params={"queue": "false"}, json=payload, headers=owner["headers"]) assert response.status_code == 200, response.text report = response.json() assert_valid(spec, operation["responses"]["200"]["content"]["application/json"]["schema"], report) detail = await client.get(f"/v1/sessions/{sid}", headers=owner["headers"]) assert detail.status_code == 200, detail.text assert detail.json()["session"]["report"] == report assert_valid(spec, {"$ref": "#/components/schemas/SessionEnvelope"}, detail.json()) if kind == "current_pitch": stale = copy.deepcopy(report) stale["meta"]["prompt_version"] = "older-pitching-prompt" projected = report_for_read("p", stale, payload) PitchReport.model_validate(projected) assert_valid(spec, {"$ref": "#/components/schemas/PitchReport"}, projected) assert_valid(spec, spec["components"]["schemas"]["SessionOut"]["properties"]["report"], projected) retry = await client.post(f"/v1/sessions/{sid}/pitch-report/retry-coaching", headers=owner["headers"]) assert retry.status_code == 200, retry.text assert_valid(spec, {"$ref": "#/components/schemas/PitchReport"}, retry.json()) def test_checked_in_openapi_matches_generated_document(): snapshot = Path(__file__).resolve().parents[2] / "docs" / "openapi.json" assert json.loads(snapshot.read_text()) == create_app().openapi()