Files
mtusi2026lab2/student-tests/api/test_events.py
T
ArtyomandClaude Opus 5.5 bf8e4e3cd1 Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy and k6 configuration, migrations, hooks, evidence and level 4
scripts and the CI job from the lab 3 solution commit 61c0c28, merge
the lab 3 Makefile targets into the lab 4 skeleton Makefile without
touching its targets, and append the lab 3 solution variables to the
skeleton .env.example. The package and the application follow the
contract version 1.4.0, and the image and the throwaway test containers
are tagged lab4 so they do not collide with a lab 3 stand on the same
host.

This is the starting point of the lab 4 cycle: lint, own tests and the
offline skeleton check pass before any lab 4 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:17:51 +03:00

125 lines
3.9 KiB
Python

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)