"""D2 to D5: create, read, list and delete sessions.""" import uuid from datetime import UTC, datetime, timedelta import httpx import pytest from sqlalchemy import select from app.core.config import get_settings from app.core.database import get_session_factory from app.integrations.storage import get_storage from app.modules.billing.entitlement import FREE_WEEKLY_LIMIT from app.modules.reviews.models import Review from app.modules.sessions.models import SwingSession from app.modules.uploads.models import Upload from tests.factories import ( JPEG, OTHER_ATHLETE, PROFILE, VIDEO, create_session, make_account, make_session, make_team_row, mark_analyzed, session_body, set_session, upload, ) # ---------- D2 ---------- @pytest.mark.parametrize("explicit_null", [False, True]) async def test_create_and_read_session_without_manual_pitcher_direction(client, explicit_null): player = await make_account() video_id = await upload(client, player["headers"], "video") body = session_body(video_id, None) if explicit_null: body["marks"]["pitcher_direction"] = None else: body["marks"].pop("pitcher_direction") response = await client.post("/v1/sessions", json=body, headers=player["headers"]) assert response.status_code == 201, response.text session = response.json()["session"] assert session["marks"]["pitcher_direction"] is None response = await client.get(f"/v1/sessions/{session['id']}", headers=player["headers"]) assert response.status_code == 200, response.text assert response.json()["session"]["marks"]["pitcher_direction"] is None async def test_create_session_after_real_presigned_put(client): player = await make_account() video_id = await upload(client, player["headers"], "video") thumb_id = await upload(client, player["headers"], "thumbnail") response = await client.post("/v1/sessions", json=session_body(video_id, thumb_id), headers=player["headers"]) assert response.status_code == 201, response.text s = response.json()["session"] assert s["status"] == "pending" and s["report"] is None and s["analyzed_at"] is None assert s["owner_id"] == str(player["id"]) and s["is_self"] is True and s["mode"] == "h" assert s["athlete"] == PROFILE assert s["duration_sec"] == 3.87 and s["fps"] == 30 assert s["marks"]["pitcher_direction"] == {"from": [0.56, 0.86], "to": [0.9, 0.64]} assert s["marks"]["contact_source"] == "detected" assert s["review"] is None and s["previous"] is None and s["ordinal"] == 1 assert s["media"]["video_url"].startswith("http") and s["media"]["thumbnail_url"] assert s["media"]["expires_at"] async with httpx.AsyncClient() as s3: assert (await s3.get(s["media"]["video_url"])).content == VIDEO async with get_session_factory()() as db: attached = (await db.execute(select(Upload.attached_at).where( Upload.id.in_([uuid.UUID(video_id), uuid.UUID(thumb_id)])))).scalars().all() assert len(attached) == 2 and all(attached) async def test_create_session_for_someone_else_without_thumbnail(client): player = await make_account() video_id = await upload(client, player["headers"]) body = session_body(video_id, None, is_self=False, athlete=OTHER_ATHLETE, mode="p") response = await client.post("/v1/sessions", json=body, headers=player["headers"]) assert response.status_code == 201, response.text s = response.json()["session"] assert s["is_self"] is False and s["mode"] == "p" assert s["athlete"] == {**OTHER_ATHLETE, "height_cm": 175.0, "weight_kg": 70.0} assert s["media"]["thumbnail_url"] is None async def _post_invalid(client, headers, body) -> dict: response = await client.post("/v1/sessions", json=body, headers=headers) assert response.status_code == 400, response.text error = response.json()["error"] assert error["code"] == "VALIDATION" return error["fields"] async def test_create_session_validation_errors(client): player = await make_account() h = player["headers"] vid = str(uuid.uuid4()) marks = session_body(vid, None)["marks"] fields = await _post_invalid(client, h, session_body(vid, None, marks={ **marks, "stride_start_frame": 80, "stride_end_frame": 79})) assert "marks.stride_end_frame" in fields fields = await _post_invalid(client, h, session_body(vid, None, marks={**marks, "contact_frame": 70})) assert "marks.contact_frame" in fields # round(3.87 * 30) - 1 = 115 is the last frame fields = await _post_invalid(client, h, session_body(vid, None, marks={**marks, "contact_frame": 116})) assert "marks.contact_frame" in fields fields = await _post_invalid(client, h, session_body(vid, None, marks={ **marks, "pitcher_direction": {"from": [0.5, 0.5], "to": [0.55, 0.52]}})) assert "marks.pitcher_direction" in fields fields = await _post_invalid(client, h, session_body(vid, None, marks={ **marks, "pitcher_direction": {"from": [1.2, 0.5], "to": [0.5, 0.5]}})) assert "marks.pitcher_direction.from[0]" in fields fields = await _post_invalid(client, h, session_body(vid, None, marks={**marks, "contact_source": "audio"})) assert "marks.contact_source" in fields fields = await _post_invalid(client, h, session_body(vid, None, athlete=OTHER_ATHLETE)) assert "athlete" in fields fields = await _post_invalid(client, h, session_body(vid, None, is_self=False)) assert "athlete" in fields fields = await _post_invalid(client, h, session_body(vid, None, is_self=False, athlete={ **OTHER_ATHLETE, "name": "B", "age": 4, "height_cm": 300, "weight_kg": 10, "level": "pro"})) assert {"athlete.name", "athlete.age", "athlete.height_cm", "athlete.weight_kg", "athlete.level"} <= set(fields) fields = await _post_invalid(client, h, session_body(vid, None, fps=0, mode="x", duration_sec=61)) assert {"fps", "mode"} <= set(fields) fields = await _post_invalid(client, h, session_body(vid, None, duration_sec=61)) assert "duration_sec" in fields fields = await _post_invalid(client, h, {**session_body(vid, None), "client_created_at": "2026-10-22T10:12:03Z"}) assert "client_created_at" in fields async def test_create_session_rejects_uploads_that_are_not_claimable(client): player = await make_account() other = await make_account() h = player["headers"] thumb_as_video = await upload(client, h, "thumbnail") others_video = await upload(client, other["headers"]) for video_id in (str(uuid.uuid4()), thumb_as_video, others_video): fields = await _post_invalid(client, h, session_body(video_id, None)) assert "video_upload_id" in fields video_as_thumb = await upload(client, h) fields = await _post_invalid(client, h, session_body(await upload(client, h), video_as_thumb)) assert "thumbnail_upload_id" in fields used = await create_session(client, h) async with get_session_factory()() as db: video_id = await db.scalar(select(SwingSession.video_upload_id).where(SwingSession.id == uuid.UUID(used["id"]))) fields = await _post_invalid(client, h, session_body(str(video_id), None)) assert fields["video_upload_id"] == "This upload is already used by a session." async def test_create_session_upload_missing(client): player = await make_account() video_id = await upload(client, player["headers"], put=False) response = await client.post("/v1/sessions", json=session_body(video_id, None), headers=player["headers"]) assert response.status_code == 422 assert response.json()["error"]["code"] == "UPLOAD_MISSING" async def test_create_session_upload_invalid_content_type_deletes_object(client): player = await make_account() video_id = await upload(client, player["headers"], put=False) async with get_session_factory()() as db: key = await db.scalar(select(Upload.object_key).where(Upload.id == uuid.UUID(video_id))) storage = get_storage() storage._s3.put_object(Bucket=storage.bucket, Key=key, Body=VIDEO, ContentType="video/webm") response = await client.post("/v1/sessions", json=session_body(video_id, None), headers=player["headers"]) assert response.status_code == 422 assert response.json()["error"]["code"] == "UPLOAD_INVALID" assert await storage.head(key) is None async def test_create_session_rejects_content_that_is_not_a_video(client): player = await make_account() video_id = await upload(client, player["headers"], data=JPEG) # JPEG bytes sent with the video/mp4 header response = await client.post("/v1/sessions", json=session_body(video_id, None), headers=player["headers"]) assert response.status_code == 422 and response.json()["error"]["code"] == "UPLOAD_INVALID" async def test_create_session_upload_invalid_size(client, monkeypatch): player = await make_account() video_id = await upload(client, player["headers"]) thumb_id = await upload(client, player["headers"], "thumbnail", data=JPEG * 4) monkeypatch.setattr(get_settings(), "max_thumbnail_bytes", len(JPEG)) response = await client.post("/v1/sessions", json=session_body(video_id, thumb_id), headers=player["headers"]) assert response.status_code == 422 assert response.json()["error"]["code"] == "UPLOAD_INVALID" async def test_plan_limit_after_twenty_analysed_sessions_in_a_week(client): player = await make_account() h = player["headers"] for _ in range(FREE_WEEKLY_LIMIT - 1): await make_session(player["id"]) s = await create_session(client, h) # the 20th is still allowed await mark_analyzed(s["id"], 60) entitlement = (await client.get("/v1/me/entitlement", headers=h)).json() assert entitlement == {"plan": "free", "weekly_limit": 20, "used_this_week": 20, "left": 0, "window_days": 7} video_id = await upload(client, h) response = await client.post("/v1/sessions", json=session_body(video_id, None), headers=h) assert response.status_code == 402 assert response.json()["error"] == {"code": "PLAN_LIMIT", "message": "The free plan includes 20 analyses a week."} listed = await client.get("/v1/sessions", headers=h, params={"limit": 50}) assert len(listed.json()["items"]) == FREE_WEEKLY_LIMIT async with get_session_factory()() as db: assert (await db.get(Upload, uuid.UUID(video_id))).attached_at is None async def test_pending_sessions_do_not_count_toward_the_plan(client): player = await make_account() for _ in range(FREE_WEEKLY_LIMIT + 1): await create_session(client, player["headers"]) async def test_create_session_idempotency(client): player = await make_account() h = {**player["headers"], "Idempotency-Key": "rep-1"} body = session_body(await upload(client, h), await upload(client, h, "thumbnail")) first = await client.post("/v1/sessions", json=body, headers=h) assert first.status_code == 201 replay = await client.post("/v1/sessions", json=body, headers=h) assert replay.status_code == 201 assert replay.json() == first.json() reused = await client.post("/v1/sessions", json={**body, "fps": 60}, headers=h) assert reused.status_code == 409 assert reused.json()["error"]["code"] == "IDEMPOTENCY_KEY_REUSED" listed = await client.get("/v1/sessions", headers=player["headers"]) assert len(listed.json()["items"]) == 1 async def test_sessions_require_auth(client): sid = uuid.uuid4() for method, url in (("POST", "/v1/sessions"), ("GET", f"/v1/sessions/{sid}"), ("GET", "/v1/sessions"), ("DELETE", f"/v1/sessions/{sid}")): response = await client.request(method, url, json={} if method == "POST" else None) assert response.status_code == 401, (method, url) assert response.json()["error"]["code"] == "UNAUTHENTICATED" # ---------- D3 ---------- async def test_get_session_previous_and_ordinal(client): player = await make_account() h = player["headers"] base = datetime.now(UTC) - timedelta(days=3) first = await create_session(client, h) pending = await create_session(client, h) other_athlete = await create_session(client, h, is_self=False, athlete=OTHER_ATHLETE) pitch = await create_session(client, h, mode="p") deleted = await create_session(client, h) latest = await create_session(client, h) for i, s in enumerate((first, pending, other_athlete, pitch, deleted, latest)): await set_session(s["id"], created_at=base + timedelta(hours=i)) await mark_analyzed(first["id"], 52) await mark_analyzed(deleted["id"], 60) await set_session(deleted["id"], deleted_at=datetime.now(UTC)) await mark_analyzed(latest["id"], 55) s = (await client.get(f"/v1/sessions/{latest['id']}", headers=h)).json()["session"] assert s["status"] == "done" and s["report"]["overall_score"] == 55 and s["analyzed_at"] assert s["previous"]["id"] == first["id"] and s["previous"]["overall_score"] == 52 assert s["ordinal"] == 2 # first, latest: pending and deleted reps are not numbered assert (await client.get(f"/v1/sessions/{first['id']}", headers=h)).json()["session"]["previous"] is None waiting = (await client.get(f"/v1/sessions/{pending['id']}", headers=h)).json()["session"] assert waiting["ordinal"] == 2 # a pending rep is numbered after the analysed ones before it other = (await client.get(f"/v1/sessions/{other_athlete['id']}", headers=h)).json()["session"] assert other["ordinal"] == 1 and other["previous"] is None assert (await client.get(f"/v1/sessions/{pitch['id']}", headers=h)).json()["session"]["ordinal"] == 1 async def test_get_session_access_rules(client): coach = await make_account("coach") other_coach = await make_account("coach") player = await make_account() stranger = await make_account() await make_team_row(coach, player) await make_team_row(other_coach) own = await create_session(client, player["headers"]) someone_else = await create_session(client, player["headers"], is_self=False, athlete=OTHER_ATHLETE) async with get_session_factory()() as db: db.add(Review(session_id=uuid.UUID(own["id"]), coach_id=coach["id"], cue="Shoulder in.", drill_id="hit_13", verdicts={"hip_shoulder_separation_at_foot_down": "agree"})) await db.commit() pending = await client.get(f"/v1/sessions/{own['id']}", headers=coach["headers"]) assert pending.status_code == 403 # nothing for the coach to see until the rep is analysed await mark_analyzed(own["id"], 70) response = await client.get(f"/v1/sessions/{own['id']}", headers=coach["headers"]) assert response.status_code == 200 # private_videos (default true) does not block the coach athlete = response.json()["session"]["athlete"] assert athlete["name"] == PROFILE["name"] and not {"age", "height_cm", "weight_kg"} & athlete.keys() owner_view = (await client.get(f"/v1/sessions/{own['id']}", headers=player["headers"])).json()["session"] assert owner_view["athlete"]["height_cm"] == PROFILE["height_cm"] review = response.json()["session"]["review"] assert review["coach_id"] == str(coach["id"]) and review["coach_name"] == PROFILE["name"] assert review["cue"] == "Shoulder in." and review["drill_id"] == "hit_13" and review["at"] for viewer, session in ((coach, someone_else), (other_coach, own), (stranger, own)): response = await client.get(f"/v1/sessions/{session['id']}", headers=viewer["headers"]) assert response.status_code == 403 assert response.json()["error"]["code"] == "FORBIDDEN" unknown = await client.get(f"/v1/sessions/{uuid.uuid4()}", headers=player["headers"]) assert unknown.status_code == 404 and unknown.json()["error"]["code"] == "NOT_FOUND" await set_session(own["id"], deleted_at=datetime.now(UTC)) for viewer in (player, coach): assert (await client.get(f"/v1/sessions/{own['id']}", headers=viewer["headers"])).status_code == 404 # ---------- D4 ---------- async def test_list_sessions_filters_and_cursor(client): player = await make_account() other = await make_account() h = player["headers"] now = datetime.now(UTC) made = [] for i, overrides in enumerate(( {}, {"mode": "p"}, {"is_self": False, "athlete": OTHER_ATHLETE}, {}, {}, )): s = await create_session(client, h, **overrides) await set_session(s["id"], created_at=now - timedelta(days=10 - i)) made.append(s) await mark_analyzed(made[4]["id"], 61) await set_session(made[3]["id"], deleted_at=now) await create_session(client, other["headers"]) response = await client.get("/v1/sessions", headers=h) assert response.status_code == 200 items = response.json()["items"] assert [i["id"] for i in items] == [made[4]["id"], made[2]["id"], made[1]["id"], made[0]["id"]] top = items[0] assert top["status"] == "done" and top["overall_score"] == 61 and top["athlete_name"] == PROFILE["name"] assert top["focus"]["drill_id"] == "hit_13" and top["thumbnail_url"] and top["review"] is None async def ids(query: str) -> list[str]: r = await client.get(f"/v1/sessions?{query}", headers=h) assert r.status_code == 200, r.text return [i["id"] for i in r.json()["items"]] assert await ids("mode=p") == [made[1]["id"]] assert await ids("self=false") == [made[2]["id"]] assert await ids("mode=h&self=true") == [made[4]["id"], made[0]["id"]] assert await ids("athlete_name=Bilal%20Khan") == [made[2]["id"]] since = (now - timedelta(days=8, hours=12)).isoformat().replace("+00:00", "Z") assert await ids(f"since={since}") == [made[4]["id"], made[2]["id"]] page1 = (await client.get("/v1/sessions?limit=3", headers=h)).json() assert len(page1["items"]) == 3 and page1["next_cursor"] page2 = (await client.get(f"/v1/sessions?limit=3&cursor={page1['next_cursor']}", headers=h)).json() assert [i["id"] for i in page2["items"]] == [made[0]["id"]] and page2["next_cursor"] is None bad = await client.get("/v1/sessions?mode=x&cursor=nope", headers=h) assert bad.status_code == 400 and bad.json()["error"]["code"] == "VALIDATION" # ---------- D5 ---------- async def test_delete_session(client): player = await make_account() other = await make_account() s = await create_session(client, player["headers"]) forbidden = await client.delete(f"/v1/sessions/{s['id']}", headers=other["headers"]) assert forbidden.status_code == 403 and forbidden.json()["error"]["code"] == "FORBIDDEN" response = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"]) assert response.status_code == 204 and response.content == b"" async with httpx.AsyncClient() as s3: # the media is gone right away, not after the retention period assert (await s3.get(s["media"]["video_url"])).status_code == 404 assert (await client.get(f"/v1/sessions/{s['id']}", headers=player["headers"])).status_code == 404 assert (await client.get("/v1/sessions", headers=player["headers"])).json()["items"] == [] again = await client.delete(f"/v1/sessions/{s['id']}", headers=player["headers"]) assert again.status_code == 404 and again.json()["error"]["code"] == "NOT_FOUND" async with get_session_factory()() as db: assert (await db.get(SwingSession, uuid.UUID(s["id"]))).deleted_at is not None