Skip to content

Commit

Permalink
Use modeled exceptions instead of generic exception
Browse files Browse the repository at this point in the history
This was added in v1.5.0 of botocore so I've bumped the min
version of botocore accordingly.
  • Loading branch information
jamesls committed Mar 29, 2017
1 parent 23a3601 commit 6a13ad2
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 38 deletions.
64 changes: 27 additions & 37 deletions chalice/awsclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
Expand All @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]
Expand Down
24 changes: 24 additions & 0 deletions tests/functional/test_awsclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 6a13ad2

Please sign in to comment.