Spaces:
Running on T4
Running on T4
File size: 17,541 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | """N10-N15: conversations."""
import httpx
import pytest
from sqlalchemy import select, update
from app.core.database import get_session_factory
from app.integrations.push import get_push_client
from app.modules.academy.models import AcademyMembership
from app.modules.notifications.models import Notification
from tests.factories import FakePush, create_team, join, make_account, make_session, upload
REVIEW = {"cue": "Stay tall.", "drill_id": "hit_01", "verdicts": {}}
@pytest.fixture(autouse=True)
def push(app):
fake = FakePush()
app.dependency_overrides[get_push_client] = lambda: fake
yield fake
app.dependency_overrides.pop(get_push_client, None)
@pytest.fixture
async def team(client):
coach = await make_account("coach", name="Imran Baig")
created = await create_team(client, coach)
player = await make_account("player", name="Ahmed")
await join(client, player, created["code"])
return {"coach": coach, "player": player}
async def _general(client, team, mode="h"):
response = await client.post(f"/v1/coach/players/{team['player']['id']}/thread",
headers=team["coach"]["headers"], json={"mode": mode})
assert response.status_code in (200, 201), response.text
return response
async def _audio(client, headers, *, put=True) -> str:
data = b"\x00\x00\x00\x18ftypM4A " + b"\x00" * 40
response = await client.post("/v1/uploads", headers=headers, json={
"kind": "audio", "content_type": "audio/mp4", "size_bytes": len(data), "duration_sec": 5})
target = response.json()
if put:
async with httpx.AsyncClient() as s3:
await s3.put(target["url"], content=data, headers=target["headers"])
return target["upload_id"]
async def _send(client, headers, thread_id, **body):
return await client.post(f"/v1/threads/{thread_id}/messages", headers=headers, json=body)
async def _notes(account_id) -> list[Notification]:
async with get_session_factory()() as db:
return list(await db.scalars(select(Notification).where(Notification.recipient_id == account_id)))
async def test_ensure_general_thread_201_then_200(client, team):
first = await _general(client, team)
assert first.status_code == 201
thread = first.json()["thread"]
assert thread["session_id"] is None and thread["session_label"] == "Latest session" and thread["score"] is None
assert thread["coach_id"] == str(team["coach"]["id"]) and thread["player_name"] == "Ahmed"
assert thread["coach_name"] == "Imran Baig" and thread["messages"] == [] and thread["tone"] == "y"
second = await _general(client, team)
assert second.status_code == 200 and second.json()["thread"]["id"] == thread["id"]
other_mode = await _general(client, team, "p")
assert other_mode.status_code == 201 and other_mode.json()["thread"]["id"] != thread["id"]
async def test_ensure_general_thread_authorization(client, team):
outsider = await make_account("coach")
await create_team(client, outsider, name="Other")
stranger = await make_account("player")
url = f"/v1/coach/players/{team['player']['id']}/thread"
assert (await client.post(url, headers=outsider["headers"], json={"mode": "h"})).status_code == 404
assert (await client.post(url, headers=team["player"]["headers"], json={"mode": "h"})).status_code == 403
assert (await client.post(url, headers=team["coach"]["headers"], json={"mode": "x"})).status_code == 400
missing = f"/v1/coach/players/{stranger['id']}/thread"
assert (await client.post(missing, headers=team["coach"]["headers"], json={"mode": "h"})).status_code == 404
async def test_text_conversation_status_unread_and_read(client, team):
coach, player = team["coach"]["headers"], team["player"]["headers"]
thread_id = (await _general(client, team)).json()["thread"]["id"]
sent = await _send(client, coach, thread_id, kind="text", text=" Try the drill. ")
assert sent.status_code == 201, sent.text
body = sent.json()
assert body["thread_status"] == "reviewed" and body["message"]["from"] == "coach"
assert body["message"]["text"] == "Try the drill." and body["message"]["author_id"] == str(team["coach"]["id"])
[note] = await _notes(team["player"]["id"])
assert note.target == {"thread_id": thread_id} and note.event_key == f"message:{body['message']['id']}"
view = (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]
assert view["unread_for_player"] is True and view["unread_for_coach"] is False
reply = await _send(client, player, thread_id, kind="text", text="Will do")
assert reply.json()["thread_status"] == "waiting_for_coach" and reply.json()["message"]["from"] == "player"
assert len(await _notes(team["coach"]["id"])) == 1
view = (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]
assert [m["text"] for m in view["messages"]] == ["Try the drill.", "Will do"]
# Replying marks everything up to the reply read for the sender.
assert view["unread_for_player"] is False and view["unread_for_coach"] is True
first_id, second_id = (m["id"] for m in view["messages"])
# A read for the first message cannot move the watermark back.
assert (await client.post(f"/v1/threads/{thread_id}/read", headers=player,
json={"last_message_id": first_id})).status_code == 204
view = (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]
assert view["unread_for_player"] is False and view["unread_for_coach"] is True
assert (await client.post(f"/v1/threads/{thread_id}/read", headers=coach,
json={"last_message_id": second_id})).status_code == 204
view = (await client.get(f"/v1/threads/{thread_id}", headers=coach)).json()["thread"]
assert view["unread_for_coach"] is False
# Monotonic: an older id never moves the watermark back.
await client.post(f"/v1/threads/{thread_id}/read", headers=coach, json={"last_message_id": first_id})
assert (await client.get(f"/v1/threads/{thread_id}", headers=coach)).json()["thread"]["unread_for_coach"] is False
assert (await client.post(f"/v1/threads/{thread_id}/read", headers=coach,
json={"last_message_id": None})).status_code == 204
async def test_read_rejects_foreign_message(client, team):
one = (await _general(client, team)).json()["thread"]["id"]
two = (await _general(client, team, "p")).json()["thread"]["id"]
message = (await _send(client, team["coach"]["headers"], two, kind="text", text="hi")).json()["message"]
response = await client.post(f"/v1/threads/{one}/read", headers=team["coach"]["headers"],
json={"last_message_id": message["id"]})
assert response.status_code == 422 and response.json()["error"]["code"] == "MESSAGE_NOT_IN_THREAD"
async def test_message_validation_and_review_kind_forbidden(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
headers = team["coach"]["headers"]
for body in [{"kind": "text", "text": " "}, {"kind": "text", "text": "x" * 501}, {"kind": "review"},
{"kind": "text", "text": "hi", "from": "player"}, {"kind": "voice", "upload_id": "nope", "seconds": 3},
{"kind": "voice", "upload_id": "70000000-0000-4000-8000-000000000001", "seconds": 0}]:
response = await _send(client, headers, thread_id, **body)
assert response.status_code == 400, body
assert (await _send(client, headers, thread_id, kind="text", text="x" * 500)).status_code == 201
async def test_voice_message(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
player = team["player"]["headers"]
pending = await _audio(client, player, put=False)
response = await _send(client, player, thread_id, kind="voice", upload_id=pending, seconds=5)
assert response.status_code == 409 and response.json()["error"]["code"] == "UPLOAD_NOT_READY"
coach_audio = await _audio(client, team["coach"]["headers"])
response = await _send(client, player, thread_id, kind="voice", upload_id=coach_audio, seconds=5)
assert response.status_code == 422 and response.json()["error"]["code"] == "INVALID_UPLOAD"
thumb = await upload(client, player, "thumbnail")
assert (await _send(client, player, thread_id, kind="voice", upload_id=thumb, seconds=5)).status_code == 422
good = await _audio(client, player)
response = await _send(client, player, thread_id, kind="voice", upload_id=good, seconds=5)
assert response.status_code == 201, response.text
message = response.json()["message"]
assert message["kind"] == "voice" and message["seconds"] == 5 and message["audio"]["upload_id"] == good
assert message["audio"]["url"] and message["audio"]["expires_at"]
again = await _send(client, player, thread_id, kind="voice", upload_id=good, seconds=5)
assert again.status_code == 422 and again.json()["error"]["code"] == "UPLOAD_ALREADY_USED"
# The coach can load the playable audio.
view = (await client.get(f"/v1/threads/{thread_id}", headers=team["coach"]["headers"])).json()["thread"]
assert view["messages"][0]["audio"]["url"]
async def test_session_attachment(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
player = team["player"]["headers"]
mine = await make_session(team["player"]["id"], score=74)
response = await _send(client, player, thread_id, kind="session", session_id=str(mine))
assert response.status_code == 201, response.text
message = response.json()["message"]
assert message["kind"] == "session" and message["session_id"] == str(mine)
assert message["label"] == "Swing 1" and message["score"] == 74
pitching = await make_session(team["player"]["id"], mode="p")
deleted = await make_session(team["player"]["id"], deleted=True)
stranger = await make_account("player")
foreign = await make_session(stranger["id"])
for session_id, status in [(pitching, 422), (deleted, 404), (foreign, 404)]:
response = await _send(client, player, thread_id, kind="session", session_id=str(session_id))
assert response.status_code == status, (session_id, response.text)
async def test_send_idempotency_key(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
headers = {**team["coach"]["headers"], "Idempotency-Key": "k1"}
body = {"kind": "text", "text": "once"}
one = await client.post(f"/v1/threads/{thread_id}/messages", headers=headers, json=body)
two = await client.post(f"/v1/threads/{thread_id}/messages", headers=headers, json=body)
assert one.status_code == two.status_code == 201 and one.json() == two.json()
other = await client.post(f"/v1/threads/{thread_id}/messages", headers=headers, json={**body, "text": "twice"})
assert other.status_code == 409
view = (await client.get(f"/v1/threads/{thread_id}", headers=headers)).json()["thread"]
assert [m["text"] for m in view["messages"]] == ["once"]
async def test_message_paging(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
headers = team["coach"]["headers"]
for i in range(5):
await _send(client, headers, thread_id, kind="text", text=f"m{i}")
page = (await client.get(f"/v1/threads/{thread_id}?message_limit=2", headers=headers)).json()["thread"]
assert [m["text"] for m in page["messages"]] == ["m3", "m4"] and page["next_message_cursor"]
older = (await client.get(f"/v1/threads/{thread_id}?message_limit=2&message_cursor={page['next_message_cursor']}",
headers=headers)).json()["thread"]
assert [m["text"] for m in older["messages"]] == ["m1", "m2"]
last = (await client.get(f"/v1/threads/{thread_id}?message_limit=5&message_cursor={older['next_message_cursor']}",
headers=headers)).json()["thread"]
assert [m["text"] for m in last["messages"]] == ["m0"] and last["next_message_cursor"] is None
bad = await client.get(f"/v1/threads/{thread_id}?message_cursor=zzz", headers=headers)
assert bad.status_code == 400
assert (await client.get(f"/v1/threads/{thread_id}?message_limit=101", headers=headers)).status_code == 400
async def test_list_filters_scope_and_paging(client, team):
coach, player = team["coach"]["headers"], team["player"]["headers"]
h = (await _general(client, team, "h")).json()["thread"]["id"]
p = (await _general(client, team, "p")).json()["thread"]["id"]
await _send(client, coach, h, kind="text", text="hello")
listed = (await client.get("/v1/threads", headers=player)).json()
assert [t["id"] for t in listed["items"]] == [h, p] and listed["next_cursor"] is None # newest activity first
assert listed["items"][0]["messages"][0]["text"] == "hello"
assert [t["id"] for t in (await client.get("/v1/threads?mode=p", headers=player)).json()["items"]] == [p]
assert [t["id"] for t in (await client.get("/v1/threads?unread=true", headers=player)).json()["items"]] == [h]
assert [t["id"] for t in (await client.get("/v1/threads?unread=true", headers=coach)).json()["items"]] == []
assert len((await client.get(f"/v1/threads?player_id={team['player']['id']}", headers=coach)).json()["items"]) == 2
# A player cannot widen scope through player_id.
stranger = await make_account("player")
assert len((await client.get(f"/v1/threads?player_id={stranger['id']}", headers=player)).json()["items"]) == 2
first = (await client.get("/v1/threads?limit=1", headers=player)).json()
assert [t["id"] for t in first["items"]] == [h] and first["next_cursor"]
second = (await client.get(f"/v1/threads?limit=1&cursor={first['next_cursor']}", headers=player)).json()
assert [t["id"] for t in second["items"]] == [p] and second["next_cursor"] is None
async def test_cross_team_and_stranger_access_is_404(client, team):
thread_id = (await _general(client, team)).json()["thread"]["id"]
session_id = await make_session(team["player"]["id"])
await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"], json=REVIEW)
outsider = await make_account("coach")
await create_team(client, outsider, name="Other")
stranger = await make_account("player")
for who in (outsider, stranger):
h = who["headers"]
assert (await client.get(f"/v1/threads/{thread_id}", headers=h)).status_code == 404
assert (await client.get(f"/v1/sessions/{session_id}/thread", headers=h)).status_code == 404
assert (await client.post(f"/v1/threads/{thread_id}/read", headers=h, json={})).status_code == 404
assert (await _send(client, h, thread_id, kind="text", text="hi")).status_code == 404
assert (await client.get("/v1/threads", headers=h)).json()["items"] == []
assert (await client.get(f"/v1/threads/{thread_id}")).status_code == 401
async def test_session_thread_not_found(client, team):
session_id = await make_session(team["player"]["id"])
response = await client.get(f"/v1/sessions/{session_id}/thread", headers=team["player"]["headers"])
assert response.status_code == 404 and response.json()["error"]["code"] == "THREAD_NOT_FOUND"
async def test_review_thread_accepts_replies_and_keeps_them_on_re_review(client, team):
coach, player = team["coach"]["headers"], team["player"]["headers"]
session_id = await make_session(team["player"]["id"], score=85)
url = f"/v1/sessions/{session_id}/review"
thread_id = (await client.post(url, headers=coach, json=REVIEW)).json()["thread_id"]
await _send(client, player, thread_id, kind="text", text="Thanks coach")
await client.post(url, headers=coach, json={**REVIEW, "cue": "Updated"})
thread = (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]
assert thread["session_label"] == "Swing 1" and thread["score"] == 85 and thread["tone"] == "g"
assert thread["status"] == "reviewed"
kinds = [(m["kind"], m["from"]) for m in thread["messages"]]
assert kinds == [("text", "player"), ("review", "coach")] # the review message moved to the newest position
assert thread["messages"][1]["cue"] == "Updated"
async def test_paused_member_loses_access(client, team):
assistant = await make_account("player", name="Helper")
from app.modules.accounts.models import Account
async with get_session_factory()() as db:
team_id = await db.scalar(select(Account.team_id).where(Account.id == team["player"]["id"]))
db.add(AcademyMembership(team_id=team_id, account_id=assistant["id"], role="coach", status="active",
sees_all=True, permissions={"review": True}))
await db.commit()
thread_id = (await _general(client, team)).json()["thread"]["id"]
h = assistant["headers"]
assert (await client.get(f"/v1/threads/{thread_id}", headers=h)).status_code == 200
assert (await _send(client, h, thread_id, kind="text", text="from helper")).status_code == 201
async with get_session_factory()() as db:
await db.execute(update(AcademyMembership).where(AcademyMembership.account_id == assistant["id"])
.values(status="paused"))
await db.commit()
assert (await client.get(f"/v1/threads/{thread_id}", headers=h)).status_code == 404
assert (await client.get("/v1/threads", headers=h)).json()["items"] == []
|