Spaces:
Running on T4
Running on T4
Download backend/tests/factories.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 7.43 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/tests/factories.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/tests/factories.py
-
curl -L -o factories.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/tests/factories.py
7.43 kB
| """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] | |