Files
mtusi2026lab5/student-tests/api/test_message_attachments.py
T
ArtyomandClaude Opus 5.5 b152b6e07e Process attachment jobs through an outbox, a relay and a worker
Upload now stages the checked original under staging/, and one
transaction moves the intent to queued, inserts the job (pipeline
version 1, attempt 1), its outbox row and an audit event; the 202 is
the in-memory snapshot, never a reread. Content answers 409 until the
attachment is ready, the thumbnail variant is served from the
published version and absent variants are 404.

The relay publishes outbox rows through FastStream with publisher
confirms, mandatory routing and persistent delivery, marks a row only
after the broker acked it, returns jobs whose lease expired and deletes
the staging object of ready attachments. The worker consumes the
quorum queue through a FastStream subscriber that declares nothing,
takes prefetch from WORKER_CONCURRENCY and acks manually after the
result commit, rejects messages off jobs.schema.json to the dead letter
exchange and requeues after an infrastructure error. A job is claimed
under a lease token; the original is copied to originals/ and a
256 px JPEG thumbnail is written under a content-addressed key; the
commit is fenced by the token, inserts variants with ON CONFLICT DO
NOTHING and publishes only a newer pipeline version. A transient error
reschedules the same job with an exponential delay and a new outbox
row, the last attempt fails with retry_exhausted, an undecodable image
fails at once with invalid_image, and a redelivered finished job is a
recorded no-op.

The worker and the relay are assembled in worker.py and relay.py with
the dishka FastStream integration and the platform providers of the
API; the shared core imports neither FastStream nor aio-pika. Tests
cover the thumbnail geometry and rendering, the job message against
the contract, the pipeline against PostgreSQL (duplicates, parallel
copies, retries, the attempt bound, leases and fencing) and the broker
adapters against a throwaway RabbitMQ with the stand's topology and
permissions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 01:08:06 +03:00

109 lines
4.9 KiB
Python

from typing import Any
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register
from pictures import SAMPLE
async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
response = await http.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
content=SAMPLE,
headers={**actor(user), "Content-Type": "image/png"},
)
assert response.status_code == 202, response.text
return response.json()["id"]
async def send(
http: AsyncClient, user: dict[str, Any], chat: dict[str, Any], body: Any, key: str | None = None
) -> Any:
return await http.post(
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=keyed(user, key)
)
async def scene(http: AsyncClient) -> tuple[dict[str, Any], ...]:
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
return alice, bob, eve, await make_chat(http, alice, bob), await make_chat(http, alice)
async def test_text_message_carries_empty_list(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
response = await send(client, alice, chat, {"text": "привет"})
assert response.status_code == 201
assert response.json()["attachment_ids"] == []
async def test_empty_text_with_attachment_keeps_order(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
ids = [await attach(client, alice, chat) for _ in range(3)]
ordered = [ids[2], ids[0], ids[1]]
response = await send(client, bob, chat, {"text": "", "attachment_ids": ordered})
assert response.status_code == 201, response.text
message = response.json()
assert message["attachment_ids"] == ordered
again = await send(client, alice, chat, {"text": "ещё раз", "attachment_ids": [ids[0]]})
assert again.status_code == 201
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
assert history.json()["items"] == [message, again.json()]
async def test_replay_with_attachments_and_default_list(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
first_id, second_id = await attach(client, alice, chat), await attach(client, alice, chat)
body = {"text": "", "attachment_ids": [first_id, second_id]}
first = await send(client, alice, chat, body, "with-files")
assert (await send(client, alice, chat, body, "with-files")).json() == first.json()
swapped = {"text": "", "attachment_ids": [second_id, first_id]}
assert (await send(client, alice, chat, swapped, "with-files")).status_code == 409
plain = await send(client, alice, chat, {"text": "x"}, "plain")
explicit = await send(client, alice, chat, {"attachment_ids": [], "text": "x"}, "plain")
assert (explicit.status_code, explicit.json()) == (201, plain.json())
async def test_attachment_of_another_chat_or_unknown(client: AsyncClient) -> None:
alice, _, _, chat, solo = await scene(client)
foreign = await attach(client, alice, solo)
for ids in ([foreign], [str(uuid4())]):
response = await send(client, alice, chat, {"text": "x", "attachment_ids": ids})
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
assert history.json()["items"] == []
@pytest.mark.parametrize("kind", ["eleven", "duplicate", "not-uuid", "empty", "blank"])
async def test_invalid_attachment_lists(client: AsyncClient, kind: str) -> None:
alice, _, _, chat, _ = await scene(client)
file = await attach(client, alice, chat)
body = {
"eleven": {"text": "x", "attachment_ids": [file] + [str(uuid4()) for _ in range(10)]},
"duplicate": {"text": "x", "attachment_ids": [file, file]},
"not-uuid": {"text": "x", "attachment_ids": ["not-a-uuid"]},
"empty": {"text": "", "attachment_ids": []},
"blank": {"text": " ", "attachment_ids": [file]},
}[kind]
response = await send(client, alice, chat, body)
assert response.status_code == 400, response.text
assert response.json()["error"]["code"] == "invalid_request"
async def test_outsider_gets_not_found_before_validation(client: AsyncClient) -> None:
alice, _, eve, chat, _ = await scene(client)
file = await attach(client, alice, chat)
for body in ({"text": "", "attachment_ids": []}, {"text": "x", "attachment_ids": [file] * 11}):
assert (await send(client, eve, chat, body)).status_code == 404
async def test_one_attachment_in_several_messages(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
file = await attach(client, alice, chat)
for user in (alice, bob):
response = await send(client, user, chat, {"text": "", "attachment_ids": [file]})
assert response.status_code == 201
assert response.json()["attachment_ids"] == [file]