File size: 6,200 Bytes
7bf5a7e
a8788e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf5a7e
 
a8788e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf5a7e
a8788e5
 
 
 
 
 
 
 
 
 
 
 
 
7bf5a7e
a8788e5
 
 
 
7bf5a7e
a8788e5
 
 
be69d1e
 
a8788e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""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()