From 6a13ad283ac43129787a11049eaa805f7528420a Mon Sep 17 00:00:00 2001 From: James Saryerwinnie Date: Wed, 29 Mar 2017 09:29:09 -0700 Subject: [PATCH] Use modeled exceptions instead of generic exception This was added in v1.5.0 of botocore so I've bumped the min version of botocore accordingly. --- chalice/awsclient.py | 64 +++++++++++++----------------- setup.py | 2 +- tests/functional/test_awsclient.py | 24 +++++++++++ 3 files changed, 52 insertions(+), 38 deletions(-) diff --git a/chalice/awsclient.py b/chalice/awsclient.py index 1ecd21f94..b08d4b776 100644 --- a/chalice/awsclient.py +++ b/chalice/awsclient.py @@ -20,8 +20,7 @@ import shutil import json -import botocore.session -import botocore.exceptions +import botocore.session # noqa from typing import Any, Optional, Dict, Callable, List # noqa @@ -40,14 +39,12 @@ def __init__(self, session, sleep=time.sleep): def lambda_function_exists(self, name): # type: (str) -> bool + client = self._client('lambda') try: - self._client('lambda').get_function(FunctionName=name) - except botocore.exceptions.ClientError as e: - error = e.response['Error'] - if error['Code'] == 'ResourceNotFoundException': - return False - raise - return True + client.get_function(FunctionName=name) + return True + except client.exceptions.ResourceNotFoundException: + return False def create_function(self, function_name, role_arn, zip_contents): # type: (str, str, str) -> str @@ -64,19 +61,16 @@ def create_function(self, function_name, role_arn, zip_contents): while True: try: response = client.create_function(**kwargs) - except botocore.exceptions.ClientError as e: - code = e.response['Error'].get('Code') - if code == 'InvalidParameterValueException': - # We're assuming that if we receive an - # InvalidParameterValueException, it's because - # the role we just created can't be used by - # Lambda. - self._sleep(self.DELAY_TIME) - attempts += 1 - if attempts >= self.LAMBDA_CREATE_ATTEMPTS: - raise - continue - raise + except client.exceptions.InvalidParameterValueException: + # We're assuming that if we receive an + # InvalidParameterValueException, it's because + # the role we just created can't be used by + # Lambda. + self._sleep(self.DELAY_TIME) + attempts += 1 + if attempts >= self.LAMBDA_CREATE_ATTEMPTS: + raise + continue return response['FunctionArn'] def update_function_code(self, function_name, zip_contents): @@ -86,13 +80,11 @@ def update_function_code(self, function_name, zip_contents): def get_role_arn_for_name(self, name): # type: (str) -> str + client = self._client('iam') try: - role = self._client('iam').get_role(RoleName=name) - except botocore.exceptions.ClientError as e: - error = e.response['Error'] - if error['Code'] == 'NoSuchEntity': - raise ValueError("No role ARN found for: %s" % name) - raise + role = client.get_role(RoleName=name) + except client.exceptions.NoSuchEntityException: + raise ValueError("No role ARN found for: %s" % name) return role['Role']['Arn'] def delete_role_policy(self, role_name, policy_name): @@ -141,13 +133,12 @@ def get_rest_api_id(self, name): def rest_api_exists(self, rest_api_id): # type: (str) -> bool """Check if an an API Gateway REST API exists.""" + client = self._client('apigateway') try: - self._client('apigateway').get_rest_api(restApiId=rest_api_id) + client.get_rest_api(restApiId=rest_api_id) return True - except botocore.exceptions.ClientError as e: - if e['Code'] == 'NotFoundException': - return False - raise + except client.exceptions.NotFoundException: + return False def import_rest_api(self, swagger_document): # type: (Dict[str, Any]) -> str @@ -185,12 +176,11 @@ def add_permission_for_apigateway_if_needed(self, function_name, """ has_necessary_permissions = False + client = self._client('lambda') try: policy = self.get_function_policy(function_name) - except botocore.exceptions.ClientError as e: - error = e.response['Error'] - if error['Code'] == 'ResourceNotFoundException': - pass + except client.exceptions.ResourceNotFoundException: + pass else: source_arn = self._build_source_arn_str(region_name, account_id, rest_api_id) diff --git a/setup.py b/setup.py index ea9b64a79..00f374e08 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ install_requires = [ 'click==6.6', - 'botocore>=1.4.8,<2.0.0', + 'botocore>=1.5.0,<2.0.0', 'virtualenv>=15.0.0,<16.0.0', 'typing==3.5.3.0', ] diff --git a/tests/functional/test_awsclient.py b/tests/functional/test_awsclient.py index d814dedb2..fc3a6be49 100644 --- a/tests/functional/test_awsclient.py +++ b/tests/functional/test_awsclient.py @@ -47,6 +47,30 @@ def test_put_role_policy(stubbed_session): stubbed_session.verify_stubs() +def test_rest_api_exists(stubbed_session): + stubbed_session.stub('apigateway').get_rest_api( + restApiId='api').returns({}) + stubbed_session.activate_stubs() + + awsclient = TypedAWSClient(stubbed_session) + assert awsclient.rest_api_exists('api') + + stubbed_session.verify_stubs() + + +def test_rest_api_not_exists(stubbed_session): + stubbed_session.stub('apigateway').get_rest_api( + restApiId='api').raises_error( + error_code='NotFoundException', + message='ResourceNotFound') + stubbed_session.activate_stubs() + + awsclient = TypedAWSClient(stubbed_session) + assert not awsclient.rest_api_exists('api') + + stubbed_session.verify_stubs() + + class TestLambdaFunctionExists(object): def test_can_query_lambda_function_exists(self, stubbed_session):