Files
mtusi2026lab2/student-tests/api/test_instance.py
T
ArtyomandClaude Opus 5.5 bf0f0b4c07 Name the serving replica in every response
The platform settings default the instance id to the container
hostname, computed once per process, so every gunicorn worker of a
replica reports the same value and it matches docker ps. The request
pipeline stamps X-Instance-Id next to X-Request-Id on every response
it sends, and the unhandled error handler adds it itself, because the
500 answer is produced outside the pipeline.

Own tests cover 200, 204, 400, 401, 404, the hidden 405, 413 and 500
with a fixed instance id, and the hostname default. The application
version follows the contract version 1.3.0.

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

65 lines
2.4 KiB
Python

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