Files
mtusi2026lab2/student-tests/api/test_idempotency.py
T
Artyom 12db77133f Forward the lab 5 foundation while preserving lab 6 telemetry
Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.

Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
2026-11-06 12:29:35 +03:00

163 lines
6.9 KiB
Python

import asyncio
from typing import Any
from uuid import uuid4
import pytest
from httpx import AsyncClient, Response
from sqlalchemy import func, select
from conftest import actor, keyed, make_chat, register, running_app, scalar
from messenger.messaging.infrastructure.postgres import IdempotencyKeyRow
INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"]
async def send(http: AsyncClient, chat: dict, user: dict, text: str, key: str) -> Response:
return await http.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(user, key)
)
async def history(http: AsyncClient, chat: dict, user: dict) -> list[dict[str, Any]]:
response = await http.get(f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=actor(user))
return response.json()["items"]
async def test_replay_returns_the_same_message(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
first = await send(client, chat, alice, "один раз", "replay-1")
again = await send(client, chat, alice, "один раз", "replay-1")
assert first.status_code == again.status_code == 201
assert again.json() == first.json()
assert [item["id"] for item in await history(client, chat, alice)] == [first.json()["id"]]
async def test_same_json_in_other_layout_is_a_replay(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
first = await send(client, chat, alice, "форма", "layout-1")
again = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
content='{ "text" : "форма" }'.encode(),
headers={**keyed(alice, "layout-1"), "Content-Type": "application/json"},
)
assert again.status_code == 201
assert again.json() == first.json()
async def test_other_body_with_same_key_conflicts(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await send(client, chat, alice, "первое", "conflict-1")
response = await send(client, chat, alice, "другое", "conflict-1")
assert response.status_code == 409
assert response.json()["error"]["code"] == "conflict"
assert len(await history(client, chat, alice)) == 1
async def test_missing_key_is_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без ключа"}, headers=actor(alice)
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
assert await history(client, chat, alice) == []
@pytest.mark.parametrize("key", INVALID_KEYS, ids=range(len(INVALID_KEYS)))
async def test_malformed_key_is_rejected(client: AsyncClient, key: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
headers = {**actor(alice), "Idempotency-Key": key}
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "ключ плохой"},
headers={name.encode(): value.encode() for name, value in headers.items()},
)
assert response.status_code == 400
assert await history(client, chat, alice) == []
async def test_rejected_attempt_does_not_take_the_key(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (await send(client, chat, alice, "", "spare-1")).status_code == 400
assert (await send(client, chat, eve, "чужое", "spare-1")).status_code == 404
assert (await send(client, chat, alice, "теперь можно", "spare-1")).status_code == 201
async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
other = await make_chat(client, alice)
cases = [(chat, alice, "алиса"), (chat, bob, "боб"), (other, alice, "другой чат")]
messages = []
for target, user, text in cases:
response = await send(client, target, user, text, "shared-1")
assert response.status_code == 201
message = response.json()
assert (message["chat_id"], message["sender_id"], message["text"]) == (
target["id"],
user["id"],
text,
)
messages.append(message)
ids = {message["id"] for message in messages}
assert len(ids) == 3
for (target, user, text), message in zip(cases, messages, strict=True):
assert (await send(client, target, user, text, "shared-1")).json() == message
async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 201
assert (await send(client, chat, eve, "до выхода", "recheck-1")).status_code == 404
logout = await client.delete("/api/v1/auth/sessions/current", headers=actor(alice))
assert logout.status_code == 204
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 401
async def test_expired_key_starts_over() -> None:
async with running_app(idempotency_ttl_seconds=1) as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
first = await send(http, chat, alice, "давно", "expire-1")
await asyncio.sleep(1.1)
later = await send(http, chat, alice, "заново", "expire-1")
assert later.status_code == 201
assert later.json()["id"] != first.json()["id"]
assert len(await history(http, chat, alice)) == 2
async def test_concurrent_retries_through_two_replicas_store_one_message() -> None:
async with (
running_app(instance_id="replica-a") as first,
running_app(instance_id="replica-b") as second,
):
alice = await register(first, "alice")
chat = await make_chat(first, alice)
key, text = uuid4().hex, "гонка ключа"
responses = await asyncio.gather(
*(send(http, chat, alice, text, key) for http in (first, second) * 4)
)
assert {response.status_code for response in responses} == {201}
assert {response.headers["X-Instance-Id"] for response in responses} == {
"replica-a",
"replica-b",
}
assert all(response.json() == responses[0].json() for response in responses)
assert [item["text"] for item in await history(second, chat, alice)] == [text]
assert (
await scalar(
select(func.count()).select_from(IdempotencyKeyRow).where(IdempotencyKeyRow.key == key)
)
== 1
)