File size: 7,431 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Shared test data builders: database rows for fast setup, and API helpers for the real flows."""

import uuid
from datetime import UTC, datetime, timedelta

import httpx
from sqlalchemy import update

from app.core.database import get_session_factory
from app.core.security import create_access_token
from app.modules.accounts.models import Account
from app.modules.sessions.models import SwingSession
from app.modules.teams.models import Team
from app.modules.uploads.models import Upload
from tests.helpers import bearer

PROFILE = {"name": "Ahmed Rehman", "age": 15, "height_cm": 168.0, "weight_kg": 60.0, "bats": "R", "throws": "R",
           "level": "high_school"}
OTHER_ATHLETE = {"name": "Bilal Khan", "age": 17, "height_cm": 175, "weight_kg": 70, "bats": "L", "throws": "R",
                 "level": "high_school"}
METRICS = ("hip_shoulder_separation_at_foot_down", "stride_relative_length")
FOCUS_NAME = "Hip Shoulder Separation at Foot Down"
VIDEO = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 64
JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 32


# ---------- database rows ----------

async def make_account(role: str = "player", **fields) -> dict:
    """Inserts an account with a full athlete profile; returns {"id", "headers"}."""
    values = {"email": f"{role}-{uuid.uuid4().hex[:10]}@example.com", "role": role, **PROFILE, **fields}
    async with get_session_factory()() as db:
        account = Account(**values)
        db.add(account)
        await db.commit()
        account_id = account.id
    return {"id": account_id, "headers": bearer(create_access_token(account_id)[0])}


async def make_team_row(coach: dict, *players: dict) -> uuid.UUID:
    async with get_session_factory()() as db:
        team = Team(code=f"T-{uuid.uuid4().hex[:4]}".upper(), name="Karachi Diamond Academy",
                    coach_id=coach["id"], coaching="both")
        db.add(team)
        await db.flush()
        for player in players:
            await db.execute(update(Account).where(Account.id == player["id"]).values(team_id=team.id))
        await db.commit()
        return team.id


def sample_report(score: int, metric_ids: tuple[str, ...] = METRICS, focus_name: str = FOCUS_NAME) -> dict:
    return {
        "schema_version": "1.0", "analysis_id": "analysis_001", "analysis_revision": 1, "overall_score": score,
        "overview": {"headline": "Your stride is the area to work on."},
        "groups": [],
        "focus_area": {"metric_id": metric_ids[0] if metric_ids else "none", "group": "stride",
                       "display_name": focus_name, "rating": "off_target",
                       "drill": {"drill_id": "hit_13", "name": "Front Shoulder In Tee"}},
        "measurements": [{"metric_id": m, "value": 1.0} for m in metric_ids],
        "data_quality": [],
    }


async def make_session(owner_id, *, mode: str = "h", is_self: bool = True, score: int | None = 70,
                       analyzed: bool = True, deleted: bool = False, minutes_ago: float = 0,
                       athlete: dict | None = None) -> uuid.UUID:
    created = datetime.now(UTC) - timedelta(minutes=minutes_ago)
    async with get_session_factory()() as db:
        upload_row = Upload(owner_id=owner_id, kind="video", object_key=f"videos/{owner_id}/{uuid.uuid4()}.mp4",
                            content_type="video/mp4", size_bytes=1000, attached_at=created)
        db.add(upload_row)
        await db.flush()
        session = SwingSession(
            owner_id=owner_id, is_self=is_self, athlete=athlete or {"name": "Ahmed", "age": 15, "height_cm": 168},
            mode=mode, video_upload_id=upload_row.id, duration_sec=3.5, fps=30, marks={}, created_at=created,
            report=sample_report(score) if analyzed and score is not None else None,
            analyzed_at=created if analyzed else None, deleted_at=created if deleted else None)
        db.add(session)
        await db.commit()
        return session.id


async def set_session(session_id, **values) -> None:
    async with get_session_factory()() as db:
        await db.execute(update(SwingSession).where(SwingSession.id == uuid.UUID(str(session_id))).values(**values))
        await db.commit()


async def mark_analyzed(session_id, score: int, at: datetime | None = None) -> None:
    await set_session(session_id, report=sample_report(score), analyzed_at=at or datetime.now(UTC))


# ---------- API flows ----------

async def create_team(client: httpx.AsyncClient, coach: dict, name: str = "Karachi Diamond Academy",
                      coaching: str = "both") -> dict:
    response = await client.post("/v1/teams", headers=coach["headers"],
                                 json={"name": name, "coach_name": "Imran Baig", "coaching": coaching})
    assert response.status_code == 201, response.text
    return response.json()["team"]


async def join(client: httpx.AsyncClient, player: dict, code: str) -> None:
    response = await client.post(f"/v1/teams/{code}/join", headers=player["headers"])
    assert response.status_code == 200, response.text


async def upload(client: httpx.AsyncClient, headers: dict, kind: str = "video", *, put: bool = True,
                 content_type: str | None = None, data: bytes | None = None) -> str:
    """D1 then a real presigned PUT to the S3 server. Returns the upload id."""
    content_type = content_type or ("video/mp4" if kind == "video" else "image/jpeg")
    data = data if data is not None else (VIDEO if kind == "video" else JPEG)
    body = {"kind": kind, "content_type": content_type, "size_bytes": len(data)}
    if kind == "video":
        body["duration_sec"] = 3.87
    response = await client.post("/v1/uploads", json=body, headers=headers)
    assert response.status_code == 201, response.text
    target = response.json()
    if put:
        async with httpx.AsyncClient() as s3:
            put_response = await s3.put(target["url"], content=data, headers=target["headers"])
        assert put_response.status_code == 200, put_response.text
    return target["upload_id"]


def session_body(video_id: str, thumb_id: str | None, **overrides) -> dict:
    body = {
        "video_upload_id": video_id, "thumbnail_upload_id": thumb_id, "mode": "h", "is_self": True, "athlete": None,
        "duration_sec": 3.87, "fps": 30,
        "marks": {"contact_frame": 84, "contact_offset": -2, "contact_source": "detected",
                  "stride_start_frame": 58, "stride_end_frame": 79,
                  "pitcher_direction": {"from": [0.56, 0.86], "to": [0.90, 0.64]}},
    }
    return {**body, **overrides}


async def create_session(client: httpx.AsyncClient, headers: dict, **overrides) -> dict:
    video_id = await upload(client, headers, "video")
    thumb_id = await upload(client, headers, "thumbnail")
    response = await client.post("/v1/sessions", json=session_body(video_id, thumb_id, **overrides), headers=headers)
    assert response.status_code == 201, response.text
    return response.json()["session"]


class FakePush:
    """Records push sends; tokens listed in `dead` are reported back as unregistered."""

    def __init__(self, dead: list[str] | None = None):
        self.calls: list[tuple[list[str], dict]] = []
        self.dead = dead or []

    async def send(self, tokens: list[str], data: dict, notification: dict | None = None) -> list[str]:
        self.calls.append((list(tokens), dict(data)))
        return [t for t in tokens if t in self.dead]