|
| 1 | +import logging |
| 2 | +from http import HTTPStatus |
| 3 | +from unittest.mock import Mock |
| 4 | + |
| 5 | +import pytest |
| 6 | +from mangum.types import LambdaContext |
| 7 | + |
| 8 | + |
| 9 | +@pytest.fixture |
| 10 | +def lambda_context(): |
| 11 | + context = Mock(spec=LambdaContext) |
| 12 | + context.aws_request_id = "test-request-id" |
| 13 | + return context |
| 14 | + |
| 15 | + |
| 16 | +@pytest.mark.parametrize( |
| 17 | + ("headers", "gateway_request_id", "expected_extra"), |
| 18 | + [ |
| 19 | + ( |
| 20 | + {"X-Request-ID": "req-123", "X-Correlation-ID": "corr-abc"}, |
| 21 | + "gw-id-999", |
| 22 | + { |
| 23 | + "x_request_id": "req-123", |
| 24 | + "x_correlation_id": "corr-abc", |
| 25 | + "gateway_request_id": "gw-id-999", |
| 26 | + }, |
| 27 | + ), |
| 28 | + ( |
| 29 | + {}, # No headers |
| 30 | + "gw-id-000", |
| 31 | + { |
| 32 | + "x_request_id": None, |
| 33 | + "x_correlation_id": None, |
| 34 | + "gateway_request_id": "gw-id-000", |
| 35 | + }, |
| 36 | + ), |
| 37 | + ( |
| 38 | + {"X-Request-ID": "req-local"}, |
| 39 | + None, # No requestContext (non-Gateway trigger) |
| 40 | + { |
| 41 | + "x_request_id": "req-local", |
| 42 | + "x_correlation_id": None, |
| 43 | + "gateway_request_id": None, |
| 44 | + }, |
| 45 | + ), |
| 46 | + ], |
| 47 | +) |
| 48 | +def test_log_request_ids_decorator_logs_metadata(headers, gateway_request_id, expected_extra, lambda_context, caplog): |
| 49 | + from eligibility_signposting_api.app import log_request_ids |
| 50 | + |
| 51 | + event = {"headers": headers} |
| 52 | + if gateway_request_id is not None: |
| 53 | + event["requestContext"] = {"requestId": gateway_request_id} |
| 54 | + |
| 55 | + @log_request_ids() |
| 56 | + def test_handler(event, context): # noqa : ARG001 |
| 57 | + logger = logging.getLogger("test_logger") |
| 58 | + logger.info("Inside test handler") |
| 59 | + return HTTPStatus.OK |
| 60 | + |
| 61 | + with caplog.at_level(logging.INFO): |
| 62 | + test_handler(event, lambda_context) |
| 63 | + |
| 64 | + for record in caplog.records: |
| 65 | + if record.message == "request trace metadata": |
| 66 | + for key, val in expected_extra.items(): |
| 67 | + assert getattr(record, key) == val |
| 68 | + break |
| 69 | + else: |
| 70 | + pytest.fail("'request trace metadata' log not found") |
0 commit comments