chore: port lab 4 solution into the lab 5 skeleton

Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb.
Contracts, public tests and evidence of lab 4 are not carried over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 03:09:12 +03:00
co-authored by Claude Opus 5.5
parent 276dbdad8a
commit 04f859282d
479 changed files with 106103 additions and 24 deletions
+283
View File
@@ -0,0 +1,283 @@
"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
import uuid
from collections.abc import Iterator
from typing import Any
import pytest
import images
from api_client import API, Actor, Api, key_headers, order_key, registration
from contract import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
assert_error,
assert_errors,
assert_unauthorized,
)
@pytest.mark.spec("api-conventions", "Битый JSON")
def test_malformed_json(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
headers = {"Content-Type": "application/json"}
for path, actor, extra in (
(f"{API}/users", None, {}),
(f"{API}/chats", alice, {}),
# с ключом: 400 из-за JSON, а не из-за отсутствия ключа
(f"{API}/chats/{chat['id']}/messages", alice, key_headers()),
):
resp = api.request(
"POST",
path,
actor=actor,
headers=headers | extra,
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("chats", "Посторонний")
@pytest.mark.spec("messages", "Посторонний пишет")
@pytest.mark.spec("messages", "Посторонний читает")
def test_foreign_chat(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
path = f"{API}/chats/{chat['id']}"
missing = f"{API}/chats/{uuid.uuid4()}"
requests = (
("GET", "", None),
("GET", "/messages", None),
("POST", "/messages", {"text": "чужое"}),
)
for method, suffix, body in requests:
# POST сообщения без ключа получил бы 400 раньше проверки доступа
headers = key_headers() if method == "POST" else None
foreign = assert_error(
api.request(
method,
path + suffix,
actor=eve,
headers=headers,
json=body,
),
404,
)
absent = assert_error(
api.request(
method,
missing + suffix,
actor=eve,
headers=headers,
json=body,
),
404,
)
# чужой чат неотличим от несуществующего
assert (foreign["code"], foreign["message"]) == (
absent["code"],
absent["message"],
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Пустой текст")
@pytest.mark.spec("api-conventions", "Строка из пробелов")
def test_empty_message(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
for text in ("", " ", "\t\n "):
resp = api.post_message(alice, chat["id"], json={"text": text})
assert_error(resp, 400)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("users", "Повтор username")
def test_duplicate_username(api: Api, alice: Actor) -> None:
resp = api.request(
"POST",
f"{API}/users",
json=registration(alice.username, "Другая Алиса"),
)
assert_error(resp, 409)
@pytest.mark.spec("sessions", "Неверный пароль")
def test_wrong_password(api: Api, alice: Actor) -> None:
resp = api.login_response(alice.username, alice.password + "-wrong")
assert_unauthorized(resp, BASIC_CHALLENGE)
assert "token" not in resp.json()
@pytest.mark.spec("sessions", "Выход")
def test_logout(api: Api, alice: Actor) -> None:
resp = api.logout(alice)
assert resp.status_code == 204, resp.text
assert resp.content == b""
after = api.request("GET", f"{API}/users/me", actor=alice)
assert_unauthorized(after, BEARER_CHALLENGE)
def test_history_walk_across_pages(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""12 сообщений, страницы по 5, 3, 4: `limit` меняется между ними."""
sent = [
api.send_message(sender, chat["id"], f"walk-{number}")
for number, sender in enumerate([alice, bob] * 6)
]
pages = api.message_pages(bob, chat["id"], limits=(5, 3, 4))
assert [len(page["items"]) for page in pages] == [5, 3, 4]
assert all(page["next_cursor"] for page in pages[:-1])
assert pages[-1]["next_cursor"] is None
items = [item for page in pages for item in page["items"]]
assert len({item["id"] for item in items}) == len(sent)
assert items == sorted(sent, key=order_key)
# --- лаба 4: негативные тесты вложений (спек student-tests) -------------
def _chunks(data: bytes, size: int = 1024 * 1024) -> Iterator[bytes]:
for offset in range(0, len(data), size):
yield data[offset : offset + size]
@pytest.mark.spec("attachments", "Заявленный размер больше лимита")
@pytest.mark.spec("attachments", "Большое тело без Content-Length")
def test_rubric_too_big_file(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Слишком большой файл в рубрике»: больше
10 MiB с `Content-Length` и частями — 413 в формате контракта."""
data = images.png_of_size(images.MAX_BYTES + 1024 * 1024)
assert_errors(
{
"content-length": api.post_attachment(alice, chat["id"], data),
"chunked": api.post_attachment(alice, chat["id"], _chunks(data)),
},
413,
)
@pytest.mark.spec("attachments", "Обрезанный файл")
@pytest.mark.spec("attachments", "Испорченные данные PNG")
def test_rubric_damaged_image(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Повреждённое изображение в рубрике»:
обрезанные PNG и JPEG и PNG с изменённым байтом данных — 415."""
assert_errors(
{
"png cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.sample_png()),
),
"jpeg cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.jpeg()),
content_type="image/jpeg",
),
"png byte": api.post_attachment(
alice,
chat["id"],
images.png_idat_byte_changed(),
),
},
415,
)
@pytest.mark.spec("attachments", "Подмена MIME")
@pytest.mark.spec("attachments", "Не изображение")
def test_rubric_mime_spoofing(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Подмена MIME в рубрике»: JPEG как PNG и
текст как JPEG — 415."""
assert_errors(
{
"jpeg as png": api.post_attachment(
alice,
chat["id"],
images.jpeg(),
content_type="image/png",
),
"text as jpeg": api.post_attachment(
alice,
chat["id"],
b"plain text, not an image",
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("messages", "Чужое вложение")
@pytest.mark.spec("messages", "Неизвестное вложение")
@pytest.mark.spec("attachments", "Посторонний и неизвестный id")
def test_rubric_foreign_attachment_id(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Чужое attachment_id в рубрике»: сообщение с
вложением чужого чата и с неизвестным id, чтение постороннего — 404."""
eve_chat = api.create_chat(eve, title="Ева")
eve_attachment = api.upload(eve, eve_chat["id"], images.sample_png())
alice_attachment = api.upload(alice, chat["id"], images.sample_png())
assert_errors(
{
"foreign in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [eve_attachment["id"]]},
),
"unknown in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [str(uuid.uuid4())]},
),
"outsider meta": api.attachment_meta(eve, alice_attachment["id"]),
"outsider content": api.attachment_content(
eve,
alice_attachment["id"],
),
},
404,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Вложение другого чата")
def test_rubric_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Вложение другого чата в рубрике»: участник
двух чатов шлёт в один вложение другого — 404, в истории пусто."""
other = api.create_chat(alice, bob, title="Второй чат")
attachment = api.upload(alice, other["id"], images.sample_png())
resp = api.post_message(
alice,
chat["id"],
json={"text": "", "attachment_ids": [attachment["id"]]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []