From 2077418cb13bcdb9c69df6ca804849e7bf30b47a Mon Sep 17 00:00:00 2001 From: NogaNHS Date: Mon, 16 Dec 2024 15:33:10 +0000 Subject: [PATCH] [PRMP-1287] add handler unit tests --- .../nrl_get_document_reference_handler.py | 4 +- lambdas/models/nrl_document_search_request.py | 11 -- lambdas/tests/unit/conftest.py | 1 + ...test_nrl_get_document_reference_handler.py | 116 ++++++------------ lambdas/utils/error_response.py | 10 +- 5 files changed, 49 insertions(+), 93 deletions(-) delete mode 100644 lambdas/models/nrl_document_search_request.py diff --git a/lambdas/handlers/nrl_get_document_reference_handler.py b/lambdas/handlers/nrl_get_document_reference_handler.py index 304d86ba4..4a45ccd4f 100644 --- a/lambdas/handlers/nrl_get_document_reference_handler.py +++ b/lambdas/handlers/nrl_get_document_reference_handler.py @@ -29,12 +29,12 @@ def lambda_handler(event, context): configuration_service.set_auth_ssm_prefix() try: get_document_service = NRLGetDocumentReferenceService() - placeholder = get_document_service.handle_get_document_reference_request( + document_ref = get_document_service.handle_get_document_reference_request( document_id, bearer_token ) return ApiGatewayResponse( - status_code=200, body=placeholder, methods="GET" + status_code=200, body=document_ref, methods="GET" ).create_api_gateway_response() except NRLGetDocumentReferenceException as e: return ApiGatewayResponse( diff --git a/lambdas/models/nrl_document_search_request.py b/lambdas/models/nrl_document_search_request.py deleted file mode 100644 index c7758b265..000000000 --- a/lambdas/models/nrl_document_search_request.py +++ /dev/null @@ -1,11 +0,0 @@ -from pydantic import AliasGenerator, BaseModel, ConfigDict -from pydantic.alias_generators import to_camel - - -class NRLDocumentSearchRequest(BaseModel): - model_config = ConfigDict( - alias_generator=AliasGenerator(validation_alias=to_camel), - ) - path_parameters: str - bearer_token: str - pass diff --git a/lambdas/tests/unit/conftest.py b/lambdas/tests/unit/conftest.py index 0ab97fc6b..a93e97b1d 100644 --- a/lambdas/tests/unit/conftest.py +++ b/lambdas/tests/unit/conftest.py @@ -172,6 +172,7 @@ def set_env(monkeypatch): monkeypatch.setenv("NRL_API_ENDPOINT", FAKE_URL) monkeypatch.setenv("NRL_END_USER_ODS_CODE", "test_nrl_user_ods_ssm_key") monkeypatch.setenv("NRL_SQS_QUEUE_URL", NRL_SQS_URL) + monkeypatch.setenv("CLOUDFRONT_URL", "mock-cloudfront-url.com") EXPECTED_PARSED_PATIENT_BASE_CASE = PatientDetails( diff --git a/lambdas/tests/unit/handlers/test_nrl_get_document_reference_handler.py b/lambdas/tests/unit/handlers/test_nrl_get_document_reference_handler.py index a8f3cdacf..074e65add 100644 --- a/lambdas/tests/unit/handlers/test_nrl_get_document_reference_handler.py +++ b/lambdas/tests/unit/handlers/test_nrl_get_document_reference_handler.py @@ -1,85 +1,49 @@ -from tests.unit.conftest import FAKE_URL, TEST_UUID -from tests.unit.services.test_authoriser_service import MOCK_SESSION_ID +import json + +import pytest +from enums.lambda_error import LambdaError +from handlers.nrl_get_document_reference_handler import lambda_handler +from tests.unit.conftest import TEST_UUID +from utils.lambda_exceptions import NRLGetDocumentReferenceException MOCK_VALID_EVENT = { - "resource": "/DocumentReference/{id}", - "path": "/DocumentReference/2", "httpMethod": "GET", "headers": { - "Accept": "*/*", - "Accept-Encoding": "gzip, deflate, br", "Authorization": f"Bearer {TEST_UUID}", - "Cache-Control": "no-cache", - "Host": FAKE_URL, - "NHSD-Correlation-ID": TEST_UUID, - "NHSD-ID-Token": f"MOCK_JWT{TEST_UUID}", - "NHSD-Request-ID": "", - "NHSD-Session-URID": MOCK_SESSION_ID, - "NHSD-Session-UUID": MOCK_SESSION_ID, - "Postman-Token": TEST_UUID, - "User-Agent": "PostmanRuntime", - "X-Amzn-Trace-Id": f"Root={TEST_UUID}", - "X-API-Key": TEST_UUID, - "X-Forwarded-For": "num", - "X-Forwarded-Port": "port", - "X-Forwarded-Proto": "https", - }, - "multiValueHeaders": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate, br"], - "Authorization": [f"Bearer {TEST_UUID}"], - "Cache-Control": ["no-cache"], - "Host": [FAKE_URL], - "NHSD-Correlation-ID": [TEST_UUID], - "NHSD-ID-Token": [f"MOCK_JWT{TEST_UUID}"], - "NHSD-Request-ID": [""], - "NHSD-Session-URID": [MOCK_SESSION_ID], - "NHSD-Session-UUID": [MOCK_SESSION_ID], - "Postman-Token": [TEST_UUID], - "User-Agent": ["PostmanRuntime"], - "X-Amzn-Trace-Id": [f"Root={TEST_UUID}"], - "X-API-Key": [TEST_UUID], - "X-Forwarded-For": ["num"], - "X-Forwarded-Port": ["num"], - "X-Forwarded-Proto": ["https"], }, - "queryStringParameters": None, - "multiValueQueryStringParameters": None, "pathParameters": {"id": TEST_UUID}, - "stageVariables": None, - "requestContext": { - "resourceId": TEST_UUID, - "resourcePath": "/DocumentReference/{id}", - "httpMethod": "GET", - "extendedRequestId": "", - "requestTime": "05/Dec/2024:15:36:37 +0000", - "path": f"/DocumentReference/{TEST_UUID}", - "accountId": TEST_UUID, - "protocol": "HTTP/1.1", - "stage": "dev", - "domainPrefix": "ndr-", - "requestTimeEpoch": 1733412997840, - "requestId": TEST_UUID, - "identity": { - "cognitoIdentityPoolId": None, - "cognitoIdentityId": None, - "apiKey": TEST_UUID, - "principalOrgId": None, - "cognitoAuthenticationType": None, - "userArn": None, - "apiKeyId": TEST_UUID, - "userAgent": "PostmanRuntime", - "accountId": None, - "caller": None, - "sourceIp": "IP", - "accessKey": None, - "cognitoAuthenticationProvider": None, - "user": None, - }, - "domainName": FAKE_URL, - "deploymentId": "????", - "apiId": TEST_UUID, - }, "body": None, - "isBase64Encoded": False, } + + +@pytest.fixture +def mock_service(mocker): + mocked_class = mocker.patch( + "handlers.nrl_get_document_reference_handler.NRLGetDocumentReferenceService" + ) + mocker.patch( + "handlers.nrl_get_document_reference_handler.DynamicConfigurationService" + ) + mocked_instance = mocked_class.return_value + mocked_class.return_value.handle_get_document_reference_request.return_value = ( + "test_document_reference" + ) + return mocked_instance + + +def test_lambda_handler_happy_path(set_env, mock_service, context): + response = lambda_handler(MOCK_VALID_EVENT, context) + assert response["statusCode"] == 200 + + +def test_lambda_handler_error(set_env, mock_service, context): + expected_exception = { + "resourceType": "OperationOutcome", + "issue": [{"severity": "error", "code": "AB_XXXX", "details": "Client error"}], + } + mock_service.handle_get_document_reference_request.side_effect = ( + NRLGetDocumentReferenceException(400, LambdaError.MockError) + ) + response = lambda_handler(MOCK_VALID_EVENT, context) + assert response["statusCode"] == 400 + assert response["body"] == json.dumps(expected_exception) diff --git a/lambdas/utils/error_response.py b/lambdas/utils/error_response.py index 49224bb36..dc37fdca5 100644 --- a/lambdas/utils/error_response.py +++ b/lambdas/utils/error_response.py @@ -1,6 +1,6 @@ import json -from fhir.resources.R4B.operationoutcome import OperationOutcome +from fhir.resources.R4B.operationoutcome import OperationOutcome, OperationOutcomeIssue class ErrorResponse: @@ -20,9 +20,11 @@ def create(self) -> str: def create_error_fhir_response(self) -> str: operation_outcome = OperationOutcome.construct() - operation_outcome.severity = "error" - operation_outcome.code = self.err_code - operation_outcome.details = self.message + operation_outcome.issue = list() + issue = OperationOutcomeIssue.construct( + code=self.err_code, details=self.message, severity="error" + ) + operation_outcome.issue.append(issue) return operation_outcome.json() def __eq__(self, other):