Upload answers 202 after staging, a queued job in PostgreSQL and a broker confirm; a separate worker publishes the original and a thumbnail with bounded retries. Adds the job and variant tables, the broker service, the worker S3 user, cleanup and reconcile support for staging and variants, the failure stand with broker and worker, bench and driver updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
9.3 KiB
Python
321 lines
9.3 KiB
Python
"""Спек `messages`: отправка, валидация текста, история, вложения."""
|
||
|
||
import uuid
|
||
from typing import Any
|
||
|
||
import httpx
|
||
import pytest
|
||
|
||
import images
|
||
from api_client import Actor, Api, order_key
|
||
from contract import assert_error, assert_errors, assert_ok
|
||
|
||
|
||
def send_raw(
|
||
api: Api,
|
||
actor: Actor,
|
||
chat_id: str,
|
||
body: dict[str, Any],
|
||
) -> httpx.Response:
|
||
"""Отправка с новым ключом; ответ проверяет тест."""
|
||
return api.post_message(actor, chat_id, json=body)
|
||
|
||
|
||
@pytest.mark.spec("messages", "Участник отправляет сообщение")
|
||
def test_member_sends(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
resp = send_raw(api, alice, chat["id"], {"text": "Привет, мир 👋"})
|
||
message = assert_ok(resp, 201, "Message")
|
||
assert message["sender_id"] == alice.id
|
||
assert message["chat_id"] == chat["id"]
|
||
assert message["text"] == "Привет, мир 👋"
|
||
assert message["attachment_ids"] == []
|
||
|
||
|
||
def upload(api: Api, actor: Actor, chat_id: str) -> str:
|
||
"""Принятое вложение чата; id. Сообщение можно отправить и с вложением в
|
||
обработке: `ready` не ждём."""
|
||
return api.upload(actor, chat_id, images.sample_png())["id"]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Сообщение с вложениями")
|
||
def test_message_with_attachments(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
first, second = (
|
||
upload(api, alice, chat["id"]),
|
||
upload(api, alice, chat["id"]),
|
||
)
|
||
message = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
"два файла",
|
||
attachment_ids=[second, first],
|
||
)
|
||
assert message["attachment_ids"] == [second, first]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Пустой текст с вложением")
|
||
def test_empty_text_with_attachment(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
attachment_id = upload(api, alice, chat["id"])
|
||
message = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
"",
|
||
attachment_ids=[attachment_id],
|
||
)
|
||
assert message["text"] == ""
|
||
assert message["attachment_ids"] == [attachment_id]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Пробелы с вложением")
|
||
def test_blank_text_with_attachment(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
"""Согласовано с преподавателем 2026-10-20: пустой текст — и `""`, и
|
||
из одних пробелов; с вложением допустим и не нормализуется."""
|
||
attachment_id = upload(api, alice, chat["id"])
|
||
message = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
" ",
|
||
attachment_ids=[attachment_id],
|
||
)
|
||
assert message["text"] == " "
|
||
assert message["attachment_ids"] == [attachment_id]
|
||
assert_error(send_raw(api, alice, chat["id"], {"text": " "}), 400)
|
||
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
|
||
message["id"],
|
||
]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Вложения в истории")
|
||
def test_attachments_in_history(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
first, second = (
|
||
upload(api, alice, chat["id"]),
|
||
upload(api, alice, chat["id"]),
|
||
)
|
||
with_files = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
"с файлами",
|
||
attachment_ids=[second, first],
|
||
)
|
||
plain = api.send_message(bob, chat["id"], "без файлов")
|
||
history = api.all_messages(bob, chat["id"])
|
||
assert history == sorted([with_files, plain], key=order_key)
|
||
by_id = {item["id"]: item["attachment_ids"] for item in history}
|
||
assert by_id == {with_files["id"]: [second, first], plain["id"]: []}
|
||
|
||
|
||
@pytest.mark.spec("messages", "Вложение другого участника")
|
||
def test_attachment_of_other_member(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
attachment_id = upload(api, alice, chat["id"])
|
||
api.send_message(bob, chat["id"], "ответ", attachment_ids=[attachment_id])
|
||
|
||
|
||
@pytest.mark.spec("messages", "Вложение другого чата")
|
||
def test_attachment_of_other_chat(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
other = api.create_chat(alice, bob, title="Y")
|
||
attachment_id = upload(api, alice, other["id"])
|
||
resp = send_raw(
|
||
api,
|
||
alice,
|
||
chat["id"],
|
||
{"text": "чужой чат", "attachment_ids": [attachment_id]},
|
||
)
|
||
assert_error(resp, 404)
|
||
assert api.all_messages(alice, chat["id"]) == []
|
||
|
||
|
||
@pytest.mark.spec("messages", "Чужое вложение")
|
||
def test_foreign_attachment(
|
||
api: Api,
|
||
alice: Actor,
|
||
eve: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
eve_chat = api.create_chat(eve, title="Ева")
|
||
attachment_id = upload(api, eve, eve_chat["id"])
|
||
resp = send_raw(
|
||
api,
|
||
alice,
|
||
chat["id"],
|
||
{"text": "", "attachment_ids": [attachment_id]},
|
||
)
|
||
assert_error(resp, 404)
|
||
assert api.all_messages(alice, chat["id"]) == []
|
||
|
||
|
||
@pytest.mark.spec("messages", "Неизвестное вложение")
|
||
def test_unknown_attachment(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
resp = send_raw(
|
||
api,
|
||
alice,
|
||
chat["id"],
|
||
{"text": "x", "attachment_ids": [str(uuid.uuid4())]},
|
||
)
|
||
assert_error(resp, 404)
|
||
assert api.all_messages(alice, chat["id"]) == []
|
||
|
||
|
||
@pytest.mark.spec("messages", "Неверный список вложений")
|
||
def test_bad_attachment_list(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
attachment_id = upload(api, alice, chat["id"])
|
||
bodies = {
|
||
"repeat": [attachment_id, attachment_id],
|
||
"repeat upper": [attachment_id, attachment_id.upper()],
|
||
"eleven": [str(uuid.uuid4()) for _ in range(11)],
|
||
"string": attachment_id,
|
||
"number item": [123],
|
||
"123 item": ["123"],
|
||
}
|
||
assert_errors(
|
||
{
|
||
name: send_raw(
|
||
api,
|
||
alice,
|
||
chat["id"],
|
||
{"text": "x", "attachment_ids": value},
|
||
)
|
||
for name, value in bodies.items()
|
||
},
|
||
400,
|
||
)
|
||
assert api.all_messages(alice, chat["id"]) == []
|
||
|
||
|
||
@pytest.mark.spec("messages", "Одно вложение в двух сообщениях")
|
||
def test_one_attachment_in_two_messages(
|
||
api: Api,
|
||
alice: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
attachment_id = upload(api, alice, chat["id"])
|
||
first = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
"раз",
|
||
attachment_ids=[attachment_id],
|
||
)
|
||
second = api.send_message(
|
||
alice,
|
||
chat["id"],
|
||
"два",
|
||
attachment_ids=[attachment_id],
|
||
)
|
||
assert first["id"] != second["id"]
|
||
history = api.all_messages(alice, chat["id"])
|
||
assert [item["attachment_ids"] for item in history] == [
|
||
[attachment_id],
|
||
[attachment_id],
|
||
]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Граница длины")
|
||
def test_text_length(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
|
||
# кириллица: 2 байта на символ, считаются code points
|
||
text = "я" * 4000
|
||
message = assert_ok(
|
||
send_raw(api, alice, chat["id"], {"text": text}),
|
||
201,
|
||
"Message",
|
||
)
|
||
assert message["text"] == text
|
||
assert_error(send_raw(api, alice, chat["id"], {"text": text + "я"}), 400)
|
||
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
|
||
message["id"],
|
||
]
|
||
|
||
|
||
@pytest.mark.spec("messages", "Попытка подменить отправителя")
|
||
def test_sender_id_in_body(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
body = {"text": "от Боба", "sender_id": bob.id}
|
||
assert_error(send_raw(api, alice, chat["id"], body), 400)
|
||
assert api.all_messages(bob, chat["id"]) == []
|
||
|
||
|
||
@pytest.mark.spec("messages", "Два участника, две страницы")
|
||
def test_two_members_two_pages(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
sent = [
|
||
api.send_message(alice, chat["id"], "от Алисы"),
|
||
api.send_message(bob, chat["id"], "от Боба"),
|
||
]
|
||
first = assert_ok(
|
||
api.messages_page(bob, chat["id"], limit=1),
|
||
200,
|
||
"MessagePage",
|
||
)
|
||
assert len(first["items"]) == 1
|
||
assert first["next_cursor"]
|
||
second = assert_ok(
|
||
api.messages_page(
|
||
bob,
|
||
chat["id"],
|
||
limit=1,
|
||
cursor=first["next_cursor"],
|
||
),
|
||
200,
|
||
"MessagePage",
|
||
)
|
||
assert len(second["items"]) == 1
|
||
assert second["next_cursor"] is None
|
||
assert first["items"] + second["items"] == sorted(sent, key=order_key)
|
||
|
||
|
||
@pytest.mark.spec("messages", "Чтение после записи")
|
||
def test_read_after_write(
|
||
api: Api,
|
||
alice: Actor,
|
||
bob: Actor,
|
||
chat: dict[str, Any],
|
||
) -> None:
|
||
for number in range(5):
|
||
message = api.send_message(alice, chat["id"], f"сразу {number}")
|
||
history = api.all_messages(bob, chat["id"])
|
||
assert message in history
|