|
16 | 16 | import pytest |
17 | 17 | from fastapi import APIRouter |
18 | 18 |
|
19 | | -from servicewright import AppSpec, Service |
20 | | -from servicewright.adapters.fastapi import FastApiEntrypoint, HttpConfig |
| 19 | +from servicewright import AppSpec, Service, propagation_metadata |
| 20 | +from servicewright.adapters.fastapi import FastApiEntrypoint, HttpConfig, HttpServerSettings |
| 21 | +from servicewright.adapters.settings import BaseServiceSettings |
21 | 22 | from servicewright.testing import FakeContainer, FakeSettings |
22 | 23 |
|
23 | 24 | pytestmark = pytest.mark.integration |
24 | 25 |
|
25 | 26 |
|
| 27 | +class _Settings(BaseServiceSettings): |
| 28 | + server: HttpServerSettings = HttpServerSettings() |
| 29 | + |
| 30 | + |
26 | 31 | def _free_port() -> int: |
27 | 32 | """Reserve and release an ephemeral TCP port (robust on win32).""" |
28 | 33 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
@@ -104,3 +109,43 @@ async def request_then_stop() -> httpx.Response: |
104 | 109 | # Assert |
105 | 110 | assert response.status_code == 500, "uvicorn cancels the request itself, not a hard stop that orphans it" |
106 | 111 | assert handler_finished is False |
| 112 | + |
| 113 | + |
| 114 | +async def test__fastapi_entrypoint__context_headers_from_the_environment__forwards_only_the_request_id( |
| 115 | + monkeypatch: pytest.MonkeyPatch, |
| 116 | +) -> None: |
| 117 | + # Arrange |
| 118 | + monkeypatch.setenv("SERVER__MIDDLEWARES__CONTEXT_HEADERS", '{"x-request-id":"request_id"}') |
| 119 | + port = _free_port() |
| 120 | + spec: AppSpec[Any, Any] = AppSpec(service_name="http-it-service", create_container=lambda _s: FakeContainer()) |
| 121 | + router = APIRouter() |
| 122 | + |
| 123 | + @router.get("/outbound") |
| 124 | + async def outbound() -> dict[str, str]: |
| 125 | + return propagation_metadata() |
| 126 | + |
| 127 | + ep = FastApiEntrypoint( |
| 128 | + config=HttpConfig(host="127.0.0.1", port=port), |
| 129 | + middlewares=_Settings().server.middlewares.to_config(), |
| 130 | + routers=(router,), |
| 131 | + ) |
| 132 | + stop = asyncio.Event() |
| 133 | + |
| 134 | + async def request_then_stop() -> httpx.Response: |
| 135 | + while not spec.health.ready: |
| 136 | + await asyncio.sleep(0.01) |
| 137 | + async with httpx.AsyncClient(base_url=f"http://127.0.0.1:{port}", timeout=2.0) as client: |
| 138 | + try: |
| 139 | + return await client.get( |
| 140 | + "/outbound", headers={"X-Request-ID": "req-1", "X-User-Id": "user-9", "X-Tenant-Id": "tenant-3"} |
| 141 | + ) |
| 142 | + finally: |
| 143 | + stop.set() |
| 144 | + |
| 145 | + # Act |
| 146 | + _, response = await asyncio.gather( |
| 147 | + Service(spec, entrypoints=[ep]).run(FakeSettings(), stop=stop), request_then_stop() |
| 148 | + ) |
| 149 | + |
| 150 | + # Assert |
| 151 | + assert response.json() == {"x-request-id": "req-1"} |
0 commit comments