From 3e6394e641f29110ed29deb2e9806e2f9cb7106f Mon Sep 17 00:00:00 2001 From: Cesar Alvernaz Date: Wed, 24 Aug 2022 16:38:05 +0100 Subject: [PATCH] APIGateway: add guard against no integration when adding a new response (#5416) --- moto/apigateway/models.py | 12 +++++----- tests/test_apigateway/test_apigateway.py | 30 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/moto/apigateway/models.py b/moto/apigateway/models.py index c5d359f00..d8fda52a0 100644 --- a/moto/apigateway/models.py +++ b/moto/apigateway/models.py @@ -1381,8 +1381,7 @@ class APIGatewayBackend(BaseBackend): api = self.get_rest_api(function_id) if resource_id not in api.resources: raise ResourceIdNotFoundException - resource = api.resources[resource_id] - return resource + return api.resources[resource_id] def create_resource(self, function_id, parent_resource_id, path_part): api = self.get_rest_api(function_id) @@ -1643,10 +1642,11 @@ class APIGatewayBackend(BaseBackend): content_handling, ): integration = self.get_integration(function_id, resource_id, method_type) - integration_response = integration.create_integration_response( - status_code, selection_pattern, response_templates, content_handling - ) - return integration_response + if integration: + return integration.create_integration_response( + status_code, selection_pattern, response_templates, content_handling + ) + raise NoIntegrationResponseDefined() def get_integration_response( self, function_id, resource_id, method_type, status_code diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py index 06e1e947d..e430b9818 100644 --- a/tests/test_apigateway/test_apigateway.py +++ b/tests/test_apigateway/test_apigateway.py @@ -1055,6 +1055,36 @@ def test_put_integration_response_with_response_template(): ) +@mock_apigateway +def test_put_integration_response_but_integration_not_found(): + client = boto3.client("apigateway", region_name="us-west-2") + response = client.create_rest_api(name="my_api", description="this is my api") + api_id = response["id"] + resources = client.get_resources(restApiId=api_id) + root_id = [resource for resource in resources["items"] if resource["path"] == "/"][ + 0 + ]["id"] + + client.put_method( + restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE" + ) + client.put_method_response( + restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" + ) + + with pytest.raises(ClientError) as ex: + client.put_integration_response( + restApiId=api_id, + resourceId=root_id, + httpMethod="GET", + statusCode="200", + selectionPattern="foobar", + responseTemplates={"application/json": json.dumps({"data": "test"})}, + ) + ex.value.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(404) + + @mock_apigateway def test_put_integration_validation(): client = boto3.client("apigateway", region_name="us-west-2")