Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy and k6 configuration, migrations, hooks, evidence and level 4 scripts and the CI job from the lab 3 solution commit 61c0c28, merge the lab 3 Makefile targets into the lab 4 skeleton Makefile without touching its targets, and append the lab 3 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.4.0, and the image and the throwaway test containers are tagged lab4 so they do not collide with a lab 3 stand on the same host. This is the starting point of the lab 4 cycle: lint, own tests and the offline skeleton check pass before any lab 4 change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
189 lines
7.3 KiB
Python
189 lines
7.3 KiB
Python
import asyncio
|
|
from urllib.parse import quote
|
|
from uuid import uuid4
|
|
|
|
from httpx import AsyncClient
|
|
|
|
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
|
|
|
|
REGISTRATIONS = 25
|
|
|
|
|
|
async def drain_history(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
|
|
collected: list[dict] = []
|
|
cursor: str | None = None
|
|
while True:
|
|
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
|
page = (
|
|
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
|
|
).json()
|
|
collected.extend(page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
return collected
|
|
|
|
|
|
async def test_registration_is_visible_to_chats_immediately() -> None:
|
|
async with running_app() as client:
|
|
for _ in range(REGISTRATIONS):
|
|
user = await register(client, "race")
|
|
response = await client.post(
|
|
"/api/v1/chats",
|
|
json={"title": "Сразу после регистрации", "member_ids": [user["id"]]},
|
|
headers=actor(user),
|
|
)
|
|
assert response.status_code == 201, response.text
|
|
|
|
|
|
async def test_parallel_registrations_are_all_usable_as_members() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
bodies = [new_user(f"par{index}") for index in range(REGISTRATIONS)]
|
|
responses = await asyncio.gather(
|
|
*(client.post("/api/v1/users", json=body) for body in bodies)
|
|
)
|
|
assert all(response.status_code == 201 for response in responses)
|
|
created = [response.json()["id"] for response in responses]
|
|
chat = await client.post(
|
|
"/api/v1/chats",
|
|
json={"title": "Все параллельные", "member_ids": [alice["id"], *created]},
|
|
headers=actor(alice),
|
|
)
|
|
assert chat.status_code == 201, chat.text
|
|
assert len(chat.json()["member_ids"]) == REGISTRATIONS + 1
|
|
|
|
|
|
async def test_rejected_registration_leaves_no_trace() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
duplicate = await client.post(
|
|
"/api/v1/users",
|
|
json={"username": alice["username"], "display_name": "Двойник", "password": PASSWORD},
|
|
)
|
|
assert duplicate.status_code == 409
|
|
invalid = await client.post(
|
|
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
|
|
)
|
|
assert invalid.status_code == 400
|
|
sql = "SELECT count(*) FROM users WHERE username = $1"
|
|
assert await scalar(sql, alice["username"]) == 1
|
|
|
|
|
|
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
|
|
title = f"Откат {uuid4().hex}"
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
before = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
|
rejected = await client.post(
|
|
"/api/v1/chats",
|
|
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
|
|
headers=actor(alice),
|
|
)
|
|
assert rejected.status_code == 400
|
|
assert rejected.json()["error"]["code"] == "invalid_request"
|
|
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
|
assert after["items"] == before["items"]
|
|
assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0
|
|
members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid"
|
|
assert await scalar(members, alice["id"]) == 0
|
|
|
|
|
|
async def test_rejected_message_does_not_enter_history() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
eve = await register(client, "eve")
|
|
chat = await make_chat(client, alice)
|
|
|
|
assert (
|
|
await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": " "},
|
|
headers=keyed(alice),
|
|
)
|
|
).status_code == 400
|
|
assert (
|
|
await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": "чужое"},
|
|
headers=keyed(eve),
|
|
)
|
|
).status_code == 404
|
|
|
|
assert await drain_history(client, chat, alice) == []
|
|
|
|
|
|
async def test_confirmed_write_is_visible_to_next_read() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
bob = await register(client, "bob")
|
|
chat = await make_chat(client, alice, bob)
|
|
|
|
for index in range(30):
|
|
posted = await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"подтверждение {index}"},
|
|
headers=keyed(alice),
|
|
)
|
|
assert posted.status_code == 201
|
|
history = await drain_history(client, chat, bob)
|
|
assert history[-1]["id"] == posted.json()["id"]
|
|
assert len(history) == index + 1
|
|
|
|
|
|
async def test_parallel_writes_across_zones_keep_counts_consistent() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
chats = [await make_chat(client, alice) for _ in range(4)]
|
|
|
|
async def writer(chat: dict, worker: int) -> None:
|
|
for index in range(10):
|
|
response = await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"поток-{worker}-{index}"},
|
|
headers=keyed(alice),
|
|
)
|
|
assert response.status_code == 201
|
|
|
|
async def registrar(index: int) -> str:
|
|
return (await register(client, f"parallel{index}"))["id"]
|
|
|
|
results = await asyncio.gather(
|
|
*(writer(chat, number) for number, chat in enumerate(chats)),
|
|
*(registrar(index) for index in range(10)),
|
|
)
|
|
|
|
registered = [item for item in results if isinstance(item, str)]
|
|
assert len(set(registered)) == 10
|
|
for chat in chats:
|
|
history = await drain_history(client, chat, alice)
|
|
assert len(history) == 10
|
|
assert len({item["id"] for item in history}) == 10
|
|
keys = [(item["created_at"], item["id"]) for item in history]
|
|
assert keys == sorted(keys)
|
|
|
|
|
|
async def test_chat_membership_survives_parallel_reads_and_writes() -> None:
|
|
async with running_app() as client:
|
|
alice = await register(client, "alice")
|
|
bob = await register(client, "bob")
|
|
eve = await register(client, "eve")
|
|
chat = await make_chat(client, alice, bob)
|
|
|
|
async def write(index: int) -> None:
|
|
await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"параллельно {index}"},
|
|
headers=keyed(alice),
|
|
)
|
|
|
|
async def intruder() -> int:
|
|
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
|
|
return response.status_code
|
|
|
|
results = await asyncio.gather(
|
|
*(write(index) for index in range(20)),
|
|
*(intruder() for _ in range(20)),
|
|
)
|
|
assert {code for code in results if isinstance(code, int)} == {404}
|
|
assert len(await drain_history(client, chat, bob)) == 20
|