Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.
This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a0d3947710
commit
5ae3d77152
@@ -0,0 +1,84 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register
|
||||
|
||||
|
||||
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
response = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_unknown_chat_is_indistinguishable_from_foreign(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
foreign = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
|
||||
missing = await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(eve))
|
||||
assert foreign.status_code == missing.status_code == 404
|
||||
assert foreign.json()["error"]["code"] == missing.json()["error"]["code"]
|
||||
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
|
||||
|
||||
|
||||
async def test_outsider_cannot_write(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "чужое"},
|
||||
headers=keyed(eve),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
async def test_outsider_cannot_read_history(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_access_checked_before_body(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
headers=keyed(eve),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_chat_list_hides_foreign_chats(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
for member in (alice, bob):
|
||||
listed = await client.get("/api/v1/chats?limit=100", headers=actor(member))
|
||||
assert any(item["id"] == chat["id"] for item in listed.json()["items"])
|
||||
hidden = await client.get("/api/v1/chats?limit=100", headers=actor(eve))
|
||||
assert hidden.json()["items"] == []
|
||||
|
||||
|
||||
async def test_403_is_never_used(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
paths = [
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
]
|
||||
for path in paths:
|
||||
assert (await client.get(path, headers=actor(eve))).status_code != 403
|
||||
@@ -0,0 +1,326 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
from PIL import Image
|
||||
|
||||
from conftest import actor, make_chat, register, resolve, scalar
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import GIF, JPEG, SAMPLE, WEBP, png
|
||||
from pipeline import settle
|
||||
|
||||
LIMIT = 10_485_760
|
||||
PNG = {"Content-Type": "image/png"}
|
||||
|
||||
|
||||
async def upload(
|
||||
http: AsyncClient,
|
||||
user: dict[str, Any],
|
||||
chat: dict[str, Any],
|
||||
content: bytes | AsyncIterator[bytes] = SAMPLE,
|
||||
*,
|
||||
filename: str | None = "sample.png",
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Response:
|
||||
query = "" if filename is None else f"?filename={quote(filename, safe='')}"
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments{query}",
|
||||
content=content,
|
||||
headers={**actor(user), **(PNG if headers is None else headers)},
|
||||
)
|
||||
|
||||
|
||||
async def storage(http: AsyncClient) -> MemoryObjectStorage:
|
||||
found = await resolve(http, ObjectStorage)
|
||||
assert isinstance(found, MemoryObjectStorage)
|
||||
return found
|
||||
|
||||
|
||||
async def trio(http: AsyncClient) -> tuple[dict[str, Any], ...]:
|
||||
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
|
||||
return alice, bob, eve, await make_chat(http, alice, bob)
|
||||
|
||||
|
||||
async def test_member_uploads_and_another_member_downloads(client: AsyncClient) -> None:
|
||||
alice, bob, eve, chat = await trio(client)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
assert set(attachment) == {
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"status",
|
||||
"variants",
|
||||
"error_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
}
|
||||
assert attachment["chat_id"] == chat["id"]
|
||||
assert attachment["owner_id"] == alice["id"]
|
||||
assert attachment["filename"] == "sample.png"
|
||||
assert attachment["content_type"] == "image/png"
|
||||
assert attachment["size_bytes"] == len(SAMPLE) == 111817
|
||||
assert attachment["sha256"] == sha256(SAMPLE).hexdigest()
|
||||
assert (attachment["status"], attachment["variants"], attachment["error_code"]) == (
|
||||
"queued",
|
||||
[],
|
||||
None,
|
||||
)
|
||||
assert attachment["created_at"].endswith("Z")
|
||||
path = f"/api/v1/attachments/{attachment['id']}"
|
||||
assert (await client.get(path, headers=actor(bob))).json() == attachment
|
||||
await settle(client)
|
||||
ready = (await client.get(path, headers=actor(bob))).json()
|
||||
assert (ready["status"], ready["error_code"], ready["sha256"]) == (
|
||||
"ready",
|
||||
None,
|
||||
attachment["sha256"],
|
||||
)
|
||||
assert [variant["name"] for variant in ready["variants"]] == ["crop", "optimized", "thumbnail"]
|
||||
content = await client.get(
|
||||
f"{path}/content", headers={**actor(bob), "Accept": "application/json"}
|
||||
)
|
||||
assert content.status_code == 200
|
||||
assert content.content == SAMPLE
|
||||
assert content.headers["content-type"] == "image/png"
|
||||
assert content.headers["content-length"] == str(len(SAMPLE))
|
||||
assert content.headers["x-content-type-options"] == "nosniff"
|
||||
assert content.headers["x-request-id"]
|
||||
assert content.headers["x-instance-id"]
|
||||
for suffix in ("", "/content"):
|
||||
stranger = await client.get(f"{path}{suffix}", headers=actor(eve))
|
||||
assert stranger.status_code == 404
|
||||
assert stranger.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_object_keys_are_assigned_by_server(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat, filename="a.png")).json()
|
||||
staging = await scalar("SELECT staging_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert staging == f"staging/{attachment['id']}"
|
||||
assert set((await storage(client)).objects) >= {staging}
|
||||
await settle(client)
|
||||
original = await scalar("SELECT original_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert original == f"originals/{attachment['id']}"
|
||||
assert (await storage(client)).objects[original][0] == SAMPLE
|
||||
|
||||
|
||||
async def test_jpeg_is_accepted_by_content(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, JPEG, headers={"Content-Type": "IMAGE/JPEG"})
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["content_type"] == "image/jpeg"
|
||||
await settle(client)
|
||||
download = await client.get(
|
||||
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(bob)
|
||||
)
|
||||
assert (download.content, download.headers["content-type"]) == (JPEG, "image/jpeg")
|
||||
|
||||
|
||||
async def test_access_is_checked_before_content(client: AsyncClient) -> None:
|
||||
alice, _, eve, chat = await trio(client)
|
||||
assert (await upload(client, eve, chat, b"not an image", filename="../x")).status_code == 404
|
||||
missing = {"id": str(uuid4())}
|
||||
assert (await upload(client, alice, missing)).status_code == 404
|
||||
anonymous = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=SAMPLE, headers=PNG
|
||||
)
|
||||
assert anonymous.status_code == 401
|
||||
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
async def test_exact_limit_is_accepted(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, png(16, 16, size=LIMIT))
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["size_bytes"] == LIMIT
|
||||
|
||||
|
||||
async def test_one_byte_over_with_content_length(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, png(16, 16, size=LIMIT + 1))
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
async def test_one_byte_over_chunked(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
body = png(16, 16, size=LIMIT + 1)
|
||||
|
||||
async def chunked() -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(body), 1 << 20):
|
||||
yield body[start : start + (1 << 20)]
|
||||
|
||||
before = await scalar("SELECT count(*) FROM attachments")
|
||||
response = await upload(client, alice, chat, chunked())
|
||||
assert response.status_code == 413
|
||||
assert await scalar("SELECT count(*) FROM attachments") == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "status"),
|
||||
[(8000, 5000, 202), (8001, 5000, 413), (100_000, 100_000, 413)],
|
||||
)
|
||||
async def test_pixel_limit_is_read_from_header(
|
||||
client: AsyncClient, width: int, height: int, status: int
|
||||
) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
body = png(width, height, rows=width * height <= 40_000_000)
|
||||
assert len(body) < 64_000
|
||||
response = await upload(client, alice, chat, body)
|
||||
assert response.status_code == status, response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "header"),
|
||||
[
|
||||
(JPEG, "image/png"),
|
||||
(GIF, "image/png"),
|
||||
(WEBP, "image/png"),
|
||||
(b"plain text, not an image", "image/png"),
|
||||
(SAMPLE, "image/jpeg"),
|
||||
(SAMPLE[: len(SAMPLE) // 2], "image/png"),
|
||||
(JPEG[: len(JPEG) // 2], "image/jpeg"),
|
||||
(b"", "image/png"),
|
||||
(SAMPLE, "application/octet-stream"),
|
||||
(SAMPLE, "image/gif"),
|
||||
],
|
||||
ids=[
|
||||
"jpeg-as-png",
|
||||
"gif-as-png",
|
||||
"webp-as-png",
|
||||
"text-as-png",
|
||||
"png-as-jpeg",
|
||||
"truncated-png",
|
||||
"truncated-jpeg",
|
||||
"empty",
|
||||
"octet-stream",
|
||||
"gif-type",
|
||||
],
|
||||
)
|
||||
async def test_type_is_checked_by_content(client: AsyncClient, content: bytes, header: str) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, content, headers={"Content-Type": header})
|
||||
assert response.status_code == 415, response.text
|
||||
assert response.json()["error"]["code"] == "unsupported_media_type"
|
||||
|
||||
|
||||
async def test_missing_content_type_is_unsupported(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, headers={})
|
||||
assert response.status_code == 415
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename",
|
||||
[
|
||||
*("../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\x01.png", "a\x7f.png"),
|
||||
*("", " ", "x" * 256, None),
|
||||
],
|
||||
)
|
||||
async def test_dangerous_filename_is_rejected(client: AsyncClient, filename: str | None) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 400, response.text
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename", ["фото 1.png", "я" * 255, "%41.png"])
|
||||
async def test_display_name_is_kept(client: AsyncClient, filename: str) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["filename"] == filename
|
||||
|
||||
|
||||
async def test_content_waits_for_ready_and_serves_every_variant(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
for variant in ("original", "thumbnail", "crop", "optimized"):
|
||||
early = await client.get(f"{path}?variant={variant}", headers=actor(bob))
|
||||
assert early.status_code == 409, early.text
|
||||
assert early.json()["error"]["code"] == "conflict"
|
||||
await settle(client)
|
||||
assert (await client.get(f"{path}?variant=original", headers=actor(alice))).status_code == 200
|
||||
meta = (await client.get(path.removesuffix("/content"), headers=actor(bob))).json()
|
||||
expected = {
|
||||
"crop": ("image/jpeg", "JPEG", (128, 128)),
|
||||
"optimized": ("image/webp", "WEBP", (320, 200)),
|
||||
"thumbnail": ("image/jpeg", "JPEG", (256, 160)),
|
||||
}
|
||||
for variant in meta["variants"]:
|
||||
served = await client.get(f"{path}?variant={variant['name']}", headers=actor(bob))
|
||||
content_type, kind, size = expected[variant["name"]]
|
||||
assert (served.headers["content-type"], variant["content_type"]) == (content_type,) * 2
|
||||
assert len(served.content) == variant["size_bytes"]
|
||||
assert sha256(served.content).hexdigest() == variant["sha256"]
|
||||
image = Image.open(BytesIO(served.content))
|
||||
assert (image.format, image.size, (variant["width"], variant["height"])) == (
|
||||
kind,
|
||||
size,
|
||||
size,
|
||||
)
|
||||
await scalar(
|
||||
"DELETE FROM attachment_variants WHERE attachment_id = $1 AND name = 'crop'",
|
||||
UUID(attachment["id"]),
|
||||
)
|
||||
missing = await client.get(f"{path}?variant=crop", headers=actor(alice))
|
||||
assert missing.status_code == 404
|
||||
assert (await client.get(f"{path}?variant=preview", headers=actor(alice))).status_code == 400
|
||||
assert (
|
||||
await client.get("/api/v1/attachments/x/content", headers=actor(alice))
|
||||
).status_code == 400
|
||||
unknown = await client.get(f"/api/v1/attachments/{uuid4()}", headers=actor(alice))
|
||||
assert unknown.status_code == 404
|
||||
|
||||
|
||||
async def test_storage_failure_leaves_nothing_visible(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
ready = await upload(client, alice, chat)
|
||||
await settle(client)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
failed = await upload(client, alice, chat, filename="failed.png")
|
||||
download = await client.get(
|
||||
f"/api/v1/attachments/{ready.json()['id']}/content", headers=actor(alice)
|
||||
)
|
||||
metadata = await client.get(
|
||||
f"/api/v1/attachments/{ready.json()['id']}", headers=actor(alice)
|
||||
)
|
||||
finally:
|
||||
store.failing = False
|
||||
assert failed.status_code == 503
|
||||
assert failed.json()["error"]["code"] == "unavailable"
|
||||
assert download.status_code == 503
|
||||
assert metadata.status_code == 200
|
||||
status = await scalar(
|
||||
"SELECT string_agg(status, ',') FROM attachments WHERE chat_id = $1 AND filename = $2",
|
||||
chat["id"],
|
||||
"failed.png",
|
||||
)
|
||||
assert status == "pending"
|
||||
|
||||
|
||||
async def test_lost_object_is_not_found(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
await settle(client)
|
||||
(await storage(client)).objects.clear()
|
||||
response = await client.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
@@ -0,0 +1,289 @@
|
||||
import ast
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger"
|
||||
IDENTITY = "messenger.identity"
|
||||
MESSAGING = "messenger.messaging"
|
||||
ATTACHMENTS = "messenger.attachments"
|
||||
ZONES = ("identity", "messaging", "attachments")
|
||||
|
||||
|
||||
def imports_of(path: Path) -> list[str]:
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
found: list[str] = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module:
|
||||
found.append(node.module)
|
||||
elif isinstance(node, ast.Import):
|
||||
found.extend(alias.name for alias in node.names)
|
||||
return found
|
||||
|
||||
|
||||
def modules_under(*parts: str) -> list[Path]:
|
||||
root = SOURCE.joinpath(*parts)
|
||||
return [path for path in root.rglob("*.py") if path.name != "__init__.py"]
|
||||
|
||||
|
||||
def test_identity_does_not_know_about_messaging() -> None:
|
||||
offenders = {
|
||||
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(MESSAGING)]
|
||||
for path in modules_under("identity")
|
||||
}
|
||||
assert not {k: v for k, v in offenders.items() if v}
|
||||
|
||||
|
||||
def test_messaging_touches_identity_only_through_events() -> None:
|
||||
allowed = f"{IDENTITY}.domain.events"
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in modules_under("messaging"):
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith(IDENTITY) and module != allowed
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone, foreign in (
|
||||
("attachments", (IDENTITY, MESSAGING)),
|
||||
("identity", (ATTACHMENTS,)),
|
||||
("messaging", (ATTACHMENTS,)),
|
||||
):
|
||||
for path in modules_under(zone):
|
||||
borrowed = [m for m in imports_of(path) if m.startswith(foreign)]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_domains_do_not_import_infrastructure() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if ".infrastructure" in m]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_core_layers_do_not_import_pydantic() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders, "схемы pydantic живут на границе: в entrypoints/ и config.py"
|
||||
|
||||
|
||||
def test_shared_knows_nothing_about_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in modules_under("shared"):
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
TRANSPORT = ("fastapi", "starlette", "uvicorn", "gunicorn")
|
||||
|
||||
|
||||
def test_shared_core_is_free_of_transport() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for layer in ("domain", "application", "infrastructure"):
|
||||
for path in modules_under("shared", layer):
|
||||
borrowed = [module for module in imports_of(path) if module.split(".")[0] in TRANSPORT]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders, "ядро shared обязано жить без веб-фреймворка"
|
||||
|
||||
|
||||
def test_shared_core_holds_only_platform() -> None:
|
||||
names = {
|
||||
path.name
|
||||
for layer in ("domain", "application", "infrastructure")
|
||||
for path in modules_under("shared", layer)
|
||||
}
|
||||
assert names == {
|
||||
"errors.py",
|
||||
"events.py",
|
||||
"commands.py",
|
||||
"messagebus.py",
|
||||
"ports.py",
|
||||
"clock.py",
|
||||
"ids.py",
|
||||
"logging.py",
|
||||
"postgres.py",
|
||||
}
|
||||
|
||||
|
||||
def test_shared_entrypoints_hold_only_transport() -> None:
|
||||
names = {path.name for path in modules_under("shared", "entrypoints")}
|
||||
assert names == {
|
||||
"actor.py",
|
||||
"config.py",
|
||||
"errors.py",
|
||||
"health.py",
|
||||
"ioc.py",
|
||||
"pipeline.py",
|
||||
"schemas.py",
|
||||
}
|
||||
|
||||
|
||||
def test_every_zone_owns_its_errors_events_and_commands() -> None:
|
||||
for zone in ZONES:
|
||||
assert (SOURCE / zone / "domain" / "errors.py").is_file()
|
||||
assert (SOURCE / zone / "domain" / "events.py").is_file()
|
||||
assert (SOURCE / zone / "application" / "commands.py").is_file()
|
||||
|
||||
|
||||
def test_every_zone_owns_its_http_layer() -> None:
|
||||
for zone in ZONES:
|
||||
for part in ("http.py", "ioc.py", "errors.py", "journal.py"):
|
||||
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
|
||||
|
||||
|
||||
PROCESSES = {"relay.py": (ATTACHMENTS,), "worker.py": (ATTACHMENTS,), "admin.py": (ATTACHMENTS,)}
|
||||
|
||||
|
||||
def test_only_main_knows_several_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in SOURCE.rglob("*.py"):
|
||||
relative = path.relative_to(SOURCE)
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
|
||||
continue
|
||||
allowed = PROCESSES.get(str(relative), ())
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
and not module.startswith(allowed or ("-",))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(relative)] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_broker_framework_stays_out_of_shared_and_core_layers() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in [
|
||||
*modules_under("shared"),
|
||||
*(
|
||||
p
|
||||
for zone in ZONES
|
||||
for layer in ("domain", "application")
|
||||
for p in modules_under(zone, layer)
|
||||
),
|
||||
]:
|
||||
borrowed = [
|
||||
m for m in imports_of(path) if m.split(".")[0] in {"faststream", "aio_pika", "aiormq"}
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_application_has_no_separate_entrypoints_root() -> None:
|
||||
assert not (SOURCE / "entrypoints").exists()
|
||||
assert (SOURCE / "main.py").is_file()
|
||||
|
||||
|
||||
ZONE_WORDS = (
|
||||
"username",
|
||||
"display_name",
|
||||
"chat",
|
||||
"member",
|
||||
"history",
|
||||
"cursor",
|
||||
"sender",
|
||||
"message_id",
|
||||
"message_text",
|
||||
"attachment",
|
||||
"filename",
|
||||
)
|
||||
|
||||
|
||||
def test_shared_source_mentions_no_domain_vocabulary() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in modules_under("shared"):
|
||||
source = path.read_text().lower()
|
||||
hits = sorted({word for word in ZONE_WORDS if word in source})
|
||||
if hits:
|
||||
offenders[str(path.relative_to(SOURCE))] = hits
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_shared_declares_no_concrete_commands_or_events() -> None:
|
||||
for path in modules_under("shared"):
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
declared = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
|
||||
concrete = [
|
||||
name
|
||||
for name in declared
|
||||
if name not in {"Command", "DomainEvent", "DomainError"}
|
||||
and (
|
||||
name.endswith("Event")
|
||||
or name in {"RegisterUser", "CreateChat", "PostMessage", "UploadAttachment"}
|
||||
)
|
||||
]
|
||||
assert not concrete, f"{path.name}: {concrete}"
|
||||
|
||||
|
||||
def test_shared_has_no_test_doubles() -> None:
|
||||
for path in modules_under("shared"):
|
||||
source = path.read_text()
|
||||
for marker in ("Frozen", "Fake", "Stub", "Null", "Dummy"):
|
||||
assert marker not in source, f"{path.name} содержит подделку {marker}"
|
||||
|
||||
|
||||
def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
for zone in (*ZONES, "shared"):
|
||||
source = (SOURCE / zone / "domain" / "errors.py").read_text()
|
||||
assert "http_status" not in source
|
||||
assert "invalid_request" not in source
|
||||
assert "404" not in source
|
||||
|
||||
|
||||
IDENTITY_TABLES = ("users", "sessions")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
|
||||
ATTACHMENT_TABLES = ("attachments", "attachment_variants", "jobs", "outbox", "job_events")
|
||||
|
||||
|
||||
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
words: set[str] = set()
|
||||
for path in modules_under(zone):
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
|
||||
return words & set(tables)
|
||||
|
||||
|
||||
def test_sql_of_each_zone_reads_only_its_tables() -> None:
|
||||
owned = {
|
||||
"identity": IDENTITY_TABLES,
|
||||
"messaging": MESSAGING_TABLES,
|
||||
"attachments": ATTACHMENT_TABLES,
|
||||
}
|
||||
every = {table for tables in owned.values() for table in tables}
|
||||
for zone, tables in owned.items():
|
||||
assert sql_tables(zone, tuple(every)) == set(tables), zone
|
||||
|
||||
|
||||
def test_messaging_does_not_import_identity_at_all() -> None:
|
||||
borrowed = {
|
||||
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(IDENTITY)]
|
||||
for path in modules_under("messaging")
|
||||
}
|
||||
assert not {key: value for key, value in borrowed.items() if value}
|
||||
@@ -0,0 +1,118 @@
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
|
||||
from redis.asyncio import Redis
|
||||
|
||||
from conftest import actor, bearer, register, resolve, running_app, scalar
|
||||
from messenger.identity.application.ports import SessionDirectory
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
|
||||
BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def key_of(token: str) -> str:
|
||||
return f"session:{sha256(token.encode()).hexdigest()}"
|
||||
|
||||
|
||||
def token_of(user: dict) -> str:
|
||||
return actor(user)["Authorization"].split()[1]
|
||||
|
||||
|
||||
async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
hits = (await cache.info("stats"))["keyspace_hits"]
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
|
||||
key = key_of(token_of(alice))
|
||||
stored = str(await cache.get(key))
|
||||
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
|
||||
expires_at: datetime = await scalar(sql, alice["id"])
|
||||
assert alice["id"] in stored and token_of(alice) not in stored
|
||||
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
).status_code == 204
|
||||
assert await cache.get(key_of(token_of(alice))) == b"-"
|
||||
response = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"] == BEARER
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
directory = await resolve(http, SessionDirectory)
|
||||
assert isinstance(directory, CachedSessionDirectory)
|
||||
origin = directory._origin
|
||||
stale: list[Session | None] = []
|
||||
entered, released = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class SlowOrigin:
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
stale.append(await origin.find(token_hash, now))
|
||||
entered.set()
|
||||
await released.wait()
|
||||
return stale[-1]
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
await origin.invalidate(session)
|
||||
|
||||
directory._origin = SlowOrigin()
|
||||
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
|
||||
await entered.wait()
|
||||
directory._origin = origin
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
).status_code == 204
|
||||
released.set()
|
||||
assert (await reader).status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
|
||||
|
||||
async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
bob = await register(http, "bob")
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(bob))
|
||||
).status_code == 204
|
||||
await cache.flushall()
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
|
||||
async with running_app(cache_url="redis://127.0.0.1:1/0") as http:
|
||||
alice = await register(http, "alice")
|
||||
started = time.perf_counter()
|
||||
me = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
|
||||
elapsed = time.perf_counter() - started
|
||||
ready = await http.get("/health/ready")
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
still = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert me.json() == alice
|
||||
assert stranger.status_code == 401
|
||||
assert stranger.headers["WWW-Authenticate"] == BEARER
|
||||
assert elapsed < 1
|
||||
assert ready.status_code == 200
|
||||
assert logout.status_code == 503
|
||||
assert logout.json()["error"]["code"] == "unavailable"
|
||||
assert still.status_code == 200
|
||||
@@ -0,0 +1,88 @@
|
||||
import asyncio
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, register
|
||||
|
||||
CLIENTS = 10
|
||||
PER_CLIENT = 10
|
||||
TOTAL = CLIENTS * PER_CLIENT
|
||||
|
||||
|
||||
async def drain(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 flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
|
||||
async def writer(worker: int) -> list[int]:
|
||||
codes = []
|
||||
for index in range(PER_CLIENT):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"нагрузка-{worker}-{index}"},
|
||||
headers=keyed(sender),
|
||||
)
|
||||
codes.append(response.status_code)
|
||||
return codes
|
||||
|
||||
batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS)))
|
||||
return [code for batch in batches for code in batch]
|
||||
|
||||
|
||||
async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
|
||||
codes = await flood(client, chat, alice)
|
||||
assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}"
|
||||
|
||||
history = await drain(client, chat, bob)
|
||||
assert len(history) == TOTAL
|
||||
assert len({item["id"] for item in history}) == TOTAL
|
||||
assert len({item["text"] for item in history}) == TOTAL
|
||||
|
||||
keys = [(item["created_at"], item["id"]) for item in history]
|
||||
assert keys == sorted(keys), "история не упорядочена по (created_at, id)"
|
||||
stamps = [item["created_at"] for item in history]
|
||||
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
|
||||
|
||||
|
||||
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
|
||||
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
|
||||
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
|
||||
codes = [response.status_code for response in responses]
|
||||
assert codes.count(201) == 1
|
||||
assert codes.count(409) == len(codes) - 1
|
||||
|
||||
|
||||
async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
for index in range(20)
|
||||
)
|
||||
)
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json()
|
||||
assert len(listed["items"]) == 20
|
||||
keys = [(item["created_at"], item["id"]) for item in listed["items"]]
|
||||
assert keys == sorted(keys)
|
||||
@@ -0,0 +1,188 @@
|
||||
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
|
||||
@@ -0,0 +1,110 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
|
||||
from conftest import DATABASE, new_user
|
||||
from messenger.shared.entrypoints.health import DRAINING
|
||||
|
||||
DRAIN = 1.5
|
||||
SHUTDOWN = 4
|
||||
GUNICORN = (
|
||||
"-m",
|
||||
"gunicorn",
|
||||
"--config",
|
||||
"python:messenger.gunicorn_conf",
|
||||
"messenger.main:create_app()",
|
||||
)
|
||||
|
||||
|
||||
async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient) -> None:
|
||||
DRAINING.set()
|
||||
try:
|
||||
ready = await client.get("/health/ready")
|
||||
live = await client.get("/health/live")
|
||||
finally:
|
||||
DRAINING.clear()
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert ready.headers["X-Instance-Id"]
|
||||
assert live.status_code == 200
|
||||
assert (await client.get("/health/ready")).status_code == 200
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
return probe.getsockname()[1]
|
||||
|
||||
|
||||
def status(port: int, path: str) -> int:
|
||||
try:
|
||||
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1).status_code
|
||||
except httpx.TransportError:
|
||||
return 0
|
||||
|
||||
|
||||
def begin_registration(port: int) -> tuple[socket.socket, bytes]:
|
||||
body = json.dumps(new_user("drain")).encode()
|
||||
head = (
|
||||
"POST /api/v1/users HTTP/1.1\r\nHost: replica\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
connection = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
connection.sendall(head.encode() + body[:8])
|
||||
return connection, body[8:]
|
||||
|
||||
|
||||
def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
|
||||
port = free_port()
|
||||
settings = {
|
||||
"HOST": "127.0.0.1",
|
||||
"PORT": str(port),
|
||||
"WEB_CONCURRENCY": "2",
|
||||
"DATABASE_URL": DATABASE["url"],
|
||||
"CURSOR_SECRET": "test-secret-for-cursors",
|
||||
"S3_ACCESS_KEY_ID": "test-key",
|
||||
"S3_SECRET_ACCESS_KEY": "test-secret-key",
|
||||
"LOG_LEVEL": "WARNING",
|
||||
"DRAIN_SECONDS": str(DRAIN),
|
||||
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
|
||||
}
|
||||
server = subprocess.Popen(
|
||||
[sys.executable, *GUNICORN],
|
||||
env={**os.environ, **settings},
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while status(port, "/health/ready") != 200:
|
||||
assert time.monotonic() < deadline, "gunicorn не стал готов"
|
||||
time.sleep(0.2)
|
||||
pending, rest = begin_registration(port)
|
||||
sent = time.monotonic()
|
||||
server.send_signal(signal.SIGTERM)
|
||||
time.sleep(0.3)
|
||||
during = status(port, "/health/ready"), status(port, "/health/live")
|
||||
while status(port, "/health/live") == 200:
|
||||
time.sleep(0.05)
|
||||
closed = time.monotonic() - sent
|
||||
pending.sendall(rest)
|
||||
answer = pending.recv(64).split(b"\r\n")[0].decode()
|
||||
pending.close()
|
||||
code = server.wait(timeout=SHUTDOWN + 2)
|
||||
exited = time.monotonic() - sent
|
||||
finally:
|
||||
if server.poll() is None:
|
||||
server.kill()
|
||||
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
|
||||
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
|
||||
assert during == (503, 200)
|
||||
assert answer == "HTTP/1.1 201 Created"
|
||||
assert DRAIN - 0.2 <= closed < SHUTDOWN
|
||||
assert exited < SHUTDOWN
|
||||
assert code == 0
|
||||
@@ -0,0 +1,124 @@
|
||||
import asyncio
|
||||
from dataclasses import fields
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from conftest import keyed, make_chat, register, split_settings
|
||||
from fakes import NullLogger
|
||||
from messenger.identity.domain.events import UserRegistered
|
||||
from messenger.main import create_app
|
||||
from messenger.messaging.domain.events import MessagePosted
|
||||
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
|
||||
|
||||
|
||||
def posted() -> MessagePosted:
|
||||
return MessagePosted(
|
||||
message_id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
sender_id=uuid4(),
|
||||
text_length=5,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
async def test_event_has_no_message_text() -> None:
|
||||
names = {field.name for field in fields(posted())}
|
||||
assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"}
|
||||
|
||||
|
||||
async def test_every_subscriber_receives_event() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
seen: list[str] = []
|
||||
|
||||
async def first(_event: MessagePosted) -> None:
|
||||
seen.append("first")
|
||||
|
||||
async def second(_event: MessagePosted) -> None:
|
||||
seen.append("second")
|
||||
|
||||
bus.subscribe(MessagePosted, first)
|
||||
bus.subscribe(MessagePosted, second)
|
||||
bus.start()
|
||||
await InMemoryEventPublisher(bus).publish([posted()])
|
||||
await bus.stop()
|
||||
assert sorted(seen) == ["first", "second"]
|
||||
|
||||
|
||||
async def test_failing_subscriber_does_not_block_others() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
survived: list[str] = []
|
||||
|
||||
async def broken(_event: MessagePosted) -> None:
|
||||
raise RuntimeError("обработчик упал")
|
||||
|
||||
async def healthy(_event: MessagePosted) -> None:
|
||||
survived.append("ok")
|
||||
|
||||
bus.subscribe(MessagePosted, broken)
|
||||
bus.subscribe(MessagePosted, healthy)
|
||||
bus.start()
|
||||
await InMemoryEventPublisher(bus).publish([posted()])
|
||||
await bus.stop()
|
||||
assert survived == ["ok"]
|
||||
|
||||
|
||||
async def test_queue_overflow_drops_events_without_raising() -> None:
|
||||
bus = EventBus(NullLogger(), max_queue=16)
|
||||
|
||||
async def never_called(_event: MessagePosted) -> None:
|
||||
raise AssertionError("обработчик не должен вызываться без запущенной шины")
|
||||
|
||||
bus.subscribe(MessagePosted, never_called)
|
||||
publisher = InMemoryEventPublisher(bus)
|
||||
await publisher.publish([posted() for _ in range(64)])
|
||||
assert bus.dropped > 0
|
||||
assert bus.pending <= 16
|
||||
|
||||
|
||||
async def test_projection_runs_before_publish_returns() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
seen: list[str] = []
|
||||
|
||||
async def projection(_event: MessagePosted) -> None:
|
||||
seen.append("projected")
|
||||
|
||||
bus.project(MessagePosted, projection)
|
||||
await InMemoryEventPublisher(bus).publish([posted()])
|
||||
assert seen == ["projected"]
|
||||
|
||||
|
||||
async def test_publication_does_not_delay_response() -> None:
|
||||
app = create_app(**split_settings(log_level="CRITICAL"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
bus = await app.state.dishka_container.get(EventBus)
|
||||
slow = asyncio.Event()
|
||||
|
||||
async def blocker(_event: MessagePosted) -> None:
|
||||
await slow.wait()
|
||||
|
||||
bus.subscribe(MessagePosted, blocker)
|
||||
response = await asyncio.wait_for(
|
||||
http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "не ждём обработчик"},
|
||||
headers=keyed(alice),
|
||||
),
|
||||
timeout=2,
|
||||
)
|
||||
assert response.status_code == 201
|
||||
slow.set()
|
||||
|
||||
|
||||
async def test_null_logger_hides_everything() -> None:
|
||||
logger = NullLogger()
|
||||
logger.info("x", route="/")
|
||||
logger.warning("x")
|
||||
logger.error("x")
|
||||
assert isinstance(UserRegistered, type)
|
||||
@@ -0,0 +1,145 @@
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, running_app, scalar
|
||||
|
||||
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)
|
||||
ids = {
|
||||
(await send(client, chat, alice, "алиса", "shared-1")).json()["id"],
|
||||
(await send(client, chat, bob, "боб", "shared-1")).json()["id"],
|
||||
(await send(client, other, alice, "другой чат", "shared-1")).json()["id"],
|
||||
}
|
||||
assert len(ids) == 3
|
||||
|
||||
|
||||
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 count(*) FROM idempotency_keys WHERE key = $1", key) == 1
|
||||
@@ -0,0 +1,64 @@
|
||||
import socket
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient, Response
|
||||
|
||||
from conftest import actor, register, running_app, split_settings
|
||||
from messenger.main import create_app
|
||||
from messenger.shared.config import PlatformSettings
|
||||
|
||||
REPLICA = "replica-7f3a"
|
||||
|
||||
|
||||
def stamped(response: Response) -> bool:
|
||||
return bool(response.headers.get("X-Request-Id")) and (
|
||||
response.headers.get("X-Instance-Id") == REPLICA
|
||||
)
|
||||
|
||||
|
||||
async def test_every_response_names_the_replica() -> None:
|
||||
async with running_app(instance_id=REPLICA) as http:
|
||||
alice = await register(http, "alice")
|
||||
probes = [
|
||||
await http.get("/health/live"),
|
||||
await http.get("/health/ready"),
|
||||
await http.get("/api/v1/users/me", headers=actor(alice)),
|
||||
await http.get("/api/v1/users/me"),
|
||||
await http.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
|
||||
await http.get("/nothing-here"),
|
||||
await http.delete("/health/live"),
|
||||
await http.post("/api/v1/users", json={"username": "x"}),
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)),
|
||||
]
|
||||
assert [probe.status_code for probe in probes] == [200, 200, 200, 401, 404, 404, 404, 400, 204]
|
||||
assert all(stamped(probe) for probe in probes)
|
||||
|
||||
|
||||
async def test_rejected_body_names_the_replica() -> None:
|
||||
async with running_app(instance_id=REPLICA, max_body_bytes=4096) as http:
|
||||
response = await http.post("/api/v1/users", content=b"x" * 5000)
|
||||
assert response.status_code == 413
|
||||
assert stamped(response)
|
||||
|
||||
|
||||
async def test_unhandled_error_names_the_replica() -> None:
|
||||
app = create_app(**split_settings(instance_id=REPLICA))
|
||||
|
||||
async def boom() -> None:
|
||||
raise RuntimeError("сбой")
|
||||
|
||||
app.add_api_route("/health/boom", boom)
|
||||
transport = ASGITransport(app=app, raise_app_exceptions=False)
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=transport, base_url="http://testserver") as http,
|
||||
):
|
||||
response = await http.get("/health/boom")
|
||||
assert response.status_code == 500
|
||||
assert response.json()["error"]["code"] == "internal_error"
|
||||
assert stamped(response)
|
||||
|
||||
|
||||
def test_replica_defaults_to_container_hostname() -> None:
|
||||
settings = PlatformSettings.model_validate({"database_url": "postgresql://u@h/d"})
|
||||
assert settings.instance_id == socket.gethostname()
|
||||
@@ -0,0 +1,149 @@
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, resolve
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import SAMPLE
|
||||
from pipeline import settle
|
||||
|
||||
|
||||
async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
response = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
|
||||
content=SAMPLE,
|
||||
headers={**actor(user), "Content-Type": "image/png"},
|
||||
)
|
||||
assert response.status_code == 202, response.text
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
async def send(
|
||||
http: AsyncClient, user: dict[str, Any], chat: dict[str, Any], body: Any, key: str | None = None
|
||||
) -> Any:
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=keyed(user, key)
|
||||
)
|
||||
|
||||
|
||||
async def scene(http: AsyncClient) -> tuple[dict[str, Any], ...]:
|
||||
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
|
||||
return alice, bob, eve, await make_chat(http, alice, bob), await make_chat(http, alice)
|
||||
|
||||
|
||||
async def test_text_message_carries_empty_list(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
response = await send(client, alice, chat, {"text": "привет"})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["attachment_ids"] == []
|
||||
|
||||
|
||||
async def test_empty_text_with_attachment_keeps_order(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
ids = [await attach(client, alice, chat) for _ in range(3)]
|
||||
ordered = [ids[2], ids[0], ids[1]]
|
||||
response = await send(client, bob, chat, {"text": "", "attachment_ids": ordered})
|
||||
assert response.status_code == 201, response.text
|
||||
message = response.json()
|
||||
assert message["attachment_ids"] == ordered
|
||||
again = await send(client, alice, chat, {"text": "ещё раз", "attachment_ids": [ids[0]]})
|
||||
assert again.status_code == 201
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
|
||||
assert history.json()["items"] == [message, again.json()]
|
||||
|
||||
|
||||
async def test_replay_with_attachments_and_default_list(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
first_id, second_id = await attach(client, alice, chat), await attach(client, alice, chat)
|
||||
body = {"text": "", "attachment_ids": [first_id, second_id]}
|
||||
first = await send(client, alice, chat, body, "with-files")
|
||||
assert (await send(client, alice, chat, body, "with-files")).json() == first.json()
|
||||
swapped = {"text": "", "attachment_ids": [second_id, first_id]}
|
||||
assert (await send(client, alice, chat, swapped, "with-files")).status_code == 409
|
||||
plain = await send(client, alice, chat, {"text": "x"}, "plain")
|
||||
explicit = await send(client, alice, chat, {"attachment_ids": [], "text": "x"}, "plain")
|
||||
assert (explicit.status_code, explicit.json()) == (201, plain.json())
|
||||
|
||||
|
||||
async def test_attachment_of_another_chat_or_unknown(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, solo = await scene(client)
|
||||
foreign = await attach(client, alice, solo)
|
||||
for ids in ([foreign], [str(uuid4())]):
|
||||
response = await send(client, alice, chat, {"text": "x", "attachment_ids": ids})
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["eleven", "duplicate", "not-uuid", "empty", "blank"])
|
||||
async def test_invalid_attachment_lists(client: AsyncClient, kind: str) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
body = {
|
||||
"eleven": {"text": "x", "attachment_ids": [file] + [str(uuid4()) for _ in range(10)]},
|
||||
"duplicate": {"text": "x", "attachment_ids": [file, file]},
|
||||
"not-uuid": {"text": "x", "attachment_ids": ["not-a-uuid"]},
|
||||
"empty": {"text": "", "attachment_ids": []},
|
||||
"blank": {"text": " ", "attachment_ids": [file]},
|
||||
}[kind]
|
||||
response = await send(client, alice, chat, body)
|
||||
assert response.status_code == 400, response.text
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_outsider_gets_not_found_before_validation(client: AsyncClient) -> None:
|
||||
alice, _, eve, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
for body in ({"text": "", "attachment_ids": []}, {"text": "x", "attachment_ids": [file] * 11}):
|
||||
assert (await send(client, eve, chat, body)).status_code == 404
|
||||
|
||||
|
||||
async def test_one_attachment_in_several_messages(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
for user in (alice, bob):
|
||||
response = await send(client, user, chat, {"text": "", "attachment_ids": [file]})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["attachment_ids"] == [file]
|
||||
|
||||
|
||||
async def broken(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
attachment_id = await attach(http, user, chat)
|
||||
store = await resolve(http, ObjectStorage)
|
||||
assert isinstance(store, MemoryObjectStorage)
|
||||
store.objects[f"staging/{attachment_id}"] = (b"\x89PNG\r\n\x1a\n broken", "image/png")
|
||||
await settle(http)
|
||||
return attachment_id
|
||||
|
||||
|
||||
async def test_queued_attachment_is_sent_and_failed_is_conflict(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
queued = await attach(client, alice, chat)
|
||||
early = await send(client, alice, chat, {"text": "", "attachment_ids": [queued]})
|
||||
assert early.status_code == 201, early.text
|
||||
failed = await broken(client, bob, chat)
|
||||
meta = (await client.get(f"/api/v1/attachments/{failed}", headers=actor(alice))).json()
|
||||
assert (meta["status"], meta["error_code"]) == ("failed", "invalid_image")
|
||||
refused = await send(client, alice, chat, {"text": "x", "attachment_ids": [queued, failed]})
|
||||
assert refused.status_code == 409
|
||||
assert refused.json()["error"]["code"] == "conflict"
|
||||
content = await client.get(f"/api/v1/attachments/{failed}/content", headers=actor(bob))
|
||||
assert content.status_code == 409
|
||||
|
||||
|
||||
async def test_replay_survives_a_later_failure(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
attachment_id = await attach(client, alice, chat)
|
||||
body = {"text": "", "attachment_ids": [attachment_id]}
|
||||
first = await send(client, alice, chat, body, key="replay-after-failure")
|
||||
store = await resolve(client, ObjectStorage)
|
||||
assert isinstance(store, MemoryObjectStorage)
|
||||
store.objects[f"staging/{attachment_id}"] = (b"garbage", "image/png")
|
||||
await settle(client)
|
||||
again = await send(client, alice, chat, body, key="replay-after-failure")
|
||||
assert (first.status_code, again.status_code) == (201, 201)
|
||||
assert again.json() == first.json()
|
||||
@@ -0,0 +1,240 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
|
||||
from conftest import DATABASE, scalar
|
||||
from messenger.migrate import MigrationChangedError, migrate, migrations
|
||||
|
||||
COUNTS = """
|
||||
SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions),
|
||||
(SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members),
|
||||
(SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys),
|
||||
(SELECT count(*) FROM attachments), (SELECT count(*) FROM message_attachments),
|
||||
(SELECT count(*) FROM attachment_variants), (SELECT count(*) FROM jobs),
|
||||
(SELECT count(*) FROM outbox), (SELECT count(*) FROM job_events)
|
||||
"""
|
||||
PIPELINE_COLUMNS = {
|
||||
"attachments": {
|
||||
"id",
|
||||
"status",
|
||||
"published_version",
|
||||
"error_code",
|
||||
"staging_key",
|
||||
"original_key",
|
||||
},
|
||||
"attachment_variants": {
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"name",
|
||||
"sha256",
|
||||
"size_bytes",
|
||||
"object_key",
|
||||
},
|
||||
"jobs": {"job_id", "attachment_id", "pipeline_version", "status", "attempt"},
|
||||
"outbox": {"job_id", "payload", "published_at"},
|
||||
"job_events": {"job_id", "attachment_id", "kind", "attempt"},
|
||||
}
|
||||
|
||||
|
||||
async def counts() -> list[int]:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
return list(await connection.fetchrow(COUNTS))
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_migrations_are_ordered_and_versioned() -> None:
|
||||
versions = [version for version, _ in migrations()]
|
||||
assert versions == sorted(versions)
|
||||
assert versions[:5] == [
|
||||
"0001_init",
|
||||
"0002_idempotency_keys",
|
||||
"0003_attachments",
|
||||
"0004_jobs",
|
||||
"0005_failed_registry",
|
||||
]
|
||||
plan = await scalar("SELECT indexdef FROM pg_indexes WHERE indexname = 'jobs_failed_idx'")
|
||||
assert "WHERE (status = 'failed'::text)" in plan
|
||||
applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
|
||||
assert applied == versions
|
||||
|
||||
|
||||
async def test_rerun_changes_nothing() -> None:
|
||||
before = await counts()
|
||||
assert await migrate(DATABASE["url"]) == []
|
||||
assert await counts() == before
|
||||
|
||||
|
||||
async def test_changed_migration_is_refused() -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
original = await connection.fetchval(
|
||||
"SELECT checksum FROM schema_migrations WHERE version = '0001_init'"
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'"
|
||||
)
|
||||
with pytest.raises(MigrationChangedError):
|
||||
await migrate(DATABASE["url"])
|
||||
await connection.execute(
|
||||
"UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_sender_must_be_member_even_bypassing_api() -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
with pytest.raises(asyncpg.ForeignKeyViolationError):
|
||||
await connection.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())"
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_key_needs_a_member_and_a_message() -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
with pytest.raises(asyncpg.ForeignKeyViolationError):
|
||||
await connection.execute(
|
||||
"INSERT INTO idempotency_keys "
|
||||
"(chat_id, user_id, key, fingerprint, message_id, created_at) "
|
||||
"VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', "
|
||||
"sha256('x'), gen_random_uuid(), now())"
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_attachment_owner_must_be_member() -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
with pytest.raises(asyncpg.ForeignKeyViolationError, match="attachments_owner_fkey"):
|
||||
await connection.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, "
|
||||
"size_bytes, sha256, width, height, object_key, status, created_at, updated_at) "
|
||||
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'a.png', "
|
||||
"'image/png', 1, repeat('0', 64), 1, 1, 'attachments/x', 'pending', now(), now())"
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_message_links_only_attachments_of_its_chat() -> None:
|
||||
user, chat_a, chat_b, attachment, message = (uuid4() for _ in range(5))
|
||||
seed = [
|
||||
(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||
"VALUES ($1, $2, 'A', '$argon2id$x', now())",
|
||||
user,
|
||||
f"u_{user.hex[:12]}",
|
||||
),
|
||||
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat_a),
|
||||
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'B', now())", chat_b),
|
||||
(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
|
||||
"VALUES ($1, $3, 1, now()), ($2, $3, 1, now())",
|
||||
chat_a,
|
||||
chat_b,
|
||||
user,
|
||||
),
|
||||
(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, "
|
||||
"sha256, width, height, object_key, status, created_at, updated_at) VALUES ($1, $2, "
|
||||
"$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'ready', now(), now())",
|
||||
attachment,
|
||||
chat_a,
|
||||
user,
|
||||
f"attachments/{attachment}",
|
||||
),
|
||||
(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||
"VALUES ($1, $2, $3, '', now())",
|
||||
message,
|
||||
chat_b,
|
||||
user,
|
||||
),
|
||||
]
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
transaction = connection.transaction()
|
||||
await transaction.start()
|
||||
try:
|
||||
for sql, *arguments in seed:
|
||||
await connection.execute(sql, *arguments)
|
||||
assert await connection.fetchval("SELECT text FROM messages WHERE id = $1", message) == ""
|
||||
with pytest.raises(
|
||||
asyncpg.ForeignKeyViolationError, match="message_attachments_attachment_fkey"
|
||||
):
|
||||
await connection.execute(
|
||||
"INSERT INTO message_attachments (message_id, position, chat_id, attachment_id) "
|
||||
"VALUES ($1, 0, $2, $3)",
|
||||
message,
|
||||
chat_b,
|
||||
attachment,
|
||||
)
|
||||
finally:
|
||||
await transaction.rollback()
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def test_pipeline_tables_have_the_columns_the_suite_reads() -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
rows = await connection.fetch(
|
||||
"SELECT table_name, column_name FROM information_schema.columns "
|
||||
"WHERE table_schema = current_schema()"
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
found: dict[str, set[str]] = {}
|
||||
for row in rows:
|
||||
found.setdefault(row["table_name"], set()).add(row["column_name"])
|
||||
assert all(columns <= found.get(table, set()) for table, columns in PIPELINE_COLUMNS.items())
|
||||
|
||||
|
||||
async def test_one_variant_row_per_effect_key() -> None:
|
||||
user, chat, attachment = uuid4(), uuid4(), uuid4()
|
||||
variant = (
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, "
|
||||
"content_type, size_bytes, width, height, sha256, created_at) "
|
||||
"VALUES ($1, 1, 'thumbnail', $2, 'image/jpeg', 1, 1, 1, repeat('a', 64), now())"
|
||||
)
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
transaction = connection.transaction()
|
||||
await transaction.start()
|
||||
try:
|
||||
await connection.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||
"VALUES ($1, $2, 'A', '$argon2id$x', now())",
|
||||
user,
|
||||
f"u_{user.hex[:12]}",
|
||||
)
|
||||
await connection.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat
|
||||
)
|
||||
await connection.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
|
||||
"VALUES ($1, $2, 1, now())",
|
||||
chat,
|
||||
user,
|
||||
)
|
||||
await connection.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, "
|
||||
"sha256, width, height, staging_key, status, created_at, updated_at) VALUES ($1, $2, "
|
||||
"$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'queued', now(), now())",
|
||||
attachment,
|
||||
chat,
|
||||
user,
|
||||
f"staging/{attachment}",
|
||||
)
|
||||
await connection.execute(variant, attachment, f"variants/{attachment}/1/a")
|
||||
with pytest.raises(asyncpg.UniqueViolationError, match="attachment_variants_pkey"):
|
||||
await connection.execute(variant, attachment, f"variants/{attachment}/1/b")
|
||||
finally:
|
||||
await transaction.rollback()
|
||||
await connection.close()
|
||||
@@ -0,0 +1,196 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, register
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
}
|
||||
|
||||
|
||||
def assert_error(response, expected_status: int) -> None:
|
||||
assert response.status_code == expected_status, response.text
|
||||
assert response.headers.get("content-type", "").startswith("application/json")
|
||||
body = response.json()
|
||||
assert set(body) == {"error"}
|
||||
assert set(body["error"]) == {"code", "message", "request_id"}
|
||||
assert body["error"]["code"] == ERROR_CODES[expected_status]
|
||||
assert body["error"]["message"]
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_malformed_json(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
content=b'{"username": ',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_unexpected_field(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_wrong_types(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"username": "Alice", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "X", "password": "short"},
|
||||
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
|
||||
{"username": "abc_def", "display_name": "X", "password": " " * 20},
|
||||
{"username": "abc_def", "display_name": "X"},
|
||||
{"username": "abc_def", "password": PASSWORD},
|
||||
],
|
||||
)
|
||||
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
|
||||
assert_error(await client.post("/api/v1/users", json=body), 400)
|
||||
|
||||
|
||||
async def test_duplicate_username(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
repeat = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
|
||||
)
|
||||
assert_error(repeat, 409)
|
||||
|
||||
|
||||
async def test_missing_identity(client: AsyncClient) -> None:
|
||||
assert_error(await client.get("/api/v1/users/me"), 401)
|
||||
|
||||
|
||||
BAD_AUTHORIZATIONS = [
|
||||
"",
|
||||
"Bearer",
|
||||
"Bearer ",
|
||||
"Bearer not a token",
|
||||
"Bearer " + "x" * 43,
|
||||
"Token abcdef",
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
|
||||
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
|
||||
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
|
||||
assert_error(response, 401)
|
||||
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
assert_error(response, 401)
|
||||
|
||||
|
||||
async def test_identity_checked_before_body(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
content=b"{broken",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 401)
|
||||
|
||||
|
||||
async def test_empty_message_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
for text in ("", " ", "\n\t"):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_long_message_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": "я" * 4001},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "подмена", "sender_id": bob["id"]},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"title": "Чат", "member_ids": []},
|
||||
{"title": "", "member_ids": None},
|
||||
{"title": " ", "member_ids": None},
|
||||
{"title": "Чат", "member_ids": ["не-uuid"]},
|
||||
{"title": "Чат", "member_ids": [1]},
|
||||
{"title": "Чат", "member_ids": "не-список"},
|
||||
],
|
||||
)
|
||||
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
|
||||
alice = await register(client, "alice")
|
||||
payload = dict(body)
|
||||
if payload["member_ids"] is None:
|
||||
payload["member_ids"] = [alice["id"]]
|
||||
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_creator_must_be_member(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Чат", "member_ids": [bob["id"]]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_unknown_member_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)
|
||||
@@ -0,0 +1,144 @@
|
||||
import json
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, register, running_app, split_settings
|
||||
from messenger.main import create_app
|
||||
|
||||
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
|
||||
|
||||
|
||||
async def test_health_needs_no_identity(client: AsyncClient) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = await client.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_every_response_carries_request_id(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
probes = [
|
||||
await client.get("/health/live"),
|
||||
await client.get("/api/v1/users/me", headers=actor(alice)),
|
||||
await client.get("/api/v1/users/me"),
|
||||
await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
|
||||
await client.get("/api/v1/unknown-path"),
|
||||
]
|
||||
assert all(probe.headers.get("X-Request-Id") for probe in probes)
|
||||
|
||||
|
||||
async def test_client_request_id_is_preserved(client: AsyncClient) -> None:
|
||||
response = await client.get("/health/live", headers={"X-Request-Id": "trace-42"})
|
||||
assert response.headers["X-Request-Id"] == "trace-42"
|
||||
|
||||
|
||||
async def test_unknown_public_route_is_404(client: AsyncClient) -> None:
|
||||
response = await client.get("/nothing-here")
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_unknown_protected_route_needs_identity(client: AsyncClient) -> None:
|
||||
anonymous = await client.get("/api/v1/unknown-path")
|
||||
assert anonymous.status_code == 401
|
||||
assert set(anonymous.json()["error"]) == {"code", "message", "request_id"}
|
||||
alice = await register(client, "alice")
|
||||
identified = await client.get("/api/v1/unknown-path", headers=actor(alice))
|
||||
assert identified.status_code == 404
|
||||
|
||||
|
||||
async def test_method_not_allowed_is_hidden(client: AsyncClient) -> None:
|
||||
response = await client.delete("/health/live")
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_logs_do_not_contain_message_text(capsys) -> None:
|
||||
app = create_app(**split_settings(log_level="INFO"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
response = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": MARKER_TEXT},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert response.status_code == 201
|
||||
captured = capsys.readouterr()
|
||||
assert MARKER_TEXT not in captured.out
|
||||
assert MARKER_TEXT not in captured.err
|
||||
assert alice["display_name"] not in captured.out
|
||||
assert any("request.handled" in line for line in captured.out.splitlines())
|
||||
|
||||
|
||||
async def test_log_lines_are_json(capsys) -> None:
|
||||
app = create_app(**split_settings(log_level="INFO"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
await http.get("/health/live")
|
||||
for line in capsys.readouterr().out.splitlines():
|
||||
record = json.loads(line)
|
||||
assert {"ts", "level", "event"} <= set(record)
|
||||
|
||||
|
||||
async def test_body_limit_returns_413() -> None:
|
||||
app = create_app(**split_settings(max_body_bytes=4096))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
response = await http.post("/api/v1/users", content=b"x" * 5000)
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
async def test_ready_turns_unavailable_without_database() -> None:
|
||||
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
|
||||
started = time.perf_counter()
|
||||
ready = await http.get("/health/ready")
|
||||
live = await http.get("/health/live")
|
||||
elapsed = time.perf_counter() - started
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert live.status_code == 200
|
||||
assert elapsed < 2
|
||||
|
||||
|
||||
async def test_protected_request_is_503_not_401_without_database() -> None:
|
||||
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
|
||||
response = await http.get(
|
||||
"/api/v1/users/me", headers={"Authorization": "Bearer " + "x" * 43}
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_state_survives_new_process() -> None:
|
||||
async with running_app() as http:
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
async with running_app() as http:
|
||||
me = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
listed = await http.get("/api/v1/chats?limit=100", headers=actor(alice))
|
||||
assert me.json() == alice
|
||||
assert [item["id"] for item in listed.json()["items"]] == [chat["id"]]
|
||||
|
||||
|
||||
async def test_logs_do_not_contain_credentials(capsys) -> None:
|
||||
async with running_app(log_level="INFO") as http:
|
||||
alice = await register(http, "secret")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
output = capsys.readouterr()
|
||||
captured = output.out + output.err
|
||||
assert PASSWORD not in captured
|
||||
assert actor(alice)["Authorization"].split()[1] not in captured
|
||||
assert "audit.session_opened" in captured
|
||||
@@ -0,0 +1,155 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register
|
||||
|
||||
TOTAL = 12
|
||||
|
||||
|
||||
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
|
||||
texts = []
|
||||
for index in range(count):
|
||||
text = f"сообщение {index:02d}"
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=keyed(sender),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
|
||||
collected: list[str] = []
|
||||
cursor: str | None = None
|
||||
step = 0
|
||||
while True:
|
||||
limit = limits[min(step, len(limits) - 1)]
|
||||
query = f"?limit={limit}"
|
||||
if cursor:
|
||||
query += f"&cursor={quote(cursor, safe='')}"
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
assert len(page["items"]) <= limit
|
||||
collected.extend(item["text"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
step += 1
|
||||
if cursor is None:
|
||||
return collected
|
||||
|
||||
|
||||
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
expected = await fill(client, chat, alice, TOTAL)
|
||||
assert await walk(client, chat, bob, [5]) == expected
|
||||
|
||||
|
||||
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
expected = await fill(client, chat, alice, TOTAL)
|
||||
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
|
||||
|
||||
|
||||
async def test_last_page_closes_history(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 2)
|
||||
first = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
|
||||
).json()
|
||||
assert len(first["items"]) == 2
|
||||
assert first["next_cursor"] is None
|
||||
|
||||
|
||||
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
await fill(client, chat, alice, 3)
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
|
||||
).json()
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
first = await make_chat(client, alice)
|
||||
second = await make_chat(client, alice)
|
||||
await fill(client, first, alice, 3)
|
||||
await fill(client, second, alice, 3)
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
|
||||
).json()
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"])
|
||||
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
|
||||
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
||||
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
|
||||
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
|
||||
|
||||
|
||||
async def test_default_limit_is_50(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 51)
|
||||
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
|
||||
assert len(page["items"]) == 50
|
||||
assert page["next_cursor"] is not None
|
||||
|
||||
|
||||
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 2)
|
||||
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
||||
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
|
||||
assert response.status_code == 200, response.text
|
||||
assert len(response.json()["items"]) == 1
|
||||
|
||||
|
||||
async def test_chat_list_pagination(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
|
||||
collected: list[str] = []
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
|
||||
collected.extend(item["id"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
assert collected == created
|
||||
@@ -0,0 +1,303 @@
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import DATABASE, actor
|
||||
from messenger.attachments.application.pipeline import TRANSIENT_ERROR
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding
|
||||
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pictures import SAMPLE
|
||||
from pipeline import pipeline_of
|
||||
|
||||
|
||||
async def rows(sql: str, *args: Any) -> list[dict[str, Any]]:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
return [dict(row) for row in await connection.fetch(sql, *args)]
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def accepted(http: AsyncClient) -> tuple[dict[str, Any], dict[str, Any], str]:
|
||||
alice, bob, _, chat = await trio(http)
|
||||
response = await upload(http, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
return alice, bob, response.json()["id"]
|
||||
|
||||
|
||||
async def state(attachment_id: str) -> dict[str, Any]:
|
||||
(row,) = await rows(
|
||||
"SELECT a.status, a.error_code, a.published_version, a.staging_key, a.original_key, "
|
||||
"j.status AS job_status, j.attempt, j.claims FROM attachments a "
|
||||
"JOIN jobs j ON j.attachment_id = a.id WHERE a.id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def variants(attachment_id: str) -> list[dict[str, Any]]:
|
||||
return await rows(
|
||||
"SELECT pipeline_version, name, sha256, size_bytes, object_key FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 ORDER BY name",
|
||||
attachment_id,
|
||||
)
|
||||
|
||||
|
||||
async def events(attachment_id: str) -> list[str]:
|
||||
found = await rows(
|
||||
"SELECT kind FROM job_events WHERE attachment_id = $1 ORDER BY id", attachment_id
|
||||
)
|
||||
return [row["kind"] for row in found]
|
||||
|
||||
|
||||
async def job_of(attachment_id: str) -> Job:
|
||||
(row,) = await rows(
|
||||
"SELECT payload::text AS body FROM outbox o JOIN jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = $1 ORDER BY o.id LIMIT 1",
|
||||
attachment_id,
|
||||
)
|
||||
return JobMessage.model_validate_json(row["body"]).job()
|
||||
|
||||
|
||||
async def test_job_is_processed_once_and_staging_is_cleaned(client: AsyncClient) -> None:
|
||||
_, bob, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
outcomes = await pipeline.drain()
|
||||
assert Outcome.DONE in outcomes
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["job_status"], done["published_version"]) == ("ready", "done", 1)
|
||||
assert done["original_key"] == f"originals/{attachment_id}"
|
||||
assert done["staging_key"] == f"staging/{attachment_id}"
|
||||
pattern = rf"variants/{attachment_id}/1/(crop|optimized|thumbnail)-[0-9a-f]{{16}}\.(jpg|webp)"
|
||||
found = [re.fullmatch(pattern, row["object_key"]) for row in await variants(attachment_id)]
|
||||
assert [match.groups() for match in found if match] == [
|
||||
("crop", "jpg"),
|
||||
("optimized", "webp"),
|
||||
("thumbnail", "jpg"),
|
||||
]
|
||||
assert await pipeline.clean() >= 1
|
||||
assert (await state(attachment_id))["staging_key"] is None
|
||||
objects = (await storage(client)).objects
|
||||
assert f"staging/{attachment_id}" not in objects
|
||||
assert objects[f"originals/{attachment_id}"][0] == SAMPLE
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(bob))
|
||||
assert content.content == SAMPLE
|
||||
assert await events(attachment_id) == ["enqueued", "claimed", "done"]
|
||||
|
||||
|
||||
async def test_message_is_a_contract_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
mine = [
|
||||
json.loads(body)
|
||||
for body in pipeline.publisher.bodies
|
||||
if json.loads(body)["attachment_id"] == attachment_id
|
||||
]
|
||||
assert len(mine) == 1
|
||||
assert set(mine[0]) == {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
}
|
||||
assert (mine[0]["pipeline_version"], mine[0]["attempt"]) == (1, 1)
|
||||
assert await pipeline.publish() == []
|
||||
|
||||
|
||||
async def test_redelivery_after_ready_changes_nothing(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
before, job = await variants(attachment_id), await job_of(attachment_id)
|
||||
assert await pipeline.process(job) is Outcome.DUPLICATE
|
||||
assert await variants(attachment_id) == before
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
assert (await events(attachment_id))[-1] == "duplicate_noop"
|
||||
|
||||
|
||||
async def test_two_copies_in_flight_give_one_result(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
outcomes = await asyncio.gather(pipeline.process(job), pipeline.process(job))
|
||||
assert sorted(outcomes) == sorted([Outcome.DONE, Outcome.DUPLICATE])
|
||||
assert len(await variants(attachment_id)) == 3
|
||||
assert (await state(attachment_id))["claims"] == 1
|
||||
|
||||
|
||||
async def test_partial_variant_set_is_never_published(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
store = await storage(client)
|
||||
|
||||
async def refuse(key: str) -> None:
|
||||
if "/optimized-" in key:
|
||||
raise Unavailable("S3 недоступно")
|
||||
|
||||
store.after_put = refuse
|
||||
try:
|
||||
assert await pipeline.process(await job_of(attachment_id)) is Outcome.RESCHEDULED
|
||||
finally:
|
||||
store.after_put = None
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
assert await variants(attachment_id) == []
|
||||
|
||||
|
||||
async def test_transient_error_reschedules_with_the_same_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
assert await pipeline.process(job) is Outcome.RESCHEDULED
|
||||
finally:
|
||||
store.failing = False
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["job_status"], queued["attempt"]) == ("queued", "queued", 2)
|
||||
(retry,) = [j for j in await pipeline.publish() if str(j.attachment_id) == attachment_id]
|
||||
assert (retry.id, retry.attempt) == (job.id, 2)
|
||||
assert await pipeline.process(retry) is Outcome.DONE
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_attempts_are_bounded(client: AsyncClient) -> None:
|
||||
alice, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["job_status"]) == (
|
||||
"failed",
|
||||
"retry_exhausted",
|
||||
"failed",
|
||||
)
|
||||
assert failed["attempt"] == pipeline.policy.max_attempts
|
||||
assert (await events(attachment_id)).count("retry_scheduled") == 4
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(alice))
|
||||
assert content.status_code == 409
|
||||
|
||||
|
||||
async def test_undecodable_image_fails_without_retries(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
(await storage(client)).objects[f"staging/{attachment_id}"] = (b"not a png", "image/png")
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
|
||||
"failed",
|
||||
"invalid_image",
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
class DemandingRenderer:
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
raise ImageTooDemanding("рендер дольше допустимого времени")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cause", ["limit", "missing"])
|
||||
async def test_limits_and_lost_original_fail_without_retries(
|
||||
client: AsyncClient, cause: str
|
||||
) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
if cause == "limit":
|
||||
pipeline.renderer = DemandingRenderer()
|
||||
else:
|
||||
del (await storage(client)).objects[f"staging/{attachment_id}"]
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
|
||||
"failed",
|
||||
"processing_failed",
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
async def test_expired_lease_is_recovered_and_old_holder_is_fenced(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
uow = pipeline.uow()
|
||||
async with uow.transaction():
|
||||
claim = await uow.jobs.claim(job, uuid4(), pipeline.lease)
|
||||
await uow.commit()
|
||||
assert claim is not None
|
||||
assert (await state(attachment_id))["status"] == "processing"
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert await pipeline.recover() >= 1
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
late = pipeline.uow()
|
||||
async with late.transaction():
|
||||
outcome = await late.jobs.complete(claim.lease, [], f"originals/{attachment_id}")
|
||||
await late.commit()
|
||||
assert outcome is Outcome.FENCED
|
||||
assert await variants(attachment_id) == []
|
||||
await pipeline.drain()
|
||||
recovered = await state(attachment_id)
|
||||
assert (recovered["status"], recovered["attempt"]) == ("ready", 2)
|
||||
assert {"lease_expired", "fenced"} <= set(await events(attachment_id))
|
||||
|
||||
|
||||
async def test_unpublished_rows_stay_when_the_broker_refuses(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.publisher.failing = True
|
||||
with pytest.raises(Unavailable):
|
||||
await pipeline.publish()
|
||||
pending = await rows(
|
||||
"SELECT o.published_at FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert pending == [{"published_at": None}]
|
||||
pipeline.publisher.failing = False
|
||||
assert any(str(job.attachment_id) == attachment_id for job in await pipeline.publish())
|
||||
|
||||
|
||||
async def test_backoff_delays_the_next_attempt(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, policy=RetryPolicy(5, 30, 60))
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["attempt"]) == ("queued", 2)
|
||||
(row,) = await rows(
|
||||
"SELECT extract(epoch FROM next_attempt_at - now()) AS wait FROM jobs "
|
||||
"WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert 20 < row["wait"] <= 22.5
|
||||
(event,) = await rows(
|
||||
"SELECT (detail->>'delay_seconds')::float8 AS delay FROM job_events "
|
||||
"WHERE attachment_id = $1 AND kind = 'retry_scheduled'",
|
||||
attachment_id,
|
||||
)
|
||||
assert event["delay"] == 22.5
|
||||
|
||||
|
||||
class FailingFaults:
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == TRANSIENT_ERROR:
|
||||
raise Unavailable(point)
|
||||
@@ -0,0 +1,27 @@
|
||||
import time
|
||||
|
||||
from conftest import actor, register, resolve, running_app
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
|
||||
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
|
||||
alice = await register(http, "alice")
|
||||
database = await resolve(http, Database)
|
||||
async with database.connection():
|
||||
started = time.perf_counter()
|
||||
starved = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
elapsed = time.perf_counter() - started
|
||||
recovered = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert starved.status_code == 503
|
||||
assert starved.json()["error"]["code"] == "unavailable"
|
||||
assert 0.25 < elapsed < 1
|
||||
assert recovered.json() == alice
|
||||
|
||||
|
||||
async def test_statement_timeout_is_set_on_connections() -> None:
|
||||
async with running_app(db_command_timeout_seconds=1.5) as http:
|
||||
database = await resolve(http, Database)
|
||||
async with database.connection() as connection:
|
||||
assert await connection.fetchval("SHOW statement_timeout") == "1500ms"
|
||||
assert await connection.fetchval("SHOW lock_timeout") == "1500ms"
|
||||
@@ -0,0 +1,307 @@
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage
|
||||
from test_pipeline import FailingFaults, accepted, events, job_of, rows, state, variants
|
||||
|
||||
from conftest import DATABASE
|
||||
from fakes import NullLogger
|
||||
from messenger.admin import serve
|
||||
from messenger.attachments.application.pipeline import (
|
||||
AFTER_CLAIM,
|
||||
AFTER_COMMIT_BEFORE_ACK,
|
||||
AFTER_COMMIT_BEFORE_PUBLISH,
|
||||
AFTER_PUBLISH_BEFORE_CONFIRM,
|
||||
AFTER_S3_WRITE,
|
||||
STALL_AFTER_CLAIM,
|
||||
TRANSIENT_ERROR,
|
||||
)
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.jobs import Outcome, ReplayResult
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
|
||||
|
||||
WORKER_POINTS = [
|
||||
AFTER_CLAIM,
|
||||
STALL_AFTER_CLAIM,
|
||||
TRANSIENT_ERROR,
|
||||
AFTER_S3_WRITE,
|
||||
AFTER_COMMIT_BEFORE_ACK,
|
||||
]
|
||||
|
||||
|
||||
class Crash(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class RecordingFaults:
|
||||
__slots__ = ("crash_at", "reached")
|
||||
|
||||
def __init__(self, crash_at: str = "") -> None:
|
||||
self.crash_at = crash_at
|
||||
self.reached: list[str] = []
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
self.reached.append(point)
|
||||
if point == self.crash_at:
|
||||
raise Crash(point)
|
||||
|
||||
|
||||
class SlowRenderer:
|
||||
__slots__ = ("seconds",)
|
||||
|
||||
def __init__(self, seconds: float) -> None:
|
||||
self.seconds = seconds
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
await asyncio.sleep(self.seconds)
|
||||
return await InlineRenderer().render(data, pipeline_version)
|
||||
|
||||
|
||||
class ExpiringFaults:
|
||||
__slots__ = ("attachment_id", "pipeline")
|
||||
|
||||
def __init__(self, pipeline: InlinePipeline, attachment_id: str) -> None:
|
||||
self.pipeline = pipeline
|
||||
self.attachment_id = attachment_id
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == STALL_AFTER_CLAIM:
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' "
|
||||
"WHERE attachment_id = $1",
|
||||
self.attachment_id,
|
||||
)
|
||||
await self.pipeline.recover()
|
||||
|
||||
|
||||
async def outbox(attachment_id: str) -> list[bool]:
|
||||
found = await rows(
|
||||
"SELECT o.published_at IS NOT NULL AS published FROM outbox o JOIN jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = $1 ORDER BY o.id",
|
||||
attachment_id,
|
||||
)
|
||||
return [row["published"] for row in found]
|
||||
|
||||
|
||||
def stored(objects: dict[str, tuple[bytes, str]], attachment_id: str) -> list[str]:
|
||||
return sorted(key for key in objects if key.startswith(f"variants/{attachment_id}/"))
|
||||
|
||||
|
||||
async def test_fault_points_are_reached_in_order(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
faults = RecordingFaults()
|
||||
pipeline.faults = faults
|
||||
published = await pipeline.publish()
|
||||
assert faults.reached[:2] == [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM]
|
||||
faults.reached.clear()
|
||||
(job,) = [job for job in published if str(job.attachment_id) == attachment_id]
|
||||
assert await pipeline.process(job) is Outcome.DONE
|
||||
assert faults.reached == WORKER_POINTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM])
|
||||
async def test_relay_crash_leaves_the_row_for_the_next_relay(
|
||||
client: AsyncClient, point: str
|
||||
) -> None:
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline.faults = RecordingFaults(point)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.publish()
|
||||
assert await outbox(attachment_id) == [False]
|
||||
sent = [body for body in pipeline.publisher.bodies if attachment_id.encode() in body]
|
||||
assert len(sent) == (point == AFTER_PUBLISH_BEFORE_CONFIRM)
|
||||
pipeline.faults = RecordingFaults()
|
||||
outcomes = await pipeline.drain()
|
||||
assert Outcome.DONE in outcomes
|
||||
assert await outbox(attachment_id) == [True]
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_crash_after_s3_write_is_finished_by_the_next_attempt(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, lease=timedelta(seconds=60))
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = RecordingFaults(AFTER_S3_WRITE)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.process(job)
|
||||
objects = (await storage(client)).objects
|
||||
written = stored(objects, attachment_id)
|
||||
assert len(written) == 3
|
||||
assert await variants(attachment_id) == []
|
||||
assert (await state(attachment_id))["status"] == "processing"
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert await pipeline.recover() >= 1
|
||||
await pipeline.drain()
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"]) == ("ready", 2)
|
||||
assert stored(objects, attachment_id) == written
|
||||
assert sorted(row["object_key"] for row in await variants(attachment_id)) == written
|
||||
|
||||
|
||||
async def test_crash_after_commit_is_a_duplicate_on_redelivery(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = RecordingFaults(AFTER_COMMIT_BEFORE_ACK)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.process(job)
|
||||
before = await variants(attachment_id)
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert await pipeline.process(job) is Outcome.DUPLICATE
|
||||
assert await variants(attachment_id) == before
|
||||
|
||||
|
||||
async def test_long_render_keeps_its_lease(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, lease=timedelta(seconds=1))
|
||||
pipeline.renderer = SlowRenderer(2.5)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
|
||||
async def sweep() -> None:
|
||||
for _ in range(4):
|
||||
await asyncio.sleep(0.6)
|
||||
await pipeline.recover()
|
||||
|
||||
outcome, _ = await asyncio.gather(pipeline.process(job), sweep())
|
||||
assert outcome is Outcome.DONE
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"], done["claims"]) == ("ready", 1, 1)
|
||||
assert "lease_expired" not in await events(attachment_id)
|
||||
|
||||
|
||||
async def test_lost_lease_stops_before_side_effects(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = ExpiringFaults(pipeline, attachment_id)
|
||||
assert await pipeline.process(job) is Outcome.FENCED
|
||||
objects = (await storage(client)).objects
|
||||
assert stored(objects, attachment_id) == []
|
||||
assert f"originals/{attachment_id}" not in objects
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
assert (await events(attachment_id))[-2:] == ["lease_expired", "fenced"]
|
||||
pipeline.faults = RecordingFaults()
|
||||
await pipeline.drain()
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_environment_faults_stall_once_and_fail_transiently() -> None:
|
||||
stall = EnvironmentFaults(STALL_AFTER_CLAIM, NullLogger(), stall_seconds=0.3)
|
||||
started = asyncio.get_running_loop().time()
|
||||
await stall.reach(AFTER_CLAIM)
|
||||
await stall.reach(STALL_AFTER_CLAIM)
|
||||
await stall.reach(STALL_AFTER_CLAIM)
|
||||
assert 0.3 <= asyncio.get_running_loop().time() - started < 0.6
|
||||
with pytest.raises(Unavailable):
|
||||
await EnvironmentFaults(TRANSIENT_ERROR, NullLogger()).reach(TRANSIENT_ERROR)
|
||||
|
||||
|
||||
def test_environment_fault_crashes_the_process_with_137() -> None:
|
||||
script = (
|
||||
"import asyncio\n"
|
||||
"from fakes import NullLogger\n"
|
||||
"from messenger.attachments.infrastructure.faults import EnvironmentFaults\n"
|
||||
"asyncio.run(EnvironmentFaults('after_commit_before_ack', NullLogger())"
|
||||
".reach('after_commit_before_ack'))\n"
|
||||
"print('survived')\n"
|
||||
)
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env={"PYTHONPATH": ":".join(sys.path)},
|
||||
)
|
||||
assert (done.returncode, done.stdout) == (137, "")
|
||||
|
||||
|
||||
async def failed(client: AsyncClient) -> tuple[InlinePipeline, str]:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert (await state(attachment_id))["error_code"] == "retry_exhausted"
|
||||
return pipeline, attachment_id
|
||||
|
||||
|
||||
async def test_replay_of_failed_reaches_ready_once(client: AsyncClient) -> None:
|
||||
pipeline, attachment_id = await failed(client)
|
||||
job = await job_of(attachment_id)
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.REPLAYED
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["job_status"], queued["attempt"], queued["error_code"]) == (
|
||||
"queued",
|
||||
"queued",
|
||||
1,
|
||||
None,
|
||||
)
|
||||
assert await outbox(attachment_id) == [True] * 5 + [False]
|
||||
await pipeline.drain()
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"]) == ("ready", 1)
|
||||
assert (await job_of(attachment_id)).id == job.id
|
||||
before = await variants(attachment_id)
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.NOOP
|
||||
assert await outbox(attachment_id) == [True] * 6
|
||||
assert await variants(attachment_id) == before
|
||||
assert (await events(attachment_id))[-1] == "replay_noop"
|
||||
assert "replayed" in await events(attachment_id)
|
||||
assert await pipeline.replay(uuid4()) is ReplayResult.NOT_FOUND
|
||||
|
||||
|
||||
async def test_failed_staging_is_kept_for_the_retention_period(client: AsyncClient) -> None:
|
||||
pipeline, attachment_id = await failed(client)
|
||||
_, _, waiting = await accepted(client)
|
||||
objects = (await storage(client)).objects
|
||||
await pipeline.clean(timedelta(days=1))
|
||||
assert (await state(attachment_id))["staging_key"] == f"staging/{attachment_id}"
|
||||
assert f"staging/{attachment_id}" in objects
|
||||
await pipeline.clean(timedelta(0))
|
||||
assert (await state(attachment_id))["staging_key"] is None
|
||||
assert f"staging/{attachment_id}" not in objects
|
||||
assert (await state(waiting))["staging_key"] == f"staging/{waiting}"
|
||||
assert f"staging/{waiting}" in objects
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.EXPIRED
|
||||
assert (await state(attachment_id))["status"] == "failed"
|
||||
|
||||
|
||||
async def test_operator_cli_lists_failed_jobs_and_replays(
|
||||
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_, attachment_id = await failed(client)
|
||||
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
|
||||
monkeypatch.setenv("LOG_LEVEL", "WARNING")
|
||||
assert await serve(["failed", "--limit", "500"]) == 0
|
||||
registry = json.loads(capsys.readouterr().out.splitlines()[-1])["failed"]
|
||||
(mine,) = [row for row in registry if row["attachment_id"] == attachment_id]
|
||||
assert datetime.fromisoformat(mine["failed_at"]).utcoffset() == timedelta(0)
|
||||
assert (mine["error_code"], mine["attempt"], mine["last_error"]) == (
|
||||
"retry_exhausted",
|
||||
5,
|
||||
"Unavailable",
|
||||
)
|
||||
assert await serve(["replay", "--attachment-id", attachment_id, "--operator", "alice"]) == 0
|
||||
report = json.loads(capsys.readouterr().out.splitlines()[-1])
|
||||
assert report == {"result": "replayed", "attachment_id": attachment_id, "operator": "alice"}
|
||||
assert await serve(["replay", "--attachment-id", str(uuid4())]) == 1
|
||||
@@ -0,0 +1,172 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import (
|
||||
PASSWORD,
|
||||
actor,
|
||||
basic,
|
||||
bearer,
|
||||
login,
|
||||
make_chat,
|
||||
new_user,
|
||||
register,
|
||||
running_app,
|
||||
scalar,
|
||||
)
|
||||
|
||||
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def challenged(response, challenge: str) -> None:
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.headers["WWW-Authenticate"] == challenge
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
user = (await client.post("/api/v1/users", json=body)).json()
|
||||
session = await login(client, body["username"])
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"] == user
|
||||
assert len(session["token"]) >= 43
|
||||
assert body["username"] not in session["token"] and user["id"] not in session["token"]
|
||||
assert session["expires_at"].endswith("Z")
|
||||
expires = datetime.fromisoformat(session["expires_at"])
|
||||
created = datetime.fromisoformat(user["created_at"])
|
||||
assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700)
|
||||
|
||||
|
||||
async def test_registration_response_hides_password(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
|
||||
assert PASSWORD not in response.text
|
||||
|
||||
|
||||
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
stored = await scalar("SELECT password_hash FROM users WHERE id = $1::uuid", alice["id"])
|
||||
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
assert PASSWORD not in stored
|
||||
|
||||
|
||||
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
token = actor(alice)["Authorization"].split()[1]
|
||||
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
|
||||
assert await scalar(sql, token) == 1
|
||||
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
|
||||
assert await scalar(raw, token) == 0
|
||||
|
||||
|
||||
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
|
||||
unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD))
|
||||
challenged(wrong, BASIC)
|
||||
challenged(unknown, BASIC)
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}],
|
||||
)
|
||||
async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None:
|
||||
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
|
||||
|
||||
|
||||
async def test_password_with_colon_logs_in(client: AsyncClient) -> None:
|
||||
body = new_user("colon", password="пароль:с:двоеточием")
|
||||
assert (await client.post("/api/v1/users", json=body)).status_code == 201
|
||||
assert (await login(client, body["username"], body["password"]))["token"]
|
||||
|
||||
|
||||
async def test_login_with_body_is_rejected(client: AsyncClient) -> None:
|
||||
body = new_user("body")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
challenged(
|
||||
await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER
|
||||
)
|
||||
|
||||
|
||||
async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
response = await client.get(
|
||||
"/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]}
|
||||
)
|
||||
assert response.json() == alice
|
||||
|
||||
|
||||
async def test_authentication_precedes_validation(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/chats/not-a-uuid/messages",
|
||||
content=b"{broken",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
challenged(response, BEARER)
|
||||
|
||||
|
||||
async def test_logout_revokes_only_current_session(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
first = (await login(client, body["username"]))["token"]
|
||||
second = (await login(client, body["username"]))["token"]
|
||||
logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
|
||||
assert logout.status_code == 204
|
||||
assert logout.content == b""
|
||||
assert logout.headers["X-Request-Id"]
|
||||
challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER)
|
||||
challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER)
|
||||
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
|
||||
|
||||
|
||||
async def test_short_ttl_session_expires() -> None:
|
||||
async with running_app(session_ttl_seconds=1) as client:
|
||||
alice = await register(client, "alice")
|
||||
assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
await asyncio.sleep(1.2)
|
||||
challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER)
|
||||
|
||||
|
||||
async def test_expired_sessions_are_purged_on_next_login() -> None:
|
||||
async with running_app(session_ttl_seconds=1) as client:
|
||||
body = new_user("purge")
|
||||
user = (await client.post("/api/v1/users", json=body)).json()
|
||||
await login(client, body["username"])
|
||||
await asyncio.sleep(1.2)
|
||||
await login(client, body["username"])
|
||||
sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid"
|
||||
assert await scalar(sql, user["id"]) == 1
|
||||
|
||||
|
||||
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
for method, path in [
|
||||
("GET", "/api/v1/chats"),
|
||||
("POST", "/api/v1/chats"),
|
||||
("GET", f"/api/v1/chats/{chat['id']}"),
|
||||
("GET", f"/api/v1/chats/{chat['id']}/messages"),
|
||||
("POST", f"/api/v1/chats/{chat['id']}/messages"),
|
||||
("DELETE", "/api/v1/auth/sessions/current"),
|
||||
]:
|
||||
challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER)
|
||||
@@ -0,0 +1,97 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import keyed, make_chat, register, resolve, running_app
|
||||
from messenger.messaging.application import handlers
|
||||
from messenger.messaging.domain.events import MessagePosted
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
|
||||
MARKER = "текст-который-не-должен-утечь-при-таймауте"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def slow_post(delay: float) -> AsyncIterator[None]:
|
||||
original: Callable = handlers.PostMessageHandler.__call__
|
||||
|
||||
async def stalled(self, command):
|
||||
await asyncio.sleep(delay)
|
||||
return await original(self, command)
|
||||
|
||||
handlers.PostMessageHandler.__call__ = stalled
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
handlers.PostMessageHandler.__call__ = original
|
||||
|
||||
|
||||
async def post(client: AsyncClient, chat: dict, sender: dict, text: str):
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(sender)
|
||||
)
|
||||
|
||||
|
||||
async def prepared(client: AsyncClient) -> tuple[dict, dict]:
|
||||
alice = await register(client, "alice")
|
||||
return alice, await make_chat(client, alice)
|
||||
|
||||
|
||||
async def test_timeout_returns_unavailable_error_body() -> None:
|
||||
async with running_app(request_timeout_seconds=0.15) as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
response = await post(client, chat, alice, "медленная запись")
|
||||
assert response.status_code == 503
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_timeout_does_not_break_following_requests() -> None:
|
||||
async with running_app(request_timeout_seconds=0.15) as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
assert (await post(client, chat, alice, "зависшая запись")).status_code == 503
|
||||
assert (await post(client, chat, alice, "нормальная запись")).status_code == 201
|
||||
assert (await client.get("/health/ready")).status_code == 200
|
||||
|
||||
|
||||
async def test_timeout_is_logged_without_message_text(capsys) -> None:
|
||||
async with running_app(request_timeout_seconds=0.15, log_level="INFO") as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
assert (await post(client, chat, alice, MARKER)).status_code == 503
|
||||
captured = capsys.readouterr()
|
||||
assert "request.timeout" in captured.out
|
||||
assert MARKER not in captured.out
|
||||
assert MARKER not in captured.err
|
||||
|
||||
|
||||
async def test_normal_request_is_not_affected_by_timeout() -> None:
|
||||
async with running_app(request_timeout_seconds=5.0) as client:
|
||||
alice, chat = await prepared(client)
|
||||
assert (await post(client, chat, alice, "обычная запись")).status_code == 201
|
||||
|
||||
|
||||
async def test_slow_event_handler_does_not_trigger_timeout() -> None:
|
||||
async with running_app(request_timeout_seconds=0.3) as client:
|
||||
alice, chat = await prepared(client)
|
||||
blocked = asyncio.Event()
|
||||
bus = await resolve(client, EventBus)
|
||||
|
||||
async def stall(_event: MessagePosted) -> None:
|
||||
await blocked.wait()
|
||||
|
||||
bus.subscribe(MessagePosted, stall)
|
||||
response = await post(client, chat, alice, "ответ не ждёт обработчик")
|
||||
blocked.set()
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
assert loop.time() - started < 1.0
|
||||
@@ -0,0 +1,254 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
from httpx import AsyncClient
|
||||
from starlette.types import Message
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import APPS, DATABASE, actor, keyed, resolve, running_app, scalar
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from pictures import SAMPLE
|
||||
from pipeline import settle
|
||||
|
||||
AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE id = $1"
|
||||
|
||||
|
||||
async def execute(sql: str, *args: Any) -> None:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
await connection.execute(sql, *args)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
def sweeper(http: AsyncClient) -> UploadSweeper:
|
||||
return APPS[id(http)].state.sweeper
|
||||
|
||||
|
||||
async def discarded(http: AsyncClient) -> list[AttachmentDiscarded]:
|
||||
seen: list[AttachmentDiscarded] = []
|
||||
|
||||
async def keep(event: AttachmentDiscarded) -> None:
|
||||
seen.append(event)
|
||||
|
||||
(await resolve(http, EventBus)).project(AttachmentDiscarded, keep)
|
||||
return seen
|
||||
|
||||
|
||||
async def intent(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
store = await storage(http)
|
||||
store.failing = True
|
||||
name = f"intent-{uuid4().hex}.png"
|
||||
try:
|
||||
assert (await upload(http, user, chat, filename=name)).status_code == 503
|
||||
finally:
|
||||
store.failing = False
|
||||
found = await scalar(
|
||||
"SELECT id::text FROM attachments WHERE filename = $1 AND status = 'pending'", name
|
||||
)
|
||||
assert found is not None
|
||||
store.objects[f"staging/{found}"] = (SAMPLE, "image/png")
|
||||
return found
|
||||
|
||||
|
||||
async def exists(attachment_id: str) -> bool:
|
||||
return await scalar("SELECT count(*) FROM attachments WHERE id = $1", attachment_id) == 1
|
||||
|
||||
|
||||
async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
store = await storage(client)
|
||||
name = f"fail-{uuid4().hex}.png"
|
||||
trigger = f"lab4_fail_{uuid4().hex[:8]}"
|
||||
await execute(
|
||||
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$;
|
||||
CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename = '{name}' AND NEW.status = 'queued') EXECUTE FUNCTION {trigger}()"""
|
||||
)
|
||||
before, seen = set(store.objects), await discarded(client)
|
||||
try:
|
||||
response = await upload(client, alice, chat, filename=name)
|
||||
finally:
|
||||
await execute(f"DROP TRIGGER {trigger} ON attachments; DROP FUNCTION {trigger}()")
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
assert (
|
||||
await scalar(
|
||||
"SELECT count(*) FROM jobs j JOIN attachments a ON a.id = j.attachment_id "
|
||||
"WHERE a.filename = $1",
|
||||
name,
|
||||
)
|
||||
== 0
|
||||
)
|
||||
assert set(store.objects) == before
|
||||
assert [event.reason for event in seen] == ["compensation"]
|
||||
|
||||
|
||||
async def test_lost_intent_gives_503_and_no_object(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
store = await storage(client)
|
||||
|
||||
async def swept_meanwhile(key: str) -> None:
|
||||
await execute("DELETE FROM attachments WHERE staging_key = $1", key)
|
||||
|
||||
store.after_put = swept_meanwhile
|
||||
before = set(store.objects)
|
||||
try:
|
||||
response = await upload(client, alice, chat, filename="late.png")
|
||||
finally:
|
||||
store.after_put = None
|
||||
assert response.status_code == 503
|
||||
assert set(store.objects) == before
|
||||
|
||||
|
||||
async def test_failed_put_leaves_an_intent_until_grace_ends(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
pending = await intent(client, alice, chat)
|
||||
await sweeper(client).sweep()
|
||||
assert await exists(pending)
|
||||
await execute(AGED, pending)
|
||||
assert await sweeper(client).sweep() >= 1
|
||||
assert not await exists(pending)
|
||||
assert f"staging/{pending}" not in (await storage(client)).objects
|
||||
|
||||
|
||||
async def test_sweep_keeps_fresh_intents_and_ready_attachments(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
ready = (await upload(client, alice, chat)).json()
|
||||
await settle(client)
|
||||
sent = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [ready["id"]]},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert sent.status_code == 201
|
||||
old, fresh = await intent(client, alice, chat), await intent(client, alice, chat)
|
||||
await execute(AGED, old)
|
||||
await execute(AGED, ready["id"])
|
||||
assert await sweeper(client).sweep() == 1
|
||||
objects = (await storage(client)).objects
|
||||
assert not await exists(old)
|
||||
assert f"staging/{old}" not in objects
|
||||
assert await exists(fresh)
|
||||
assert f"staging/{fresh}" in objects
|
||||
download = await client.get(f"/api/v1/attachments/{ready['id']}/content", headers=actor(bob))
|
||||
assert download.status_code == 200
|
||||
assert download.content == SAMPLE
|
||||
assert await sweeper(client).sweep() == 0
|
||||
|
||||
|
||||
async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
pending = [await intent(client, alice, chat) for _ in range(5)]
|
||||
for attachment_id in pending:
|
||||
await execute(AGED, attachment_id)
|
||||
seen = await discarded(client)
|
||||
first, second = await asyncio.gather(sweeper(client).sweep(), sweeper(client).sweep())
|
||||
assert first + second == 5
|
||||
assert sorted(str(event.attachment_id) for event in seen) == sorted(pending)
|
||||
assert {event.reason for event in seen} == {"abandoned"}
|
||||
assert await sweeper(client).sweep() == 0
|
||||
objects = (await storage(client)).objects
|
||||
assert not any(f"staging/{attachment_id}" in objects for attachment_id in pending)
|
||||
|
||||
|
||||
async def test_background_sweeper_removes_abandoned_intents() -> None:
|
||||
async with running_app(upload_sweep_interval_seconds=0.05) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
pending = await intent(http, alice, chat)
|
||||
await execute(AGED, pending)
|
||||
for _ in range(100):
|
||||
if not await exists(pending):
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert not await exists(pending)
|
||||
|
||||
|
||||
async def test_upload_waits_for_a_free_slot() -> None:
|
||||
async with running_app(upload_concurrency=1) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
gate, holding, read = asyncio.Event(), asyncio.Event(), []
|
||||
|
||||
async def held() -> AsyncIterator[bytes]:
|
||||
read.append("first")
|
||||
holding.set()
|
||||
yield SAMPLE[:1000]
|
||||
await gate.wait()
|
||||
yield SAMPLE[1000:]
|
||||
|
||||
async def queued() -> AsyncIterator[bytes]:
|
||||
read.append("second")
|
||||
yield SAMPLE
|
||||
|
||||
first = asyncio.create_task(upload(http, alice, chat, held()))
|
||||
await holding.wait()
|
||||
second = asyncio.create_task(upload(http, alice, chat, queued()))
|
||||
await asyncio.sleep(0.3)
|
||||
assert read == ["first"]
|
||||
gate.set()
|
||||
assert [(await first).status_code, (await second).status_code] == [202, 202]
|
||||
assert read == ["first", "second"]
|
||||
|
||||
|
||||
async def test_aborted_upload_is_a_client_error(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
name = f"abort-{uuid4().hex}.png"
|
||||
headers = [(k.lower().encode(), v.encode()) for k, v in actor(alice).items()]
|
||||
scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": "3.0"},
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": f"/api/v1/chats/{chat['id']}/attachments",
|
||||
"raw_path": f"/api/v1/chats/{chat['id']}/attachments".encode(),
|
||||
"query_string": f"filename={name}".encode(),
|
||||
"root_path": "",
|
||||
"headers": [
|
||||
*headers,
|
||||
(b"content-type", b"image/png"),
|
||||
(b"content-length", b"1000000"),
|
||||
],
|
||||
"client": ("127.0.0.1", 50000),
|
||||
"server": ("testserver", 80),
|
||||
}
|
||||
messages = iter(
|
||||
[
|
||||
{"type": "http.request", "body": SAMPLE[:1000], "more_body": True},
|
||||
{"type": "http.disconnect"},
|
||||
]
|
||||
)
|
||||
sent: list[Message] = []
|
||||
|
||||
async def receive() -> dict[str, Any]:
|
||||
return next(messages, {"type": "http.disconnect"})
|
||||
|
||||
async def send(message: Message) -> None:
|
||||
sent.append(message)
|
||||
|
||||
await APPS[id(client)](scope, receive, send)
|
||||
assert sent[0]["status"] == 400
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
|
||||
|
||||
async def test_stalled_upload_times_out_and_frees_the_slot() -> None:
|
||||
async with running_app(upload_concurrency=1, request_timeout_seconds=0.5) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
name = f"stalled-{uuid4().hex}.png"
|
||||
|
||||
async def stalled() -> AsyncIterator[bytes]:
|
||||
yield SAMPLE[:1000]
|
||||
await asyncio.Event().wait()
|
||||
|
||||
response = await upload(http, alice, chat, stalled(), filename=name)
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
assert (await upload(http, alice, chat)).status_code == 202
|
||||
@@ -0,0 +1,69 @@
|
||||
import json
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from httpx import Response
|
||||
|
||||
from conftest import bearer, login, new_user, running_app
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
RFC3339_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z\Z")
|
||||
MOMENTS = [
|
||||
datetime(2026, 10, 12, 8, 49, 2, tzinfo=UTC),
|
||||
datetime(2026, 10, 12, 8, 49, 2, 120, tzinfo=UTC),
|
||||
]
|
||||
|
||||
|
||||
def assert_wire(response: Response, expected: dict[str, Any]) -> None:
|
||||
assert (
|
||||
response.content == json.dumps(expected, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("moment", MOMENTS, ids=["whole-second", "microseconds"])
|
||||
async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment: datetime) -> None:
|
||||
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self: moment)
|
||||
stamp = moment.isoformat().replace("+00:00", "Z")
|
||||
assert RFC3339_UTC.match(stamp)
|
||||
async with running_app() as http:
|
||||
body = new_user("wire")
|
||||
response = await http.post("/api/v1/users", json=body)
|
||||
user_id = response.json()["id"]
|
||||
user = {
|
||||
"id": user_id,
|
||||
"username": body["username"],
|
||||
"display_name": body["display_name"],
|
||||
"created_at": stamp,
|
||||
}
|
||||
assert_wire(response, user)
|
||||
session = await login(http, body["username"])
|
||||
headers = bearer(session["token"])
|
||||
assert session["user"] == user
|
||||
assert_wire(await http.get("/api/v1/users/me", headers=headers), user)
|
||||
|
||||
response = await http.post(
|
||||
"/api/v1/chats", json={"title": "Чат", "member_ids": [user_id]}, headers=headers
|
||||
)
|
||||
chat_id = response.json()["id"]
|
||||
chat = {"id": chat_id, "title": "Чат", "member_ids": [user_id], "created_at": stamp}
|
||||
assert_wire(response, chat)
|
||||
assert_wire(await http.get(f"/api/v1/chats/{chat_id}", headers=headers), chat)
|
||||
listed = await http.get("/api/v1/chats", headers=headers)
|
||||
assert_wire(listed, {"items": [chat], "next_cursor": None})
|
||||
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
sent = {**headers, "Idempotency-Key": "wire-1"}
|
||||
response = await http.post(path, json={"text": "привет"}, headers=sent)
|
||||
message = {
|
||||
"id": response.json()["id"],
|
||||
"chat_id": chat_id,
|
||||
"sender_id": user_id,
|
||||
"text": "привет",
|
||||
"created_at": stamp,
|
||||
"attachment_ids": [],
|
||||
}
|
||||
assert_wire(response, message)
|
||||
history = await http.get(path, headers=headers)
|
||||
assert_wire(history, {"items": [message], "next_cursor": None})
|
||||
Reference in New Issue
Block a user