Link messages to attachments of the same chat
A message now carries attachment_ids in the request, in every response, in the idempotent replay and in history, in the order they were sent. The chat aggregate checks membership first, then refuses whitespace text, more than ten or repeated attachments, and an empty text without attachments, so an outsider still gets 404 before any 400. The send statement inserts the links next to the message and the idempotency key, and the foreign key from message_attachments to attachments of the same chat turns an unknown or foreign attachment into 404 and rolls the whole send back, without the messaging zone reading the attachments table. Replay and history read the list with a subquery on the primary key. The request fingerprint covers the list, so a missing attachment_ids and [] are the same body while a different order is a conflict. The zone dependency test now covers three zones, and the SQL ownership test checks that every zone touches only its own tables. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
00826a40d3
commit
f9760fc098
@@ -22,14 +22,14 @@
|
||||
|
||||
- [x] 4.1 Платформа: лимит тела по шаблону маршрута в конвейере
|
||||
- [x] 4.2 `main.py`: зона `attachments`, адаптер `MessagingMembership` для порта `ChatMembership`, лимит upload, поля журнала, реестр ошибок; `create_app` принимает дополнительные провайдеры для тестов
|
||||
- [ ] 4.3 Проверка группы: тест графа импортов — `attachments` не импортирует `identity`/`messaging`, `messaging` не импортирует `attachments`, `shared` не знает зон
|
||||
- [x] 4.3 Проверка группы: тест графа импортов — `attachments` не импортирует `identity`/`messaging`, `messaging` не импортирует `attachments`, `shared` не знает зон
|
||||
|
||||
## 5. Зона `messaging`: `attachment_ids`
|
||||
|
||||
- [ ] 5.1 Домен: `Message.attachment_ids`, `Chat.post` с проверкой списка вложений, `MessageText` с пустой строкой, ошибки `InvalidAttachmentList` и `UnknownAttachment`
|
||||
- [ ] 5.2 HTTP и команда: `CreateMessageRequest.attachment_ids` (по умолчанию `[]`, отпечаток), `MessageOut.attachment_ids`
|
||||
- [ ] 5.3 PostgreSQL: запись `message_attachments` в операторе отправки, FK → `404`, `attachment_ids` в повторе и истории подзапросом
|
||||
- [ ] 5.4 Проверка группы: тесты — пустой текст с вложением, порядок, другой чат и неизвестный id `404`, 11 и повторы `400`, посторонний `404` раньше `400`, повтор с вложением, отсутствующий ≡ `[]`, другой порядок `409`, история с `attachment_ids`
|
||||
- [x] 5.1 Домен: `Message.attachment_ids`, `Chat.post` с проверкой списка вложений, `MessageText` с пустой строкой, ошибки `InvalidAttachmentList` и `UnknownAttachment`
|
||||
- [x] 5.2 HTTP и команда: `CreateMessageRequest.attachment_ids` (по умолчанию `[]`, отпечаток), `MessageOut.attachment_ids`
|
||||
- [x] 5.3 PostgreSQL: запись `message_attachments` в операторе отправки, FK → `404`, `attachment_ids` в повторе и истории подзапросом
|
||||
- [x] 5.4 Проверка группы: тесты — пустой текст с вложением, порядок, другой чат и неизвестный id `404`, 11 и повторы `400`, посторонний `404` раньше `400`, повтор с вложением, отсутствующий ≡ `[]`, другой порядок `409`, история с `attachment_ids`
|
||||
|
||||
## 6. API-тесты вложений
|
||||
|
||||
|
||||
@@ -19,3 +19,4 @@ class PostMessage(Command):
|
||||
text: str
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
|
||||
@@ -51,6 +51,7 @@ class PostMessageHandler:
|
||||
sender_id=command.sender_id,
|
||||
text=command.text,
|
||||
now=now,
|
||||
attachment_ids=command.attachment_ids,
|
||||
)
|
||||
known = await self._uow.chats.receipt(
|
||||
chat.id, command.sender_id, command.key, now - self._ttl
|
||||
|
||||
@@ -23,3 +23,11 @@ class ChatNotFound(MessagingError):
|
||||
|
||||
class IdempotencyConflict(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidAttachmentList(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownAttachment(MessagingError):
|
||||
pass
|
||||
|
||||
@@ -3,10 +3,21 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import ChatNotFound, IdempotencyConflict, InvalidChatData
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.events import ChatCreated, MessagePosted
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.values import CHAT_MEMBERS_MAX, ChatTitle, MessageText
|
||||
from messenger.messaging.domain.values import (
|
||||
CHAT_MEMBERS_MAX,
|
||||
MESSAGE_ATTACHMENTS_MAX,
|
||||
ChatTitle,
|
||||
MessageText,
|
||||
)
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
@@ -19,12 +30,25 @@ class Message:
|
||||
sender_id: UUID
|
||||
text: MessageText
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
|
||||
@property
|
||||
def key(self) -> HistoryKey:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
|
||||
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
|
||||
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
|
||||
raise InvalidAttachmentList(
|
||||
f"поле attachment_ids содержит больше {MESSAGE_ATTACHMENTS_MAX} вложений"
|
||||
)
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise InvalidAttachmentList("поле attachment_ids содержит дубликаты")
|
||||
if not text.value and not attachment_ids:
|
||||
raise InvalidMessageText("пустой text допустим только с вложением")
|
||||
return tuple(attachment_ids)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Receipt:
|
||||
key: str
|
||||
@@ -114,16 +138,27 @@ class Chat:
|
||||
if not self.is_member(user_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
|
||||
def post(self, *, message_id: UUID, sender_id: UUID, text: str, now: datetime) -> Message:
|
||||
def post(
|
||||
self,
|
||||
*,
|
||||
message_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
now: datetime,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> Message:
|
||||
self.require_member(sender_id)
|
||||
body = MessageText(text)
|
||||
attachments = attachment_list(body, attachment_ids)
|
||||
last = self.last_message_at
|
||||
created_at = now if last is None or now > last else last + TICK
|
||||
message = Message(
|
||||
id=message_id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text=MessageText(text),
|
||||
text=body,
|
||||
created_at=created_at,
|
||||
attachment_ids=attachments,
|
||||
)
|
||||
self.last_message_at = created_at
|
||||
self.record(
|
||||
|
||||
@@ -5,6 +5,7 @@ from messenger.messaging.domain.errors import InvalidChatData, InvalidMessageTex
|
||||
CHAT_TITLE_MAX = 100
|
||||
MESSAGE_TEXT_MAX = 4000
|
||||
CHAT_MEMBERS_MAX = 100
|
||||
MESSAGE_ATTACHMENTS_MAX = 10
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -30,8 +31,8 @@ class MessageText:
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidMessageText("поле text должно быть строкой")
|
||||
if not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может быть пустым или состоять из пробелов")
|
||||
if self.value and not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может состоять из пробелов")
|
||||
if len(self.value) > MESSAGE_TEXT_MAX:
|
||||
raise InvalidMessageText(f"поле text длиннее {MESSAGE_TEXT_MAX} символов Unicode")
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
InvalidPageRequest,
|
||||
UnknownAttachment,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
@@ -11,6 +13,8 @@ ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidChatData: ("invalid_request", 400),
|
||||
InvalidMessageText: ("invalid_request", 400),
|
||||
InvalidPageRequest: ("invalid_request", 400),
|
||||
InvalidAttachmentList: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
UnknownAttachment: ("not_found", 404),
|
||||
IdempotencyConflict: ("conflict", 409),
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ async def post_message(
|
||||
text=body.text,
|
||||
key=key,
|
||||
fingerprint=body.fingerprint(),
|
||||
attachment_ids=tuple(body.attachment_ids),
|
||||
)
|
||||
)
|
||||
return MessageOut.of(message)
|
||||
|
||||
@@ -29,6 +29,7 @@ class CreateMessageRequest(BaseModel):
|
||||
model_config = STRICT
|
||||
|
||||
text: str
|
||||
attachment_ids: list[Annotated[UUID, Field(strict=False)]] = Field(default_factory=list)
|
||||
|
||||
def fingerprint(self) -> bytes:
|
||||
return sha256(self.model_dump_json().encode()).digest()
|
||||
@@ -61,6 +62,7 @@ class MessageOut(BaseModel):
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...]
|
||||
|
||||
@classmethod
|
||||
def of(cls, message: Message) -> MessageOut:
|
||||
@@ -70,6 +72,7 @@ class MessageOut(BaseModel):
|
||||
sender_id=message.sender_id,
|
||||
text=message.text.value,
|
||||
created_at=message.created_at,
|
||||
attachment_ids=message.attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData
|
||||
from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
@@ -28,8 +28,11 @@ FROM chats c
|
||||
WHERE c.id = $1
|
||||
FOR UPDATE
|
||||
"""
|
||||
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
|
||||
"""
|
||||
@@ -38,6 +41,10 @@ WITH message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, chat_id, sender_id, created_at
|
||||
), links AS (
|
||||
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
|
||||
SELECT message.id, link.position - 1, message.chat_id, link.attachment_id
|
||||
FROM message, unnest($8::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
|
||||
@@ -73,17 +80,21 @@ ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $4
|
||||
"""
|
||||
HISTORY_FIRST = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
"""
|
||||
HISTORY_AFTER = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
"""
|
||||
|
||||
@@ -105,6 +116,7 @@ def message_of(row: Record) -> Message:
|
||||
sender_id=row["sender_id"],
|
||||
text=MessageText(row["text"]),
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=tuple(row["attachment_ids"]),
|
||||
)
|
||||
|
||||
|
||||
@@ -145,16 +157,22 @@ class PostgresChatRepository:
|
||||
|
||||
async def append(self, receipt: Receipt) -> None:
|
||||
message = receipt.message
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
list(message.attachment_ids),
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@@ -5,6 +5,8 @@ from pathlib import Path
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger"
|
||||
IDENTITY = "messenger.identity"
|
||||
MESSAGING = "messenger.messaging"
|
||||
ATTACHMENTS = "messenger.attachments"
|
||||
ZONES = ("identity", "messaging", "attachments")
|
||||
|
||||
|
||||
def imports_of(path: Path) -> list[str]:
|
||||
@@ -45,9 +47,23 @@ def test_messaging_touches_identity_only_through_events() -> None:
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone, foreign in (
|
||||
("attachments", (IDENTITY, MESSAGING)),
|
||||
("identity", (ATTACHMENTS,)),
|
||||
("messaging", (ATTACHMENTS,)),
|
||||
):
|
||||
for path in modules_under(zone):
|
||||
borrowed = [m for m in imports_of(path) if m.startswith(foreign)]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_domains_do_not_import_infrastructure() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in ("identity", "messaging", "shared"):
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if ".infrastructure" in m]
|
||||
@@ -58,7 +74,7 @@ def test_domains_do_not_import_infrastructure() -> None:
|
||||
|
||||
def test_core_layers_do_not_import_pydantic() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in ("identity", "messaging", "shared"):
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"]
|
||||
@@ -73,7 +89,7 @@ def test_shared_knows_nothing_about_zones() -> None:
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
@@ -126,31 +142,28 @@ def test_shared_entrypoints_hold_only_transport() -> None:
|
||||
|
||||
|
||||
def test_every_zone_owns_its_errors_events_and_commands() -> None:
|
||||
for zone in ("identity", "messaging"):
|
||||
for zone in ZONES:
|
||||
assert (SOURCE / zone / "domain" / "errors.py").is_file()
|
||||
assert (SOURCE / zone / "domain" / "events.py").is_file()
|
||||
assert (SOURCE / zone / "application" / "commands.py").is_file()
|
||||
|
||||
|
||||
def test_every_zone_owns_its_http_layer() -> None:
|
||||
for zone in ("identity", "messaging"):
|
||||
for zone in ZONES:
|
||||
for part in ("http.py", "ioc.py", "errors.py", "journal.py"):
|
||||
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
|
||||
|
||||
|
||||
def test_only_main_knows_both_zones() -> None:
|
||||
def test_only_main_knows_several_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in SOURCE.rglob("*.py"):
|
||||
relative = path.relative_to(SOURCE)
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in {
|
||||
"identity",
|
||||
"messaging",
|
||||
}:
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
|
||||
continue
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(relative)] = borrowed
|
||||
@@ -172,6 +185,8 @@ ZONE_WORDS = (
|
||||
"sender",
|
||||
"message_id",
|
||||
"message_text",
|
||||
"attachment",
|
||||
"filename",
|
||||
)
|
||||
|
||||
|
||||
@@ -193,7 +208,10 @@ def test_shared_declares_no_concrete_commands_or_events() -> None:
|
||||
name
|
||||
for name in declared
|
||||
if name not in {"Command", "DomainEvent", "DomainError"}
|
||||
and (name.endswith("Event") or name in {"RegisterUser", "CreateChat", "PostMessage"})
|
||||
and (
|
||||
name.endswith("Event")
|
||||
or name in {"RegisterUser", "CreateChat", "PostMessage", "UploadAttachment"}
|
||||
)
|
||||
]
|
||||
assert not concrete, f"{path.name}: {concrete}"
|
||||
|
||||
@@ -206,7 +224,7 @@ def test_shared_has_no_test_doubles() -> None:
|
||||
|
||||
|
||||
def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
for zone in ("identity", "messaging", "shared"):
|
||||
for zone in (*ZONES, "shared"):
|
||||
source = (SOURCE / zone / "domain" / "errors.py").read_text()
|
||||
assert "http_status" not in source
|
||||
assert "invalid_request" not in source
|
||||
@@ -214,7 +232,8 @@ def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
|
||||
|
||||
IDENTITY_TABLES = ("users", "sessions")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
|
||||
ATTACHMENT_TABLES = ("attachments",)
|
||||
|
||||
|
||||
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
@@ -228,10 +247,14 @@ def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
|
||||
|
||||
def test_sql_of_each_zone_reads_only_its_tables() -> None:
|
||||
assert sql_tables("messaging", IDENTITY_TABLES) == set()
|
||||
assert sql_tables("identity", MESSAGING_TABLES) == set()
|
||||
assert sql_tables("messaging", MESSAGING_TABLES) == set(MESSAGING_TABLES)
|
||||
assert sql_tables("identity", IDENTITY_TABLES) == set(IDENTITY_TABLES)
|
||||
owned = {
|
||||
"identity": IDENTITY_TABLES,
|
||||
"messaging": MESSAGING_TABLES,
|
||||
"attachments": ATTACHMENT_TABLES,
|
||||
}
|
||||
every = {table for tables in owned.values() for table in tables}
|
||||
for zone, tables in owned.items():
|
||||
assert sql_tables(zone, tuple(every)) == set(tables), zone
|
||||
|
||||
|
||||
def test_messaging_does_not_import_identity_at_all() -> None:
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
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 == 201, 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]
|
||||
@@ -62,6 +62,7 @@ async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment
|
||||
"sender_id": user_id,
|
||||
"text": "привет",
|
||||
"created_at": stamp,
|
||||
"attachment_ids": [],
|
||||
}
|
||||
assert_wire(response, message)
|
||||
history = await http.get(path, headers=headers)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from dataclasses import fields
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from itertools import pairwise
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -11,6 +11,7 @@ from messenger.identity.domain.values import DisplayName, Password, Username
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
)
|
||||
@@ -19,6 +20,7 @@ from messenger.messaging.domain.values import MessageText
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
MOMENT = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
UUID_TWICE = uuid4()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -81,10 +83,11 @@ def test_message_text_counts_code_points_not_bytes() -> None:
|
||||
MessageText("👋" * 4001)
|
||||
|
||||
|
||||
def test_message_text_rejects_blank() -> None:
|
||||
for raw in ("", " ", "\n\t "):
|
||||
def test_message_text_rejects_whitespace() -> None:
|
||||
for raw in (" ", "\n\t "):
|
||||
with pytest.raises(InvalidMessageText):
|
||||
MessageText(raw)
|
||||
assert MessageText("").value == ""
|
||||
|
||||
|
||||
def make_chat(*members: object) -> Chat:
|
||||
@@ -167,6 +170,45 @@ def test_post_validates_membership_before_text() -> None:
|
||||
chat.post(message_id=uuid4(), sender_id=uuid4(), text="", now=MOMENT)
|
||||
|
||||
|
||||
def test_empty_text_needs_an_attachment() -> None:
|
||||
chat = make_chat(1)
|
||||
sender = chat.member_ids[0]
|
||||
with pytest.raises(InvalidMessageText):
|
||||
chat.post(message_id=uuid4(), sender_id=sender, text="", now=MOMENT)
|
||||
ids = (uuid4(), uuid4())
|
||||
message = chat.post(
|
||||
message_id=uuid4(), sender_id=sender, text="", now=MOMENT, attachment_ids=ids
|
||||
)
|
||||
assert message.attachment_ids == ids
|
||||
with pytest.raises(InvalidMessageText):
|
||||
chat.post(message_id=uuid4(), sender_id=sender, text=" ", now=MOMENT, attachment_ids=ids)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids", [[uuid4() for _ in range(11)], [UUID_TWICE, UUID_TWICE]])
|
||||
def test_attachment_list_is_bounded_and_unique(ids: list[UUID]) -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(InvalidAttachmentList):
|
||||
chat.post(
|
||||
message_id=uuid4(),
|
||||
sender_id=chat.member_ids[0],
|
||||
text="x",
|
||||
now=MOMENT,
|
||||
attachment_ids=ids,
|
||||
)
|
||||
|
||||
|
||||
def test_membership_is_checked_before_attachments() -> None:
|
||||
chat = make_chat(1)
|
||||
with pytest.raises(ChatNotFound):
|
||||
chat.post(
|
||||
message_id=uuid4(),
|
||||
sender_id=uuid4(),
|
||||
text="",
|
||||
now=MOMENT,
|
||||
attachment_ids=[uuid4() for _ in range(11)],
|
||||
)
|
||||
|
||||
|
||||
def test_receipt_replays_only_the_same_request() -> None:
|
||||
chat = make_chat(1)
|
||||
message = chat.post(message_id=uuid4(), sender_id=chat.member_ids[0], text="раз", now=MOMENT)
|
||||
|
||||
Reference in New Issue
Block a user