|
39 | 39 | from servicewright.adapters import _uvicorn as uvicorn_mod |
40 | 40 | from servicewright.adapters.fastapi import ( |
41 | 41 | AuthorizationHeader, |
| 42 | + CorrelationIdMiddlewareConfig, |
42 | 43 | CORSMiddlewareConfig, |
43 | 44 | FastApiEntrypoint, |
44 | 45 | FastApiPlugin, |
@@ -1741,6 +1742,45 @@ async def test__context_middleware__client_supplied_id__is_preserved_end_to_end( |
1741 | 1742 | assert response.headers["x-request-id"] == "order-sync-42" |
1742 | 1743 |
|
1743 | 1744 |
|
| 1745 | +async def _client_with_request_id_header(header_name: str) -> TestClient: |
| 1746 | + """A client over the default stack with the request id moved to ``header_name``.""" |
| 1747 | + middlewares = MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(header_name=header_name)) |
| 1748 | + ep = FastApiEntrypoint(config=HttpConfig(port=0), middlewares=middlewares) |
| 1749 | + app = await ep.build_app(_make_service_ctx(FakeContainer())) |
| 1750 | + |
| 1751 | + @app.get("/echo") |
| 1752 | + def echo() -> dict[str, Any]: |
| 1753 | + return {"request_id": get_context_value("request_id")} |
| 1754 | + |
| 1755 | + return TestClient(app) |
| 1756 | + |
| 1757 | + |
| 1758 | +async def test__context_middleware__custom_request_id_header__reads_the_id_from_it() -> None: |
| 1759 | + # Arrange |
| 1760 | + client = await _client_with_request_id_header("X-Correlation-ID") |
| 1761 | + |
| 1762 | + # Act |
| 1763 | + response = client.get("/echo", headers={"X-Correlation-ID": "order-sync-42"}) |
| 1764 | + |
| 1765 | + # Assert |
| 1766 | + assert response.json()["request_id"] == "order-sync-42" |
| 1767 | + assert response.headers["x-correlation-id"] == "order-sync-42" |
| 1768 | + |
| 1769 | + |
| 1770 | +async def test__context_middleware__custom_request_id_header__no_longer_reads_x_request_id() -> None: |
| 1771 | + # Arrange |
| 1772 | + client = await _client_with_request_id_header("X-Correlation-ID") |
| 1773 | + |
| 1774 | + # Act |
| 1775 | + response = client.get("/echo", headers={"X-Request-ID": "order-sync-42"}) |
| 1776 | + |
| 1777 | + # Assert |
| 1778 | + minted = response.json()["request_id"] |
| 1779 | + assert minted != "order-sync-42" |
| 1780 | + assert UUID(minted) |
| 1781 | + assert response.headers["x-correlation-id"] == minted |
| 1782 | + |
| 1783 | + |
1744 | 1784 | async def test__unhandled_exception__masked_500__still_carries_the_request_id(correlated_client: Any) -> None: |
1745 | 1785 | # Act |
1746 | 1786 | response = correlated_client.get("/boom") |
|
0 commit comments