Spaces:
Running on T4
Running on T4
File size: 5,834 Bytes
35e80ff | 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | """HTTP API: auth, input errors, size cap, and that a real session returns a guardrail-clean note."""
import pytest
from fastapi.testclient import TestClient
from pydantic import SecretStr
from ai_coach.api import create_app
from ai_coach.config import Settings
from ai_coach.service import CoachService
from .helpers import FakeGenerator, example_note, load_example
EXAMPLE = "hitting_stride_and_lunging_240fps"
def client(keyed_settings, api_key="secret-key", script=None, llm=True, **overrides):
settings = keyed_settings.model_copy(
update={
"api_key": SecretStr(api_key) if api_key else None,
"log_dir": keyed_settings.cache_path.parent / "logs",
"google_api_key": keyed_settings.google_api_key if llm else None,
**overrides,
}
)
generator = FakeGenerator(script if script is not None else [example_note(EXAMPLE)]) if llm else None
return TestClient(create_app(settings, CoachService(settings, generator=generator)))
def test_health_needs_no_key_and_ready_reports_the_model(keyed_settings):
with client(keyed_settings) as c:
assert c.get("/healthz").json() == {"status": "ok"}
assert c.get("/readyz").json() == {"status": "ready", "llm": True, "model": "gemini-3.1-flash-lite"}
@pytest.mark.parametrize("headers", [{}, {"X-API-Key": "wrong"}])
def test_coach_requires_the_right_key(keyed_settings, headers):
with client(keyed_settings) as c:
assert c.post("/v1/coach", json=load_example(EXAMPLE), headers=headers).status_code == 401
assert c.get("/v1/usage", headers=headers).status_code == 401
def test_a_real_session_returns_the_v2_response(keyed_settings):
with client(keyed_settings) as c:
r = c.post("/v1/coach", json=load_example(EXAMPLE), headers={"X-API-Key": "secret-key"})
body = r.json()
assert r.status_code == 200 and body["response_version"] == "2.0" and body["request_id"]
assert body["meta"]["source"] == "llm" and body["summary"] and body["focus"] and body["drill"]["name"]
assert 0 <= body["score"]["value"] <= 100 and body["score"]["breakdown"]
assert body["timing"] is None and body["arm_care"] is None
for dropped in ("note", "chosen_problem", "baseline_problem", "agrees_with_baseline", "usage", "source"):
assert dropped not in body
def test_without_a_model_key_the_api_still_answers_with_the_rule_based_note(keyed_settings):
with client(keyed_settings, api_key=None, llm=False) as c:
r = c.post("/v1/coach", json=load_example(EXAMPLE))
assert r.status_code == 200 and r.json()["meta"]["source"] == "rules" and r.json()["score"]["value"] is not None
def timed_session():
session = load_example(EXAMPLE)
session["session_id"] = "sess_42"
session["timing"] = {
"schema_version": "3.1",
"discipline": "hitting",
"capture": {"capture_fps": 240.0, "time_source": "original_pts"},
"reps": [
{
"rep": 1,
"outcome": "unknown",
"stepped": True,
"context": {"practice_type": "tee"},
"metrics": [
{"key": "load_to_swing_ms", "value": 300, "unit": "ms", "status": "estimated", "confidence": "est"},
{"key": "foot_down_to_swing_ms", "value": 50, "unit": "ms", "status": "estimated", "confidence": "est"},
],
}
],
}
return session
def test_timing_rides_along_and_the_session_id_is_echoed(keyed_settings):
with client(keyed_settings, api_key=None) as c:
body = c.post("/v1/coach", json=timed_session()).json()
assert body["session_id"] == "sess_42"
assert {o["metric_key"] for o in body["timing"]["observations"]} == {"load_to_swing_ms", "foot_down_to_swing_ms"}
assert body["timing"]["summary"].startswith("Timing:")
def test_bad_timing_is_a_422_and_costs_nothing(keyed_settings):
session = timed_session()
session["timing"]["schema_version"] = "9.9"
with client(keyed_settings, api_key=None, script=[]) as c: # an empty script: any model call would crash the test
r = c.post("/v1/coach", json=session)
assert r.status_code == 422 and "schema_version" in r.json()["detail"]
assert c.app.state.service.ledger.summary(1)["requests"] == 0
def test_an_unsafe_session_id_is_dropped(keyed_settings):
session = timed_session()
session["session_id"] = "<script>alert(1)</script>"
with client(keyed_settings, api_key=None) as c:
assert c.post("/v1/coach", json=session).json()["session_id"] is None
@pytest.mark.parametrize(
"content",
[b"{not json", b"[1, 2]", b'{"discipline": "hitting"}'],
ids=["bad-json", "not-an-object", "missing-parts"],
)
def test_bad_input_is_a_422_with_a_reason(keyed_settings, content):
with client(keyed_settings, api_key=None) as c:
r = c.post("/v1/coach", content=content, headers={"Content-Type": "application/json"})
assert r.status_code == 422 and r.json()["detail"]
def test_oversized_body_is_rejected(keyed_settings):
with client(keyed_settings, api_key=None, max_body_bytes=1000) as c:
assert c.post("/v1/coach", json=load_example(EXAMPLE)).status_code == 413
def test_usage_reports_the_ledger(keyed_settings):
with client(keyed_settings) as c:
c.post("/v1/coach", json=load_example(EXAMPLE), headers={"X-API-Key": "secret-key"})
usage = c.get("/v1/usage?days=1", headers={"X-API-Key": "secret-key"})
assert usage.status_code == 200 and usage.json()["requests"] == 1
def test_production_refuses_to_start_without_an_api_key(tmp_path):
settings = Settings(_env_file=None, COACH_ENV="prod", cache_path=tmp_path / "c.sqlite3")
with pytest.raises(RuntimeError, match="COACH_API_KEY"):
create_app(settings)
|