Files
mtusi2026labs/student-tests/api/test_message_attachments.py
ArtyomandClaude Opus 5.5 34741dc2d2 Refuse failed attachments in messages through a zone port
The messaging zone asks a new AttachmentStates port whether any listed
attachment of the chat has failed and answers 409 conflict before the
message is stored; queued and processing attachments can still be
sent right after the upload. The check runs only on the first execution
of a key, so a replay returns the original 201 even if the attachment
failed later. main.py wires the port to the attachments directory, so
neither zone reads the other's tables.

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

150 lines
6.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, resolve
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from pictures import SAMPLE
from pipeline import settle
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]
async def broken(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
attachment_id = await attach(http, user, chat)
store = await resolve(http, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.objects[f"staging/{attachment_id}"] = (b"\x89PNG\r\n\x1a\n broken", "image/png")
await settle(http)
return attachment_id
async def test_queued_attachment_is_sent_and_failed_is_conflict(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
queued = await attach(client, alice, chat)
early = await send(client, alice, chat, {"text": "", "attachment_ids": [queued]})
assert early.status_code == 201, early.text
failed = await broken(client, bob, chat)
meta = (await client.get(f"/api/v1/attachments/{failed}", headers=actor(alice))).json()
assert (meta["status"], meta["error_code"]) == ("failed", "invalid_image")
refused = await send(client, alice, chat, {"text": "x", "attachment_ids": [queued, failed]})
assert refused.status_code == 409
assert refused.json()["error"]["code"] == "conflict"
content = await client.get(f"/api/v1/attachments/{failed}/content", headers=actor(bob))
assert content.status_code == 409
async def test_replay_survives_a_later_failure(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
attachment_id = await attach(client, alice, chat)
body = {"text": "", "attachment_ids": [attachment_id]}
first = await send(client, alice, chat, body, key="replay-after-failure")
store = await resolve(client, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.objects[f"staging/{attachment_id}"] = (b"garbage", "image/png")
await settle(client)
again = await send(client, alice, chat, body, key="replay-after-failure")
assert (first.status_code, again.status_code) == (201, 201)
assert again.json() == first.json()