async def request_id_middleware(request: BaseRequest, handler: Callable) -> StreamResponse: request_id_token = set_request_id(request.headers.get("X-Request-Id")) request_id = get_request_id() try: if sentry_sdk: with configure_scope() as scope: scope.set_tag("request_id", request_id) response = await handler(request) response.headers["X-Request-Id"] = get_request_id() return response finally: reset_request_id(request_id_token)
def test_request_id_generated_if_bad_given(uuid4_mock, caplog): set_request_id("bad_request_id") assert get_request_id() == uuid4_mock assert "Received invalid request id" in caplog.text
def test_request_id_generated_and_saved_if_not_given(uuid4_mock): set_request_id() assert get_request_id() == uuid4_mock
def test_request_id_saved_if_given(): request_id = uuid4().hex set_request_id(request_id) assert get_request_id() == request_id
def log(self, request: BaseRequest, response: StreamResponse, time: float): token = set_request_id(response.headers.get("X-Request-Id")) try: super().log(request, response, time) finally: reset_request_id(token)