Spaces:
Running on T4
Running on T4
Download backend/e2e/qa_coach_loop.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/e2e/qa_coach_loop.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/e2e/qa_coach_loop.py
-
curl -L -o qa_coach_loop.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/e2e/qa_coach_loop.py
29.3 kB
| """End-to-end QA: coach review loop (journey 3.6, milestone 3 acceptance). | |
| Run from backend/: .venv/bin/python e2e/qa_coach_loop.py | |
| BASE_URL defaults to http://127.0.0.1:8000. Creates qa-coach-<runid>-<n>@example.com accounts and deletes | |
| them at the end (DELETE /v1/me). Exit code 1 if any check fails. | |
| """ | |
| import copy | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import time | |
| import uuid | |
| import httpx | |
| BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/") | |
| RUN_ID = uuid.uuid4().hex[:8] | |
| PASSWORD = "QaCoach!2345" | |
| BODY_KEYS = {"age", "height_cm", "weight_kg", "age_years"} | |
| client = httpx.Client(base_url=BASE_URL, timeout=60) | |
| results = {"pass": 0, "fail": 0} | |
| failures: list[str] = [] | |
| created_accounts: list[dict] = [] | |
| _n = 0 | |
| PAYLOAD = { | |
| "schema_version": "1.0", "analysis_id": "analysis_001", "analysis_revision": 1, "swing_id": "swing_001", | |
| "status": "completed", | |
| "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left", | |
| "age_years": None, "height_cm": None}, | |
| "context": {"sport": "baseball", "practice_type": "tee"}, | |
| "measurement_definitions_version": "1.0", | |
| "events": { | |
| "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"}, | |
| "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available", | |
| "source": "manual_review"}, | |
| "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None, | |
| "reasons": ["contact_not_verified"]}, | |
| }, | |
| "measurements": [ | |
| {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 28, "unit": "deg", | |
| "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading", | |
| "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [], | |
| "benchmark": None}, | |
| {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm", | |
| "start_event_id": "stride_start", "end_event_id": "front_foot_down", | |
| "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None, | |
| "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None}, | |
| {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None, | |
| "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading", | |
| "status": "unavailable", "confidence": None, "uses_interpolated_input": False, | |
| "reasons": ["contact_not_verified"], "benchmark": None}, | |
| ], | |
| } | |
| VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 2000 | |
| JPEG_BYTES = b"\xff\xd8\xff\xe0" + b"\x00" * 500 + b"\xff\xd9" | |
| # ---------------------------------------------------------------- helpers | |
| def body_of(r: httpx.Response): | |
| try: | |
| return r.json() | |
| except Exception: | |
| return r.text | |
| def check(name: str, ok: bool, r: httpx.Response | None = None, detail: str = "") -> bool: | |
| req = "" | |
| if r is not None: | |
| q = r.request.url.query.decode() if r.request.url.query else "" | |
| if "X-Amz" in q: | |
| q = "<presigned>" | |
| req = f"{r.request.method} {r.request.url.path}{'?' + q if q else ''} -> {r.status_code}" | |
| if ok: | |
| results["pass"] += 1 | |
| print(f"PASS {name} [{req}]") | |
| else: | |
| results["fail"] += 1 | |
| body = json.dumps(body_of(r))[:1500] if r is not None else "" | |
| line = f"FAIL {name} [{req}] {detail} body={body}" | |
| failures.append(line) | |
| print(line) | |
| return ok | |
| def h(tok: str | None) -> dict: | |
| return {"Authorization": f"Bearer {tok}"} if tok else {} | |
| def call(method: str, path: str, tok: str | None = None, **kw) -> httpx.Response: | |
| r = client.request(method, path, headers={**h(tok), **kw.pop("headers", {})}, **kw) | |
| if r.status_code >= 500: | |
| check(f"no 5xx on {method} {path}", False, r) | |
| return r | |
| def find_keys(obj, keys: set[str], path="$") -> list[str]: | |
| hits = [] | |
| if isinstance(obj, dict): | |
| for k, v in obj.items(): | |
| if k in keys: | |
| hits.append(f"{path}.{k}") | |
| hits += find_keys(v, keys, f"{path}.{k}") | |
| elif isinstance(obj, list): | |
| for i, v in enumerate(obj): | |
| hits += find_keys(v, keys, f"{path}[{i}]") | |
| return hits | |
| CAMEL = re.compile(r"^[a-z]+[A-Z]") | |
| # Report payload carries free-form ids as values, not keys; keys of verdicts are metric ids (snake_case). | |
| def camel_keys(obj, path="$") -> list[str]: | |
| hits = [] | |
| if isinstance(obj, dict): | |
| for k, v in obj.items(): | |
| if isinstance(k, str) and CAMEL.match(k): | |
| hits.append(f"{path}.{k}") | |
| hits += camel_keys(v, f"{path}.{k}") | |
| elif isinstance(obj, list): | |
| for i, v in enumerate(obj): | |
| hits += camel_keys(v, f"{path}[{i}]") | |
| return hits | |
| def no_camel(name: str, r: httpx.Response): | |
| hits = camel_keys(body_of(r)) | |
| check(f"{name}: snake_case keys only", not hits, r, f"camelCase keys: {hits[:10]}") | |
| def register(role: str, name: str) -> dict: | |
| global _n | |
| _n += 1 | |
| email = f"qa-coach-{RUN_ID}-{_n}@example.com" | |
| r = call("POST", "/v1/auth/register", json={"email": email, "password": PASSWORD, "role": role}) | |
| if not check(f"register {role} {name}", r.status_code == 201, r): | |
| raise SystemExit("cannot register; aborting") | |
| data = r.json() | |
| acct = {"email": email, "token": data["tokens"]["access_token"], "id": data["user"]["id"], "name": name, | |
| "role": role} | |
| created_accounts.append(acct) | |
| return acct | |
| def set_profile(acct: dict, player: bool): | |
| profile = {"name": acct["name"]} | |
| if player: | |
| profile.update({"age": 15, "height_cm": 168, "weight_kg": 60, "bats": "R", "throws": "R", | |
| "level": "high_school"}) | |
| r = call("PATCH", "/v1/me", acct["token"], json={"focus": "h", "profile": profile}) | |
| check(f"PATCH /me profile {acct['name']}", r.status_code == 200, r) | |
| def upload(acct: dict, kind: str) -> str: | |
| data = VIDEO_BYTES if kind == "video" else JPEG_BYTES | |
| ctype = "video/mp4" if kind == "video" else "image/jpeg" | |
| body = {"kind": kind, "content_type": ctype, "size_bytes": len(data)} | |
| if kind == "video": | |
| body["duration_sec"] = 3.0 | |
| r = call("POST", "/v1/uploads", acct["token"], json=body) | |
| if not check(f"POST /uploads {kind} ({acct['name']})", r.status_code in (200, 201), r): | |
| raise RuntimeError("upload failed") | |
| out = r.json() | |
| out = out.get("upload", out) | |
| put = httpx.put(out["url"], content=data, headers=out.get("headers") or {"Content-Type": ctype}, timeout=60) | |
| check(f"PUT presigned {kind} ({acct['name']})", put.status_code in (200, 201, 204), put) | |
| return out["upload_id"] | |
| def make_session(acct: dict, *, is_self=True, analyse=True, tag="") -> dict: | |
| vid, thumb = upload(acct, "video"), upload(acct, "thumbnail") | |
| body = {"video_upload_id": vid, "thumbnail_upload_id": thumb, "mode": "h", "is_self": is_self, | |
| "athlete": None if is_self else {"name": "Cousin Ray", "age": 12, "height_cm": 150, "weight_kg": 45, | |
| "bats": "L", "throws": "L", "level": "youth"}, | |
| "duration_sec": 3.0, "fps": 30, | |
| "marks": {"contact_frame": 70, "contact_offset": 0, "contact_source": "manual", | |
| "stride_start_frame": 30, "stride_end_frame": 50, | |
| "pitcher_direction": {"from": [0.1, 0.5], "to": [0.9, 0.5]}}} | |
| r = call("POST", "/v1/sessions", acct["token"], json=body) | |
| if not check(f"POST /sessions {tag}", r.status_code == 201, r): | |
| raise RuntimeError("session create failed") | |
| s = r.json()["session"] | |
| check(f"new session {tag} is pending", s["status"] == "pending" and s["report"] is None, r) | |
| if analyse: | |
| p = copy.deepcopy(PAYLOAD) | |
| p["analysis_id"] = f"qa_{RUN_ID}_{tag}" | |
| p["swing_id"] = f"swing_{RUN_ID}_{tag}" | |
| # vary the value a bit so scores/deltas differ | |
| p["measurements"][0]["value"] = {"a": 28, "b": 45, "c": 10}.get(tag[-1:], 28) | |
| r = call("POST", f"/v1/sessions/{s['id']}/swing-report?queue=false", acct["token"], json=p) | |
| check(f"POST swing-report {tag}", r.status_code == 200, r) | |
| s["report"] = r.json() if r.status_code == 200 else None | |
| time.sleep(1.1) # distinct created_at for ordering checks | |
| return s | |
| # ---------------------------------------------------------------- the suite | |
| def run(): | |
| # 1. Setup ---------------------------------------------------------- | |
| coach_a = register("coach", "Coach Alpha") | |
| coach_b = register("coach", "Coach Bravo") | |
| p1 = register("player", "Pat One") | |
| p2 = register("player", "Quinn Two") | |
| p3 = register("player", "Riley Three") | |
| p4 = register("player", "Sam Four") # on A's team, never films | |
| for a in (coach_a, coach_b): | |
| set_profile(a, False) | |
| for p in (p1, p2, p3, p4): | |
| set_profile(p, True) | |
| r = call("POST", "/v1/teams", coach_a["token"], json={"name": "QA Alphas", "coach_name": "Coach Alpha", | |
| "coaching": "h"}) | |
| check("coach A creates team", r.status_code == 201, r) | |
| code_a = r.json()["team"]["code"] | |
| r = call("POST", "/v1/teams", coach_b["token"], json={"name": "QA Bravos", "coach_name": "Coach Bravo", | |
| "coaching": "both"}) | |
| check("coach B creates team", r.status_code == 201, r) | |
| code_b = r.json()["team"]["code"] | |
| for p, code in ((p1, code_a), (p2, code_a), (p4, code_a), (p3, code_b)): | |
| r = call("POST", f"/v1/teams/{code.lower()}/join", p["token"]) | |
| check(f"{p['name']} joins team (lowercased code)", r.status_code == 200, r) | |
| # Sessions. Free plan = 20 analyses/week/owner. | |
| p1_a = make_session(p1, tag="p1a") # oldest open | |
| p2_a = make_session(p2, tag="p2a") | |
| p1_b = make_session(p1, tag="p1b") # P1 newest self | |
| p1_pending = make_session(p1, analyse=False, tag="p1pend") # pending ones don't count toward the plan | |
| p1_other = make_session(p1, is_self=False, tag="p1oc") # someone else (3rd analysis for P1) | |
| p2_pending = make_session(p2, analyse=False, tag="p2pend") | |
| p3_a = make_session(p3, tag="p3a") | |
| # D4 shape for comparison | |
| r = call("GET", "/v1/sessions", p1["token"]) | |
| check("P1 GET /sessions 200", r.status_code == 200, r) | |
| d4_items = r.json()["items"] | |
| d4_keys = set(d4_items[0].keys()) if d4_items else set() | |
| no_camel("D4 list", r) | |
| # report metric ids & drill | |
| report = p1_a["report"] or {} | |
| metric_ids = [m["metric_id"] for m in report.get("measurements", [])] | |
| check("report has metric_ids", len(metric_ids) == 3, r, f"metric_ids={metric_ids}") | |
| drill_id = ((report.get("focus_area") or {}).get("drill") or {}).get("drill_id") | |
| r = call("GET", "/v1/catalog/metrics?mode=h", p1["token"]) | |
| cat = body_of(r) | |
| cat_drills = sorted(set(re.findall(r'"(?:drill_id|id)":\s*"(hit_\d+)"', json.dumps(cat)))) | |
| if not drill_id: | |
| drill_id = cat_drills[0] if cat_drills else "hit_13" | |
| print(f"INFO metric_ids={metric_ids} drill_id={drill_id} focus={report.get('focus_area', {}).get('display_name')}") | |
| # 2. Roster (F1) ---------------------------------------------------- | |
| r = call("GET", "/v1/coach/roster", coach_a["token"]) | |
| check("F1 roster 200", r.status_code == 200, r) | |
| roster = {i["id"]: i for i in r.json().get("items", [])} | |
| check("F1 lists P1, P2, P4 and not P3", {p1["id"], p2["id"], p4["id"]} == set(roster), r, | |
| f"ids={list(roster)}") | |
| no_camel("F1 roster", r) | |
| hits = find_keys(r.json(), BODY_KEYS) | |
| check("F1 has no body data (age/height/weight)", not hits, r, f"found {hits}") | |
| raw = r.text | |
| check("F1 raw JSON has no 168/60 body values as keys", '"height' not in raw and '"weight' not in raw, r) | |
| i1 = roster.get(p1["id"], {}) | |
| check("F1 P1 pending_count == 2", i1.get("pending_count") == 2, r, f"got {i1.get('pending_count')}") | |
| last_h = (i1.get("last") or {}).get("h") or {} | |
| check("F1 P1 last.h is newest self session", last_h.get("session_id") == p1_b["id"], r, f"last.h={last_h}") | |
| exp_delta = (p1_b["report"] or {}).get("overall_score", 0) - (p1_a["report"] or {}).get("overall_score", 0) | |
| check("F1 P1 last.h delta = newest - previous", last_h.get("delta") == exp_delta, r, | |
| f"expected {exp_delta} got {last_h.get('delta')}") | |
| check("F1 P1 last.h score + focus_name", last_h.get("overall_score") == p1_b["report"]["overall_score"] | |
| and last_h.get("focus_name") == (p1_b["report"].get("focus_area") or {}).get("display_name"), r) | |
| check("F1 P1 recent.h newest first", | |
| (i1.get("recent") or {}).get("h") == [p1_b["report"]["overall_score"], p1_a["report"]["overall_score"]], | |
| r, f"recent={i1.get('recent')}") | |
| i2 = roster.get(p2["id"], {}) | |
| check("F1 P2 pending_count == 1 (pending session not counted)", i2.get("pending_count") == 1, r) | |
| i4 = roster.get(p4["id"], {}) | |
| check("F1 P4 (not filmed) last.h null", (i4.get("last") or {}).get("h") is None and i4.get("pending_count") == 0, | |
| r, f"P4={i4}") | |
| r = call("GET", "/v1/coach/roster", coach_b["token"]) | |
| check("F1 coach B sees only P3", [i["id"] for i in r.json().get("items", [])] == [p3["id"]], r) | |
| # 3. Queue (F3) ----------------------------------------------------- | |
| r = call("GET", "/v1/coach/queue", coach_a["token"]) | |
| check("F3 queue 200", r.status_code == 200, r) | |
| q = r.json() | |
| no_camel("F3 queue", r) | |
| hits = find_keys(q, BODY_KEYS) | |
| check("F3 has no body data", not hits, r, f"found {hits}") | |
| open_ids = [i["id"] for i in q.get("open", [])] | |
| check("F3 open = [p1a, p2a, p1b] oldest first", open_ids == [p1_a["id"], p2_a["id"], p1_b["id"]], r, | |
| f"open={open_ids}") | |
| check("F3 someone-else session absent", p1_other["id"] not in open_ids, r) | |
| check("F3 pending sessions absent", p1_pending["id"] not in open_ids and p2_pending["id"] not in open_ids, r) | |
| check("F3 P3 session absent", p3_a["id"] not in open_ids, r) | |
| check("F3 owner_name set", all(i.get("owner_name") == {p1["id"]: p1["name"], p2["id"]: p2["name"]}.get( | |
| i["owner_id"]) for i in q.get("open", [])), r) | |
| check("F3 reviewed_today empty", q.get("reviewed_today") == [], r) | |
| if q.get("open"): | |
| qkeys = set(q["open"][0].keys()) | |
| check("F3 item keys == D4 keys + owner_name", qkeys == d4_keys | {"owner_name"}, r, | |
| f"diff={qkeys ^ (d4_keys | {'owner_name'})}") | |
| check("F3 item has focus + thumbnail_url", q["open"][0].get("focus") is not None | |
| and q["open"][0].get("thumbnail_url"), r) | |
| # 4. Coach access --------------------------------------------------- | |
| r = call("GET", f"/v1/sessions/{p1_a['id']}", coach_a["token"]) | |
| check("D3 coach A reads P1 self session", r.status_code == 200, r) | |
| if r.status_code == 200: | |
| s = r.json()["session"] | |
| check("D3 coach view has report", bool(s.get("report")) and s["status"] == "done", r) | |
| no_camel("D3 (coach)", r) | |
| hits = find_keys(s, BODY_KEYS) | |
| check("D3 coach response has no body data (spec 7.7/11: no body data in coach responses)", not hits, r, | |
| f"found {hits} athlete={s.get('athlete')}") | |
| media = s.get("media") or {} | |
| v = httpx.get(media.get("video_url", "http://invalid"), timeout=60) | |
| check("D3 video_url downloads the uploaded bytes", v.status_code == 200 and v.content == VIDEO_BYTES, v) | |
| t = httpx.get(media.get("thumbnail_url") or "http://invalid", timeout=60) | |
| check("D3 thumbnail_url downloads the uploaded bytes", t.status_code == 200 and t.content == JPEG_BYTES, t) | |
| r = call("GET", f"/v1/sessions/{p1_other['id']}", coach_a["token"]) | |
| check("D3 coach A cannot read P1's someone-else session (403)", r.status_code == 403, r) | |
| r = call("GET", f"/v1/sessions/{p1_pending['id']}", coach_a["token"]) | |
| print(f"INFO D3 coach A on P1 pending self session -> {r.status_code}") | |
| r = call("GET", f"/v1/sessions/{p3_a['id']}", coach_a["token"]) | |
| check("D3 coach A cannot read P3 session (403)", r.status_code == 403, r) | |
| r = call("GET", f"/v1/sessions/{p1_a['id']}", p2["token"]) | |
| check("D3 teammate P2 cannot read P1 session (403)", r.status_code == 403, r) | |
| r = call("GET", f"/v1/sessions/{p1_a['id']}", coach_b["token"]) | |
| check("D3 coach B cannot read P1 session (403)", r.status_code == 403, r) | |
| r = call("GET", f"/v1/sessions/{uuid.uuid4()}", coach_a["token"]) | |
| check("D3 unknown id -> 404", r.status_code == 404, r) | |
| r = call("GET", f"/v1/coach/players/{p1['id']}/sessions", coach_a["token"]) | |
| check("F2 P1 sessions 200", r.status_code == 200, r) | |
| f2 = r.json() | |
| f2_ids = [i["id"] for i in f2.get("items", [])] | |
| check("F2 lists only analysed self sessions newest first", f2_ids == [p1_b["id"], p1_a["id"]], r, | |
| f"ids={f2_ids}") | |
| no_camel("F2", r) | |
| check("F2 has no body data", not find_keys(f2, BODY_KEYS), r) | |
| if f2.get("items"): | |
| check("F2 item keys == D4 keys", set(f2["items"][0]) == d4_keys, r, | |
| f"diff={set(f2['items'][0]) ^ d4_keys}") | |
| r = call("GET", f"/v1/coach/players/{p1['id']}/sessions?limit=1", coach_a["token"]) | |
| pg = r.json() | |
| check("F2 limit=1 returns 1 item + next_cursor", len(pg.get("items", [])) == 1 and pg.get("next_cursor"), r) | |
| if pg.get("next_cursor"): | |
| r2 = call("GET", f"/v1/coach/players/{p1['id']}/sessions", coach_a["token"], | |
| params={"limit": 1, "cursor": pg["next_cursor"]}) | |
| pg2 = r2.json() | |
| check("F2 cursor page 2 = older session, then end", | |
| [i["id"] for i in pg2.get("items", [])] == [p1_a["id"]] and pg2.get("next_cursor") is None, r2) | |
| r = call("GET", f"/v1/coach/players/{p1['id']}/sessions?mode=p", coach_a["token"]) | |
| check("F2 mode=p -> empty", r.status_code == 200 and r.json()["items"] == [], r) | |
| r = call("GET", f"/v1/coach/players/{p3['id']}/sessions", coach_a["token"]) | |
| check("F2 P3 via coach A -> 404 PLAYER_NOT_ON_TEAM", r.status_code == 404 | |
| and (body_of(r).get("error") or {}).get("code") == "PLAYER_NOT_ON_TEAM", r) | |
| r = call("GET", f"/v1/coach/players/{coach_a['id']}/sessions", coach_a["token"]) | |
| check("F2 coach's own id -> 404", r.status_code == 404, r) | |
| # 8. Push device (before review) ----------------------------------- | |
| token = f"qa-fcm-{RUN_ID}-" + "x" * 40 | |
| r = call("POST", "/v1/devices", p1["token"], json={"platform": "ios", "push_token": token}) | |
| check("B3 P1 registers device", r.status_code == 201, r) | |
| no_camel("B3", r) | |
| r = call("POST", "/v1/devices", p1["token"], json={"platform": "ios", "push_token": token}) | |
| check("B3 re-register same token -> 200", r.status_code == 200, r) | |
| # 5. Review (F4) ---------------------------------------------------- | |
| verdicts = {metric_ids[0]: "agree", metric_ids[1]: "change"} if len(metric_ids) >= 2 else {} | |
| rev_body = {"cue": "Stay closed a beat longer.", "drill_id": drill_id, "verdicts": verdicts} | |
| r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_a["token"], json=rev_body) | |
| check("F4 first review -> 201 (with device registered, FCM unconfigured)", r.status_code == 201, r) | |
| no_camel("F4", r) | |
| rv = (body_of(r) or {}).get("review", {}) if r.status_code in (200, 201) else {} | |
| check("F4 review shape", set(rv) == {"coach_id", "coach_name", "cue", "drill_id", "verdicts", "at"} | |
| and rv.get("coach_id") == coach_a["id"] and rv.get("coach_name") == coach_a["name"] | |
| and rv.get("verdicts") == verdicts and rv.get("drill_id") == drill_id, r) | |
| first_at = rv.get("at") | |
| time.sleep(1.1) | |
| rev2 = {"cue": "Load into the back hip.", "drill_id": drill_id, "verdicts": {metric_ids[0]: "later"}} | |
| r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_a["token"], json=rev2) | |
| check("F4 resend -> 200 overwrite", r.status_code == 200 and r.json()["review"]["cue"] == rev2["cue"] | |
| and r.json()["review"]["verdicts"] == rev2["verdicts"], r) | |
| check("F4 overwrite bumps at", r.status_code == 200 and r.json()["review"]["at"] != first_at, r) | |
| def expect_400(name, body, field_hint=None): | |
| rr = call("POST", f"/v1/sessions/{p1_b['id']}/review", coach_a["token"], json=body) | |
| err = (body_of(rr) or {}).get("error", {}) if isinstance(body_of(rr), dict) else {} | |
| ok = rr.status_code == 400 and err.get("code") == "VALIDATION" | |
| if ok and field_hint: | |
| ok = any(field_hint in k for k in (err.get("fields") or {})) | |
| check(name, ok, rr) | |
| expect_400("F4 invalid drill id -> 400 VALIDATION", {**rev_body, "drill_id": "hit_9999"}, "drill_id") | |
| expect_400("F4 pitching drill on hitting session -> 400", {**rev_body, "drill_id": "pit_01"}, "drill_id") | |
| expect_400("F4 verdict key not in report -> 400", {**rev_body, "verdicts": {"pelvis": "agree"}}, "verdicts") | |
| expect_400("F4 verdict value invalid -> 400", {**rev_body, "verdicts": {metric_ids[0]: "maybe"}}, "verdicts") | |
| expect_400("F4 cue too long -> 400", {**rev_body, "cue": "x" * 201}, "cue") | |
| expect_400("F4 empty cue -> 400", {**rev_body, "cue": ""}, "cue") | |
| expect_400("F4 unknown field -> 400", {**rev_body, "extra": 1}) | |
| expect_400("F4 missing drill_id -> 400", {"cue": "hi", "verdicts": {}}, "drill_id") | |
| r = call("POST", f"/v1/sessions/{p1_b['id']}/review", coach_a["token"], | |
| json={**rev_body, "cue": "x" * 200, "verdicts": {}}) | |
| check("F4 cue of exactly 200 chars + empty verdicts accepted (201)", r.status_code == 201, r) | |
| # undo: p1_b is now reviewed. That's fine; keep tracking it. | |
| r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_b["token"], json=rev_body) | |
| check("F4 coach B reviewing P1 session -> 403", r.status_code == 403, r) | |
| r = call("POST", f"/v1/sessions/{p1_a['id']}/review", p1["token"], json=rev_body) | |
| check("F4 player (owner) calling review -> 403", r.status_code == 403, r) | |
| r = call("POST", f"/v1/sessions/{p1_pending['id']}/review", coach_a["token"], json=rev_body) | |
| check("F4 pending session -> 4xx", 400 <= r.status_code < 500, r) | |
| print(f"INFO F4 on pending session -> {r.status_code} {r.text[:200]}") | |
| r = call("POST", f"/v1/sessions/{p1_other['id']}/review", coach_a["token"], json=rev_body) | |
| check("F4 someone-else session -> 403", r.status_code == 403, r) | |
| r = call("POST", f"/v1/sessions/{uuid.uuid4()}/review", coach_a["token"], json=rev_body) | |
| check("F4 unknown session -> 404", r.status_code == 404, r) | |
| r = call("POST", f"/v1/sessions/{p1_a['id']}/review", None, json=rev_body) | |
| check("F4 no token -> 401", r.status_code == 401, r) | |
| # 6. After review --------------------------------------------------- | |
| r = call("GET", "/v1/coach/queue", coach_a["token"]) | |
| q = r.json() | |
| open_ids = [i["id"] for i in q.get("open", [])] | |
| rt_ids = [i["id"] for i in q.get("reviewed_today", [])] | |
| check("F3 reviewed sessions left open", open_ids == [p2_a["id"]], r, f"open={open_ids}") | |
| check("F3 reviewed_today has p1a & p1b", set(rt_ids) == {p1_a["id"], p1_b["id"]}, r, f"rt={rt_ids}") | |
| rt = {i["id"]: i for i in q.get("reviewed_today", [])} | |
| check("F3 reviewed_today item carries review summary", | |
| (rt.get(p1_a["id"], {}).get("review") or {}).get("coach_name") == coach_a["name"], r) | |
| r = call("GET", f"/v1/sessions/{p1_a['id']}", p1["token"]) | |
| rv = (r.json()["session"].get("review") or {}) if r.status_code == 200 else {} | |
| check("D3 player sees review (latest overwrite)", rv.get("cue") == rev2["cue"] | |
| and rv.get("coach_name") == coach_a["name"] and rv.get("drill_id") == drill_id, r) | |
| r = call("GET", "/v1/sessions", p1["token"]) | |
| items = {i["id"]: i for i in r.json()["items"]} | |
| rs = items.get(p1_a["id"], {}).get("review") or {} | |
| check("D4 summary shows review {coach_name, at}", set(rs) == {"coach_name", "at"} | |
| and rs.get("coach_name") == coach_a["name"], r, f"review={rs}") | |
| check("D4 unreviewed summary review null", items.get(p1_other["id"], {}).get("review") is None, r) | |
| r = call("GET", "/v1/coach/roster", coach_a["token"]) | |
| roster = {i["id"]: i for i in r.json()["items"]} | |
| check("F1 P1 pending_count dropped to 0", roster.get(p1["id"], {}).get("pending_count") == 0, r) | |
| check("F1 P2 pending_count still 1", roster.get(p2["id"], {}).get("pending_count") == 1, r) | |
| r = call("GET", "/v1/coach/queue", coach_a["token"], params={"since": "2999-01-01T00:00:00Z"}) | |
| check("F3 since in future -> reviewed_today empty", r.status_code == 200 and r.json()["reviewed_today"] == [], r) | |
| # 7. Leaving -------------------------------------------------------- | |
| r = call("DELETE", "/v1/me/team", p2["token"]) | |
| check("C4 P2 leaves team -> 204", r.status_code == 204, r) | |
| r = call("GET", "/v1/coach/roster", coach_a["token"]) | |
| check("F1 P2 gone from roster", p2["id"] not in [i["id"] for i in r.json()["items"]], r) | |
| r = call("GET", "/v1/coach/queue", coach_a["token"]) | |
| queue_items = r.json()["open"] + r.json()["reviewed_today"] | |
| check("F3 P2 gone from queue", all(i["owner_id"] != p2["id"] for i in queue_items), r) | |
| r = call("GET", f"/v1/sessions/{p2_a['id']}", coach_a["token"]) | |
| check("D3 coach A loses access to P2 session (403)", r.status_code == 403, r) | |
| r = call("POST", f"/v1/sessions/{p2_a['id']}/review", coach_a["token"], json=rev_body) | |
| check("F4 coach A cannot review ex-member P2 session (403)", r.status_code == 403, r) | |
| r = call("GET", f"/v1/coach/players/{p2['id']}/sessions", coach_a["token"]) | |
| check("F2 ex-member -> 404 PLAYER_NOT_ON_TEAM", r.status_code == 404, r) | |
| r = call("GET", "/v1/me", p2["token"]) | |
| check("B1 P2 team null after leaving", r.status_code == 200 and r.json().get("team") is None, r) | |
| r = call("POST", f"/v1/teams/{code_a}/join", p2["token"]) | |
| check("C3 P2 rejoins", r.status_code == 200, r) | |
| r = call("GET", "/v1/coach/queue", coach_a["token"]) | |
| check("F3 P2 session back in open after rejoin", p2_a["id"] in [i["id"] for i in r.json()["open"]], r) | |
| # Player switching teams: P1's reviewed session must not be visible to coach B. | |
| # (Not part of required list; covered implicitly by D3 coach B 403.) | |
| # 9. Role/auth gates ----------------------------------------------- | |
| for path in ("/v1/coach/roster", "/v1/coach/queue", f"/v1/coach/players/{p1['id']}/sessions"): | |
| r = call("GET", path, p1["token"]) | |
| check(f"{path} as player -> 403", r.status_code == 403, r) | |
| r = call("GET", path) | |
| check(f"{path} without token -> 401", r.status_code == 401, r) | |
| r = call("GET", path, "not-a-jwt") | |
| check(f"{path} bad token -> 401", r.status_code == 401, r) | |
| r = call("POST", "/v1/devices", None, json={"platform": "ios", "push_token": "x"}) | |
| check("B3 without token -> 401", r.status_code == 401, r) | |
| r = call("GET", "/v1/coach/players/not-a-uuid/sessions", coach_a["token"]) | |
| check("F2 bad uuid -> 4xx (not 500)", 400 <= r.status_code < 500, r) | |
| r = call("GET", "/v1/coach/queue", coach_a["token"], params={"since": "garbage"}) | |
| check("F3 bad since -> 4xx", 400 <= r.status_code < 500, r) | |
| # 8b. device token takeover (informational) | |
| r = call("POST", "/v1/devices", p2["token"], json={"platform": "android", "push_token": token}) | |
| print(f"INFO B3 P2 registering P1's push token -> {r.status_code} (token reassigned silently if 200/201)") | |
| r = call("DELETE", f"/v1/devices/{token}", p2["token"]) | |
| check("B4 delete device -> 204", r.status_code == 204, r) | |
| # 10. Error envelope shape | |
| r = call("GET", "/v1/coach/roster", p1["token"]) | |
| e = body_of(r) | |
| check("error envelope {error:{code,message}}", isinstance(e, dict) and "error" in e | |
| and {"code", "message"} <= set(e["error"]), r) | |
| def cleanup(): | |
| print("---- cleanup") | |
| for a in created_accounts: | |
| r = client.delete("/v1/me", headers=h(a["token"])) | |
| ok = r.status_code == 204 | |
| if not ok: # token may have expired; log in again | |
| lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD}) | |
| if lr.status_code == 200: | |
| r = client.delete("/v1/me", headers=h(lr.json()["tokens"]["access_token"])) | |
| ok = r.status_code == 204 | |
| check(f"DELETE /me {a['email']}", ok, r) | |
| lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD}) | |
| check(f"deleted account cannot log in {a['email']}", lr.status_code == 401, lr) | |
| if __name__ == "__main__": | |
| print(f"BASE_URL={BASE_URL} RUN_ID={RUN_ID}") | |
| try: | |
| run() | |
| except Exception as exc: # noqa: BLE001 | |
| import traceback | |
| traceback.print_exc() | |
| results["fail"] += 1 | |
| failures.append(f"FAIL suite aborted: {exc!r}") | |
| finally: | |
| cleanup() | |
| print(f"==== {results['pass']} passed, {results['fail']} failed") | |
| for f in failures: | |
| print(f) | |
| sys.exit(1 if results["fail"] else 0) | |