From 54b83b6699f2ff79b66c9abae0dcfce33832a55b Mon Sep 17 00:00:00 2001 From: "eric.goulart" Date: Tue, 29 Oct 2024 12:24:11 -0300 Subject: [PATCH] test(request_id): add tests for request id middleware context handling Add tests to verify that request_id is unique per request and correctly set in response headers. Tests include checks for isolation in async calls and persistence in synchronous requests. Related to issue falconry#2260 --- examples/recipes/request_id_middleware.py | 6 ++++-- tests/test_recipes.py | 18 +++++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/examples/recipes/request_id_middleware.py b/examples/recipes/request_id_middleware.py index 1ced07522..54757eb11 100644 --- a/examples/recipes/request_id_middleware.py +++ b/examples/recipes/request_id_middleware.py @@ -1,13 +1,15 @@ # middleware.py from uuid import uuid4 + from .request_id_context import ctx + class RequestIDMiddleware: def process_request(self, req, resp): request_id = str(uuid4()) - ctx.request_id = request_id - req.context.request_id = request_id + ctx.request_id = request_id + req.context.request_id = request_id # It may also be helpful to include the ID in the response def process_response(self, req, resp, resource, req_succeeded): diff --git a/tests/test_recipes.py b/tests/test_recipes.py index 26761ba03..90846cfc4 100644 --- a/tests/test_recipes.py +++ b/tests/test_recipes.py @@ -1,10 +1,11 @@ +import asyncio + import pytest +from examples.recipes.request_id_middleware import RequestIDMiddleware import falcon import falcon.testing -import asyncio -from examples.recipes.request_id_middleware import RequestIDMiddleware class TestMultipartMixed: """Test parsing example from the now-obsolete RFC 1867: @@ -143,7 +144,8 @@ def test_raw_path(self, asgi, app_kind, util): ) assert result2.status_code == 200 assert result2.json == {'cached': True} - + + class TestRequestIDContext: @pytest.fixture def app(self): @@ -162,15 +164,17 @@ async def make_request(): return response.json['request_id'] loop = asyncio.get_event_loop() - request_id1, request_id2 = loop.run_until_complete(asyncio.gather(make_request(), make_request())) + request_id1, request_id2 = loop.run_until_complete( + asyncio.gather(make_request(), make_request()) + ) assert request_id1 != request_id2 def test_request_id_persistence(self, app): client = falcon.testing.TestClient(app) - + response = client.simulate_get('/test') request_id1 = response.json['request_id'] - + response = client.simulate_get('/test') request_id2 = response.json['request_id'] @@ -181,4 +185,4 @@ def test_request_id_in_response_header(self, app): response = client.simulate_get('/test') assert 'X-Request-ID' in response.headers - assert response.headers['X-Request-ID'] == response.json['request_id'] \ No newline at end of file + assert response.headers['X-Request-ID'] == response.json['request_id']