Spaces:
Running on T4
Running on T4
File size: 9,983 Bytes
fe40b87 | 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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | """N20-N22: drill assignments and set completion (C08)."""
import asyncio
import uuid
from datetime import UTC, datetime, timedelta
from app.core.database import get_session_factory
from app.modules.academy.models import LibraryDrill
from tests.factories import create_session, make_account, make_team_row
TODAY = datetime.now(UTC).date()
def due(days=1):
return (TODAY + timedelta(days=days)).isoformat()
async def team(n=1):
coach = await make_account("coach", name="Jamie")
players = [await make_account("player") for _ in range(n)]
team_id = await make_team_row(coach, *players)
return coach, players, team_id
def assign_url(player):
return f"/v1/coach/players/{player['id']}/drill-assignments"
async def assign(client, coach, player, **overrides):
body = {"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due(), **overrides}
return await client.post(assign_url(player), json=body, headers=coach["headers"])
async def log_set(client, player, assignment_id, set_number=1, reps_done=8, key=None, day=None):
headers = {**player["headers"], **({"Idempotency-Key": key} if key else {})}
return await client.post(f"/v1/drill-assignments/{assignment_id}/sets", headers=headers,
json={"set_number": set_number, "reps_done": reps_done, "day": day or TODAY.isoformat()})
async def test_assign_and_list(client):
coach, (player, other), _ = await team(2)
response = await assign(client, coach, player)
assert response.status_code == 201, response.text
a = response.json()["assignment"]
assert a["drill_id"] == "hit_13" and a["sets"] == 3 and a["reps"] == 8 and a["done"] == 0
assert a["due"] == "Tomorrow" and a["assigned_by"] == "Jamie" and a["media"] is None and a["name"]
assert a["session_id"] is None
listed = (await client.get("/v1/drill-assignments?mode=h", headers=player["headers"])).json()
assert [i["id"] for i in listed["items"]] == [a["id"]]
assert (await client.get("/v1/drill-assignments?mode=h", headers=other["headers"])).json()["items"] == []
assert (await client.get("/v1/drill-assignments?mode=p", headers=player["headers"])).json()["items"] == []
staff_view = await client.get(f"/v1/drill-assignments?mode=h&player_id={player['id']}", headers=coach["headers"])
assert [i["id"] for i in staff_view.json()["items"]] == [a["id"]]
assert (await client.get("/v1/drill-assignments?mode=h", headers=coach["headers"])).json()["items"][0]["id"] \
== a["id"]
assert (await client.get(f"/v1/drill-assignments?mode=h&player_id={other['id']}",
headers=player["headers"])).status_code == 404
async def test_assign_validation_and_permissions(client):
coach, (player,), _ = await team()
assert (await assign(client, coach, player, due_date=due(-1))).status_code == 400
assert (await assign(client, coach, player, drill_id="nope")).status_code == 404
mismatch = await assign(client, coach, player, drill_id="pit_02")
assert mismatch.status_code == 422 and mismatch.json()["error"]["code"] == "MODE_MISMATCH"
assert (await assign(client, coach, player, source_session_id=str(uuid.uuid4()))).status_code == 404
other_session = await create_session(client, (await make_account())["headers"])
assert (await assign(client, coach, player, source_session_id=other_session["id"])).status_code == 404
own = await create_session(client, player["headers"])
ok = await assign(client, coach, player, source_session_id=own["id"])
assert ok.status_code == 201 and ok.json()["assignment"]["session_id"] == own["id"]
assert (await client.post(assign_url(player), json={"mode": "h"}, headers=coach["headers"])).status_code == 400
assert (await assign(client, player, player)).status_code == 403
async def test_assign_cross_team_404(client):
_, (player,), _ = await team()
other_coach, _, _ = await team()
assert (await assign(client, other_coach, player)).status_code == 404
async def test_assign_library_drill(client):
coach, (player,), team_id = await team()
_, _, other_team = await team()
async with get_session_factory()() as db:
mine = LibraryDrill(team_id=team_id, name="Wall drill", fixes="Stride", mode="h")
theirs = LibraryDrill(team_id=other_team, name="Theirs", fixes="", mode="h")
pit = LibraryDrill(team_id=team_id, name="Pitch", fixes="", mode="p")
db.add_all([mine, theirs, pit])
await db.commit()
ids = (str(mine.id), str(theirs.id), str(pit.id))
ok = await assign(client, coach, player, drill_source="library", drill_id=ids[0])
assert ok.status_code == 201, ok.text
assert (ok.json()["assignment"]["name"], ok.json()["assignment"]["fixes"]) == ("Wall drill", "Stride")
assert (await assign(client, coach, player, drill_source="library", drill_id=ids[1])).status_code == 404
assert (await assign(client, coach, player, drill_source="library", drill_id=ids[2])).status_code == 422
assert (await assign(client, coach, player, drill_source="library", drill_id="x")).status_code == 400
async def test_assign_idempotent(client):
coach, (player,), _ = await team()
headers = {**coach["headers"], "Idempotency-Key": "k1"}
body = {"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due()}
first = await client.post(assign_url(player), json=body, headers=headers)
second = await client.post(assign_url(player), json=body, headers=headers)
assert first.json() == second.json()
items = (await client.get("/v1/drill-assignments?mode=h", headers=player["headers"])).json()["items"]
assert len(items) == 1
async def test_same_drill_two_players_progress_is_separate(client):
coach, (p1, p2), _ = await team(2)
a1 = (await assign(client, coach, p1)).json()["assignment"]
a2 = (await assign(client, coach, p2)).json()["assignment"]
a3 = (await assign(client, coach, p1)).json()["assignment"]
result = await log_set(client, p1, a1["id"])
assert result.status_code == 201, result.text
assert result.json()["assignment"]["done"] == 1
assert result.json()["set_log"]["set_number"] == 1
for who, a, expected in ((p1, a1, 1), (p2, a2, 0), (p1, a3, 0)):
items = (await client.get("/v1/drill-assignments?mode=h", headers=who["headers"])).json()["items"]
assert {i["id"]: i["done"] for i in items}[a["id"]] == expected
assert (await log_set(client, p2, a1["id"])).status_code == 404
assert (await log_set(client, coach, a1["id"])).status_code == 403
async def test_set_retry_counts_once_and_log_appears_once(client):
coach, (player,), _ = await team()
a = (await assign(client, coach, player)).json()["assignment"]
first = await log_set(client, player, a["id"], key="same")
retry = await log_set(client, player, a["id"], key="same")
other_key = await log_set(client, player, a["id"], key="other")
assert first.status_code == retry.status_code == other_key.status_code == 201
assert first.json()["set_log"] == retry.json()["set_log"] == other_key.json()["set_log"]
assert other_key.json()["assignment"]["done"] == 1
conflict = await log_set(client, player, a["id"], reps_done=5)
assert conflict.status_code == 409
logs = (await client.get(f"/v1/drill-logs?from={TODAY}&to={TODAY}", headers=player["headers"])).json()["items"]
assert len(logs) == 1
assert logs[0]["assignment_id"] == a["id"] and logs[0]["drill_id"] == "hit_13" and logs[0]["reps"] == 8
done = (await client.get("/v1/drill-assignments?mode=h&status=completed", headers=player["headers"])).json()
assert done["items"] == []
open_ = (await client.get("/v1/drill-assignments?mode=h&status=open", headers=player["headers"])).json()
assert len(open_["items"]) == 1
async def test_set_validation(client):
coach, (player,), _ = await team()
a = (await assign(client, coach, player)).json()["assignment"]
assert (await log_set(client, player, a["id"], set_number=4)).status_code == 422
assert (await log_set(client, player, a["id"], reps_done=9)).status_code == 422
assert (await log_set(client, player, a["id"], set_number=0)).status_code == 400
assert (await log_set(client, player, uuid.uuid4())).status_code == 404
async def test_concurrent_completion_cannot_exceed_sets(client):
coach, (player,), _ = await team()
a = (await assign(client, coach, player)).json()["assignment"]
results = await asyncio.gather(*(log_set(client, player, a["id"], set_number=n) for n in range(1, 6)),
*(log_set(client, player, a["id"], set_number=1) for _ in range(3)))
statuses = sorted(r.status_code for r in results)
assert statuses.count(201) == 3 + 3 and statuses.count(422) == 2
items = (await client.get("/v1/drill-assignments?mode=h&status=completed", headers=player["headers"])).json()
assert items["items"][0]["done"] == 3
logs = (await client.get(f"/v1/drill-logs?from={TODAY}&to={TODAY}", headers=player["headers"])).json()["items"]
assert len(logs) == 3
async def test_due_label_and_pagination(client):
coach, (player,), _ = await team()
ids = [(await assign(client, coach, player, due_date=due(d))).json()["assignment"] for d in (0, 3, 20)]
assert ids[0]["due"] == "Today"
assert ids[1]["due"] == (TODAY + timedelta(days=3)).strftime("%A")
assert ids[2]["due"] == (TODAY + timedelta(days=20)).strftime("%b %d")
page = (await client.get("/v1/drill-assignments?mode=h&limit=2", headers=player["headers"])).json()
assert len(page["items"]) == 2 and page["next_cursor"]
rest = (await client.get(f"/v1/drill-assignments?mode=h&limit=2&cursor={page['next_cursor']}",
headers=player["headers"])).json()
assert len(rest["items"]) == 1 and rest["next_cursor"] is None
assert {i["id"] for i in page["items"] + rest["items"]} == {a["id"] for a in ids}
|