Spaces:
Running on T4
Running on T4
File size: 13,557 Bytes
e980186 | 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 | """The chat socket (WS /v1/chat/ws): every chat command and the live events, driven through serve() with an
in-memory socket so the test shares the app's event loop and database pool."""
import asyncio
import itertools
import json
from datetime import UTC, datetime, timedelta
import httpx
import pytest
from fastapi import WebSocketDisconnect
from app.modules.threads import live
from app.modules.threads.socket import CLOSE_UNAUTHENTICATED, serve
from tests.factories import create_team, join, make_account, make_session, upload
REVIEW = {"cue": "Stay tall.", "drill_id": "hit_01", "verdicts": {}}
_ids = itertools.count(1)
class FakeSocket:
def __init__(self):
self.inbox: asyncio.Queue = asyncio.Queue()
self.outbox: asyncio.Queue = asyncio.Queue()
self.events: list[dict] = []
self.closed: int | None = None
async def accept(self):
pass
async def receive_text(self) -> str:
item = await self.inbox.get()
if item is None:
raise WebSocketDisconnect()
return item
async def send_text(self, data: str):
await self.outbox.put(json.loads(data))
async def close(self, code: int = 1000):
self.closed = code
async def call(self, kind: str, **params) -> dict:
"""Send one command and return its reply; events that arrive meanwhile are kept in .events."""
request_id = f"r{next(_ids)}"
await self.inbox.put(json.dumps({"id": request_id, "type": kind, **params}))
while True:
frame = await asyncio.wait_for(self.outbox.get(), 10)
if frame.get("id") == request_id:
return frame
self.events.append(frame)
async def pushed(self) -> list[dict]:
"""Events received so far, after every pending delivery has finished."""
await live.idle()
while not self.outbox.empty():
self.events.append(self.outbox.get_nowait())
events, self.events = self.events, []
return events
@pytest.fixture
async def sockets():
opened: list[tuple[FakeSocket, asyncio.Task]] = []
async def connect(account: dict | None = None) -> FakeSocket:
socket = FakeSocket()
opened.append((socket, asyncio.create_task(serve(socket))))
if account is not None:
reply = await socket.call("auth", token=account["headers"]["Authorization"][7:])
assert reply["type"] == "auth.ok" and reply["data"]["account_id"] == str(account["id"])
return socket
yield connect
await live.idle()
for socket, task in opened:
await socket.inbox.put(None)
await task
assert not live.CONNECTIONS
async def ensure_thread(coach: FakeSocket, team: dict, mode: str = "h") -> str:
reply = await coach.call("thread.ensure", player_id=str(team["player"]["id"]), mode=mode)
return reply["data"]["thread"]["id"]
@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 test_first_frame_must_be_a_valid_auth(sockets):
socket = await sockets()
reply = await socket.call("threads.list")
assert reply["type"] == "error" and reply["status"] == 401 and reply["error"]["code"] == "UNAUTHENTICATED"
assert socket.closed == CLOSE_UNAUTHENTICATED
other = await sockets()
assert (await other.call("auth", token="not-a-token"))["error"]["code"] == "UNAUTHENTICATED"
assert other.closed == CLOSE_UNAUTHENTICATED and not live.CONNECTIONS
async def test_conversation_runs_entirely_over_the_socket(client, sockets, team):
coach, player = await sockets(team["coach"]), await sockets(team["player"])
ensured = await coach.call("thread.ensure", player_id=str(team["player"]["id"]), mode="h")
assert ensured["type"] == "thread.ensure.ok" and ensured["data"]["created"] is True
thread_id = ensured["data"]["thread"]["id"]
[new] = await player.pushed()
assert new["type"] == "thread.new" and new["data"]["thread"]["id"] == thread_id
again = await coach.call("thread.ensure", player_id=str(team["player"]["id"]), mode="h")
assert again["data"]["created"] is False and await player.pushed() == []
listed = await player.call("threads.list")
assert [t["id"] for t in listed["data"]["items"]] == [thread_id] and listed["data"]["next_cursor"] is None
sent = await player.call("message.send", thread_id=thread_id, message={"kind": "text", "text": "Hi coach"})
assert sent["type"] == "message.send.ok" and sent["data"]["thread_status"] == "waiting_for_coach"
message = sent["data"]["message"]
assert (message["kind"], message["from"], message["text"]) == ("text", "player", "Hi coach")
[event] = [e for e in await coach.pushed() if e["type"] == "message.new"]
assert event["data"]["message"] == message and event["data"]["thread_id"] == thread_id
assert event["data"]["unread_for_coach"] is True and event["data"]["unread_for_player"] is False
[echo] = await player.pushed() # the sender's own sockets get the event too
assert echo["data"]["message"]["id"] == message["id"]
read = await coach.call("thread.read", thread_id=thread_id, last_message_id=message["id"])
assert read == {"id": read["id"], "type": "thread.read.ok", "data": {}}
[seen] = await player.pushed()
assert seen["type"] == "thread.read" and seen["data"]["unread_for_coach"] is False
opened = await coach.call("thread.get", thread_id=thread_id, message_limit=10)
assert [m["id"] for m in opened["data"]["thread"]["messages"]] == [message["id"]]
# The socket and REST return the same thread.
rest = (await client.get(f"/v1/threads/{thread_id}", headers=team["coach"]["headers"])).json()["thread"]
assert opened["data"]["thread"] == rest
async def test_rest_writes_and_coach_reviews_reach_open_sockets(client, sockets, team):
player = await sockets(team["player"])
session_id = await make_session(team["player"]["id"], score=85)
review = await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"], json=REVIEW)
thread_id = review.json()["thread_id"]
events = await player.pushed()
assert [e["data"]["message"]["kind"] for e in events if e["type"] == "message.new"] == ["review"]
response = await client.post(f"/v1/threads/{thread_id}/messages", headers=team["coach"]["headers"],
json={"kind": "text", "text": "From an older app build"})
assert response.status_code == 201
[event] = await player.pushed()
assert event["data"]["message"]["id"] == response.json()["message"]["id"]
by_session = await player.call("thread.for_session", session_id=str(session_id))
assert by_session["data"]["thread"]["id"] == thread_id
async def test_resend_with_the_same_key_creates_one_message(sockets, team):
coach, player = await sockets(team["coach"]), await sockets(team["player"])
thread_id = await ensure_thread(coach, team, "p")
await player.pushed()
body = {"thread_id": thread_id, "idempotency_key": "send-1", "message": {"kind": "text", "text": "Once"}}
first, second = await player.call("message.send", **body), await player.call("message.send", **body)
assert first["data"] == second["data"]
assert len([e for e in await coach.pushed() if e["type"] == "message.new"]) == 1
reused = await player.call("message.send", **{**body, "message": {"kind": "text", "text": "Other"}})
assert reused["status"] == 409 and reused["error"]["code"] == "IDEMPOTENCY_KEY_REUSED"
async def test_errors_use_the_api_error_shape(sockets, team):
coach, player = await sockets(team["coach"]), await sockets(team["player"])
thread_id = await ensure_thread(coach, team)
unknown = await player.call("threads.delete")
assert unknown["status"] == 400 and unknown["error"]["fields"] == {"type": "Unknown command."}
bad = await player.call("message.send", thread_id=thread_id, message={"kind": "text", "text": ""})
assert bad["error"]["code"] == "VALIDATION" and "message.text.text" in bad["error"]["fields"]
assert (await player.call("thread.ensure", player_id=str(team["player"]["id"]), mode="h"))["status"] == 403
stranger = await sockets(await make_account("player", name="Other"))
hidden = await stranger.call("thread.get", thread_id=thread_id)
assert hidden["status"] == 404 and hidden["error"]["code"] == "NOT_FOUND"
await player.call("message.send", thread_id=thread_id, message={"kind": "text", "text": "Private"})
assert await stranger.pushed() == []
await player.pushed()
await player.inbox.put("{not json")
assert (await asyncio.wait_for(player.outbox.get(), 10))["error"]["code"] == "VALIDATION"
assert (await player.call("ping"))["type"] == "pong"
async def test_expired_token_stops_commands_and_events_until_auth_is_sent_again(sockets, team):
coach, player = await sockets(team["coach"]), await sockets(team["player"])
thread_id = await ensure_thread(coach, team)
await player.pushed()
[connection] = [c for c in live.CONNECTIONS if c.account_id == team["player"]["id"]]
connection.expires_at = datetime.now(UTC) - timedelta(seconds=1)
expired = await player.call("threads.list")
assert expired["status"] == 401 and expired["error"]["code"] == "TOKEN_EXPIRED" and player.closed is None
await coach.call("message.send", thread_id=thread_id, message={"kind": "text", "text": "While expired"})
assert await player.pushed() == []
renewed = await player.call("auth", token=team["player"]["headers"]["Authorization"][7:])
assert renewed["type"] == "auth.ok"
other = await make_account("player", name="Other")
swapped = await player.call("auth", token=other["headers"]["Authorization"][7:])
assert swapped["status"] == 401
thread = (await player.call("thread.get", thread_id=thread_id))["data"]["thread"]
assert [m["text"] for m in thread["messages"]] == ["While expired"]
async def test_image_and_video_messages_carry_a_media_url(client, sockets, team):
coach, player = await sockets(team["coach"]), await sockets(team["player"])
thread_id = await ensure_thread(coach, team)
headers = team["player"]["headers"]
image_id, video_id = await upload(client, headers, "image"), await upload(client, headers, "video")
photo = await player.call("message.send", thread_id=thread_id, message={"kind": "image", "upload_id": image_id})
assert photo["type"] == "message.send.ok", photo
message = photo["data"]["message"]
assert message["kind"] == "image" and message["media"]["upload_id"] == image_id
assert message["media"]["url"].startswith("http") and message["media"]["expires_at"]
async with httpx.AsyncClient() as storage: # the URL really serves the file
assert (await storage.get(message["media"]["url"])).status_code == 200
clip = await player.call("message.send", thread_id=thread_id,
message={"kind": "video", "upload_id": video_id, "seconds": 3.9})
video = clip["data"]["message"]
assert (video["kind"], video["seconds"], video["media"]["seconds"]) == ("video", 3.9, 3.9)
assert "/videos/" in video["media"]["url"]
pushed = [e["data"]["message"] for e in await coach.pushed() if e["type"] == "message.new"]
assert [(m["kind"], m["media"]["upload_id"]) for m in pushed] == [("image", image_id), ("video", video_id)]
thread = (await coach.call("thread.get", thread_id=thread_id))["data"]["thread"]
assert [m["kind"] for m in thread["messages"]] == ["image", "video"]
rest = (await client.get(f"/v1/threads/{thread_id}", headers=headers)).json()["thread"]
assert [m["media"]["upload_id"] for m in rest["messages"]] == [image_id, video_id]
# An upload is used once, must be the right kind, and must be the sender's own.
again = await player.call("message.send", thread_id=thread_id, message={"kind": "image", "upload_id": image_id})
assert again["status"] == 422 and again["error"]["code"] == "UPLOAD_ALREADY_USED"
other_video = await upload(client, headers, "video")
wrong = await player.call("message.send", thread_id=thread_id, message={"kind": "image", "upload_id": other_video})
assert wrong["error"]["code"] == "INVALID_UPLOAD"
theirs = await coach.call("message.send", thread_id=thread_id,
message={"kind": "video", "upload_id": other_video, "seconds": 3.9})
assert theirs["error"]["code"] == "INVALID_UPLOAD"
unfinished = await upload(client, headers, "image", put=False)
pending = await player.call("message.send", thread_id=thread_id, message={"kind": "image", "upload_id": unfinished})
assert pending["status"] == 409 and pending["error"]["code"] == "UPLOAD_NOT_READY"
async def test_image_upload_limits(client, team):
headers = team["player"]["headers"]
body = {"kind": "image", "content_type": "image/png", "size_bytes": 1000}
assert (await client.post("/v1/uploads", json=body, headers=headers)).status_code == 201
gif = await client.post("/v1/uploads", json={**body, "content_type": "image/gif"}, headers=headers)
assert gif.status_code == 400 and "content_type" in gif.json()["error"]["fields"]
big = await client.post("/v1/uploads", json={**body, "size_bytes": 10 * 1024 * 1024 + 1}, headers=headers)
assert big.status_code == 413
|