Files
mtusi2026lab3/student-tests/test_rubric.py
T
ricoromaandClaude Opus 5.5 af4bca08c9 feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec
  change instance-id-idempotency)
- rename the compose project to mtusi-lab3 and the image to :lab3
- add X-Instance-Id to every response and instance_id to every log
  record ([app] instance_id, hostname by default)
- require Idempotency-Key on POST messages: keys table in Postgres,
  key and message in one transaction, replay returns the same 201,
  another body gets 409, TTL from [idempotency] ttl_seconds
- send the key from student-tests, k6 scenarios and the skill driver;
  add idempotency, X-Instance-Id, key race and fault tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:42:36 +03:00

137 lines
4.4 KiB
Python

"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
import uuid
from typing import Any
import pytest
from api_client import API, Actor, Api, key_headers, order_key, registration
from contract import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
assert_error,
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)