Skip to content

Commit

Permalink
test(request_id): add tests for request id middleware context handling
Browse files Browse the repository at this point in the history
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
  • Loading branch information
EricGoulart committed Oct 29, 2024
1 parent 9c0f151 commit 54b83b6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
6 changes: 4 additions & 2 deletions examples/recipes/request_id_middleware.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
18 changes: 11 additions & 7 deletions tests/test_recipes.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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):
Expand All @@ -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']

Expand All @@ -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']
assert response.headers['X-Request-ID'] == response.json['request_id']

0 comments on commit 54b83b6

Please sign in to comment.