github-actions[bot] commited on
Commit
4598c11
·
1 Parent(s): 2756f0f

Automated Deploy: 1c15f6a6a518178434481f94bd8b693302081f4f

Browse files
AI-coach-agent/src/ai_coach/swing_report/text.py CHANGED
@@ -169,6 +169,12 @@ class TextResult:
169
  rejected: dict[str, list[str]] = field(default_factory=dict)
170
 
171
 
 
 
 
 
 
 
172
  def _parse(raw: str, rules: dict[str, str | None], facts: dict) -> dict[str, str]:
173
  """Model JSON -> {field key: text}. Raises ValueError when the shape does not match the request."""
174
  data = json.loads(raw)
@@ -181,7 +187,7 @@ def _parse(raw: str, rules: dict[str, str | None], facts: dict) -> dict[str, str
181
  out["coach_message"] = data["coach_message"]
182
  for item in data.get("group_summaries") or []:
183
  if isinstance(item, dict) and isinstance(item.get("summary"), str):
184
- out[f"group:{item.get('group')}"] = item["summary"]
185
  for item in data.get("measurements") or []:
186
  if not isinstance(item, dict):
187
  continue
@@ -201,6 +207,9 @@ def _merge(candidate: dict[str, str], rules: dict[str, str | None]) -> tuple[dic
201
  used, rejected = 0, {}
202
  for key, rule_text in rules.items():
203
  text = candidate.get(key)
 
 
 
204
  problems = check_text(text, _kind(key)) if text is not None else ["missing"]
205
  if problems:
206
  texts[key] = rule_text
 
169
  rejected: dict[str, list[str]] = field(default_factory=dict)
170
 
171
 
172
+ def _group_id(name: object) -> str:
173
+ """Models often answer with the display name ("Stride", "Balance and Load") instead of the id."""
174
+ words = re.sub(r"[^a-z]+", " ", str(name or "").lower()).split()
175
+ return "_".join(w for w in words if w != "and")
176
+
177
+
178
  def _parse(raw: str, rules: dict[str, str | None], facts: dict) -> dict[str, str]:
179
  """Model JSON -> {field key: text}. Raises ValueError when the shape does not match the request."""
180
  data = json.loads(raw)
 
187
  out["coach_message"] = data["coach_message"]
188
  for item in data.get("group_summaries") or []:
189
  if isinstance(item, dict) and isinstance(item.get("summary"), str):
190
+ out[f"group:{_group_id(item.get('group'))}"] = item["summary"]
191
  for item in data.get("measurements") or []:
192
  if not isinstance(item, dict):
193
  continue
 
207
  used, rejected = 0, {}
208
  for key, rule_text in rules.items():
209
  text = candidate.get(key)
210
+ if rule_text is None and not (text or "").strip():
211
+ texts[key] = None # nothing is wanted here (e.g. no tip for an on-target measurement)
212
+ continue
213
  problems = check_text(text, _kind(key)) if text is not None else ["missing"]
214
  if problems:
215
  texts[key] = rule_text
AI-coach-agent/tests/test_swing_report_report.py CHANGED
@@ -303,6 +303,15 @@ def test_llm_text_used_when_it_passes(tmp_path):
303
  assert not re.search(r"\d|-?\d+\.\d", calls[0].split("The facts:")[1]) # the model never sees values
304
 
305
 
 
 
 
 
 
 
 
 
 
306
  def test_llm_field_with_digit_falls_back_to_rules(tmp_path):
307
  bad = json.loads(json.dumps(GOOD))
308
  bad["coach_message"] = "Your shoulders open about twenty degrees early, at 3 degrees."
 
303
  assert not re.search(r"\d|-?\d+\.\d", calls[0].split("The facts:")[1]) # the model never sees values
304
 
305
 
306
+ def test_llm_group_display_names_are_accepted(tmp_path):
307
+ named = json.loads(json.dumps(GOOD))
308
+ for item in named["group_summaries"]:
309
+ item["group"] = {"stride": "Stride", "contact_follow_through": "Contact and Follow-Through"}.get(
310
+ item["group"], item["group"])
311
+ r = build(settings=llm_settings(tmp_path), generator=fake_generator(named))
312
+ assert r["meta"]["text_source"] == "llm" and r["meta"]["fallback_reason"] is None
313
+
314
+
315
  def test_llm_field_with_digit_falls_back_to_rules(tmp_path):
316
  bad = json.loads(json.dumps(GOOD))
317
  bad["coach_message"] = "Your shoulders open about twenty degrees early, at 3 degrees."
backend/Dockerfile CHANGED
@@ -18,4 +18,7 @@ USER app
18
  EXPOSE 8000
19
 
20
  # Migrations run as a separate release step: docker run ... alembic upgrade head
21
- CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"]
 
 
 
 
18
  EXPOSE 8000
19
 
20
  # Migrations run as a separate release step: docker run ... alembic upgrade head
21
+ # Behind a proxy, set FORWARDED_ALLOW_IPS to the proxy's address only (never "*"), or clients can spoof their IP
22
+ # and get around the per-IP login limits.
23
+ ENV FORWARDED_ALLOW_IPS=127.0.0.1
24
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"]
backend/app/core/errors.py CHANGED
@@ -9,6 +9,7 @@ import logging
9
  from fastapi import FastAPI, Request
10
  from fastapi.exceptions import RequestValidationError
11
  from fastapi.responses import JSONResponse
 
12
 
13
  log = logging.getLogger(__name__)
14
 
@@ -85,6 +86,13 @@ def register_error_handlers(app: FastAPI) -> None:
85
  async def _app_error(_: Request, exc: AppError) -> JSONResponse:
86
  return JSONResponse(_body(exc.code, exc.message, exc.fields), status_code=exc.status_code)
87
 
 
 
 
 
 
 
 
88
  @app.exception_handler(RequestValidationError)
89
  async def _validation_error(_: Request, exc: RequestValidationError) -> JSONResponse:
90
  fields: dict[str, str] = {}
 
9
  from fastapi import FastAPI, Request
10
  from fastapi.exceptions import RequestValidationError
11
  from fastapi.responses import JSONResponse
12
+ from starlette.exceptions import HTTPException as StarletteHTTPException
13
 
14
  log = logging.getLogger(__name__)
15
 
 
86
  async def _app_error(_: Request, exc: AppError) -> JSONResponse:
87
  return JSONResponse(_body(exc.code, exc.message, exc.fields), status_code=exc.status_code)
88
 
89
+ @app.exception_handler(StarletteHTTPException)
90
+ async def _http_error(_: Request, exc: StarletteHTTPException) -> JSONResponse:
91
+ """Routing errors (unknown path, wrong method) use the same envelope as everything else."""
92
+ codes = {404: ("NOT_FOUND", NotFound.message), 405: ("METHOD_NOT_ALLOWED", "This method is not allowed here.")}
93
+ code, message = codes.get(exc.status_code, ("HTTP_ERROR", str(exc.detail)))
94
+ return JSONResponse(_body(code, message), status_code=exc.status_code, headers=getattr(exc, "headers", None))
95
+
96
  @app.exception_handler(RequestValidationError)
97
  async def _validation_error(_: Request, exc: RequestValidationError) -> JSONResponse:
98
  fields: dict[str, str] = {}
backend/app/core/rate_limit.py CHANGED
@@ -1,6 +1,6 @@
1
  """In-memory sliding-window rate limiters (per process; enough for a single API instance).
2
 
3
- Keys look like "login:email:a@b.com", "login:ip:1.2.3.4" or "team_lookup:<account id>".
4
  Every limiter registers itself so tests can call reset_all() between tests.
5
  """
6
 
 
1
  """In-memory sliding-window rate limiters (per process; enough for a single API instance).
2
 
3
+ Keys look like "login:email_ip:a@b.com:1.2.3.4", "login:ip:1.2.3.4" or "team_lookup:<account id>".
4
  Every limiter registers itself so tests can call reset_all() between tests.
5
  """
6
 
backend/app/integrations/storage.py CHANGED
@@ -49,6 +49,11 @@ class StorageClient:
49
  raise
50
  return ObjectInfo(size_bytes=int(meta["ContentLength"]), content_type=meta.get("ContentType", ""))
51
 
 
 
 
 
 
52
  async def delete_many(self, keys: list[str]) -> None:
53
  for start in range(0, len(keys), 1000):
54
  batch = [{"Key": k} for k in keys[start:start + 1000]]
 
49
  raise
50
  return ObjectInfo(size_bytes=int(meta["ContentLength"]), content_type=meta.get("ContentType", ""))
51
 
52
+ async def read_prefix(self, key: str, length: int) -> bytes:
53
+ response = await asyncio.to_thread(
54
+ self._s3.get_object, Bucket=self.bucket, Key=key, Range=f"bytes=0-{length - 1}")
55
+ return await asyncio.to_thread(response["Body"].read)
56
+
57
  async def delete_many(self, keys: list[str]) -> None:
58
  for start in range(0, len(keys), 1000):
59
  batch = [{"Key": k} for k in keys[start:start + 1000]]
backend/app/modules/auth/service.py CHANGED
@@ -66,9 +66,10 @@ class AuthService:
66
  return await self._auth_body(account)
67
 
68
  async def login(self, email: str, password: str, client_ip: str) -> AuthOut:
69
- """Only failed attempts count toward the per-email and per-IP limits."""
 
70
  email = email.strip().lower()
71
- keys = (f"login:email:{email}", f"login:ip:{client_ip}")
72
  self.limiter.check(*keys)
73
  account = await self.accounts.by_email(email)
74
  valid = verify_password(password, account.password_hash if account else _dummy_hash())
 
66
  return await self._auth_body(account)
67
 
68
  async def login(self, email: str, password: str, client_ip: str) -> AuthOut:
69
+ """Only failed attempts count. Limits are per (email, IP) and per IP, never per email alone,
70
+ so failing logins from elsewhere cannot lock the real user out of their account."""
71
  email = email.strip().lower()
72
+ keys = (f"login:email_ip:{email}:{client_ip}", f"login:ip:{client_ip}")
73
  self.limiter.check(*keys)
74
  account = await self.accounts.by_email(email)
75
  valid = verify_password(password, account.password_hash if account else _dummy_hash())
backend/app/modules/sessions/repository.py CHANGED
@@ -38,9 +38,14 @@ class SessionRepository(BaseRepository[SwingSession]):
38
  .limit(1))
39
 
40
  async def ordinal(self, s: SwingSession) -> int:
41
- """1-based position among the owner's sessions for the same mode and athlete ("Swing 4")."""
42
- return await self.session.scalar(
43
- select(func.count()).where(*self._same_athlete(s), SwingSession.created_at <= s.created_at)) or 0
 
 
 
 
 
44
 
45
  async def review_with_coach_name(self, session_id: UUID) -> tuple[Review, str] | None:
46
  row = (await self.session.execute(
 
38
  .limit(1))
39
 
40
  async def ordinal(self, s: SwingSession) -> int:
41
+ """1-based position among the owner's analysed sessions for the same mode and athlete ("Swing 4").
42
+
43
+ Pending reps are not counted (they may be abandoned and cleaned up); a pending rep is numbered next.
44
+ """
45
+ analysed_before = await self.session.scalar(select(func.count()).where(
46
+ *self._same_athlete(s), SwingSession.analyzed_at.is_not(None), SwingSession.created_at <= s.created_at,
47
+ SwingSession.id != s.id)) or 0
48
+ return analysed_before + 1
49
 
50
  async def review_with_coach_name(self, session_id: UUID) -> tuple[Review, str] | None:
51
  row = (await self.session.execute(
backend/app/modules/sessions/service.py CHANGED
@@ -1,5 +1,6 @@
1
  """Sessions (D2 to D5): create with mark validation, plan and media checks; read with access rules; list; delete."""
2
 
 
3
  import math
4
  from datetime import UTC, datetime, timedelta
5
  from uuid import UUID
@@ -59,6 +60,26 @@ def profile_snapshot(account: Account) -> dict:
59
  "level": account.level}
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  class SessionService:
63
  def __init__(self, db: AsyncSession, storage: StorageClient):
64
  self.db = db
@@ -104,7 +125,8 @@ class SessionService:
104
  raise Unprocessable("The upload has not finished. Please try again.", code="UPLOAD_MISSING")
105
  settings = get_settings()
106
  limit = settings.max_video_bytes if upload.kind == "video" else settings.max_thumbnail_bytes
107
- if info.size_bytes > limit or info.content_type != upload.content_type:
 
108
  await self.storage.delete_many([upload.object_key])
109
  raise Unprocessable("The uploaded file is not valid. Please record again.", code="UPLOAD_INVALID")
110
  if info.size_bytes != upload.size_bytes:
@@ -115,15 +137,16 @@ class SessionService:
115
  session = await self.sessions.get_live(session_id)
116
  if session is None:
117
  raise NotFound()
118
- if session.owner_id != viewer.id:
119
- # A coach sees their team's players' own reps; private_videos does not block the coach.
120
- allowed = (session.is_self and viewer.role == "coach"
 
121
  and await self.sessions.is_team_coach(viewer.id, session.owner_id))
122
  if not allowed:
123
  raise Forbidden()
124
- return await self._out(session)
125
 
126
- async def _out(self, s: SwingSession) -> SessionOut:
127
  keys = await self.uploads.object_keys(s.video_upload_id, s.thumbnail_upload_id)
128
  review_row = await self.sessions.review_with_coach_name(s.id)
129
  review = None
@@ -135,7 +158,8 @@ class SessionService:
135
  thumb_key = keys.get(s.thumbnail_upload_id) if s.thumbnail_upload_id else None
136
  return SessionOut(
137
  id=s.id, owner_id=s.owner_id, is_self=s.is_self, mode=s.mode, status=s.status,
138
- created_at=s.created_at, analyzed_at=s.analyzed_at, athlete=s.athlete,
 
139
  duration_sec=float(s.duration_sec), fps=s.fps, marks=s.marks, report=s.report, review=review,
140
  media=MediaOut(
141
  video_url=self.storage.presign_get(keys[s.video_upload_id]),
@@ -168,3 +192,9 @@ class SessionService:
168
  if session.owner_id != owner.id:
169
  raise Forbidden()
170
  await self.sessions.update(session, deleted_at=datetime.now(UTC))
 
 
 
 
 
 
 
1
  """Sessions (D2 to D5): create with mark validation, plan and media checks; read with access rules; list; delete."""
2
 
3
+ import logging
4
  import math
5
  from datetime import UTC, datetime, timedelta
6
  from uuid import UUID
 
60
  "level": account.level}
61
 
62
 
63
+
64
+ log = logging.getLogger(__name__)
65
+
66
+ BODY_DATA_KEYS = ("age", "height_cm", "weight_kg")
67
+
68
+
69
+ def _without_body_data(athlete: dict) -> dict:
70
+ """Coaches see scores and targets, never the athlete's body data."""
71
+ return {k: v for k, v in athlete.items() if k not in BODY_DATA_KEYS}
72
+
73
+
74
+ VIDEO_BOX_TYPES = (b"ftyp", b"moov", b"wide", b"mdat", b"free", b"skip") # first box of an MP4 / QuickTime file
75
+
76
+
77
+ def _looks_like(kind: str, head: bytes) -> bool:
78
+ """Cheap content check: the file must start like the type it claims to be."""
79
+ if kind == "thumbnail":
80
+ return head.startswith(b"\xff\xd8\xff")
81
+ return head[4:8] in VIDEO_BOX_TYPES
82
+
83
  class SessionService:
84
  def __init__(self, db: AsyncSession, storage: StorageClient):
85
  self.db = db
 
125
  raise Unprocessable("The upload has not finished. Please try again.", code="UPLOAD_MISSING")
126
  settings = get_settings()
127
  limit = settings.max_video_bytes if upload.kind == "video" else settings.max_thumbnail_bytes
128
+ if (info.size_bytes > limit or info.content_type != upload.content_type
129
+ or not _looks_like(upload.kind, await self.storage.read_prefix(upload.object_key, 16))):
130
  await self.storage.delete_many([upload.object_key])
131
  raise Unprocessable("The uploaded file is not valid. Please record again.", code="UPLOAD_INVALID")
132
  if info.size_bytes != upload.size_bytes:
 
137
  session = await self.sessions.get_live(session_id)
138
  if session is None:
139
  raise NotFound()
140
+ is_owner = session.owner_id == viewer.id
141
+ if not is_owner:
142
+ # A coach sees their team's players' own analysed reps; private_videos does not block the coach.
143
+ allowed = (session.is_self and session.analyzed_at is not None and viewer.role == "coach"
144
  and await self.sessions.is_team_coach(viewer.id, session.owner_id))
145
  if not allowed:
146
  raise Forbidden()
147
+ return await self._out(session, include_body_data=is_owner)
148
 
149
+ async def _out(self, s: SwingSession, *, include_body_data: bool = True) -> SessionOut:
150
  keys = await self.uploads.object_keys(s.video_upload_id, s.thumbnail_upload_id)
151
  review_row = await self.sessions.review_with_coach_name(s.id)
152
  review = None
 
158
  thumb_key = keys.get(s.thumbnail_upload_id) if s.thumbnail_upload_id else None
159
  return SessionOut(
160
  id=s.id, owner_id=s.owner_id, is_self=s.is_self, mode=s.mode, status=s.status,
161
+ created_at=s.created_at, analyzed_at=s.analyzed_at,
162
+ athlete=s.athlete if include_body_data else _without_body_data(s.athlete),
163
  duration_sec=float(s.duration_sec), fps=s.fps, marks=s.marks, report=s.report, review=review,
164
  media=MediaOut(
165
  video_url=self.storage.presign_get(keys[s.video_upload_id]),
 
192
  if session.owner_id != owner.id:
193
  raise Forbidden()
194
  await self.sessions.update(session, deleted_at=datetime.now(UTC))
195
+ # The media goes now; the cleanup job removes the rows later (and retries if this delete fails).
196
+ keys = await self.uploads.object_keys(session.video_upload_id, session.thumbnail_upload_id)
197
+ try:
198
+ await self.storage.delete_many(list(keys.values()))
199
+ except Exception:
200
+ log.exception("media delete failed for session %s; cleanup will retry", session.id)
backend/e2e/README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # End-to-end QA suites
2
+
3
+ These suites run against a running API, by default `http://127.0.0.1:8000`; set `BASE_URL` to test another server. They use the real database and storage the server is configured with.
4
+
5
+ Every suite creates its own accounts (`qa-<suite>-<runid>-<n>@example.com`) and deletes them again at the end, along with their media.
6
+
7
+ ```bash
8
+ cd backend
9
+ .venv/bin/python e2e/qa_accounts_teams.py # auth, /me, teams, devices, billing error paths
10
+ .venv/bin/python e2e/qa_sessions_reports.py # uploads, sessions, swing report, plan limit, drills, catalog
11
+ .venv/bin/python e2e/qa_coach_loop.py # roster, queue, coach access, reviews, leaving a team
12
+ ```
13
+
14
+ Each check prints PASS or FAIL. The exit code is 1 if any check fails.
backend/e2e/qa_accounts_teams.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end QA suite: accounts, auth, teams, devices, billing (journeys 3.1, 3.2, 3.5, milestone 1).
2
+
3
+ Run: .venv/bin/python e2e/qa_accounts_teams.py (BASE_URL defaults to http://127.0.0.1:8000)
4
+
5
+ Runs against a live server. Every account it creates is qa-acct-<runid>-<n>@example.com and is deleted at the end.
6
+ Failed logins and forgot-password calls send a per-run X-Forwarded-For address (uvicorn trusts it from localhost),
7
+ so this suite does not eat into the per-IP rate-limit budget of other clients on 127.0.0.1. 429s are tested last.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import random
13
+ import re
14
+ import secrets
15
+ import sys
16
+ import uuid
17
+ from urllib.parse import quote
18
+
19
+ import httpx
20
+
21
+ BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/")
22
+ RUN = secrets.token_hex(4)
23
+ PASSWORD = "Sup3r-secret-pw"
24
+ CODE_RE = re.compile(r"^[A-Z]{3}-\d{4}$")
25
+ RID_RE = re.compile(r"^[0-9a-f]{32}$")
26
+
27
+ results: list[tuple[bool, str]] = []
28
+ server_errors: list[str] = []
29
+ created: dict[str, dict] = {} # email -> {"password", "access", "refresh"}
30
+ _n = 0
31
+
32
+
33
+ def rand_ip() -> str:
34
+ return f"10.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(1, 254)}"
35
+
36
+
37
+ RUN_IP = rand_ip()
38
+ client = httpx.Client(base_url=BASE_URL, timeout=30)
39
+
40
+
41
+ def new_email() -> str:
42
+ global _n
43
+ _n += 1
44
+ return f"qa-acct-{RUN}-{_n}@example.com"
45
+
46
+
47
+ def call(method: str, path: str, *, token: str | None = None, body=None, raw: bytes | None = None,
48
+ headers: dict | None = None, ip: str | None = None) -> httpx.Response:
49
+ h = {"X-Forwarded-For": ip or RUN_IP}
50
+ if token:
51
+ h["Authorization"] = f"Bearer {token}"
52
+ if headers:
53
+ h.update(headers)
54
+ if raw is not None:
55
+ h.setdefault("Content-Type", "application/json")
56
+ r = client.request(method, path, content=raw, headers=h)
57
+ else:
58
+ r = client.request(method, path, json=body, headers=h)
59
+ if r.status_code >= 500:
60
+ server_errors.append(f"{method} {path} -> {r.status_code} {r.text[:300]}")
61
+ if not r.headers.get("x-request-id"):
62
+ record(False, f"X-Request-Id present on {method} {path}", r)
63
+ return r
64
+
65
+
66
+ def body_of(r: httpx.Response):
67
+ try:
68
+ return r.json()
69
+ except Exception:
70
+ return r.text
71
+
72
+
73
+ def record(ok: bool, name: str, r: httpx.Response | None = None, detail: str = "") -> bool:
74
+ results.append((ok, name))
75
+ if ok:
76
+ print(f"PASS {name}" + (f" [{r.request.method} {r.request.url.path} {r.status_code}]" if r else ""))
77
+ else:
78
+ extra = ""
79
+ if r is not None:
80
+ query = r.request.url.query
81
+ query = query.decode() if isinstance(query, bytes) else query
82
+ extra = (f"\n {r.request.method} {r.request.url.path}?{query} -> {r.status_code}"
83
+ f"\n body: {json.dumps(body_of(r))[:800]}")
84
+ print(f"FAIL {name}{(' -- ' + detail) if detail else ''}{extra}")
85
+ return ok
86
+
87
+
88
+ def expect(name: str, r: httpx.Response, status: int, code: str | None = None, message: str | None = None,
89
+ fields: list[str] | None = None, check=None) -> bool:
90
+ """Status, then (for errors) the envelope code/message/fields, then a custom check(body) -> str|None."""
91
+ b = body_of(r)
92
+ problems = []
93
+ if r.status_code != status:
94
+ problems.append(f"expected status {status}, got {r.status_code}")
95
+ if code is not None or message is not None or fields:
96
+ err = b.get("error") if isinstance(b, dict) else None
97
+ if not isinstance(err, dict) or set(b.keys()) != {"error"}:
98
+ problems.append("not an error envelope {error:{code,message}}")
99
+ else:
100
+ if not isinstance(err.get("message"), str) or not err.get("message"):
101
+ problems.append("missing error.message")
102
+ if code is not None and err.get("code") != code:
103
+ problems.append(f"expected code {code}, got {err.get('code')}")
104
+ if message is not None and err.get("message") != message:
105
+ problems.append(f"expected message {message!r}, got {err.get('message')!r}")
106
+ for f in fields or []:
107
+ if f not in (err.get("fields") or {}):
108
+ problems.append(f"expected fields.{f}")
109
+ if check is not None and not problems:
110
+ try:
111
+ msg = check(b)
112
+ except Exception as exc: # noqa: BLE001
113
+ msg = f"check raised {exc!r}"
114
+ if msg:
115
+ problems.append(msg)
116
+ return record(not problems, name, r, "; ".join(problems))
117
+
118
+
119
+ def walk_keys(obj, path=""):
120
+ if isinstance(obj, dict):
121
+ for k, v in obj.items():
122
+ yield k, f"{path}.{k}"
123
+ yield from walk_keys(v, f"{path}.{k}")
124
+ elif isinstance(obj, list):
125
+ for i, v in enumerate(obj):
126
+ yield from walk_keys(v, f"{path}[{i}]")
127
+
128
+
129
+ SNAKE = re.compile(r"^[a-z][a-z0-9_]*$")
130
+
131
+
132
+ def snake_and_no_secrets(b) -> str | None:
133
+ for k, p in walk_keys(b):
134
+ if not SNAKE.match(k):
135
+ return f"non snake_case key {p}"
136
+ if "password" in k or "hash" in k:
137
+ return f"secret-looking key {p}"
138
+ return None
139
+
140
+
141
+ def register(role: str, email: str | None = None) -> dict:
142
+ email = email or new_email()
143
+ r = call("POST", "/v1/auth/register", body={"email": email, "password": PASSWORD, "role": role})
144
+ if r.status_code == 201:
145
+ b = r.json()
146
+ created[email] = {"password": PASSWORD, "access": b["tokens"]["access_token"],
147
+ "refresh": b["tokens"]["refresh_token"], "id": b["user"]["id"], "resp": r}
148
+ else:
149
+ created.setdefault(email, {"password": PASSWORD, "access": None, "refresh": None, "resp": r})
150
+ created[email]["email"] = email
151
+ return created[email]
152
+
153
+
154
+ def login(email: str, password: str = PASSWORD, ip: str | None = None) -> httpx.Response:
155
+ return call("POST", "/v1/auth/login", body={"email": email, "password": password}, ip=ip)
156
+
157
+
158
+ # ---------------------------------------------------------------------------------------------------------------
159
+
160
+ def t_general():
161
+ r = call("GET", "/docs")
162
+ expect("GET /docs reachable in dev", r, 200)
163
+ r = call("GET", "/openapi.json")
164
+ expect("GET /openapi.json", r, 200)
165
+ r = call("GET", "/v1/does-not-exist")
166
+ expect("unknown route -> 404 in error envelope", r, 404, code="NOT_FOUND")
167
+ r = call("DELETE", "/v1/auth/register")
168
+ expect("wrong method -> 405 in error envelope", r, 405, code=None,
169
+ check=lambda b: None if isinstance(b, dict) and "error" in b else "405 not in error envelope")
170
+ r = call("POST", "/v1/auth/register", raw=b'{"email": "x@example.com", "password": ')
171
+ expect("malformed JSON -> 400 VALIDATION", r, 400, code="VALIDATION")
172
+ r = call("POST", "/v1/auth/login", raw=b"[1,2,3]")
173
+ expect("JSON array body -> 400 VALIDATION", r, 400, code="VALIDATION")
174
+ r = call("GET", "/healthz", headers={"X-Request-Id": "qa-trace-" + RUN})
175
+ record(r.headers.get("x-request-id") == "qa-trace-" + RUN, "X-Request-Id echoed when supplied", r)
176
+ r = call("GET", "/healthz")
177
+ record(bool(RID_RE.match(r.headers.get("x-request-id", ""))), "X-Request-Id generated when absent", r)
178
+
179
+
180
+ def t_register(P: dict, C: dict):
181
+ def shape(role):
182
+ def check(b):
183
+ if set(b) != {"user", "tokens"}:
184
+ return f"top-level keys {sorted(b)}"
185
+ u, t = b["user"], b["tokens"]
186
+ want = {"id", "email", "role", "focus", "profile", "unit", "private_videos", "team_code", "created_at"}
187
+ if set(u) != want:
188
+ return f"user keys {sorted(u)}"
189
+ if set(u["profile"]) != {"name", "age", "height_cm", "weight_kg", "bats", "throws", "level"}:
190
+ return f"profile keys {sorted(u['profile'])}"
191
+ if set(t) != {"access_token", "refresh_token", "expires_in"}:
192
+ return f"token keys {sorted(t)}"
193
+ if u["role"] != role or u["team_code"] is not None or u["focus"] != "both":
194
+ return f"role/team_code/focus wrong: {u['role']} {u['team_code']} {u['focus']}"
195
+ if not (900 <= t["expires_in"] <= 3600):
196
+ return f"access token TTL {t['expires_in']} outside 15-60 min"
197
+ uuid.UUID(u["id"])
198
+ return snake_and_no_secrets(b)
199
+ return check
200
+
201
+ expect("register player 201 + shape", P["resp"], 201, check=shape("player"))
202
+ expect("register coach 201 + shape (role kept)", C["resp"], 201, check=shape("coach"))
203
+
204
+ r = call("POST", "/v1/auth/register", body={"email": P["email"], "password": PASSWORD, "role": "player"})
205
+ expect("duplicate email -> 409 EMAIL_TAKEN", r, 409, code="EMAIL_TAKEN",
206
+ message="An account with this email already exists.")
207
+ r = call("POST", "/v1/auth/register", body={"email": " " + P["email"].upper() + " ", "password": PASSWORD,
208
+ "role": "coach"})
209
+ expect("duplicate email (upper-case, padded) -> 409 EMAIL_TAKEN", r, 409, code="EMAIL_TAKEN")
210
+ r = call("POST", "/v1/auth/register", body={"email": "not-an-email", "password": PASSWORD, "role": "player"})
211
+ expect("invalid email -> 400 VALIDATION fields.email", r, 400, code="VALIDATION", fields=["email"])
212
+ r = call("POST", "/v1/auth/register", body={"email": new_email(), "password": "short", "role": "player"})
213
+ expect("short password -> 400 VALIDATION fields.password", r, 400, code="VALIDATION", fields=["password"])
214
+ r = call("POST", "/v1/auth/register", body={"email": new_email(), "password": "x" * 129, "role": "player"})
215
+ expect("129-char password -> 400 VALIDATION", r, 400, code="VALIDATION", fields=["password"])
216
+ r = call("POST", "/v1/auth/register", body={"email": new_email(), "password": PASSWORD, "role": "admin"})
217
+ expect("bad role -> 400 VALIDATION fields.role", r, 400, code="VALIDATION", fields=["role"])
218
+ r = call("POST", "/v1/auth/register", body={"email": new_email(), "password": PASSWORD})
219
+ expect("missing role -> 400 VALIDATION", r, 400, code="VALIDATION", fields=["role"])
220
+ r = call("POST", "/v1/auth/register",
221
+ body={"email": new_email(), "password": PASSWORD, "role": "player", "is_admin": True})
222
+ expect("unknown field -> 400 VALIDATION", r, 400, code="VALIDATION", fields=["is_admin"])
223
+ r = call("POST", "/v1/auth/register", body={"email": new_email(), "password": PASSWORD, "role": "player",
224
+ "plan": "pro"})
225
+ expect("unknown field 'plan' -> 400", r, 400, code="VALIDATION")
226
+
227
+
228
+ def t_login(P: dict):
229
+ r = login(P["email"])
230
+ expect("login success 200", r, 200, check=lambda b: None if b["user"]["email"] == P["email"] else "email")
231
+ r = login(" " + P["email"].upper() + " ")
232
+ expect("login with upper-case padded email 200", r, 200)
233
+ r = login(P["email"], "wrong-password-1")
234
+ expect("login wrong password -> 401 INVALID_CREDENTIALS", r, 401, code="INVALID_CREDENTIALS",
235
+ message="Wrong email or password.")
236
+ r = login(f"qa-acct-{RUN}-nobody@example.com", "whatever-123")
237
+ expect("login unknown email -> same 401 INVALID_CREDENTIALS", r, 401, code="INVALID_CREDENTIALS",
238
+ message="Wrong email or password.")
239
+ r = call("POST", "/v1/auth/login", body={"email": P["email"]})
240
+ expect("login missing password -> 400", r, 400, code="VALIDATION", fields=["password"])
241
+
242
+
243
+ def t_tokens(P: dict):
244
+ r = login(P["email"])
245
+ r1 = r.json()["tokens"]["refresh_token"]
246
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": r1})
247
+ ok = expect("refresh -> 200 new pair", r, 200,
248
+ check=lambda b: None if set(b) == {"access_token", "refresh_token", "expires_in"}
249
+ and b["refresh_token"] != r1 else f"bad body {b}")
250
+ if not ok:
251
+ return
252
+ a2, r2 = r.json()["access_token"], r.json()["refresh_token"]
253
+ expect("new access token works on /me", call("GET", "/v1/me", token=a2), 200)
254
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": r2})
255
+ expect("newest refresh rotates again", r, 200)
256
+ r3 = r.json().get("refresh_token") if r.status_code == 200 else r2
257
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": r1})
258
+ expect("reuse of old refresh -> 401 TOKEN_REVOKED", r, 401, code="TOKEN_REVOKED")
259
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": r3})
260
+ expect("theft detection: newest token of family also revoked", r, 401, code="TOKEN_REVOKED")
261
+ # Other sign-ins (other families) are untouched.
262
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": P["refresh"]})
263
+ expect("other refresh family unaffected", r, 200)
264
+ if r.status_code == 200:
265
+ P["refresh"], P["access"] = r.json()["refresh_token"], r.json()["access_token"]
266
+
267
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": "garbage-" + secrets.token_hex(8)})
268
+ expect("garbage refresh -> 401 TOKEN_REVOKED", r, 401, code="TOKEN_REVOKED")
269
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": ""})
270
+ expect("empty refresh -> 400", r, 400, code="VALIDATION")
271
+
272
+ # Logout
273
+ lr = login(P["email"]).json()["tokens"]
274
+ r = call("POST", "/v1/auth/logout", token=lr["access_token"], body={"refresh_token": lr["refresh_token"]})
275
+ expect("logout -> 204", r, 204)
276
+ r = call("POST", "/v1/auth/refresh", body={"refresh_token": lr["refresh_token"]})
277
+ expect("refresh after logout -> 401 TOKEN_REVOKED", r, 401, code="TOKEN_REVOKED")
278
+ r = call("POST", "/v1/auth/logout", body={"refresh_token": "x"})
279
+ expect("logout without bearer -> 401", r, 401, code="UNAUTHENTICATED")
280
+
281
+ # Bad access tokens
282
+ for name, tok in [("garbage", "garbage.token.value"), ("refresh token as bearer", P["refresh"]),
283
+ ("alg none", "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0"
284
+ "wMDAwMDAwMDAwMDAiLCJ0eXAiOiJhY2Nlc3MiLCJleHAiOjQxMDI0NDQ4MDB9.")]:
285
+ expect(f"access with {name} token -> 401 UNAUTHENTICATED", call("GET", "/v1/me", token=tok), 401,
286
+ code="UNAUTHENTICATED")
287
+ # Tampered signature on a real token
288
+ parts = P["access"].split(".")
289
+ tampered = ".".join(parts[:2] + [parts[2][:-4] + ("AAAA" if not parts[2].endswith("AAAA") else "BBBB")])
290
+ expect("tampered signature -> 401", call("GET", "/v1/me", token=tampered), 401, code="UNAUTHENTICATED")
291
+ # Expired token: forge one with exp in the past (wrong key too, so this proves rejection, not expiry per se)
292
+ import base64
293
+
294
+ def b64(d):
295
+ return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()
296
+ expired = f"{b64({'alg': 'HS256', 'typ': 'JWT'})}.{b64({'sub': P['id'], 'typ': 'access', 'exp': 1})}.sig"
297
+ expect("expired/forged token -> 401", call("GET", "/v1/me", token=expired), 401, code="UNAUTHENTICATED")
298
+ expect("no Authorization header -> 401", call("GET", "/v1/me"), 401, code="UNAUTHENTICATED")
299
+ r = client.get("/v1/me", headers={"Authorization": "Token " + P["access"], "X-Forwarded-For": RUN_IP})
300
+ expect("non-Bearer scheme -> 401", r, 401, code="UNAUTHENTICATED")
301
+
302
+
303
+ def t_me(P: dict):
304
+ def check(b):
305
+ if set(b) != {"user", "team", "entitlement"}:
306
+ return f"keys {sorted(b)}"
307
+ e = b["entitlement"]
308
+ if b["team"] is not None:
309
+ return "team should be null"
310
+ if e.get("plan") != "free" or e.get("left") != 3 or e.get("used_this_week") != 0 or e.get("weekly_limit") != 3:
311
+ return f"entitlement {e}"
312
+ return snake_and_no_secrets(b)
313
+ expect("GET /me -> user, team null, free 3 left", call("GET", "/v1/me", token=P["access"]), 200, check=check)
314
+
315
+
316
+ def t_patch(X: dict):
317
+ tok = X["access"]
318
+
319
+ def patch(body):
320
+ return call("PATCH", "/v1/me", token=tok, body=body)
321
+
322
+ r = patch({"role": "coach"})
323
+ expect("role change before team/session allowed (player->coach)", r, 200,
324
+ check=lambda b: None if b["user"]["role"] == "coach" else b)
325
+ r = patch({"role": "player"})
326
+ expect("role change back (coach->player)", r, 200, check=lambda b: None if b["user"]["role"] == "player" else b)
327
+ r = patch({"focus": "h", "unit": "metric", "private_videos": True,
328
+ "profile": {"name": "QA Player", "age": 15, "height_cm": 168.25, "weight_kg": 60, "bats": "R",
329
+ "throws": "L", "level": "high_school"}})
330
+
331
+ def full(b):
332
+ u = b["user"]
333
+ p = u["profile"]
334
+ want = {"name": "QA Player", "age": 15, "height_cm": 168.2, "weight_kg": 60.0, "bats": "R", "throws": "L",
335
+ "level": "high_school"}
336
+ if u["focus"] != "h" or u["unit"] != "metric" or u["private_videos"] is not True:
337
+ return f"top-level not applied {u}"
338
+ bad = {k: p[k] for k in want if p[k] != want[k] and not (k == "height_cm" and p[k] in (168.2, 168.3))}
339
+ return f"profile mismatch {bad}" if bad else snake_and_no_secrets(b)
340
+ expect("PATCH full profile 200 (body = {user})", r, 200, check=full)
341
+
342
+ boundary = [("age", 5), ("age", 70), ("height_cm", 90), ("height_cm", 230), ("weight_kg", 20), ("weight_kg", 200)]
343
+ for k, v in boundary:
344
+ expect(f"profile.{k}={v} accepted (boundary)", patch({"profile": {k: v}}), 200,
345
+ check=lambda b, k=k, v=v: None if b["user"]["profile"][k] == v else b["user"]["profile"])
346
+ bad = [("age", 4), ("age", 71), ("age", "15"), ("age", 15.5), ("height_cm", 89), ("height_cm", 231),
347
+ ("weight_kg", 19), ("weight_kg", 201), ("bats", "X"), ("throws", "S"), ("level", "pro"),
348
+ ("level", "Youth"), ("name", "A"), ("name", "x" * 81), ("name", None)]
349
+ for k, v in bad:
350
+ expect(f"profile.{k}={v!r} rejected 400", patch({"profile": {k: v}}), 400, code="VALIDATION",
351
+ fields=[f"profile.{k}"])
352
+ for k, v in [("focus", "x"), ("unit", "km"), ("private_videos", "maybe"), ("role", "admin"), ("role", None),
353
+ ("focus", None), ("profile", None)]:
354
+ expect(f"{k}={v!r} rejected 400", patch({k: v}), 400, code="VALIDATION", fields=[k])
355
+ expect("unknown top-level field rejected", patch({"plan": "pro"}), 400, code="VALIDATION", fields=["plan"])
356
+ expect("unknown profile field rejected", patch({"profile": {"shoe": 10}}), 400, code="VALIDATION")
357
+ expect("email not patchable", patch({"email": "evil@example.com"}), 400, code="VALIDATION")
358
+
359
+ r = patch({"profile": {"height_cm": None, "bats": None}})
360
+ expect("null clears inside profile, others kept", r, 200,
361
+ check=lambda b: None if b["user"]["profile"]["height_cm"] is None and b["user"]["profile"]["bats"] is None
362
+ and b["user"]["profile"]["age"] == 70 and b["user"]["profile"]["weight_kg"] == 200 else b["user"]["profile"])
363
+ r = call("GET", "/v1/me", token=tok)
364
+ expect("PATCH persisted (GET /me)", r, 200,
365
+ check=lambda b: None if b["user"]["profile"]["height_cm"] is None and b["user"]["unit"] == "metric"
366
+ else b["user"])
367
+ expect("empty PATCH is a no-op 200", patch({}), 200)
368
+
369
+
370
+ def t_forgot_reset(P: dict):
371
+ r = call("POST", "/v1/auth/password/forgot", body={"email": P["email"]})
372
+ expect("forgot existing -> 202", r, 202)
373
+ r2 = call("POST", "/v1/auth/password/forgot", body={"email": f"qa-acct-{RUN}-ghost@example.com"})
374
+ expect("forgot unknown -> 202 (no enumeration)", r2, 202)
375
+ record(r.text == r2.text, "forgot responses identical for known/unknown", r2)
376
+ r = call("POST", "/v1/auth/password/forgot", body={"email": "nope"})
377
+ expect("forgot invalid email -> 400", r, 400, code="VALIDATION", fields=["email"])
378
+ r = call("POST", "/v1/auth/password/reset", body={"token": "bogus-" + secrets.token_hex(16),
379
+ "password": "Another-pw-123"})
380
+ expect("reset with bogus token -> 400 TOKEN_INVALID", r, 400, code="TOKEN_INVALID")
381
+ r = call("POST", "/v1/auth/password/reset", body={"token": "bogus", "password": "short"})
382
+ expect("reset short password -> 400 VALIDATION", r, 400, code="VALIDATION", fields=["password"])
383
+ expect("login still works with old password after bogus reset", login(P["email"]), 200)
384
+
385
+
386
+ def t_social():
387
+ for provider in ("apple", "google"):
388
+ r = call("POST", "/v1/auth/social", body={"provider": provider, "id_token": "garbage." + secrets.token_hex(8)})
389
+ expect(f"social {provider} garbage id_token -> 401 INVALID_TOKEN", r, 401, code="INVALID_TOKEN")
390
+ r = call("POST", "/v1/auth/social", body={"provider": "facebook", "id_token": "x"})
391
+ expect("social unknown provider -> 400", r, 400, code="VALIDATION", fields=["provider"])
392
+ # A syntactically valid but unsigned JWT
393
+ r = call("POST", "/v1/auth/social", body={
394
+ "provider": "google", "id_token": "eyJhbGciOiJub25lIn0.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMSIs"
395
+ "ImVtYWlsIjoiYUBleGFtcGxlLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlfQ."})
396
+ expect("social google alg-none token -> 401 INVALID_TOKEN", r, 401, code="INVALID_TOKEN")
397
+
398
+
399
+ def t_teams(P: dict, C: dict, C2: dict, P2: dict):
400
+ r = call("POST", "/v1/teams", token=C["access"],
401
+ body={"name": "Karachi Diamond Academy", "coach_name": "Imran Baig", "coaching": "both"})
402
+
403
+ def team_shape(b):
404
+ t = b.get("team", {})
405
+ if set(t) != {"id", "code", "name", "coach_id", "coach_name", "coaching", "created_at"}:
406
+ return f"team keys {sorted(t)}"
407
+ if not CODE_RE.match(t["code"]) or not t["code"].startswith("KDA-"):
408
+ return f"code {t['code']}"
409
+ if t["coach_name"] != "Imran Baig" or t["coach_id"] != C["id"]:
410
+ return f"coach {t}"
411
+ return snake_and_no_secrets(b)
412
+ if not expect("coach creates team 201, code KDA-dddd", r, 201, check=team_shape):
413
+ return
414
+ code = r.json()["team"]["code"]
415
+ r = call("GET", "/v1/me", token=C["access"])
416
+ expect("coach profile.name and focus set from team", r, 200,
417
+ check=lambda b: None if b["user"]["profile"]["name"] == "Imran Baig" and b["user"]["focus"] == "both"
418
+ else b["user"])
419
+ expect("coach /me shows the team", r, 200,
420
+ check=lambda b: None if (b.get("team") or {}).get("code") == code else f"team={b.get('team')}")
421
+
422
+ r = call("POST", "/v1/teams", token=C["access"],
423
+ body={"name": "Lahore Hitters", "coach_name": "Imran B", "coaching": "h"})
424
+ expect("second POST /teams updates: 200 same code", r, 200,
425
+ check=lambda b: None if b["team"]["code"] == code and b["team"]["name"] == "Lahore Hitters"
426
+ and b["team"]["coaching"] == "h" and b["team"]["coach_name"] == "Imran B" else b)
427
+ expect("coach focus follows coaching=h", call("GET", "/v1/me", token=C["access"]), 200,
428
+ check=lambda b: None if b["user"]["focus"] == "h" else b["user"]["focus"])
429
+
430
+ for body, f in [({"name": "K", "coach_name": "Imran", "coaching": "h"}, "name"),
431
+ ({"name": "Karachi", "coach_name": "I", "coaching": "h"}, "coach_name"),
432
+ ({"name": "Karachi", "coach_name": "Imran", "coaching": "x"}, "coaching"),
433
+ ({"name": "x" * 61, "coach_name": "Imran", "coaching": "h"}, "name"),
434
+ ({"name": "Karachi", "coach_name": "Imran", "coaching": "h", "code": "AAA-0000"}, "code")]:
435
+ expect(f"POST /teams invalid {f} -> 400", call("POST", "/v1/teams", token=C["access"], body=body), 400,
436
+ code="VALIDATION", fields=[f])
437
+
438
+ expect("player POST /teams -> 403 FORBIDDEN",
439
+ call("POST", "/v1/teams", token=P["access"], body={"name": "Mine", "coach_name": "Me Me", "coaching": "h"}),
440
+ 403, code="FORBIDDEN")
441
+
442
+ # Lookup
443
+ def summary(b):
444
+ t = b.get("team", {})
445
+ if set(t) != {"code", "name", "coach_name", "coaching"}:
446
+ return f"summary keys {sorted(t)} (should expose no ids)"
447
+ return None if t["code"] == code and t["coach_name"] == "Imran B" else f"{t}"
448
+ r = call("GET", "/v1/teams/lookup?code=" + quote(" " + code.lower() + " "), token=P["access"])
449
+ expect("lookup case-insensitive and trimmed -> 200 summary", r, 200, check=summary)
450
+ r = call("GET", "/v1/teams/lookup?code=QQQ-" + str(random.randint(10000, 99999)), token=P["access"])
451
+ expect("lookup unknown -> 404 TEAM_NOT_FOUND", r, 404, code="TEAM_NOT_FOUND",
452
+ message="We couldn't find a team with that code.")
453
+ expect("lookup without token -> 401", call("GET", "/v1/teams/lookup?code=" + code), 401, code="UNAUTHENTICATED")
454
+ expect("lookup missing code -> 400", call("GET", "/v1/teams/lookup", token=P["access"]), 400, code="VALIDATION")
455
+
456
+ # Join
457
+ expect("coach join -> 403 FORBIDDEN", call("POST", f"/v1/teams/{code}/join", token=C["access"]), 403,
458
+ code="FORBIDDEN")
459
+ expect("join unknown code -> 404 TEAM_NOT_FOUND", call("POST", "/v1/teams/QQQ-12345/join", token=P["access"]),
460
+ 404, code="TEAM_NOT_FOUND", message="We couldn't find a team with that code.")
461
+ r = call("POST", f"/v1/teams/{quote(' ' + code.lower() + ' ')}/join", token=P["access"])
462
+ expect("player joins (lower-case, padded code) -> 200 {team}", r, 200,
463
+ check=lambda b: None if b["team"]["code"] == code else b)
464
+ r = call("GET", "/v1/me", token=P["access"])
465
+ expect("player /me shows team_code and team", r, 200,
466
+ check=lambda b: None if b["user"]["team_code"] == code and (b["team"] or {}).get("code") == code else b)
467
+ expect("join same team again is idempotent 200", call("POST", f"/v1/teams/{code}/join", token=P["access"]), 200)
468
+
469
+ # Acceptance: coach sees player in roster, without body data
470
+ def in_roster(b, present=True):
471
+ ids = [i["id"] for i in b.get("items", [])]
472
+ if (P["id"] in ids) != present:
473
+ return f"player {'missing from' if present else 'still in'} roster: {ids}"
474
+ for k, p in walk_keys(b):
475
+ if k in ("age", "height_cm", "weight_kg", "weight", "height", "password_hash"):
476
+ return f"roster leaks body data/secret: {p}"
477
+ return snake_and_no_secrets(b)
478
+ r = call("GET", "/v1/coach/roster", token=C["access"])
479
+ expect("acceptance: joined player appears in coach roster (no body data)", r, 200, check=in_roster)
480
+ if r.status_code == 200:
481
+ item = next((i for i in r.json()["items"] if i["id"] == P["id"]), None)
482
+ if item:
483
+ record(item.get("name") == "QA Player" and item.get("level") == "high_school",
484
+ "roster item carries name and level", r, f"item={item}")
485
+ expect("player GET /coach/roster -> 403", call("GET", "/v1/coach/roster", token=P["access"]), 403,
486
+ code="FORBIDDEN")
487
+
488
+ # ROLE_LOCKED
489
+ r = call("PATCH", "/v1/me", token=P["access"], body={"role": "coach"})
490
+ expect("player on a team: role change -> 409 ROLE_LOCKED", r, 409, code="ROLE_LOCKED")
491
+ r = call("PATCH", "/v1/me", token=P["access"], body={"role": "player"})
492
+ expect("PATCH same role while locked is allowed (no change)", r, 200)
493
+ r = call("PATCH", "/v1/me", token=C["access"], body={"role": "player"})
494
+ expect("coach with a team: role change -> 409 ROLE_LOCKED", r, 409, code="ROLE_LOCKED")
495
+
496
+ # Move to another team
497
+ r = call("POST", "/v1/teams", token=C2["access"], body={"name": "zebra", "coach_name": "Second Coach",
498
+ "coaching": "p"})
499
+ expect("second coach creates team (initials padded with X: ZXX-dddd)", r, 201,
500
+ check=lambda b: None if re.match(r"^ZXX-\d{4}$", b["team"]["code"]) else b["team"]["code"])
501
+ if r.status_code != 201:
502
+ return
503
+ code2 = r.json()["team"]["code"]
504
+ r = call("POST", f"/v1/teams/{code2}/join", token=P["access"])
505
+ expect("player joins another team (moves)", r, 200, check=lambda b: None if b["team"]["code"] == code2 else b)
506
+ expect("me.team_code moved", call("GET", "/v1/me", token=P["access"]), 200,
507
+ check=lambda b: None if b["user"]["team_code"] == code2 else b["user"]["team_code"])
508
+ expect("old coach roster dropped the player", call("GET", "/v1/coach/roster", token=C["access"]), 200,
509
+ check=lambda b: in_roster(b, present=False))
510
+ expect("new coach roster has the player", call("GET", "/v1/coach/roster", token=C2["access"]), 200,
511
+ check=in_roster)
512
+
513
+ # P2 joins C's team so the roster is not trivially empty
514
+ call("POST", f"/v1/teams/{code}/join", token=P2["access"])
515
+
516
+ # Leave
517
+ expect("leave team -> 204", call("DELETE", "/v1/me/team", token=P["access"]), 204)
518
+ expect("leave again idempotent -> 204", call("DELETE", "/v1/me/team", token=P["access"]), 204)
519
+ expect("after leave: team null", call("GET", "/v1/me", token=P["access"]), 200,
520
+ check=lambda b: None if b["user"]["team_code"] is None and b["team"] is None else b)
521
+ expect("after leave: coach roster drops player", call("GET", "/v1/coach/roster", token=C2["access"]), 200,
522
+ check=lambda b: in_roster(b, present=False))
523
+ expect("coach DELETE /me/team -> 403", call("DELETE", "/v1/me/team", token=C["access"]), 403, code="FORBIDDEN")
524
+ r = call("PATCH", "/v1/me", token=P["access"], body={"role": "coach"})
525
+ expect("after leaving (no sessions) role unlocks again", r, 200)
526
+ call("PATCH", "/v1/me", token=P["access"], body={"role": "player"})
527
+ return code
528
+
529
+
530
+ def t_devices(A: dict, B: dict):
531
+ tok = f"qa{RUN}:APA91b-{secrets.token_hex(12)}"
532
+ r = call("POST", "/v1/devices", token=A["access"], body={"platform": "ios", "push_token": tok})
533
+ expect("register ios token -> 201", r, 201,
534
+ check=lambda b: None if set(b.get("device", {})) == {"id", "platform", "push_token", "created_at"}
535
+ and b["device"]["push_token"] == tok else b)
536
+ expect("re-register same token same account -> 200",
537
+ call("POST", "/v1/devices", token=A["access"], body={"platform": "ios", "push_token": tok}), 200)
538
+ expect("another account registers same token -> 201 (moved)",
539
+ call("POST", "/v1/devices", token=B["access"], body={"platform": "android", "push_token": tok}), 201,
540
+ check=lambda b: None if b["device"]["platform"] == "android" else b)
541
+ expect("delete someone else's token -> silent 204",
542
+ call("DELETE", f"/v1/devices/{quote(tok, safe='')}", token=A["access"]), 204)
543
+ expect("...and it was not removed (owner re-register -> 200)",
544
+ call("POST", "/v1/devices", token=B["access"], body={"platform": "android", "push_token": tok}), 200)
545
+ expect("delete own token -> 204", call("DELETE", f"/v1/devices/{quote(tok, safe='')}", token=B["access"]), 204)
546
+ expect("...and it is gone (re-register -> 201)",
547
+ call("POST", "/v1/devices", token=B["access"], body={"platform": "android", "push_token": tok}), 201)
548
+ call("DELETE", f"/v1/devices/{quote(tok, safe='')}", token=B["access"])
549
+ expect("delete unknown token -> 204", call("DELETE", "/v1/devices/nope-" + RUN, token=B["access"]), 204)
550
+ expect("bad platform -> 400", call("POST", "/v1/devices", token=A["access"],
551
+ body={"platform": "web", "push_token": "x"}), 400, code="VALIDATION",
552
+ fields=["platform"])
553
+ expect("empty push_token -> 400", call("POST", "/v1/devices", token=A["access"],
554
+ body={"platform": "ios", "push_token": ""}), 400, code="VALIDATION")
555
+ expect("devices without auth -> 401", call("POST", "/v1/devices", body={"platform": "ios", "push_token": "x"}),
556
+ 401, code="UNAUTHENTICATED")
557
+
558
+
559
+ def t_billing(A: dict):
560
+ tok = A["access"]
561
+ expect("GET /me/entitlement free", call("GET", "/v1/me/entitlement", token=tok), 200,
562
+ check=lambda b: None if b == {"plan": "free", "weekly_limit": 3, "used_this_week": 0, "left": 3,
563
+ "window_days": b.get("window_days")} else b)
564
+ r = call("POST", "/v1/billing/receipts", token=tok,
565
+ body={"platform": "ios", "product_id": "pro_lifetime_free", "signed_transaction": "x"})
566
+ expect("receipt with product not in allowlist -> 400 VALIDATION", r, 400, code="VALIDATION", fields=["product_id"])
567
+ r = call("POST", "/v1/billing/receipts", token=tok, body={"platform": "ios", "product_id": "pro_monthly"})
568
+ expect("ios receipt without signed_transaction -> 400", r, 400, code="VALIDATION", fields=["signed_transaction"])
569
+ r = call("POST", "/v1/billing/receipts", token=tok,
570
+ body={"platform": "ios", "product_id": "pro_monthly", "signed_transaction": "garbage.jws.value"})
571
+ expect("ios garbage signed_transaction -> 422 RECEIPT_INVALID", r, 422, code="RECEIPT_INVALID")
572
+ r = call("POST", "/v1/billing/receipts", token=tok,
573
+ body={"platform": "android", "product_id": "pro_monthly", "purchase_token": "garbage-" + RUN})
574
+ print(f"INFO android receipt (Play not configured) -> {r.status_code} {json.dumps(body_of(r))[:300]}")
575
+ expect("android receipt with Play unconfigured -> 4xx (not 5xx)", r, 422, code="RECEIPT_INVALID")
576
+ r = call("POST", "/v1/billing/receipts", token=tok, body={"platform": "android", "product_id": "pro_monthly"})
577
+ expect("android receipt without purchase_token -> 400", r, 400, code="VALIDATION", fields=["purchase_token"])
578
+ expect("entitlement still free after bad receipts", call("GET", "/v1/me/entitlement", token=tok), 200,
579
+ check=lambda b: None if b["plan"] == "free" else b)
580
+ expect("entitlement without auth -> 401", call("GET", "/v1/me/entitlement"), 401, code="UNAUTHENTICATED")
581
+
582
+ r = call("POST", "/v1/billing/webhooks/apple", body={"signedPayload": "garbage.payload.sig"})
583
+ expect("apple webhook garbage signedPayload -> 401", r, 401, code="UNAUTHENTICATED")
584
+ r = call("POST", "/v1/billing/webhooks/apple", body={})
585
+ expect("apple webhook without signedPayload -> 400", r, 400, code="VALIDATION")
586
+ r = call("POST", "/v1/billing/webhooks/google", body={"message": {"data": "e30="}, "subscription": "x"})
587
+ expect("google webhook without OIDC -> 401", r, 401, code="UNAUTHENTICATED")
588
+ r = call("POST", "/v1/billing/webhooks/google", body={"message": {"data": "e30="}},
589
+ headers={"Authorization": "Bearer garbage"})
590
+ expect("google webhook with garbage bearer -> 401", r, 401, code="UNAUTHENTICATED")
591
+ r = call("POST", "/v1/billing/webhooks/stripe", body={})
592
+ expect("unknown webhook provider -> 404", r, 404, code="NOT_FOUND")
593
+
594
+
595
+ def t_delete_and_reregister():
596
+ X = register("player")
597
+ email = X["email"]
598
+ if not expect("register account for deletion", X["resp"], 201):
599
+ return
600
+ r = call("DELETE", "/v1/me", token=X["access"])
601
+ expect("DELETE /me -> 204", r, 204)
602
+ expect("access token stops working after delete", call("GET", "/v1/me", token=X["access"]), 401,
603
+ code="UNAUTHENTICATED")
604
+ expect("refresh token stops working after delete",
605
+ call("POST", "/v1/auth/refresh", body={"refresh_token": X["refresh"]}), 401, code="TOKEN_REVOKED")
606
+ expect("login after delete -> 401", login(email, ip=rand_ip()), 401, code="INVALID_CREDENTIALS")
607
+ expect("DELETE /me again with old token -> 401", call("DELETE", "/v1/me", token=X["access"]), 401)
608
+ created.pop(email, None)
609
+ X2 = register("coach", email)
610
+ expect("re-register same email after delete -> 201", X2["resp"], 201,
611
+ check=lambda b: None if b["user"]["id"] != X["id"] and b["user"]["role"] == "coach" else b)
612
+
613
+
614
+ def t_team_lookup_rate_limit(A: dict):
615
+ # Fire concurrently: against a remote DB 31 sequential lookups can take longer than the 60 s window.
616
+ from concurrent.futures import ThreadPoolExecutor
617
+ with ThreadPoolExecutor(max_workers=16) as pool:
618
+ rs = list(pool.map(lambda i: call("GET", f"/v1/teams/lookup?code=QQQ-{i:05d}", token=A["access"]),
619
+ range(31)))
620
+ statuses = sorted(r.status_code for r in rs)
621
+ record(statuses.count(404) == 30, "team lookup: 30 lookups per minute allowed", None, f"statuses={statuses}")
622
+ limited = next((r for r in rs if r.status_code == 429), rs[-1])
623
+ expect("team lookup 31st in a minute -> 429 RATE_LIMITED", limited, 429, code="RATE_LIMITED")
624
+ r = call("GET", "/v1/teams/lookup?code=QQQ-99999", token=A["access"])
625
+ expect("team lookup still limited right after", r, 429, code="RATE_LIMITED")
626
+
627
+
628
+ def t_login_rate_limits(P3: dict):
629
+ # Per email and IP: a guesser on one network is blocked, the real user elsewhere is not locked out.
630
+ guesser = rand_ip()
631
+ st = [login(P3["email"], "wrong-pw-123", ip=guesser).status_code for _ in range(10)]
632
+ record(st == [401] * 10, "login: 10 failures per email+IP allowed (401)", None, f"statuses={st}")
633
+ r = login(P3["email"], "wrong-pw-123", ip=guesser)
634
+ expect("login 11th failure for same email+IP -> 429 RATE_LIMITED", r, 429, code="RATE_LIMITED")
635
+ expect("guessing IP stays blocked even with the correct password", login(P3["email"], ip=guesser), 429,
636
+ code="RATE_LIMITED")
637
+ expect("real user on another IP is not locked out by someone else's failures",
638
+ login(P3["email"], ip=rand_ip()), 200)
639
+ # Per IP: one fixed IP, different emails.
640
+ ip = rand_ip()
641
+ st = [login(f"qa-acct-{RUN}-ipr{i}@example.com", "wrong-pw-123", ip=ip).status_code for i in range(10)]
642
+ record(st == [401] * 10, "login: 10 failures per IP allowed (401)", None, f"statuses={st}")
643
+ r = login(P3["email"], ip=ip)
644
+ expect("login from rate-limited IP (even correct password) -> 429", r, 429, code="RATE_LIMITED")
645
+ expect("same account from another IP still logs in", login(P3["email"], ip=rand_ip()), 200)
646
+
647
+
648
+ def t_forgot_rate_limit():
649
+ ghost = f"qa-acct-{RUN}-forgotrl@example.com"
650
+ st = [call("POST", "/v1/auth/password/forgot", body={"email": ghost}, ip=rand_ip()).status_code
651
+ for _ in range(10)]
652
+ record(st == [202] * 10, "forgot: 10 per email per minute allowed", None, f"statuses={st}")
653
+ r = call("POST", "/v1/auth/password/forgot", body={"email": ghost}, ip=rand_ip())
654
+ expect("forgot 11th for same email -> 429 RATE_LIMITED", r, 429, code="RATE_LIMITED")
655
+
656
+
657
+ def cleanup():
658
+ print("\n--- cleanup ---")
659
+ for email, info in list(created.items()):
660
+ if info.get("access") is None and info.get("resp") is not None and info["resp"].status_code != 201:
661
+ continue
662
+ r = call("DELETE", "/v1/me", token=info.get("access")) if info.get("access") else None
663
+ if r is None or r.status_code == 401:
664
+ lr = login(email, ip=rand_ip())
665
+ if lr.status_code == 200:
666
+ r = call("DELETE", "/v1/me", token=lr.json()["tokens"]["access_token"])
667
+ ok = r is not None and r.status_code == 204
668
+ record(ok, f"cleanup: DELETE /me {email}", r)
669
+ lr = login(email, ip=rand_ip())
670
+ expect(f"cleanup: login after delete -> 401 ({email})", lr, 401, code="INVALID_CREDENTIALS")
671
+
672
+
673
+ def main() -> int:
674
+ print(f"BASE_URL={BASE_URL} run={RUN} ip={RUN_IP}\n")
675
+ try:
676
+ t_general()
677
+ P = register("player")
678
+ C = register("coach")
679
+ C2 = register("coach")
680
+ P2 = register("player")
681
+ P3 = register("player")
682
+ for acct in (C2, P2, P3):
683
+ if acct["resp"].status_code != 201:
684
+ record(False, f"setup register {acct['email']}", acct["resp"])
685
+ t_register(P, C)
686
+ if not P.get("access") or not C.get("access"):
687
+ return 1
688
+ t_login(P)
689
+ t_tokens(P)
690
+ t_me(P)
691
+ t_patch(P)
692
+ t_forgot_reset(P)
693
+ t_social()
694
+ t_teams(P, C, C2, P2)
695
+ t_devices(P2, P3)
696
+ t_billing(P2)
697
+ t_delete_and_reregister()
698
+ # Rate limits last
699
+ t_team_lookup_rate_limit(P3)
700
+ t_login_rate_limits(P3)
701
+ t_forgot_rate_limit()
702
+ except Exception as exc: # noqa: BLE001
703
+ import traceback
704
+ traceback.print_exc()
705
+ record(False, f"suite crashed: {exc!r}")
706
+ finally:
707
+ cleanup()
708
+
709
+ passed = sum(1 for ok, _ in results if ok)
710
+ failed = [n for ok, n in results if not ok]
711
+ print(f"\n=== {passed} passed, {len(failed)} failed ===")
712
+ for n in failed:
713
+ print(f" FAIL {n}")
714
+ if server_errors:
715
+ print("5xx responses seen:")
716
+ for e in server_errors:
717
+ print(" " + e)
718
+ return 1 if failed or server_errors else 0
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
backend/e2e/qa_coach_loop.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end QA: coach review loop (journey 3.6, milestone 3 acceptance).
2
+
3
+ Run from backend/: .venv/bin/python e2e/qa_coach_loop.py
4
+ BASE_URL defaults to http://127.0.0.1:8000. Creates qa-coach-<runid>-<n>@example.com accounts and deletes
5
+ them at the end (DELETE /v1/me). Exit code 1 if any check fails.
6
+ """
7
+
8
+ import copy
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import time
14
+ import uuid
15
+
16
+ import httpx
17
+
18
+ BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/")
19
+ RUN_ID = uuid.uuid4().hex[:8]
20
+ PASSWORD = "QaCoach!2345"
21
+ BODY_KEYS = {"age", "height_cm", "weight_kg", "age_years"}
22
+
23
+ client = httpx.Client(base_url=BASE_URL, timeout=60)
24
+ results = {"pass": 0, "fail": 0}
25
+ failures: list[str] = []
26
+ created_accounts: list[dict] = []
27
+ _n = 0
28
+
29
+ PAYLOAD = {
30
+ "schema_version": "1.0", "analysis_id": "analysis_001", "analysis_revision": 1, "swing_id": "swing_001",
31
+ "status": "completed",
32
+ "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left",
33
+ "age_years": None, "height_cm": None},
34
+ "context": {"sport": "baseball", "practice_type": "tee"},
35
+ "measurement_definitions_version": "1.0",
36
+ "events": {
37
+ "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"},
38
+ "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available",
39
+ "source": "manual_review"},
40
+ "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None,
41
+ "reasons": ["contact_not_verified"]},
42
+ },
43
+ "measurements": [
44
+ {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 28, "unit": "deg",
45
+ "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading",
46
+ "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [],
47
+ "benchmark": None},
48
+ {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm",
49
+ "start_event_id": "stride_start", "end_event_id": "front_foot_down",
50
+ "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None,
51
+ "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None},
52
+ {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None,
53
+ "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading",
54
+ "status": "unavailable", "confidence": None, "uses_interpolated_input": False,
55
+ "reasons": ["contact_not_verified"], "benchmark": None},
56
+ ],
57
+ }
58
+
59
+ VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 2000
60
+ JPEG_BYTES = b"\xff\xd8\xff\xe0" + b"\x00" * 500 + b"\xff\xd9"
61
+
62
+
63
+ # ---------------------------------------------------------------- helpers
64
+
65
+ def body_of(r: httpx.Response):
66
+ try:
67
+ return r.json()
68
+ except Exception:
69
+ return r.text
70
+
71
+
72
+ def check(name: str, ok: bool, r: httpx.Response | None = None, detail: str = "") -> bool:
73
+ req = ""
74
+ if r is not None:
75
+ q = r.request.url.query.decode() if r.request.url.query else ""
76
+ if "X-Amz" in q:
77
+ q = "<presigned>"
78
+ req = f"{r.request.method} {r.request.url.path}{'?' + q if q else ''} -> {r.status_code}"
79
+ if ok:
80
+ results["pass"] += 1
81
+ print(f"PASS {name} [{req}]")
82
+ else:
83
+ results["fail"] += 1
84
+ body = json.dumps(body_of(r))[:1500] if r is not None else ""
85
+ line = f"FAIL {name} [{req}] {detail} body={body}"
86
+ failures.append(line)
87
+ print(line)
88
+ return ok
89
+
90
+
91
+ def h(tok: str | None) -> dict:
92
+ return {"Authorization": f"Bearer {tok}"} if tok else {}
93
+
94
+
95
+ def call(method: str, path: str, tok: str | None = None, **kw) -> httpx.Response:
96
+ r = client.request(method, path, headers={**h(tok), **kw.pop("headers", {})}, **kw)
97
+ if r.status_code >= 500:
98
+ check(f"no 5xx on {method} {path}", False, r)
99
+ return r
100
+
101
+
102
+ def find_keys(obj, keys: set[str], path="$") -> list[str]:
103
+ hits = []
104
+ if isinstance(obj, dict):
105
+ for k, v in obj.items():
106
+ if k in keys:
107
+ hits.append(f"{path}.{k}")
108
+ hits += find_keys(v, keys, f"{path}.{k}")
109
+ elif isinstance(obj, list):
110
+ for i, v in enumerate(obj):
111
+ hits += find_keys(v, keys, f"{path}[{i}]")
112
+ return hits
113
+
114
+
115
+ CAMEL = re.compile(r"^[a-z]+[A-Z]")
116
+ # Report payload carries free-form ids as values, not keys; keys of verdicts are metric ids (snake_case).
117
+
118
+
119
+ def camel_keys(obj, path="$") -> list[str]:
120
+ hits = []
121
+ if isinstance(obj, dict):
122
+ for k, v in obj.items():
123
+ if isinstance(k, str) and CAMEL.match(k):
124
+ hits.append(f"{path}.{k}")
125
+ hits += camel_keys(v, f"{path}.{k}")
126
+ elif isinstance(obj, list):
127
+ for i, v in enumerate(obj):
128
+ hits += camel_keys(v, f"{path}[{i}]")
129
+ return hits
130
+
131
+
132
+ def no_camel(name: str, r: httpx.Response):
133
+ hits = camel_keys(body_of(r))
134
+ check(f"{name}: snake_case keys only", not hits, r, f"camelCase keys: {hits[:10]}")
135
+
136
+
137
+ def register(role: str, name: str) -> dict:
138
+ global _n
139
+ _n += 1
140
+ email = f"qa-coach-{RUN_ID}-{_n}@example.com"
141
+ r = call("POST", "/v1/auth/register", json={"email": email, "password": PASSWORD, "role": role})
142
+ if not check(f"register {role} {name}", r.status_code == 201, r):
143
+ raise SystemExit("cannot register; aborting")
144
+ data = r.json()
145
+ acct = {"email": email, "token": data["tokens"]["access_token"], "id": data["user"]["id"], "name": name,
146
+ "role": role}
147
+ created_accounts.append(acct)
148
+ return acct
149
+
150
+
151
+ def set_profile(acct: dict, player: bool):
152
+ profile = {"name": acct["name"]}
153
+ if player:
154
+ profile.update({"age": 15, "height_cm": 168, "weight_kg": 60, "bats": "R", "throws": "R",
155
+ "level": "high_school"})
156
+ r = call("PATCH", "/v1/me", acct["token"], json={"focus": "h", "profile": profile})
157
+ check(f"PATCH /me profile {acct['name']}", r.status_code == 200, r)
158
+
159
+
160
+ def upload(acct: dict, kind: str) -> str:
161
+ data = VIDEO_BYTES if kind == "video" else JPEG_BYTES
162
+ ctype = "video/mp4" if kind == "video" else "image/jpeg"
163
+ body = {"kind": kind, "content_type": ctype, "size_bytes": len(data)}
164
+ if kind == "video":
165
+ body["duration_sec"] = 3.0
166
+ r = call("POST", "/v1/uploads", acct["token"], json=body)
167
+ if not check(f"POST /uploads {kind} ({acct['name']})", r.status_code in (200, 201), r):
168
+ raise RuntimeError("upload failed")
169
+ out = r.json()
170
+ out = out.get("upload", out)
171
+ put = httpx.put(out["url"], content=data, headers=out.get("headers") or {"Content-Type": ctype}, timeout=60)
172
+ check(f"PUT presigned {kind} ({acct['name']})", put.status_code in (200, 201, 204), put)
173
+ return out["upload_id"]
174
+
175
+
176
+ def make_session(acct: dict, *, is_self=True, analyse=True, tag="") -> dict:
177
+ vid, thumb = upload(acct, "video"), upload(acct, "thumbnail")
178
+ body = {"video_upload_id": vid, "thumbnail_upload_id": thumb, "mode": "h", "is_self": is_self,
179
+ "athlete": None if is_self else {"name": "Cousin Ray", "age": 12, "height_cm": 150, "weight_kg": 45,
180
+ "bats": "L", "throws": "L", "level": "youth"},
181
+ "duration_sec": 3.0, "fps": 30,
182
+ "marks": {"contact_frame": 70, "contact_offset": 0, "contact_source": "manual",
183
+ "stride_start_frame": 30, "stride_end_frame": 50,
184
+ "pitcher_direction": {"from": [0.1, 0.5], "to": [0.9, 0.5]}}}
185
+ r = call("POST", "/v1/sessions", acct["token"], json=body)
186
+ if not check(f"POST /sessions {tag}", r.status_code == 201, r):
187
+ raise RuntimeError("session create failed")
188
+ s = r.json()["session"]
189
+ check(f"new session {tag} is pending", s["status"] == "pending" and s["report"] is None, r)
190
+ if analyse:
191
+ p = copy.deepcopy(PAYLOAD)
192
+ p["analysis_id"] = f"qa_{RUN_ID}_{tag}"
193
+ p["swing_id"] = f"swing_{RUN_ID}_{tag}"
194
+ # vary the value a bit so scores/deltas differ
195
+ p["measurements"][0]["value"] = {"a": 28, "b": 45, "c": 10}.get(tag[-1:], 28)
196
+ r = call("POST", f"/v1/sessions/{s['id']}/swing-report", acct["token"], json=p)
197
+ check(f"POST swing-report {tag}", r.status_code == 200, r)
198
+ s["report"] = r.json() if r.status_code == 200 else None
199
+ time.sleep(1.1) # distinct created_at for ordering checks
200
+ return s
201
+
202
+
203
+ # ---------------------------------------------------------------- the suite
204
+
205
+ def run():
206
+ # 1. Setup ----------------------------------------------------------
207
+ coach_a = register("coach", "Coach Alpha")
208
+ coach_b = register("coach", "Coach Bravo")
209
+ p1 = register("player", "Pat One")
210
+ p2 = register("player", "Quinn Two")
211
+ p3 = register("player", "Riley Three")
212
+ p4 = register("player", "Sam Four") # on A's team, never films
213
+ for a in (coach_a, coach_b):
214
+ set_profile(a, False)
215
+ for p in (p1, p2, p3, p4):
216
+ set_profile(p, True)
217
+
218
+ r = call("POST", "/v1/teams", coach_a["token"], json={"name": "QA Alphas", "coach_name": "Coach Alpha",
219
+ "coaching": "h"})
220
+ check("coach A creates team", r.status_code == 201, r)
221
+ code_a = r.json()["team"]["code"]
222
+ r = call("POST", "/v1/teams", coach_b["token"], json={"name": "QA Bravos", "coach_name": "Coach Bravo",
223
+ "coaching": "both"})
224
+ check("coach B creates team", r.status_code == 201, r)
225
+ code_b = r.json()["team"]["code"]
226
+ for p, code in ((p1, code_a), (p2, code_a), (p4, code_a), (p3, code_b)):
227
+ r = call("POST", f"/v1/teams/{code.lower()}/join", p["token"])
228
+ check(f"{p['name']} joins team (lowercased code)", r.status_code == 200, r)
229
+
230
+ # Sessions. Free plan = 3 analyses/week/owner.
231
+ p1_a = make_session(p1, tag="p1a") # oldest open
232
+ p2_a = make_session(p2, tag="p2a")
233
+ p1_b = make_session(p1, tag="p1b") # P1 newest self
234
+ p1_pending = make_session(p1, analyse=False, tag="p1pend") # pending ones don't count toward the plan
235
+ p1_other = make_session(p1, is_self=False, tag="p1oc") # someone else (3rd analysis for P1)
236
+ p2_pending = make_session(p2, analyse=False, tag="p2pend")
237
+ p3_a = make_session(p3, tag="p3a")
238
+
239
+ # D4 shape for comparison
240
+ r = call("GET", "/v1/sessions", p1["token"])
241
+ check("P1 GET /sessions 200", r.status_code == 200, r)
242
+ d4_items = r.json()["items"]
243
+ d4_keys = set(d4_items[0].keys()) if d4_items else set()
244
+ no_camel("D4 list", r)
245
+
246
+ # report metric ids & drill
247
+ report = p1_a["report"] or {}
248
+ metric_ids = [m["metric_id"] for m in report.get("measurements", [])]
249
+ check("report has metric_ids", len(metric_ids) == 3, r, f"metric_ids={metric_ids}")
250
+ drill_id = ((report.get("focus_area") or {}).get("drill") or {}).get("drill_id")
251
+ r = call("GET", "/v1/catalog/metrics?mode=h", p1["token"])
252
+ cat = body_of(r)
253
+ cat_drills = sorted(set(re.findall(r'"(?:drill_id|id)":\s*"(hit_\d+)"', json.dumps(cat))))
254
+ if not drill_id:
255
+ drill_id = cat_drills[0] if cat_drills else "hit_13"
256
+ print(f"INFO metric_ids={metric_ids} drill_id={drill_id} focus={report.get('focus_area', {}).get('display_name')}")
257
+
258
+ # 2. Roster (F1) ----------------------------------------------------
259
+ r = call("GET", "/v1/coach/roster", coach_a["token"])
260
+ check("F1 roster 200", r.status_code == 200, r)
261
+ roster = {i["id"]: i for i in r.json().get("items", [])}
262
+ check("F1 lists P1, P2, P4 and not P3", {p1["id"], p2["id"], p4["id"]} == set(roster), r,
263
+ f"ids={list(roster)}")
264
+ no_camel("F1 roster", r)
265
+ hits = find_keys(r.json(), BODY_KEYS)
266
+ check("F1 has no body data (age/height/weight)", not hits, r, f"found {hits}")
267
+ raw = r.text
268
+ check("F1 raw JSON has no 168/60 body values as keys", '"height' not in raw and '"weight' not in raw, r)
269
+ i1 = roster.get(p1["id"], {})
270
+ check("F1 P1 pending_count == 2", i1.get("pending_count") == 2, r, f"got {i1.get('pending_count')}")
271
+ last_h = (i1.get("last") or {}).get("h") or {}
272
+ check("F1 P1 last.h is newest self session", last_h.get("session_id") == p1_b["id"], r, f"last.h={last_h}")
273
+ exp_delta = (p1_b["report"] or {}).get("overall_score", 0) - (p1_a["report"] or {}).get("overall_score", 0)
274
+ check("F1 P1 last.h delta = newest - previous", last_h.get("delta") == exp_delta, r,
275
+ f"expected {exp_delta} got {last_h.get('delta')}")
276
+ check("F1 P1 last.h score + focus_name", last_h.get("overall_score") == p1_b["report"]["overall_score"]
277
+ and last_h.get("focus_name") == (p1_b["report"].get("focus_area") or {}).get("display_name"), r)
278
+ check("F1 P1 recent.h newest first",
279
+ (i1.get("recent") or {}).get("h") == [p1_b["report"]["overall_score"], p1_a["report"]["overall_score"]],
280
+ r, f"recent={i1.get('recent')}")
281
+ i2 = roster.get(p2["id"], {})
282
+ check("F1 P2 pending_count == 1 (pending session not counted)", i2.get("pending_count") == 1, r)
283
+ i4 = roster.get(p4["id"], {})
284
+ check("F1 P4 (not filmed) last.h null", (i4.get("last") or {}).get("h") is None and i4.get("pending_count") == 0,
285
+ r, f"P4={i4}")
286
+
287
+ r = call("GET", "/v1/coach/roster", coach_b["token"])
288
+ check("F1 coach B sees only P3", [i["id"] for i in r.json().get("items", [])] == [p3["id"]], r)
289
+
290
+ # 3. Queue (F3) -----------------------------------------------------
291
+ r = call("GET", "/v1/coach/queue", coach_a["token"])
292
+ check("F3 queue 200", r.status_code == 200, r)
293
+ q = r.json()
294
+ no_camel("F3 queue", r)
295
+ hits = find_keys(q, BODY_KEYS)
296
+ check("F3 has no body data", not hits, r, f"found {hits}")
297
+ open_ids = [i["id"] for i in q.get("open", [])]
298
+ check("F3 open = [p1a, p2a, p1b] oldest first", open_ids == [p1_a["id"], p2_a["id"], p1_b["id"]], r,
299
+ f"open={open_ids}")
300
+ check("F3 someone-else session absent", p1_other["id"] not in open_ids, r)
301
+ check("F3 pending sessions absent", p1_pending["id"] not in open_ids and p2_pending["id"] not in open_ids, r)
302
+ check("F3 P3 session absent", p3_a["id"] not in open_ids, r)
303
+ check("F3 owner_name set", all(i.get("owner_name") == {p1["id"]: p1["name"], p2["id"]: p2["name"]}.get(
304
+ i["owner_id"]) for i in q.get("open", [])), r)
305
+ check("F3 reviewed_today empty", q.get("reviewed_today") == [], r)
306
+ if q.get("open"):
307
+ qkeys = set(q["open"][0].keys())
308
+ check("F3 item keys == D4 keys + owner_name", qkeys == d4_keys | {"owner_name"}, r,
309
+ f"diff={qkeys ^ (d4_keys | {'owner_name'})}")
310
+ check("F3 item has focus + thumbnail_url", q["open"][0].get("focus") is not None
311
+ and q["open"][0].get("thumbnail_url"), r)
312
+
313
+ # 4. Coach access ---------------------------------------------------
314
+ r = call("GET", f"/v1/sessions/{p1_a['id']}", coach_a["token"])
315
+ check("D3 coach A reads P1 self session", r.status_code == 200, r)
316
+ if r.status_code == 200:
317
+ s = r.json()["session"]
318
+ check("D3 coach view has report", bool(s.get("report")) and s["status"] == "done", r)
319
+ no_camel("D3 (coach)", r)
320
+ hits = find_keys(s, BODY_KEYS)
321
+ check("D3 coach response has no body data (spec 7.7/11: no body data in coach responses)", not hits, r,
322
+ f"found {hits} athlete={s.get('athlete')}")
323
+ media = s.get("media") or {}
324
+ v = httpx.get(media.get("video_url", "http://invalid"), timeout=60)
325
+ check("D3 video_url downloads the uploaded bytes", v.status_code == 200 and v.content == VIDEO_BYTES, v)
326
+ t = httpx.get(media.get("thumbnail_url") or "http://invalid", timeout=60)
327
+ check("D3 thumbnail_url downloads the uploaded bytes", t.status_code == 200 and t.content == JPEG_BYTES, t)
328
+ r = call("GET", f"/v1/sessions/{p1_other['id']}", coach_a["token"])
329
+ check("D3 coach A cannot read P1's someone-else session (403)", r.status_code == 403, r)
330
+ r = call("GET", f"/v1/sessions/{p1_pending['id']}", coach_a["token"])
331
+ print(f"INFO D3 coach A on P1 pending self session -> {r.status_code}")
332
+ r = call("GET", f"/v1/sessions/{p3_a['id']}", coach_a["token"])
333
+ check("D3 coach A cannot read P3 session (403)", r.status_code == 403, r)
334
+ r = call("GET", f"/v1/sessions/{p1_a['id']}", p2["token"])
335
+ check("D3 teammate P2 cannot read P1 session (403)", r.status_code == 403, r)
336
+ r = call("GET", f"/v1/sessions/{p1_a['id']}", coach_b["token"])
337
+ check("D3 coach B cannot read P1 session (403)", r.status_code == 403, r)
338
+ r = call("GET", f"/v1/sessions/{uuid.uuid4()}", coach_a["token"])
339
+ check("D3 unknown id -> 404", r.status_code == 404, r)
340
+
341
+ r = call("GET", f"/v1/coach/players/{p1['id']}/sessions", coach_a["token"])
342
+ check("F2 P1 sessions 200", r.status_code == 200, r)
343
+ f2 = r.json()
344
+ f2_ids = [i["id"] for i in f2.get("items", [])]
345
+ check("F2 lists only analysed self sessions newest first", f2_ids == [p1_b["id"], p1_a["id"]], r,
346
+ f"ids={f2_ids}")
347
+ no_camel("F2", r)
348
+ check("F2 has no body data", not find_keys(f2, BODY_KEYS), r)
349
+ if f2.get("items"):
350
+ check("F2 item keys == D4 keys", set(f2["items"][0]) == d4_keys, r,
351
+ f"diff={set(f2['items'][0]) ^ d4_keys}")
352
+ r = call("GET", f"/v1/coach/players/{p1['id']}/sessions?limit=1", coach_a["token"])
353
+ pg = r.json()
354
+ check("F2 limit=1 returns 1 item + next_cursor", len(pg.get("items", [])) == 1 and pg.get("next_cursor"), r)
355
+ if pg.get("next_cursor"):
356
+ r2 = call("GET", f"/v1/coach/players/{p1['id']}/sessions", coach_a["token"],
357
+ params={"limit": 1, "cursor": pg["next_cursor"]})
358
+ pg2 = r2.json()
359
+ check("F2 cursor page 2 = older session, then end",
360
+ [i["id"] for i in pg2.get("items", [])] == [p1_a["id"]] and pg2.get("next_cursor") is None, r2)
361
+ r = call("GET", f"/v1/coach/players/{p1['id']}/sessions?mode=p", coach_a["token"])
362
+ check("F2 mode=p -> empty", r.status_code == 200 and r.json()["items"] == [], r)
363
+ r = call("GET", f"/v1/coach/players/{p3['id']}/sessions", coach_a["token"])
364
+ check("F2 P3 via coach A -> 404 PLAYER_NOT_ON_TEAM", r.status_code == 404
365
+ and (body_of(r).get("error") or {}).get("code") == "PLAYER_NOT_ON_TEAM", r)
366
+ r = call("GET", f"/v1/coach/players/{coach_a['id']}/sessions", coach_a["token"])
367
+ check("F2 coach's own id -> 404", r.status_code == 404, r)
368
+
369
+ # 8. Push device (before review) -----------------------------------
370
+ token = f"qa-fcm-{RUN_ID}-" + "x" * 40
371
+ r = call("POST", "/v1/devices", p1["token"], json={"platform": "ios", "push_token": token})
372
+ check("B3 P1 registers device", r.status_code == 201, r)
373
+ no_camel("B3", r)
374
+ r = call("POST", "/v1/devices", p1["token"], json={"platform": "ios", "push_token": token})
375
+ check("B3 re-register same token -> 200", r.status_code == 200, r)
376
+
377
+ # 5. Review (F4) ----------------------------------------------------
378
+ verdicts = {metric_ids[0]: "agree", metric_ids[1]: "change"} if len(metric_ids) >= 2 else {}
379
+ rev_body = {"cue": "Stay closed a beat longer.", "drill_id": drill_id, "verdicts": verdicts}
380
+ r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_a["token"], json=rev_body)
381
+ check("F4 first review -> 201 (with device registered, FCM unconfigured)", r.status_code == 201, r)
382
+ no_camel("F4", r)
383
+ rv = (body_of(r) or {}).get("review", {}) if r.status_code in (200, 201) else {}
384
+ check("F4 review shape", set(rv) == {"coach_id", "coach_name", "cue", "drill_id", "verdicts", "at"}
385
+ and rv.get("coach_id") == coach_a["id"] and rv.get("coach_name") == coach_a["name"]
386
+ and rv.get("verdicts") == verdicts and rv.get("drill_id") == drill_id, r)
387
+ first_at = rv.get("at")
388
+ time.sleep(1.1)
389
+ rev2 = {"cue": "Load into the back hip.", "drill_id": drill_id, "verdicts": {metric_ids[0]: "later"}}
390
+ r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_a["token"], json=rev2)
391
+ check("F4 resend -> 200 overwrite", r.status_code == 200 and r.json()["review"]["cue"] == rev2["cue"]
392
+ and r.json()["review"]["verdicts"] == rev2["verdicts"], r)
393
+ check("F4 overwrite bumps at", r.status_code == 200 and r.json()["review"]["at"] != first_at, r)
394
+
395
+ def expect_400(name, body, field_hint=None):
396
+ rr = call("POST", f"/v1/sessions/{p1_b['id']}/review", coach_a["token"], json=body)
397
+ err = (body_of(rr) or {}).get("error", {}) if isinstance(body_of(rr), dict) else {}
398
+ ok = rr.status_code == 400 and err.get("code") == "VALIDATION"
399
+ if ok and field_hint:
400
+ ok = any(field_hint in k for k in (err.get("fields") or {}))
401
+ check(name, ok, rr)
402
+
403
+ expect_400("F4 invalid drill id -> 400 VALIDATION", {**rev_body, "drill_id": "hit_9999"}, "drill_id")
404
+ expect_400("F4 pitching drill on hitting session -> 400", {**rev_body, "drill_id": "pit_01"}, "drill_id")
405
+ expect_400("F4 verdict key not in report -> 400", {**rev_body, "verdicts": {"pelvis": "agree"}}, "verdicts")
406
+ expect_400("F4 verdict value invalid -> 400", {**rev_body, "verdicts": {metric_ids[0]: "maybe"}}, "verdicts")
407
+ expect_400("F4 cue too long -> 400", {**rev_body, "cue": "x" * 201}, "cue")
408
+ expect_400("F4 empty cue -> 400", {**rev_body, "cue": ""}, "cue")
409
+ expect_400("F4 unknown field -> 400", {**rev_body, "extra": 1})
410
+ expect_400("F4 missing drill_id -> 400", {"cue": "hi", "verdicts": {}}, "drill_id")
411
+ r = call("POST", f"/v1/sessions/{p1_b['id']}/review", coach_a["token"],
412
+ json={**rev_body, "cue": "x" * 200, "verdicts": {}})
413
+ check("F4 cue of exactly 200 chars + empty verdicts accepted (201)", r.status_code == 201, r)
414
+ # undo: p1_b is now reviewed. That's fine; keep tracking it.
415
+ r = call("POST", f"/v1/sessions/{p1_a['id']}/review", coach_b["token"], json=rev_body)
416
+ check("F4 coach B reviewing P1 session -> 403", r.status_code == 403, r)
417
+ r = call("POST", f"/v1/sessions/{p1_a['id']}/review", p1["token"], json=rev_body)
418
+ check("F4 player (owner) calling review -> 403", r.status_code == 403, r)
419
+ r = call("POST", f"/v1/sessions/{p1_pending['id']}/review", coach_a["token"], json=rev_body)
420
+ check("F4 pending session -> 4xx", 400 <= r.status_code < 500, r)
421
+ print(f"INFO F4 on pending session -> {r.status_code} {r.text[:200]}")
422
+ r = call("POST", f"/v1/sessions/{p1_other['id']}/review", coach_a["token"], json=rev_body)
423
+ check("F4 someone-else session -> 403", r.status_code == 403, r)
424
+ r = call("POST", f"/v1/sessions/{uuid.uuid4()}/review", coach_a["token"], json=rev_body)
425
+ check("F4 unknown session -> 404", r.status_code == 404, r)
426
+ r = call("POST", f"/v1/sessions/{p1_a['id']}/review", None, json=rev_body)
427
+ check("F4 no token -> 401", r.status_code == 401, r)
428
+
429
+ # 6. After review ---------------------------------------------------
430
+ r = call("GET", "/v1/coach/queue", coach_a["token"])
431
+ q = r.json()
432
+ open_ids = [i["id"] for i in q.get("open", [])]
433
+ rt_ids = [i["id"] for i in q.get("reviewed_today", [])]
434
+ check("F3 reviewed sessions left open", open_ids == [p2_a["id"]], r, f"open={open_ids}")
435
+ check("F3 reviewed_today has p1a & p1b", set(rt_ids) == {p1_a["id"], p1_b["id"]}, r, f"rt={rt_ids}")
436
+ rt = {i["id"]: i for i in q.get("reviewed_today", [])}
437
+ check("F3 reviewed_today item carries review summary",
438
+ (rt.get(p1_a["id"], {}).get("review") or {}).get("coach_name") == coach_a["name"], r)
439
+ r = call("GET", f"/v1/sessions/{p1_a['id']}", p1["token"])
440
+ rv = (r.json()["session"].get("review") or {}) if r.status_code == 200 else {}
441
+ check("D3 player sees review (latest overwrite)", rv.get("cue") == rev2["cue"]
442
+ and rv.get("coach_name") == coach_a["name"] and rv.get("drill_id") == drill_id, r)
443
+ r = call("GET", "/v1/sessions", p1["token"])
444
+ items = {i["id"]: i for i in r.json()["items"]}
445
+ rs = items.get(p1_a["id"], {}).get("review") or {}
446
+ check("D4 summary shows review {coach_name, at}", set(rs) == {"coach_name", "at"}
447
+ and rs.get("coach_name") == coach_a["name"], r, f"review={rs}")
448
+ check("D4 unreviewed summary review null", items.get(p1_other["id"], {}).get("review") is None, r)
449
+ r = call("GET", "/v1/coach/roster", coach_a["token"])
450
+ roster = {i["id"]: i for i in r.json()["items"]}
451
+ check("F1 P1 pending_count dropped to 0", roster.get(p1["id"], {}).get("pending_count") == 0, r)
452
+ check("F1 P2 pending_count still 1", roster.get(p2["id"], {}).get("pending_count") == 1, r)
453
+ r = call("GET", "/v1/coach/queue", coach_a["token"], params={"since": "2999-01-01T00:00:00Z"})
454
+ check("F3 since in future -> reviewed_today empty", r.status_code == 200 and r.json()["reviewed_today"] == [], r)
455
+
456
+ # 7. Leaving --------------------------------------------------------
457
+ r = call("DELETE", "/v1/me/team", p2["token"])
458
+ check("C4 P2 leaves team -> 204", r.status_code == 204, r)
459
+ r = call("GET", "/v1/coach/roster", coach_a["token"])
460
+ check("F1 P2 gone from roster", p2["id"] not in [i["id"] for i in r.json()["items"]], r)
461
+ r = call("GET", "/v1/coach/queue", coach_a["token"])
462
+ queue_items = r.json()["open"] + r.json()["reviewed_today"]
463
+ check("F3 P2 gone from queue", all(i["owner_id"] != p2["id"] for i in queue_items), r)
464
+ r = call("GET", f"/v1/sessions/{p2_a['id']}", coach_a["token"])
465
+ check("D3 coach A loses access to P2 session (403)", r.status_code == 403, r)
466
+ r = call("POST", f"/v1/sessions/{p2_a['id']}/review", coach_a["token"], json=rev_body)
467
+ check("F4 coach A cannot review ex-member P2 session (403)", r.status_code == 403, r)
468
+ r = call("GET", f"/v1/coach/players/{p2['id']}/sessions", coach_a["token"])
469
+ check("F2 ex-member -> 404 PLAYER_NOT_ON_TEAM", r.status_code == 404, r)
470
+ r = call("GET", "/v1/me", p2["token"])
471
+ check("B1 P2 team null after leaving", r.status_code == 200 and r.json().get("team") is None, r)
472
+ r = call("POST", f"/v1/teams/{code_a}/join", p2["token"])
473
+ check("C3 P2 rejoins", r.status_code == 200, r)
474
+ r = call("GET", "/v1/coach/queue", coach_a["token"])
475
+ check("F3 P2 session back in open after rejoin", p2_a["id"] in [i["id"] for i in r.json()["open"]], r)
476
+
477
+ # Player switching teams: P1's reviewed session must not be visible to coach B.
478
+ # (Not part of required list; covered implicitly by D3 coach B 403.)
479
+
480
+ # 9. Role/auth gates -----------------------------------------------
481
+ for path in ("/v1/coach/roster", "/v1/coach/queue", f"/v1/coach/players/{p1['id']}/sessions"):
482
+ r = call("GET", path, p1["token"])
483
+ check(f"{path} as player -> 403", r.status_code == 403, r)
484
+ r = call("GET", path)
485
+ check(f"{path} without token -> 401", r.status_code == 401, r)
486
+ r = call("GET", path, "not-a-jwt")
487
+ check(f"{path} bad token -> 401", r.status_code == 401, r)
488
+ r = call("POST", "/v1/devices", None, json={"platform": "ios", "push_token": "x"})
489
+ check("B3 without token -> 401", r.status_code == 401, r)
490
+ r = call("GET", "/v1/coach/players/not-a-uuid/sessions", coach_a["token"])
491
+ check("F2 bad uuid -> 4xx (not 500)", 400 <= r.status_code < 500, r)
492
+ r = call("GET", "/v1/coach/queue", coach_a["token"], params={"since": "garbage"})
493
+ check("F3 bad since -> 4xx", 400 <= r.status_code < 500, r)
494
+
495
+ # 8b. device token takeover (informational)
496
+ r = call("POST", "/v1/devices", p2["token"], json={"platform": "android", "push_token": token})
497
+ print(f"INFO B3 P2 registering P1's push token -> {r.status_code} (token reassigned silently if 200/201)")
498
+ r = call("DELETE", f"/v1/devices/{token}", p2["token"])
499
+ check("B4 delete device -> 204", r.status_code == 204, r)
500
+
501
+ # 10. Error envelope shape
502
+ r = call("GET", "/v1/coach/roster", p1["token"])
503
+ e = body_of(r)
504
+ check("error envelope {error:{code,message}}", isinstance(e, dict) and "error" in e
505
+ and {"code", "message"} <= set(e["error"]), r)
506
+
507
+
508
+ def cleanup():
509
+ print("---- cleanup")
510
+ for a in created_accounts:
511
+ r = client.delete("/v1/me", headers=h(a["token"]))
512
+ ok = r.status_code == 204
513
+ if not ok: # token may have expired; log in again
514
+ lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD})
515
+ if lr.status_code == 200:
516
+ r = client.delete("/v1/me", headers=h(lr.json()["tokens"]["access_token"]))
517
+ ok = r.status_code == 204
518
+ check(f"DELETE /me {a['email']}", ok, r)
519
+ lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD})
520
+ check(f"deleted account cannot log in {a['email']}", lr.status_code == 401, lr)
521
+
522
+
523
+ if __name__ == "__main__":
524
+ print(f"BASE_URL={BASE_URL} RUN_ID={RUN_ID}")
525
+ try:
526
+ run()
527
+ except Exception as exc: # noqa: BLE001
528
+ import traceback
529
+ traceback.print_exc()
530
+ results["fail"] += 1
531
+ failures.append(f"FAIL suite aborted: {exc!r}")
532
+ finally:
533
+ cleanup()
534
+ print(f"==== {results['pass']} passed, {results['fail']} failed")
535
+ for f in failures:
536
+ print(f)
537
+ sys.exit(1 if results["fail"] else 0)
backend/e2e/qa_sessions_reports.py ADDED
@@ -0,0 +1,962 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end QA suite: uploads, sessions, swing reports, plan limit, drills, catalog (journeys 3.3 / 3.4, milestone 2).
2
+
3
+ Runs against a live server (real database and real storage). Creates its own accounts and deletes them at the end.
4
+
5
+ BASE_URL=http://127.0.0.1:8000 .venv/bin/python e2e/qa_sessions_reports.py
6
+ """
7
+
8
+ import copy
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import uuid
14
+ from datetime import UTC, date, datetime, timedelta
15
+
16
+ import httpx
17
+
18
+ BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/")
19
+ RUN_ID = uuid.uuid4().hex[:8]
20
+ PASSWORD = "Qa-pass-12345"
21
+
22
+ VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00\x00\x00\x00mp42isom" + os.urandom(512)
23
+ JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00" + os.urandom(256) + b"\xff\xd9"
24
+
25
+ client = httpx.Client(base_url=BASE_URL, timeout=90)
26
+ raw = httpx.Client(timeout=60) # for presigned storage URLs
27
+
28
+ RESULTS = {"PASS": 0, "FAIL": 0}
29
+ FAILS: list[str] = []
30
+ NOTES: list[str] = []
31
+ CAMEL: set[str] = set()
32
+ FIVE_HUNDREDS: list[str] = []
33
+ FORBIDDEN_KEYS = {"password_hash", "password", "measurement_payload", "refresh_token_hash", "object_key"}
34
+ LEAKS: list[str] = []
35
+
36
+
37
+ # ---------------------------------------------------------------- helpers
38
+
39
+ def _short(text: str, n: int = 900) -> str:
40
+ return text if len(text) <= n else text[:n] + "..."
41
+
42
+
43
+ def check(name: str, ok: bool, resp: httpx.Response | None = None, detail: str = "") -> bool:
44
+ tag = "PASS" if ok else "FAIL"
45
+ RESULTS[tag] += 1
46
+ where = ""
47
+ if resp is not None:
48
+ where = f" [{resp.request.method} {resp.request.url.path} -> {resp.status_code}]"
49
+ line = f"{tag}: {name}{where}"
50
+ if not ok:
51
+ body = ""
52
+ if resp is not None:
53
+ body = _short(resp.text)
54
+ line += f"\n detail: {detail}" if detail else ""
55
+ line += f"\n body: {body}" if body else ""
56
+ FAILS.append(line)
57
+ print(line, flush=True)
58
+ return ok
59
+
60
+
61
+ def note(text: str) -> None:
62
+ NOTES.append(text)
63
+ print(f"NOTE: {text}", flush=True)
64
+
65
+
66
+ def scan_keys(obj, path="$", skip_children_of=("headers", "fields")):
67
+ if isinstance(obj, dict):
68
+ for k, v in obj.items():
69
+ if isinstance(k, str):
70
+ if re.search(r"[A-Z]", k) and not path.endswith(skip_children_of):
71
+ CAMEL.add(f"{path}.{k}")
72
+ if k in FORBIDDEN_KEYS:
73
+ LEAKS.append(f"{path}.{k}")
74
+ if k in skip_children_of:
75
+ continue
76
+ scan_keys(v, f"{path}.{k}")
77
+ elif isinstance(obj, list):
78
+ for v in obj[:50]:
79
+ scan_keys(v, f"{path}[]")
80
+
81
+
82
+ def call(method: str, path: str, token: str | None = None, **kw) -> httpx.Response:
83
+ headers = kw.pop("headers", {}) or {}
84
+ if token:
85
+ headers["Authorization"] = f"Bearer {token}"
86
+ r = client.request(method, path, headers=headers, **kw)
87
+ if r.status_code >= 500:
88
+ FIVE_HUNDREDS.append(f"{method} {path} -> {r.status_code}: {_short(r.text, 300)}")
89
+ try:
90
+ if r.content:
91
+ scan_keys(r.json(), f"{method} {re.sub(r'[0-9a-f-]{36}', '{id}', path)}")
92
+ except ValueError:
93
+ pass
94
+ return r
95
+
96
+
97
+ def err_code(r: httpx.Response) -> str | None:
98
+ try:
99
+ return r.json()["error"]["code"]
100
+ except Exception:
101
+ return None
102
+
103
+
104
+ def err_fields(r: httpx.Response) -> dict:
105
+ try:
106
+ return r.json()["error"].get("fields") or {}
107
+ except Exception:
108
+ return {}
109
+
110
+
111
+ def expect_error(name: str, r: httpx.Response, status: int, code: str | None = None, field_prefix: str | None = None):
112
+ ok = r.status_code == status and (code is None or err_code(r) == code)
113
+ detail = f"expected {status} {code or ''}"
114
+ if ok and field_prefix is not None:
115
+ ok = any(k.startswith(field_prefix) for k in err_fields(r))
116
+ detail += f" with a field starting {field_prefix!r}; got fields {list(err_fields(r))}"
117
+ return check(name, ok, r, detail)
118
+
119
+
120
+ ACCOUNTS: list[dict] = []
121
+ n_accounts = 0
122
+
123
+
124
+ def register(role: str = "player") -> dict:
125
+ global n_accounts
126
+ n_accounts += 1
127
+ email = f"qa-sess-{RUN_ID}-{n_accounts}@example.com"
128
+ r = call("POST", "/v1/auth/register", json={"email": email, "password": PASSWORD, "role": role})
129
+ if not check(f"register {email}", r.status_code == 201, r, "expected 201"):
130
+ raise SystemExit("cannot continue without an account")
131
+ data = r.json()
132
+ acct = {"email": email, "token": data["tokens"]["access_token"], "id": data["user"]["id"], "deleted": False}
133
+ ACCOUNTS.append(acct)
134
+ return acct
135
+
136
+
137
+ def set_profile(acct: dict, **profile) -> httpx.Response:
138
+ r = call("PATCH", "/v1/me", acct["token"], json={"profile": profile})
139
+ check(f"PATCH /me profile {profile.get('name')}", r.status_code == 200, r, "expected 200")
140
+ return r
141
+
142
+
143
+ def presign(acct, kind="video", content_type=None, size=None, duration=3.0) -> httpx.Response:
144
+ body = {"kind": kind, "content_type": content_type or ("video/mp4" if kind == "video" else "image/jpeg"),
145
+ "size_bytes": size if size is not None else (len(VIDEO_BYTES) if kind == "video" else len(JPEG_BYTES))}
146
+ if kind == "video" and duration is not None:
147
+ body["duration_sec"] = duration
148
+ return call("POST", "/v1/uploads", acct["token"], json=body)
149
+
150
+
151
+ def put_object(upload: dict, data: bytes, headers: dict | None = None) -> httpx.Response:
152
+ return raw.put(upload["url"], content=data, headers=headers if headers is not None else upload["headers"])
153
+
154
+
155
+ def uploaded(acct, kind="video", data=None) -> dict:
156
+ r = presign(acct, kind)
157
+ if r.status_code != 201:
158
+ check(f"presign {kind}", False, r, "expected 201")
159
+ raise SystemExit("presign failed")
160
+ up = r.json()
161
+ p = put_object(up, data if data is not None else (VIDEO_BYTES if kind == "video" else JPEG_BYTES))
162
+ if p.status_code not in (200, 204):
163
+ check(f"PUT {kind} to storage", False, None, f"storage returned {p.status_code}: {p.text[:300]}")
164
+ raise SystemExit("storage PUT failed")
165
+ return up
166
+
167
+
168
+ def marks(**over):
169
+ m = {"contact_frame": 80, "contact_offset": 0, "contact_source": "detected", "stride_start_frame": 30,
170
+ "stride_end_frame": 60, "pitcher_direction": {"from": [0.3, 0.5], "to": [0.7, 0.5]}}
171
+ m.update(over)
172
+ return m
173
+
174
+
175
+ def session_body(video_id, thumb_id=None, mode="h", is_self=True, athlete=None, **over):
176
+ b = {"video_upload_id": video_id, "thumbnail_upload_id": thumb_id, "mode": mode, "is_self": is_self,
177
+ "athlete": athlete, "duration_sec": 3.0, "fps": 30, "marks": marks()}
178
+ b.update(over)
179
+ return b
180
+
181
+
182
+ def new_session(acct, name, mode="h", is_self=True, athlete=None, with_thumb=True, expect=201) -> dict | None:
183
+ v = uploaded(acct, "video")
184
+ t = uploaded(acct, "thumbnail") if with_thumb else None
185
+ r = call("POST", "/v1/sessions", acct["token"],
186
+ json=session_body(v["upload_id"], t["upload_id"] if t else None, mode, is_self, athlete))
187
+ if not check(f"create session {name}", r.status_code == expect, r, f"expected {expect}"):
188
+ return None
189
+ s = r.json()["session"]
190
+ s["_video_upload"] = v
191
+ return s
192
+
193
+
194
+ # ---------------------------------------------------------------- ML payload
195
+
196
+ BASE_PAYLOAD = {
197
+ "schema_version": "1.0",
198
+ "analysis_id": "analysis_001",
199
+ "analysis_revision": 1,
200
+ "swing_id": "swing_001",
201
+ "status": "completed",
202
+ "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left", "age_years": None,
203
+ "height_cm": None},
204
+ "context": {"sport": "baseball", "practice_type": "tee"},
205
+ "measurement_definitions_version": "1.0",
206
+ "events": {
207
+ "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"},
208
+ "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available",
209
+ "source": "manual_review"},
210
+ "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None,
211
+ "reasons": ["contact_not_verified"]},
212
+ },
213
+ "measurements": [
214
+ {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 28, "unit": "deg",
215
+ "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading",
216
+ "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [],
217
+ "benchmark": None},
218
+ {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm",
219
+ "start_event_id": "stride_start", "end_event_id": "front_foot_down",
220
+ "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None,
221
+ "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None},
222
+ {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None,
223
+ "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading",
224
+ "status": "unavailable", "confidence": None, "uses_interpolated_input": False,
225
+ "reasons": ["contact_not_verified"], "benchmark": None},
226
+ ],
227
+ }
228
+
229
+
230
+ def payload(sep=3, analysis_id=None, rev=1, hand="right", lead="left", stride=24):
231
+ p = copy.deepcopy(BASE_PAYLOAD)
232
+ p["analysis_id"] = analysis_id or f"analysis-{RUN_ID}-{uuid.uuid4().hex[:6]}"
233
+ p["analysis_revision"] = rev
234
+ p["athlete"]["batting_hand"] = hand
235
+ p["athlete"]["lead_foot"] = lead
236
+ p["measurements"][0]["value"] = sep
237
+ p["measurements"][1]["value"] = stride
238
+ return p
239
+
240
+
241
+ def post_report(acct, sid, body, **kw) -> httpx.Response:
242
+ return call("POST", f"/v1/sessions/{sid}/swing-report", acct["token"], json=body, **kw)
243
+
244
+
245
+ TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overview", "groups",
246
+ "focus_area", "measurements", "data_quality", "meta"}
247
+ GROUP_ORDER = ["balance_load", "stride", "power_move", "contact_follow_through"]
248
+
249
+
250
+ def rating_for(score):
251
+ if score is None:
252
+ return "not_rated"
253
+ if score == 100:
254
+ return "on_target"
255
+ if score >= 70:
256
+ return "satisfactory"
257
+ return "off_target"
258
+
259
+
260
+ def text_fields(rep: dict):
261
+ """(path, text) for every prose field that must contain no digits."""
262
+ yield "overview.headline", rep["overview"].get("headline")
263
+ for g in rep["groups"]:
264
+ yield f"groups.{g['group']}.summary", g.get("summary")
265
+ yield f"groups.{g['group']}.rating_label", g.get("rating_label")
266
+ yield f"groups.{g['group']}.display_name", g.get("display_name")
267
+ fa = rep.get("focus_area")
268
+ if fa:
269
+ for k in ("coach_message", "practice_feel", "display_name", "rating_label"):
270
+ yield f"focus_area.{k}", fa.get(k)
271
+ if fa.get("drill"):
272
+ for k in ("name", "how", "cue"):
273
+ yield f"focus_area.drill.{k}", fa["drill"].get(k)
274
+ for m in rep["measurements"]:
275
+ for k in ("display_name", "what_it_means", "result_text", "coach_tip", "rating_label"):
276
+ yield f"measurements.{m['metric_id']}.{k}", m.get(k)
277
+ for lim in m.get("limitations") or []:
278
+ yield f"measurements.{m['metric_id']}.limitations.{lim.get('code')}", lim.get("text")
279
+ for dq in rep.get("data_quality") or []:
280
+ yield f"data_quality.{dq.get('code')}", dq.get("text")
281
+
282
+
283
+ def check_report_shape(name: str, r: httpx.Response) -> dict | None:
284
+ if not check(f"{name}: 200", r.status_code == 200, r, "expected 200"):
285
+ return None
286
+ rep = r.json()
287
+ check(f"{name}: exact top-level keys", set(rep) == TOP_KEYS, r,
288
+ f"extra={set(rep) - TOP_KEYS} missing={TOP_KEYS - set(rep)}")
289
+ groups = rep.get("groups") or []
290
+ check(f"{name}: 4 groups in fixed order", [g.get("group") for g in groups] == GROUP_ORDER, r,
291
+ f"got {[g.get('group') for g in groups]}")
292
+ ms = rep.get("measurements") or []
293
+ check(f"{name}: 3 measurements", len(ms) == 3 and len({m["metric_id"] for m in ms}) == 3, r)
294
+ by_id = {m["metric_id"]: m for m in ms}
295
+ for m in ms:
296
+ check(f"{name}: measurement {m['metric_id']} rating matches score ({m.get('score')} -> {m.get('rating')})",
297
+ m.get("rating") == rating_for(m.get("score")), r)
298
+ if m["status"] == "unavailable":
299
+ check(f"{name}: unavailable {m['metric_id']} is not_rated with null score/value/display_value",
300
+ m["rating"] == "not_rated" and m["score"] is None and m["value"] is None
301
+ and m["display_value"] is None and m["not_rated_reason"] == "measurement_unavailable", r)
302
+ if m["status"] == "limited":
303
+ check(f"{name}: limited {m['metric_id']} tentative with limitation text",
304
+ m.get("rating_is_tentative") is True and bool(m.get("limitations"))
305
+ and all(lim.get("text") for lim in m["limitations"]), r)
306
+ if m.get("score") is not None:
307
+ b = m.get("benchmark") or {}
308
+ check(f"{name}: rated {m['metric_id']} has benchmark population",
309
+ bool(b.get("population")) and "on_target" in b and "satisfactory" in b, r, json.dumps(b))
310
+ # group score = mean of available rated measurement scores; limited excluded
311
+ group_scores = []
312
+ for g in groups:
313
+ members = [by_id[mid] for mid in g.get("metric_ids", []) if mid in by_id]
314
+ avail = [m["score"] for m in members if m["status"] == "available" and m["score"] is not None]
315
+ expected = None if not avail else int(sum(avail) / len(avail) + 0.5)
316
+ if expected is not None and expected == 100 and any(s < 100 for s in avail):
317
+ expected = 99
318
+ check(f"{name}: group {g['group']} score excludes limited (expected {expected}, got {g.get('score')})",
319
+ g.get("score") == expected, r)
320
+ check(f"{name}: group {g['group']} rating matches score", g.get("rating") == rating_for(g.get("score")), r)
321
+ if g.get("score") is not None:
322
+ group_scores.append(g["score"])
323
+ exp_overall = None if not group_scores else int(sum(group_scores) / len(group_scores) + 0.5)
324
+ if exp_overall == 100 and any(s < 100 for s in group_scores):
325
+ exp_overall = 99
326
+ check(f"{name}: overall_score = mean of group scores ({exp_overall})", rep.get("overall_score") == exp_overall,
327
+ r, f"got {rep.get('overall_score')}")
328
+ fa = rep.get("focus_area")
329
+ if fa:
330
+ fm = by_id.get(fa.get("metric_id"), {})
331
+ check(f"{name}: focus area is an available, non-on-target measurement",
332
+ fm.get("status") == "available" and fm.get("rating") in ("off_target", "satisfactory"), r,
333
+ f"focus={fa.get('metric_id')} status={fm.get('status')} rating={fm.get('rating')}")
334
+ check(f"{name}: focus evidence cites its metric", fa.get("metric_id") in (fa.get("evidence_metric_ids") or []),
335
+ r)
336
+ bad = [(p, t) for p, t in text_fields(rep) if isinstance(t, str) and re.search(r"\d", t)]
337
+ check(f"{name}: no digits in text fields", not bad, r, f"digits in {bad}")
338
+ return rep
339
+
340
+
341
+ # ---------------------------------------------------------------- the suite
342
+
343
+ def run():
344
+ today = date.today()
345
+ # ------------------------------------------------------------ accounts
346
+ A = register()
347
+ set_profile(A, name="QA Alpha", age=20, height_cm=183, weight_kg=85, bats="R", throws="R", level="college")
348
+ B = register()
349
+ set_profile(B, name="QA Bravo", age=17, height_cm=175, weight_kg=70, bats="L", throws="L", level="college")
350
+ C = register() # fresh plan budget for idempotency, delete and the hand-fallback report
351
+ set_profile(C, name="QA Charlie", age=16, height_cm=170, weight_kg=65, bats="L", throws="L", level="high_school")
352
+
353
+ r = call("GET", "/v1/me", A["token"])
354
+ ent0 = r.json().get("entitlement", {}) if r.status_code == 200 else {}
355
+ check("GET /me entitlement starts free 3/0", ent0.get("plan") == "free" and ent0.get("weekly_limit") == 3
356
+ and ent0.get("used_this_week") == 0 and ent0.get("left") == 3, r, json.dumps(ent0))
357
+
358
+ # ------------------------------------------------------------ 1. uploads
359
+ r = presign(A, "video")
360
+ check("presign video 201 with url, headers, expires_at", r.status_code == 201 and {"upload_id", "url", "headers",
361
+ "expires_at"} <= set(r.json()), r)
362
+ vid = r.json()
363
+ p = put_object(vid, VIDEO_BYTES)
364
+ check(f"real PUT of video to Spaces succeeds ({p.status_code})", p.status_code in (200, 204), None,
365
+ p.text[:300])
366
+ r = presign(A, "thumbnail")
367
+ check("presign thumbnail 201", r.status_code == 201, r)
368
+ thumb = r.json()
369
+ p = put_object(thumb, JPEG_BYTES)
370
+ check(f"real PUT of thumbnail to Spaces succeeds ({p.status_code})", p.status_code in (200, 204), None,
371
+ p.text[:300])
372
+ r = presign(A, "video", content_type="video/quicktime")
373
+ check("presign video/quicktime accepted (iOS .mov)", r.status_code == 201, r)
374
+ expect_error("presign video with image/jpeg -> 400", presign(A, "video", content_type="image/jpeg"), 400,
375
+ "VALIDATION", "content_type")
376
+ expect_error("presign thumbnail with image/png -> 400", presign(A, "thumbnail", content_type="image/png"), 400,
377
+ "VALIDATION", "content_type")
378
+ expect_error("presign video 251 MB -> 413 TOO_LARGE", presign(A, "video", size=251 * 1024 * 1024), 413, "TOO_LARGE")
379
+ expect_error("presign thumbnail 6 MB -> 413 TOO_LARGE", presign(A, "thumbnail", size=6 * 1024 * 1024), 413,
380
+ "TOO_LARGE")
381
+ expect_error("presign video 61 s -> 400", presign(A, "video", duration=61), 400, "VALIDATION", "duration_sec")
382
+ expect_error("presign video without duration -> 400", presign(A, "video", duration=None), 400, "VALIDATION")
383
+ expect_error("presign size 0 -> 400", presign(A, "video", size=0), 400, "VALIDATION")
384
+ r = call("POST", "/v1/uploads", A["token"], json={"kind": "video", "contentType": "video/mp4", "bytes": 10,
385
+ "durationSec": 2})
386
+ expect_error("presign with camelCase (unknown) fields -> 400", r, 400, "VALIDATION")
387
+ expect_error("presign without auth -> 401", call("POST", "/v1/uploads", json={"kind": "video"}), 401,
388
+ "UNAUTHENTICATED")
389
+ # signed content type mismatch on PUT
390
+ up = presign(A, "video").json()
391
+ p = put_object(up, JPEG_BYTES, {"Content-Type": "image/jpeg"})
392
+ check(f"storage refuses PUT whose Content-Type differs from the signed one ({p.status_code})",
393
+ p.status_code in (400, 403), None, p.text[:200])
394
+
395
+ # ------------------------------------------------------------ 2. sessions
396
+ body = session_body(vid["upload_id"], thumb["upload_id"])
397
+ r = call("POST", "/v1/sessions", A["token"], json=body)
398
+ S1 = None
399
+ if check("create self session 201", r.status_code == 201, r):
400
+ S1 = r.json()["session"]
401
+ check("new session status pending, report null, analyzed_at null",
402
+ S1["status"] == "pending" and S1["report"] is None and S1["analyzed_at"] is None, r)
403
+ check("athlete snapshot = profile", S1["athlete"] == {"name": "QA Alpha", "age": 20, "height_cm": 183.0,
404
+ "weight_kg": 85.0, "bats": "R", "throws": "R", "level": "college"}, r, json.dumps(S1["athlete"]))
405
+ check("first session ordinal 1, previous null", S1["ordinal"] == 1 and S1["previous"] is None, r)
406
+ check("marks echoed with from/to", S1["marks"].get("pitcher_direction", {}).get("from") == [0.3, 0.5], r,
407
+ json.dumps(S1["marks"]))
408
+ g = raw.get(S1["media"]["video_url"])
409
+ check("video_url downloads the exact uploaded bytes", g.status_code == 200 and g.content == VIDEO_BYTES, None,
410
+ f"status {g.status_code}, len {len(g.content)}")
411
+ g = raw.get(S1["media"]["thumbnail_url"])
412
+ check("thumbnail_url downloads the exact uploaded bytes", g.status_code == 200 and g.content == JPEG_BYTES,
413
+ None, f"status {g.status_code}")
414
+ exp = datetime.fromisoformat(S1["media"]["expires_at"].replace("Z", "+00:00"))
415
+ check("media URLs live at least ~1 hour", exp - datetime.now(UTC) > timedelta(minutes=55), r)
416
+ A["video_url"] = S1["media"]["video_url"]
417
+ # reuse attached upload
418
+ expect_error("reuse of an attached upload -> 400",
419
+ call("POST", "/v1/sessions", A["token"], json=body), 400, "VALIDATION", "video_upload_id")
420
+ # thumbnail id used as video
421
+ t2 = uploaded(A, "thumbnail")
422
+ expect_error("thumbnail upload used as video_upload_id -> 400",
423
+ call("POST", "/v1/sessions", A["token"], json=session_body(t2["upload_id"])), 400, "VALIDATION",
424
+ "video_upload_id")
425
+ # other user's upload
426
+ vb = uploaded(B, "video")
427
+ expect_error("another user's upload id -> 400",
428
+ call("POST", "/v1/sessions", A["token"], json=session_body(vb["upload_id"])), 400, "VALIDATION",
429
+ "video_upload_id")
430
+ # upload never PUT
431
+ nv = presign(A, "video").json()
432
+ expect_error("upload not uploaded -> 422 UPLOAD_MISSING",
433
+ call("POST", "/v1/sessions", A["token"], json=session_body(nv["upload_id"])), 422, "UPLOAD_MISSING")
434
+ # JPEG bytes PUT to the video URL with the signed video/mp4 header: storage cannot tell; backend checks headers only
435
+ jv = presign(A, "video").json()
436
+ put_object(jv, JPEG_BYTES)
437
+ r = call("POST", "/v1/sessions", A["token"], json=session_body(jv["upload_id"]))
438
+ if r.status_code == 201:
439
+ note("A JPEG body PUT to a video upload with the signed 'video/mp4' header is accepted as a session video "
440
+ "(201). The backend validates the stored Content-Type and size only (HEAD), not the file bytes "
441
+ "(app/modules/sessions/service.py _verify_object). A different Content-Type cannot be stored because "
442
+ "it is part of the presigned signature. Session created; it counts as pending only.")
443
+ JUNK_SESSION = r.json()["session"]["id"]
444
+ call("DELETE", f"/v1/sessions/{JUNK_SESSION}", A["token"])
445
+ else:
446
+ note(f"JPEG bytes in a video upload: POST /v1/sessions -> {r.status_code} {err_code(r)}")
447
+
448
+ # mark validation (runs before any upload lookup, so a random upload id is fine)
449
+ rid = str(uuid.uuid4())
450
+ cases = [
451
+ ("stride start after stride end", dict(marks=marks(stride_start_frame=60, stride_end_frame=40)),
452
+ "marks.stride_end_frame"),
453
+ ("stride end after contact", dict(marks=marks(stride_end_frame=85, contact_frame=80)), "marks.contact_frame"),
454
+ ("contact frame beyond the last frame", dict(marks=marks(contact_frame=90)), "marks.contact_frame"),
455
+ ("negative stride start", dict(marks=marks(stride_start_frame=-1)), "marks.stride_start_frame"),
456
+ ("pitcher_direction too short", dict(marks=marks(pitcher_direction={"from": [0.5, 0.5], "to": [0.55, 0.5]})),
457
+ "marks.pitcher_direction"),
458
+ ("pitcher_direction point out of 0..1", dict(marks=marks(pitcher_direction={"from": [0.1, 0.5],
459
+ "to": [1.5, 0.5]})),
460
+ "marks.pitcher_direction"),
461
+ ("pitcher_direction negative", dict(marks=marks(pitcher_direction={"from": [-0.1, 0.5], "to": [0.7, 0.5]})),
462
+ "marks.pitcher_direction"),
463
+ ("contact_source invalid", dict(marks=marks(contact_source="audio")), "marks.contact_source"),
464
+ ("mode x", dict(mode="x"), "mode"),
465
+ ("duration 61 s", dict(duration_sec=61), "duration_sec"),
466
+ ("self with an athlete", dict(athlete={"name": "Some One", "age": 15, "height_cm": 170, "weight_kg": 60,
467
+ "bats": "R", "throws": "R", "level": "high_school"}), "athlete"),
468
+ ("someone else without athlete", dict(is_self=False), "athlete"),
469
+ ("someone else athlete missing weight", dict(is_self=False, athlete={"name": "Some One", "age": 15,
470
+ "height_cm": 170, "bats": "R",
471
+ "throws": "R", "level": "college"}),
472
+ "athlete.weight_kg"),
473
+ ("unknown field", dict(extra_field=1), "extra_field"),
474
+ ]
475
+ for label, over, field in cases:
476
+ b = session_body(rid)
477
+ b.update(over)
478
+ expect_error(f"session marks: {label} -> 400 with field {field}",
479
+ call("POST", "/v1/sessions", A["token"], json=b), 400, "VALIDATION", field)
480
+
481
+ # ------------------------------------------------------------ 3. swing report: spec example
482
+ rep1 = None
483
+ if S1:
484
+ p1 = payload(sep=3, analysis_id=f"analysis-{RUN_ID}-s1", rev=1)
485
+ r = post_report(A, S1["id"], p1)
486
+ rep1 = check_report_shape("spec example (R college, sep 3)", r)
487
+ if rep1:
488
+ by = {m["metric_id"]: m for m in rep1["measurements"]}
489
+ sep, stride, contact = (by["hip_shoulder_separation_at_foot_down"], by["stride_relative_length"],
490
+ by["hip_shoulder_separation_at_contact"])
491
+ check("spec: separation score 55 off_target", sep["score"] == 55 and sep["rating"] == "off_target", r,
492
+ json.dumps({k: sep.get(k) for k in ("score", "rating")}))
493
+ check("spec: separation display_value '3°'", sep["display_value"] == "3°", r, sep["display_value"])
494
+ check("spec: separation benchmark right/college",
495
+ (sep.get("benchmark") or {}).get("benchmark_id")
496
+ == "obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college"
497
+ and sep["benchmark"].get("on_target") == {"lower": -25.3, "upper": -8.5}, r,
498
+ json.dumps(sep.get("benchmark")))
499
+ check("spec: stride 24 limited -> score 100 on_target tentative",
500
+ stride["score"] == 100 and stride["rating"] == "on_target" and stride["rating_is_tentative"] is True,
501
+ r, json.dumps({k: stride.get(k) for k in ("score", "rating", "rating_is_tentative")}))
502
+ check("spec: contact unavailable -> not_rated", contact["rating"] == "not_rated", r)
503
+ check("spec: overall_score 55", rep1["overall_score"] == 55, r, str(rep1["overall_score"]))
504
+ g = {x["group"]: x for x in rep1["groups"]}
505
+ check("spec: stride group 55 off_target", g["stride"]["score"] == 55 and
506
+ g["stride"]["rating"] == "off_target", r)
507
+ check("spec: balance_load not_rated no_measurements_available",
508
+ g["balance_load"]["not_rated_reason"] == "no_measurements_available"
509
+ and g["balance_load"]["metric_ids"] == [], r)
510
+ check("spec: contact group not_rated measurements_unavailable",
511
+ g["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable", r)
512
+ fa = rep1.get("focus_area") or {}
513
+ check("spec: focus hip_shoulder_separation_at_foot_down with drill hit_13",
514
+ fa.get("metric_id") == "hip_shoulder_separation_at_foot_down"
515
+ and (fa.get("drill") or {}).get("drill_id") == "hit_13", r, json.dumps(fa)[:300])
516
+ check("spec: analysis_id/revision echoed", rep1["analysis_id"] == p1["analysis_id"]
517
+ and rep1["analysis_revision"] == 1, r)
518
+ check("spec: data_quality has contact_not_verified and scale_is_model_estimated",
519
+ {"contact_not_verified", "scale_is_model_estimated"} <= {d["code"] for d in rep1["data_quality"]},
520
+ r)
521
+ check("meta has generated_at, text_source, versions",
522
+ all(k in rep1["meta"] for k in ("generated_at", "text_source", "input_schema_version",
523
+ "benchmark_registry_version", "coaching_rules_version")), r)
524
+ print(f" (meta.text_source={rep1['meta'].get('text_source')}, model={rep1['meta'].get('model')}, "
525
+ f"fallback_reason={rep1['meta'].get('fallback_reason')})")
526
+
527
+ # same id+rev -> identical report, no rebuild
528
+ r = post_report(A, S1["id"], p1)
529
+ check("same analysis_id+revision -> identical stored report (generated_at unchanged)",
530
+ r.status_code == 200 and r.json() == rep1, r)
531
+ # same id+rev with a different body -> stored report (documented)
532
+ p1b = copy.deepcopy(p1)
533
+ p1b["measurements"][0]["value"] = -15
534
+ r = post_report(A, S1["id"], p1b)
535
+ check("same id+revision with different values -> still the stored report", r.status_code == 200
536
+ and r.json() == rep1, r)
537
+ # revision 2 -> rebuilt
538
+ p2 = copy.deepcopy(p1)
539
+ p2["analysis_revision"] = 2
540
+ p2["measurements"][0]["value"] = -15 # inside on-target
541
+ r = post_report(A, S1["id"], p2)
542
+ rep1v2 = check_report_shape("revision 2 rebuild", r)
543
+ if rep1v2 and rep1:
544
+ check("revision 2 rebuilt (revision 2, new generated_at, separation now on_target)",
545
+ rep1v2["analysis_revision"] == 2 and rep1v2["meta"]["generated_at"] != rep1["meta"]["generated_at"]
546
+ and rep1v2["measurements"][0]["rating"] == "on_target", r)
547
+ check("all on-target available -> focus_area null and headline present",
548
+ rep1v2["focus_area"] is None and bool(rep1v2["overview"]["headline"]), r)
549
+ rep1 = rep1v2
550
+ expect_error("revision 1 after 2 -> 409 STALE_REVISION", post_report(A, S1["id"], p1), 409, "STALE_REVISION")
551
+ p_other = copy.deepcopy(p2)
552
+ p_other["analysis_id"] = f"analysis-{RUN_ID}-other"
553
+ expect_error("different analysis_id -> 409 ANALYSIS_MISMATCH", post_report(A, S1["id"], p_other), 409,
554
+ "ANALYSIS_MISMATCH")
555
+ r = call("GET", f"/v1/sessions/{S1['id']}", A["token"])
556
+ if check("GET session after report 200", r.status_code == 200, r):
557
+ s = r.json()["session"]
558
+ check("GET session: status done, analyzed_at set", s["status"] == "done" and s["analyzed_at"], r)
559
+ check("GET session: report equals the latest H1 response", s["report"] == rep1, r)
560
+ check("GET session: measurement_payload not exposed", "measurement_payload" not in s, r)
561
+ r = call("GET", "/v1/me", A["token"])
562
+ ent = r.json().get("entitlement", {})
563
+ check("entitlement used 1 after first report (re-posts and revisions do not count again)",
564
+ ent.get("used_this_week") == 1 and ent.get("left") == 2, r, json.dumps(ent))
565
+
566
+ # ------------------------------------------------------------ more sessions on A
567
+ S_else = new_session(A, "someone else's (Kid Brother)", is_self=False, athlete={
568
+ "name": "Kid Brother", "age": 12, "height_cm": 150, "weight_kg": 40, "bats": "L", "throws": "L",
569
+ "level": "youth"})
570
+ if S_else:
571
+ check("someone-else snapshot = provided athlete", S_else["athlete"]["name"] == "Kid Brother"
572
+ and S_else["athlete"]["bats"] == "L" and S_else["is_self"] is False, None, json.dumps(S_else["athlete"]))
573
+ S_p = new_session(A, "pitching self", mode="p")
574
+ if S_p:
575
+ expect_error("pitching session report -> 422 MODE_NOT_SUPPORTED", post_report(A, S_p["id"], payload()), 422,
576
+ "MODE_NOT_SUPPORTED")
577
+
578
+ # invalid payloads (on a pending session, so nothing is ever counted)
579
+ if S_else:
580
+ def mutate(fn):
581
+ p = payload()
582
+ fn(p)
583
+ return p
584
+
585
+ bad = [
586
+ ("schema_version 2.0", lambda p: p.update(schema_version="2.0"), "schema_version"),
587
+ ("measurement_definitions_version 2.0", lambda p: p.update(measurement_definitions_version="2.0"),
588
+ "measurement_definitions_version"),
589
+ ("missing metric", lambda p: p["measurements"].pop(2), "measurements"),
590
+ ("duplicate metric", lambda p: p["measurements"].__setitem__(2, copy.deepcopy(p["measurements"][0])),
591
+ "measurements"),
592
+ ("available with null value", lambda p: p["measurements"][0].update(value=None), "measurements[0]"),
593
+ ("limited without reasons", lambda p: p["measurements"][1].update(reasons=[]), "measurements[1]"),
594
+ ("unavailable with a value", lambda p: p["measurements"][2].update(value=5), "measurements[2]"),
595
+ ("stride end before start", lambda p: p["events"]["stride_start"].update(video_time_s=1.3),
596
+ "events.stride_start"),
597
+ ("pose_estimated contact source", lambda p: p["events"].__setitem__("contact", {
598
+ "video_time_s": 1.4, "capture_time_s": 1.4, "status": "available", "source": "pose_estimated"}),
599
+ "events.contact"),
600
+ ("separation 180", lambda p: p["measurements"][0].update(value=180), "measurements[0]"),
601
+ ("negative stride", lambda p: p["measurements"][1].update(value=-1), "measurements[1]"),
602
+ ("revision 0", lambda p: p.update(analysis_revision=0), "analysis_revision"),
603
+ ("empty analysis_id", lambda p: p.update(analysis_id=""), "analysis_id"),
604
+ ("missing contact event", lambda p: p["events"].pop("contact"), "events"),
605
+ ("wrong unit", lambda p: p["measurements"][0].update(unit="cm"), "measurements[0]"),
606
+ ("unregistered reason", lambda p: p["measurements"][1].update(reasons=["made_up"]), "measurements[1]"),
607
+ ("confidence 2", lambda p: p["measurements"][0].update(confidence=2), "measurements[0]"),
608
+ ("bat_ball_detector on stride_start", lambda p: p["events"]["stride_start"].update(
609
+ source="bat_ball_detector"), "events.stride_start"),
610
+ ("benchmark lower > upper", lambda p: p["measurements"][0].update(benchmark={
611
+ "benchmark_id": "x", "version": "1", "kind": "reference_interval", "lower": 10, "upper": 0,
612
+ "unit": "deg", "source_reference": "x"}), "measurements[0]"),
613
+ ]
614
+ for label, fn, field in bad:
615
+ expect_error(f"invalid payload: {label} -> 422 INVALID_PAYLOAD", post_report(A, S_else["id"], mutate(fn)),
616
+ 422, "INVALID_PAYLOAD", field)
617
+ r = call("POST", f"/v1/sessions/{S_else['id']}/swing-report", A["token"], json=[1, 2])
618
+ expect_error("invalid payload: JSON array body -> 422 INVALID_PAYLOAD", r, 422, "INVALID_PAYLOAD")
619
+ r = call("POST", f"/v1/sessions/{S_else['id']}/swing-report", A["token"], content=b"{not json",
620
+ headers={"Content-Type": "application/json"})
621
+ check(f"invalid payload: malformed JSON -> 4xx (got {r.status_code})", 400 <= r.status_code < 500, r)
622
+ big = payload()
623
+ big["swing_id"] = "x" * (300 * 1024)
624
+ expect_error("payload over 256 KB -> 413 TOO_LARGE", post_report(A, S_else["id"], big), 413, "TOO_LARGE")
625
+ r = call("GET", f"/v1/sessions/{S_else['id']}", A["token"])
626
+ check("invalid payloads left the session pending", r.status_code == 200 and
627
+ r.json()["session"]["status"] == "pending", r)
628
+
629
+ # B cannot touch A's sessions; unknown ids
630
+ if S1:
631
+ expect_error("other user's session report -> 403", post_report(B, S1["id"], payload()), 403, "FORBIDDEN")
632
+ expect_error("other user's GET session -> 403", call("GET", f"/v1/sessions/{S1['id']}", B["token"]), 403,
633
+ "FORBIDDEN")
634
+ expect_error("other user's DELETE session -> 403", call("DELETE", f"/v1/sessions/{S1['id']}", B["token"]), 403,
635
+ "FORBIDDEN")
636
+ unknown = str(uuid.uuid4())
637
+ expect_error("unknown session report -> 404", post_report(A, unknown, payload()), 404, "NOT_FOUND")
638
+ expect_error("unknown GET session -> 404", call("GET", f"/v1/sessions/{unknown}", A["token"]), 404, "NOT_FOUND")
639
+ expect_error("report without auth -> 401", call("POST", f"/v1/sessions/{unknown}/swing-report", json={}), 401,
640
+ "UNAUTHENTICATED")
641
+ r = call("GET", "/v1/sessions/not-a-uuid", A["token"])
642
+ check(f"malformed session id -> 400/404/422 (got {r.status_code})", r.status_code in (400, 404, 422), r)
643
+
644
+ # ------------------------------------------------------------ 4. ordinal/previous across 3 analysed sessions
645
+ S2 = new_session(A, "self #2")
646
+ S3 = None
647
+ rep2 = rep3 = None
648
+ if S2:
649
+ check("S2 ordinal 2 and previous = S1 (analysed)", S2["ordinal"] == 2 and S2["previous"]
650
+ and S2["previous"]["id"] == S1["id"] and S2["previous"]["overall_score"] == rep1["overall_score"], None,
651
+ json.dumps({"ordinal": S2["ordinal"], "previous": S2["previous"]}))
652
+ r = post_report(A, S2["id"], payload(sep=-30)) # satisfactory band
653
+ rep2 = check_report_shape("S2 report (sep -30, satisfactory)", r)
654
+ if rep2:
655
+ sep = rep2["measurements"][0]
656
+ check(f"S2 separation -30 satisfactory (score {sep['score']})", sep["rating"] == "satisfactory", r)
657
+ # pending session not analysed does not count: S_else and S_p exist pending
658
+ S3 = new_session(A, "self #3")
659
+ if S3:
660
+ r = post_report(A, S3["id"], payload(sep=10))
661
+ rep3 = check_report_shape("S3 report (sep 10)", r)
662
+ r = call("GET", f"/v1/sessions/{S3['id']}", A["token"])
663
+ if r.status_code == 200:
664
+ s = r.json()["session"]
665
+ # self sessions for "QA Alpha" in mode h: S1, S2, S3 (S_p is pitching, S_else other athlete)
666
+ check("S3 ordinal 3 ('Swing 3')", s["ordinal"] == 3, r, f"ordinal={s['ordinal']}")
667
+ check("S3 previous = S2 with S2's score", s["previous"] and s["previous"]["id"] == S2["id"]
668
+ and s["previous"]["overall_score"] == rep2["overall_score"], r, json.dumps(s["previous"]))
669
+ check("S3 report equals H1 response", s["report"] == rep3, r)
670
+
671
+ # ------------------------------------------------------------ 6. plan limit
672
+ r = call("GET", "/v1/me", A["token"])
673
+ ent = r.json().get("entitlement", {})
674
+ check("entitlement used 3, left 0 (pending sessions S_else, S_p not counted)",
675
+ ent.get("used_this_week") == 3 and ent.get("left") == 0, r, json.dumps(ent))
676
+ r = call("GET", "/v1/me/entitlement", A["token"])
677
+ check("GET /me/entitlement matches", r.status_code == 200 and (r.json().get("entitlement", r.json()).get("left")
678
+ == 0), r)
679
+ v4 = uploaded(A, "video")
680
+ r = call("POST", "/v1/sessions", A["token"], json=session_body(v4["upload_id"]))
681
+ expect_error("4th session in a week on free -> 402 PLAN_LIMIT", r, 402, "PLAN_LIMIT")
682
+ check("402 message is the app's text", (r.json().get("error") or {}).get("message")
683
+ == "The free plan includes 3 analyses a week.", r)
684
+ if S_else:
685
+ expect_error("reporting a pending session after the limit -> 402 PLAN_LIMIT",
686
+ post_report(A, S_else["id"], payload(hand="left", lead="right")), 402, "PLAN_LIMIT")
687
+ if S1:
688
+ r = post_report(A, S1["id"], payload(sep=-15, analysis_id=rep1["analysis_id"], rev=3))
689
+ check("a new revision on an already analysed session still works at the limit", r.status_code == 200, r)
690
+ if r.status_code == 200:
691
+ rep1 = r.json()
692
+
693
+ # ------------------------------------------------------------ left-handed hitter (B, someone else's swing)
694
+ LB = new_session(B, "B someone else, left-handed college", is_self=False, athlete={
695
+ "name": "Lefty Lou", "age": 20, "height_cm": 180, "weight_kg": 80, "bats": "L", "throws": "L",
696
+ "level": "college"})
697
+ if LB:
698
+ r = post_report(B, LB["id"], payload(sep=17, hand="left", lead="right", stride=30))
699
+ repL = check_report_shape("left-handed college (sep +17)", r)
700
+ if repL:
701
+ sep = repL["measurements"][0]
702
+ check("left-handed +17 deg -> on_target 100 against left/college ranges",
703
+ sep["score"] == 100 and sep["rating"] == "on_target"
704
+ and "left" in (sep.get("benchmark") or {}).get("benchmark_id", ""), r,
705
+ json.dumps({"score": sep["score"], "benchmark": sep.get("benchmark")}))
706
+ # left-handed but separation in the right-handed range -> off target
707
+ LB2 = new_session(B, "B someone else, left-handed #2", is_self=False, athlete={
708
+ "name": "Lefty Lou", "age": 20, "height_cm": 180, "weight_kg": 80, "bats": "L", "throws": "L",
709
+ "level": "college"})
710
+ if LB2:
711
+ r = post_report(B, LB2["id"], payload(sep=-20, hand="left", lead="right", stride=30))
712
+ repL2 = check_report_shape("left-handed college (sep -20)", r)
713
+ if repL2:
714
+ check("left-handed -20 deg -> off_target", repL2["measurements"][0]["rating"] == "off_target", r)
715
+ r = call("GET", f"/v1/sessions/{LB2['id']}", B["token"])
716
+ check("Lefty Lou #2: ordinal 2, previous = #1", r.status_code == 200 and r.json()["session"]["ordinal"] == 2
717
+ and (r.json()["session"]["previous"] or {}).get("id") == LB["id"], r)
718
+ # B: high-school self session, unknown hand fallback via profile bats=L when payload batting_hand null
719
+ BS = new_session(C, "C self high school, hand from profile")
720
+ if BS:
721
+ p = payload(sep=17, hand="right", lead="right")
722
+ p["athlete"]["batting_hand"] = None
723
+ r = post_report(C, BS["id"], p)
724
+ repB = check_report_shape("hand fallback to profile bats=L, high school", r)
725
+ if repB:
726
+ bid = (repB["measurements"][0].get("benchmark") or {}).get("benchmark_id", "")
727
+ codes = {d["code"] for d in repB["data_quality"]}
728
+ check("left high school falls back to left college with population_fallback note",
729
+ bid.endswith("left.college") and "population_fallback" in codes, r, f"{bid} {codes}")
730
+
731
+ # ------------------------------------------------------------ 5. list
732
+ r = call("GET", "/v1/sessions", A["token"])
733
+ if check("GET /v1/sessions 200", r.status_code == 200, r):
734
+ items = r.json()["items"]
735
+ ids = [i["id"] for i in items]
736
+ expected = {s["id"] for s in (S1, S2, S3, S_else, S_p) if s}
737
+ check(f"list has all {len(expected)} live sessions of A", set(ids) == expected, r, f"got {ids}")
738
+ it1 = next((i for i in items if S1 and i["id"] == S1["id"]), None)
739
+ it2 = next((i for i in items if S2 and i["id"] == S2["id"]), None)
740
+ if it2:
741
+ check("summary of S2: overall_score, focus with drill, thumbnail_url",
742
+ it2["overall_score"] == rep2["overall_score"] and it2["focus"]
743
+ and it2["focus"]["metric_id"] == rep2["focus_area"]["metric_id"] and it2["thumbnail_url"], r,
744
+ json.dumps(it2)[:400])
745
+ g = raw.get(it2["thumbnail_url"])
746
+ check("summary thumbnail_url downloads", g.status_code == 200 and g.content == JPEG_BYTES, None,
747
+ str(g.status_code))
748
+ if it1:
749
+ check("summary of S1 (all on target): focus null, score from latest revision",
750
+ it1["focus"] is None and it1["overall_score"] == rep1["overall_score"], r, json.dumps(it1)[:300])
751
+ check("list ordered newest first", ids == [i["id"] for i in sorted(items, key=lambda x: (x["created_at"],
752
+ x["id"]), reverse=True)],
753
+ r)
754
+ r = call("GET", "/v1/sessions", A["token"], params={"mode": "p"})
755
+ check("filter mode=p -> only the pitching session", r.status_code == 200 and S_p and
756
+ [i["id"] for i in r.json()["items"]] == [S_p["id"]], r)
757
+ r = call("GET", "/v1/sessions", A["token"], params={"mode": "h", "self": "true"})
758
+ check("filter mode=h self=true -> S1,S2,S3", r.status_code == 200 and
759
+ {i["id"] for i in r.json()["items"]} == {s["id"] for s in (S1, S2, S3) if s}, r)
760
+ r = call("GET", "/v1/sessions", A["token"], params={"self": "false"})
761
+ check("filter self=false -> only Kid Brother", r.status_code == 200 and S_else and
762
+ [i["id"] for i in r.json()["items"]] == [S_else["id"]], r)
763
+ r = call("GET", "/v1/sessions", A["token"], params={"athlete_name": "Kid Brother"})
764
+ check("filter athlete_name=Kid Brother", r.status_code == 200 and S_else and
765
+ [i["athlete_name"] for i in r.json()["items"]] == ["Kid Brother"], r)
766
+ r = call("GET", "/v1/sessions", A["token"], params={"athlete_name": "Nobody Here"})
767
+ check("filter athlete_name unknown -> empty", r.status_code == 200 and r.json()["items"] == [], r)
768
+ future = (datetime.now(UTC) + timedelta(days=1)).isoformat()
769
+ r = call("GET", "/v1/sessions", A["token"], params={"since": future})
770
+ check("filter since=tomorrow -> empty", r.status_code == 200 and r.json()["items"] == [], r)
771
+ if S3:
772
+ r = call("GET", "/v1/sessions", A["token"], params={"since": S3["created_at"]})
773
+ check("filter since=S3.created_at -> only S3 (inclusive)", r.status_code == 200 and
774
+ [i["id"] for i in r.json()["items"]] == [S3["id"]], r)
775
+ expect_error("filter mode=x -> 400", call("GET", "/v1/sessions", A["token"], params={"mode": "x"}), 400)
776
+ expect_error("filter since=garbage -> 400", call("GET", "/v1/sessions", A["token"], params={"since": "yesterday"}),
777
+ 400)
778
+ expect_error("bad cursor -> 400", call("GET", "/v1/sessions", A["token"], params={"cursor": "!!!"}), 400)
779
+ expect_error("limit=0 -> 400", call("GET", "/v1/sessions", A["token"], params={"limit": 0}), 400)
780
+ walked, cursor, pages = [], None, 0
781
+ while pages < 20:
782
+ params = {"limit": 1}
783
+ if cursor:
784
+ params["cursor"] = cursor
785
+ r = call("GET", "/v1/sessions", A["token"], params=params)
786
+ if r.status_code != 200:
787
+ check("cursor walk page", False, r)
788
+ break
789
+ d = r.json()
790
+ walked += [i["id"] for i in d["items"]]
791
+ pages += 1
792
+ cursor = d.get("next_cursor")
793
+ if not cursor:
794
+ break
795
+ full = [i["id"] for i in call("GET", "/v1/sessions", A["token"]).json()["items"]]
796
+ check(f"cursor walk with limit=1 visits all items once in order ({len(walked)} of {len(full)})",
797
+ walked == full and len(set(walked)) == len(walked), None, f"walked={walked} full={full}")
798
+ r = call("GET", "/v1/sessions", B["token"])
799
+ check("B's list does not include A's sessions", r.status_code == 200 and
800
+ not ({i["id"] for i in r.json()["items"]} & {s["id"] for s in (S1, S2, S3, S_else, S_p) if s}), r)
801
+
802
+ # ------------------------------------------------------------ 2b. idempotency on POST /sessions (B)
803
+ iv = uploaded(C, "video")
804
+ ib = session_body(iv["upload_id"])
805
+ key = f"qa-{RUN_ID}-sess"
806
+ r1 = call("POST", "/v1/sessions", C["token"], json=ib, headers={"Idempotency-Key": key})
807
+ r2 = call("POST", "/v1/sessions", C["token"], json=ib, headers={"Idempotency-Key": key})
808
+ check("Idempotency-Key replay returns the identical body and status", r1.status_code == 201
809
+ and r2.status_code == 201 and r1.json() == r2.json(), r2)
810
+ ib2 = copy.deepcopy(ib)
811
+ ib2["fps"] = 60
812
+ expect_error("same Idempotency-Key with a different body -> 409 IDEMPOTENCY_KEY_REUSED",
813
+ call("POST", "/v1/sessions", C["token"], json=ib2, headers={"Idempotency-Key": key}), 409,
814
+ "IDEMPOTENCY_KEY_REUSED")
815
+ r = call("GET", "/v1/sessions", C["token"], params={"mode": "h", "self": "true"})
816
+ if r1.status_code == 201:
817
+ n = sum(1 for i in r.json()["items"] if i["id"] == r1.json()["session"]["id"])
818
+ check("replay created only one session", n == 1, r)
819
+ r = call("POST", "/v1/sessions", B["token"], json=ib, headers={"Idempotency-Key": key})
820
+ check(f"same key and body from another account is not a replay (got {r.status_code} {err_code(r)})",
821
+ r.status_code != 201 or r.json() != r1.json(), r)
822
+
823
+ # ------------------------------------------------------------ 7. delete session (B)
824
+ DS = new_session(C, "C to delete")
825
+ if DS:
826
+ r = call("DELETE", f"/v1/sessions/{DS['id']}", C["token"])
827
+ check("DELETE session -> 204", r.status_code == 204, r)
828
+ expect_error("GET deleted session -> 404", call("GET", f"/v1/sessions/{DS['id']}", C["token"]), 404,
829
+ "NOT_FOUND")
830
+ r = call("GET", "/v1/sessions", C["token"])
831
+ check("deleted session gone from list", r.status_code == 200 and DS["id"] not in
832
+ [i["id"] for i in r.json()["items"]], r)
833
+ expect_error("DELETE deleted session again -> 404", call("DELETE", f"/v1/sessions/{DS['id']}", C["token"]), 404)
834
+ expect_error("report on deleted session -> 404", post_report(C, DS["id"], payload()), 404, "NOT_FOUND")
835
+ g = raw.get(DS["media"]["video_url"])
836
+ if g.status_code == 200:
837
+ note("After DELETE /v1/sessions/{id} the earlier presigned video URL still downloads (200). By design "
838
+ "(DESIGN.md D5 soft delete; media removed later by app/jobs/cleanup.py), but frontend_spec 7.5 says "
839
+ "'D5 returns 204, deletes the objects'. Signed URLs live 1 h, so a deleted clip stays reachable up "
840
+ "to an hour, longer until the cleanup job runs.")
841
+ else:
842
+ check("deleted session's video URL unreachable", g.status_code in (403, 404), None, str(g.status_code))
843
+
844
+ # ------------------------------------------------------------ 8. drills (B)
845
+ dl = {"drill_id": "hit_13", "reps": 8, "day": today.isoformat()}
846
+ r = call("POST", "/v1/drill-logs", B["token"], json=dl)
847
+ if check("POST drill log valid -> 201", r.status_code == 201, r):
848
+ log = r.json()["log"]
849
+ check("drill log echoes fields", log["drill_id"] == "hit_13" and log["reps"] == 8 and log["day"] == dl["day"],
850
+ r)
851
+ if LB:
852
+ r = call("POST", "/v1/drill-logs", B["token"], json={**dl, "session_id": LB["id"]})
853
+ check("drill log linked to own session -> 201", r.status_code == 201, r)
854
+ if S1:
855
+ r = call("POST", "/v1/drill-logs", B["token"], json={**dl, "session_id": S1["id"]})
856
+ check(f"drill log on another user's session refused (got {r.status_code})", r.status_code in (403, 404), r)
857
+ expect_error("drill log unknown drill id -> 400", call("POST", "/v1/drill-logs", B["token"],
858
+ json={**dl, "drill_id": "hit_999"}), 400, "VALIDATION", "drill_id")
859
+ expect_error("drill log reps 9 -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 9}), 400,
860
+ "VALIDATION", "reps")
861
+ expect_error("drill log reps 0 -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 0}), 400,
862
+ "VALIDATION", "reps")
863
+ expect_error("drill log bad day -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "day": "today"}),
864
+ 400, "VALIDATION", "day")
865
+ dkey = f"qa-{RUN_ID}-drill"
866
+ d1 = call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 5}, headers={"Idempotency-Key": dkey})
867
+ d2 = call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 5}, headers={"Idempotency-Key": dkey})
868
+ check("drill log Idempotency-Key replay identical", d1.status_code == 201 and d2.status_code == 201
869
+ and d1.json() == d2.json(), d2)
870
+ expect_error("drill log same key different body -> 409", call("POST", "/v1/drill-logs", B["token"],
871
+ json={**dl, "reps": 6}, headers={"Idempotency-Key": dkey}), 409, "IDEMPOTENCY_KEY_REUSED")
872
+ old = {"drill_id": "hit_01", "reps": 3, "day": (today - timedelta(days=20)).isoformat()}
873
+ call("POST", "/v1/drill-logs", B["token"], json=old)
874
+ r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=6)).isoformat(),
875
+ "to": today.isoformat()})
876
+ if check("GET drill logs 7-day range 200", r.status_code == 200, r):
877
+ items = r.json()["items"]
878
+ check("range filter: 3 logs in the last 7 days, old one excluded",
879
+ len(items) == 3 and all(i["day"] >= (today - timedelta(days=6)).isoformat() for i in items), r,
880
+ f"{len(items)} items")
881
+ r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=30)).isoformat(),
882
+ "to": today.isoformat()})
883
+ check("range 30 days includes the old log", r.status_code == 200 and len(r.json()["items"]) == 4, r)
884
+ expect_error("drill logs range > 90 days -> 400", call("GET", "/v1/drill-logs", B["token"], params={
885
+ "from": (today - timedelta(days=91)).isoformat(), "to": today.isoformat()}), 400, "VALIDATION")
886
+ r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=90)).isoformat(),
887
+ "to": today.isoformat()})
888
+ check("drill logs range exactly 90 days -> 200", r.status_code == 200, r)
889
+ expect_error("drill logs to < from -> 400", call("GET", "/v1/drill-logs", B["token"], params={
890
+ "from": today.isoformat(), "to": (today - timedelta(days=1)).isoformat()}), 400)
891
+ expect_error("drill logs missing from -> 400", call("GET", "/v1/drill-logs", B["token"],
892
+ params={"to": today.isoformat()}), 400)
893
+ r = call("GET", "/v1/drill-logs", A["token"], params={"from": (today - timedelta(days=6)).isoformat(),
894
+ "to": today.isoformat()})
895
+ check("A does not see B's drill logs", r.status_code == 200 and r.json()["items"] == [], r)
896
+
897
+ # ------------------------------------------------------------ 9. catalog
898
+ r = call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "h"})
899
+ if check("catalog mode=h 200", r.status_code == 200, r):
900
+ c = r.json()
901
+ check("catalog h: 4 groups in order", [g["group"] for g in c["groups"]] == GROUP_ORDER, r)
902
+ check("catalog h: 3 metrics", {m["metric_id"] for m in c["metrics"]} == {
903
+ "hip_shoulder_separation_at_foot_down", "stride_relative_length", "hip_shoulder_separation_at_contact"}, r)
904
+ check("catalog h: drills include hit_13", any(d["drill_id"] == "hit_13" for d in c["drills"]), r)
905
+ r = call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "p"})
906
+ check("catalog mode=p 200 with drills and no metrics yet", r.status_code == 200 and r.json()["metrics"] == []
907
+ and len(r.json()["drills"]) > 0, r)
908
+ expect_error("catalog mode=x -> 400", call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "x"}), 400)
909
+ expect_error("catalog without auth -> 401", call("GET", "/v1/catalog/metrics", params={"mode": "h"}), 401)
910
+
911
+ # ------------------------------------------------------------ openapi sanity: no camelCase in schemas
912
+ spec = client.get("/openapi.json").json()
913
+ camel_props = []
914
+ for name, schema in spec.get("components", {}).get("schemas", {}).items():
915
+ for prop in (schema.get("properties") or {}):
916
+ if re.search(r"[A-Z]", prop) and not (name.startswith("Apple") and prop == "signedPayload"):
917
+ camel_props.append(f"{name}.{prop}")
918
+ check("openapi: no camelCase properties", not camel_props, None, str(camel_props))
919
+
920
+
921
+ def cleanup():
922
+ print("\n--- cleanup ---")
923
+ for acct in ACCOUNTS:
924
+ r = call("DELETE", "/v1/me", acct["token"])
925
+ acct["deleted"] = check(f"DELETE /v1/me {acct['email']} -> 204", r.status_code == 204, r)
926
+ r = call("GET", "/v1/me", acct["token"])
927
+ check(f"deleted account token no longer works ({acct['email']})", r.status_code in (401, 404), r)
928
+ r = client.post("/v1/auth/login", json={"email": acct["email"], "password": PASSWORD})
929
+ check(f"deleted account cannot log in ({acct['email']})", r.status_code in (400, 401), r)
930
+ for acct in ACCOUNTS:
931
+ url = acct.get("video_url")
932
+ if url:
933
+ g = raw.get(url)
934
+ check(f"presigned video URL unreachable after account deletion ({g.status_code})",
935
+ g.status_code in (403, 404), None, f"status {g.status_code}")
936
+
937
+
938
+ def main() -> int:
939
+ print(f"QA sessions/reports suite against {BASE_URL}, run {RUN_ID}\n")
940
+ try:
941
+ run()
942
+ except SystemExit as exc:
943
+ check(f"suite aborted: {exc}", False)
944
+ except Exception as exc: # keep going to cleanup
945
+ import traceback
946
+ traceback.print_exc()
947
+ check(f"suite crashed: {exc!r}", False)
948
+ finally:
949
+ cleanup()
950
+ check("no 5xx responses", not FIVE_HUNDREDS, None, "; ".join(FIVE_HUNDREDS))
951
+ check("no camelCase keys in responses", not CAMEL, None, ", ".join(sorted(CAMEL)))
952
+ check("no forbidden keys leaked", not LEAKS, None, ", ".join(sorted(set(LEAKS))))
953
+ print(f"\n=== {RESULTS['PASS']} passed, {RESULTS['FAIL']} failed ===")
954
+ for f in FAILS:
955
+ print(f)
956
+ for n in NOTES:
957
+ print(f"NOTE: {n}")
958
+ return 1 if RESULTS["FAIL"] else 0
959
+
960
+
961
+ if __name__ == "__main__":
962
+ sys.exit(main())
backend/tests/integration/test_auth.py CHANGED
@@ -1,5 +1,6 @@
1
  """A1-A7 auth endpoints."""
2
 
 
3
  import pytest
4
  from sqlalchemy import text
5
 
@@ -112,16 +113,21 @@ async def test_login_wrong_credentials(client, email):
112
  assert response.json() == {"error": {"code": "INVALID_CREDENTIALS", "message": "Wrong email or password."}}
113
 
114
 
115
- async def test_login_rate_limited_by_email(client):
116
  await register(client, email="victim@example.com")
117
  limit = get_rate_limiter().limit
118
  for _ in range(limit):
119
  response = await client.post("/v1/auth/login", json={"email": "victim@example.com", "password": "nope-nope"})
120
  assert response.status_code == 401
121
- # Even the right password is refused until the window passes.
122
  response = await client.post("/v1/auth/login", json={"email": "victim@example.com", "password": PASSWORD})
123
  assert response.status_code == 429
124
  assert response.json()["error"]["code"] == "RATE_LIMITED"
 
 
 
 
 
125
 
126
 
127
  async def test_login_rate_limited_by_ip(client):
 
1
  """A1-A7 auth endpoints."""
2
 
3
+ import httpx
4
  import pytest
5
  from sqlalchemy import text
6
 
 
113
  assert response.json() == {"error": {"code": "INVALID_CREDENTIALS", "message": "Wrong email or password."}}
114
 
115
 
116
+ async def test_login_rate_limited_by_email_and_ip(client, app):
117
  await register(client, email="victim@example.com")
118
  limit = get_rate_limiter().limit
119
  for _ in range(limit):
120
  response = await client.post("/v1/auth/login", json={"email": "victim@example.com", "password": "nope-nope"})
121
  assert response.status_code == 401
122
+ # The guessing client stays blocked, even with the right password, until the window passes.
123
  response = await client.post("/v1/auth/login", json={"email": "victim@example.com", "password": PASSWORD})
124
  assert response.status_code == 429
125
  assert response.json()["error"]["code"] == "RATE_LIMITED"
126
+ # The real user on another network is not locked out by someone else's failures.
127
+ transport = httpx.ASGITransport(app=app, client=("10.0.0.9", 50000))
128
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as victim:
129
+ response = await victim.post("/v1/auth/login", json={"email": "victim@example.com", "password": PASSWORD})
130
+ assert response.status_code == 200
131
 
132
 
133
  async def test_login_rate_limited_by_ip(client):
backend/tests/integration/test_health.py CHANGED
@@ -7,3 +7,12 @@ async def test_healthz(client):
7
  async def test_unknown_route_uses_error_envelope_for_auth(client):
8
  response = await client.get("/v1/me")
9
  assert response.status_code in (401, 404)
 
 
 
 
 
 
 
 
 
 
7
  async def test_unknown_route_uses_error_envelope_for_auth(client):
8
  response = await client.get("/v1/me")
9
  assert response.status_code in (401, 404)
10
+
11
+
12
+ async def test_routing_errors_use_the_error_envelope(client):
13
+ response = await client.get("/v1/does-not-exist")
14
+ assert response.status_code == 404
15
+ assert response.json()["error"]["code"] == "NOT_FOUND"
16
+ response = await client.delete("/v1/auth/register")
17
+ assert response.status_code == 405
18
+ assert response.json()["error"]["code"] == "METHOD_NOT_ALLOWED"
backend/tests/integration/test_sessions.py CHANGED
@@ -150,6 +150,13 @@ async def test_create_session_upload_invalid_content_type_deletes_object(client)
150
  assert await storage.head(key) is None
151
 
152
 
 
 
 
 
 
 
 
153
  async def test_create_session_upload_invalid_size(client, monkeypatch):
154
  player = await make_account()
155
  video_id = await upload(client, player["headers"])
@@ -229,8 +236,10 @@ async def test_get_session_previous_and_ordinal(client):
229
  s = (await client.get(f"/v1/sessions/{latest['id']}", headers=h)).json()["session"]
230
  assert s["status"] == "done" and s["report"]["overall_score"] == 55 and s["analyzed_at"]
231
  assert s["previous"]["id"] == first["id"] and s["previous"]["overall_score"] == 52
232
- assert s["ordinal"] == 3 # first, pending, latest (deleted excluded; other athlete and mode excluded)
233
  assert (await client.get(f"/v1/sessions/{first['id']}", headers=h)).json()["session"]["previous"] is None
 
 
234
  other = (await client.get(f"/v1/sessions/{other_athlete['id']}", headers=h)).json()["session"]
235
  assert other["ordinal"] == 1 and other["previous"] is None
236
  assert (await client.get(f"/v1/sessions/{pitch['id']}", headers=h)).json()["session"]["ordinal"] == 1
@@ -250,8 +259,16 @@ async def test_get_session_access_rules(client):
250
  verdicts={"hip_shoulder_separation_at_foot_down": "agree"}))
251
  await db.commit()
252
 
 
 
 
 
253
  response = await client.get(f"/v1/sessions/{own['id']}", headers=coach["headers"])
254
  assert response.status_code == 200 # private_videos (default true) does not block the coach
 
 
 
 
255
  review = response.json()["session"]["review"]
256
  assert review["coach_id"] == str(coach["id"]) and review["coach_name"] == PROFILE["name"]
257
  assert review["cue"] == "Shoulder in." and review["drill_id"] == "hit_13" and review["at"]
@@ -325,6 +342,8 @@ async def test_delete_session(client):
325
  assert forbidden.status_code == 403 and forbidden.json()["error"]["code"] == "FORBIDDEN"
326
  response = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"])
327
  assert response.status_code == 204 and response.content == b""
 
 
328
  assert (await client.get(f"/v1/sessions/{s['id']}", headers=player["headers"])).status_code == 404
329
  assert (await client.get("/v1/sessions", headers=player["headers"])).json()["items"] == []
330
  again = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"])
 
150
  assert await storage.head(key) is None
151
 
152
 
153
+ async def test_create_session_rejects_content_that_is_not_a_video(client):
154
+ player = await make_account()
155
+ video_id = await upload(client, player["headers"], data=JPEG) # JPEG bytes sent with the video/mp4 header
156
+ response = await client.post("/v1/sessions", json=session_body(video_id, None), headers=player["headers"])
157
+ assert response.status_code == 422 and response.json()["error"]["code"] == "UPLOAD_INVALID"
158
+
159
+
160
  async def test_create_session_upload_invalid_size(client, monkeypatch):
161
  player = await make_account()
162
  video_id = await upload(client, player["headers"])
 
236
  s = (await client.get(f"/v1/sessions/{latest['id']}", headers=h)).json()["session"]
237
  assert s["status"] == "done" and s["report"]["overall_score"] == 55 and s["analyzed_at"]
238
  assert s["previous"]["id"] == first["id"] and s["previous"]["overall_score"] == 52
239
+ assert s["ordinal"] == 2 # first, latest: pending and deleted reps are not numbered
240
  assert (await client.get(f"/v1/sessions/{first['id']}", headers=h)).json()["session"]["previous"] is None
241
+ waiting = (await client.get(f"/v1/sessions/{pending['id']}", headers=h)).json()["session"]
242
+ assert waiting["ordinal"] == 2 # a pending rep is numbered after the analysed ones before it
243
  other = (await client.get(f"/v1/sessions/{other_athlete['id']}", headers=h)).json()["session"]
244
  assert other["ordinal"] == 1 and other["previous"] is None
245
  assert (await client.get(f"/v1/sessions/{pitch['id']}", headers=h)).json()["session"]["ordinal"] == 1
 
259
  verdicts={"hip_shoulder_separation_at_foot_down": "agree"}))
260
  await db.commit()
261
 
262
+ pending = await client.get(f"/v1/sessions/{own['id']}", headers=coach["headers"])
263
+ assert pending.status_code == 403 # nothing for the coach to see until the rep is analysed
264
+ await mark_analyzed(own["id"], 70)
265
+
266
  response = await client.get(f"/v1/sessions/{own['id']}", headers=coach["headers"])
267
  assert response.status_code == 200 # private_videos (default true) does not block the coach
268
+ athlete = response.json()["session"]["athlete"]
269
+ assert athlete["name"] == PROFILE["name"] and not {"age", "height_cm", "weight_kg"} & athlete.keys()
270
+ owner_view = (await client.get(f"/v1/sessions/{own['id']}", headers=player["headers"])).json()["session"]
271
+ assert owner_view["athlete"]["height_cm"] == PROFILE["height_cm"]
272
  review = response.json()["session"]["review"]
273
  assert review["coach_id"] == str(coach["id"]) and review["coach_name"] == PROFILE["name"]
274
  assert review["cue"] == "Shoulder in." and review["drill_id"] == "hit_13" and review["at"]
 
342
  assert forbidden.status_code == 403 and forbidden.json()["error"]["code"] == "FORBIDDEN"
343
  response = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"])
344
  assert response.status_code == 204 and response.content == b""
345
+ async with httpx.AsyncClient() as s3: # the media is gone right away, not after the retention period
346
+ assert (await s3.get(s["media"]["video_url"])).status_code == 404
347
  assert (await client.get(f"/v1/sessions/{s['id']}", headers=player["headers"])).status_code == 404
348
  assert (await client.get("/v1/sessions", headers=player["headers"])).json()["items"] == []
349
  again = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"])