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()