Skip to content

Commit 0b6c2da

Browse files
licjunvicheey
andauthored
chore: Refactor TenantIdValidationError handling for consistency (#8474)
* Refactor TenantIdValidationError handling for consistency * Add unit test for TenantIdValidationError handling in API Gateway service --------- Co-authored-by: Chengjun Li <> Co-authored-by: vicheey <181402101+vicheey@users.noreply.github.com>
1 parent 7266601 commit 0b6c2da

3 files changed

Lines changed: 45 additions & 4 deletions

File tree

samcli/local/apigw/local_apigw_service.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from time import time
99
from typing import Any, Dict, List, Optional, Tuple, Union
1010

11-
from flask import Flask, Request, jsonify, make_response, request
11+
from flask import Flask, Request, request
1212
from werkzeug.datastructures import Headers
1313
from werkzeug.routing import BaseConverter
1414
from werkzeug.serving import WSGIRequestHandler
@@ -740,8 +740,7 @@ def _request_handler(self, **kwargs):
740740
# invoke the route's Lambda function
741741
lambda_response = self._invoke_lambda_function(route.function_name, route_lambda_event, tenant_id)
742742
except TenantIdValidationError as e:
743-
response_data = jsonify({"message": str(e)})
744-
endpoint_service_error = make_response(response_data, 400) # HTTP 400 Bad Request
743+
endpoint_service_error = ServiceErrorResponses.tenant_id_validation_error(str(e))
745744
except FunctionNotFound:
746745
endpoint_service_error = ServiceErrorResponses.lambda_not_found_response()
747746
except UnsupportedInlineCodeError:

samcli/local/apigw/service_error_responses.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class ServiceErrorResponses:
1919
HTTP_STATUS_CODE_502 = 502
2020
HTTP_STATUS_CODE_403 = 403
2121
HTTP_STATUS_CODE_401 = 401
22+
HTTP_STATUS_CODE_400 = 400
2223

2324
@staticmethod
2425
def lambda_authorizer_unauthorized() -> Response:
@@ -110,3 +111,21 @@ def container_creation_failed(message):
110111
"""
111112
response_data = jsonify({"message": message})
112113
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_501)
114+
115+
@staticmethod
116+
def tenant_id_validation_error(message: str) -> Response:
117+
"""
118+
Constructs a Flask Response for when tenant ID validation fails
119+
120+
Parameters
121+
----------
122+
message : str
123+
The error message describing the validation failure
124+
125+
Returns
126+
-------
127+
Response
128+
A Flask Response object with HTTP 400 status
129+
"""
130+
response_data = jsonify({"message": message})
131+
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_400)

tests/unit/local/apigw/test_local_apigw_service.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from samcli.local.apigw.service_error_responses import ServiceErrorResponses
2828
from samcli.local.docker.exceptions import DockerContainerCreationFailedException
2929
from samcli.local.lambdafn.exceptions import FunctionNotFound
30-
from samcli.commands.local.lib.exceptions import UnsupportedInlineCodeError
30+
from samcli.commands.local.lib.exceptions import TenantIdValidationError, UnsupportedInlineCodeError
3131

3232

3333
class TestApiGatewayService(TestCase):
@@ -460,6 +460,29 @@ def test_request_handles_error_when_invoke_function_with_inline_code(
460460

461461
self.assertEqual(response, not_implemented_response_mock)
462462

463+
@patch.object(LocalApigwService, "get_request_methods_endpoints")
464+
@patch("samcli.local.apigw.local_apigw_service.ServiceErrorResponses")
465+
@patch("samcli.local.apigw.local_apigw_service.LocalApigwService._generate_lambda_event")
466+
def test_request_handles_error_when_tenant_id_validation_fails(
467+
self, generate_mock, service_error_responses_patch, request_mock
468+
):
469+
generate_mock.return_value = {}
470+
tenant_id_error_response_mock = Mock()
471+
self.api_service._get_current_route = MagicMock()
472+
self.api_service._get_current_route.return_value.payload_format_version = "2.0"
473+
self.api_service._get_current_route.return_value.authorizer_object = None
474+
self.api_service._get_current_route.methods = []
475+
476+
service_error_responses_patch.tenant_id_validation_error.return_value = tenant_id_error_response_mock
477+
478+
self.lambda_runner.invoke.side_effect = TenantIdValidationError(
479+
"The invoked function is enabled with tenancy configuration. Add a valid tenant ID in your request and try again."
480+
)
481+
request_mock.return_value = ("test", "test")
482+
response = self.api_service._request_handler()
483+
484+
self.assertEqual(response, tenant_id_error_response_mock)
485+
463486
@patch.object(LocalApigwService, "get_request_methods_endpoints")
464487
@patch("samcli.local.apigw.local_apigw_service.ServiceErrorResponses")
465488
@patch("samcli.local.apigw.local_apigw_service.LocalApigwService._generate_lambda_event")

0 commit comments

Comments
 (0)