def test_create_rest_api(stubbed_session): stubbed_session.stub('apigateway').create_rest_api( name='name').returns({'id': 'rest_api_id'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.create_rest_api('name') == 'rest_api_id' stubbed_session.verify_stubs()
def test_skip_if_permission_already_granted(stubbed_session): lambda_client = stubbed_session.stub('lambda') policy = { 'Id': 'default', 'Statement': [ {'Action': 'lambda:InvokeFunction', 'Condition': { 'ArnLike': { 'AWS:SourceArn': 'rule-arn', } }, 'Effect': 'Allow', 'Principal': {'Service': 'events.amazonaws.com'}, 'Resource': 'resource-arn', 'Sid': 'statement-id'}, ], 'Version': '2012-10-17' } lambda_client.get_policy( FunctionName='function-arn').returns({'Policy': json.dumps(policy)}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.add_permission_for_scheduled_event( 'rule-arn', 'function-arn') stubbed_session.verify_stubs()
def test_can_iterate_logs(stubbed_session): stubbed_session.stub('logs').filter_log_events( logGroupName='loggroup', interleaved=True).returns({ "events": [{ "logStreamName": "logStreamName", "timestamp": 1501278366000, "message": "message", "ingestionTime": 1501278366000, "eventId": "eventId" }], }) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) logs = list(awsclient.iter_log_events('loggroup')) timestamp = datetime.datetime.fromtimestamp(1501278366) assert logs == [ {'logStreamName': 'logStreamName', # We should have converted the ints to timestamps. 'timestamp': timestamp, 'message': 'message', 'ingestionTime': timestamp, 'eventId': 'eventId'} ] stubbed_session.verify_stubs()
def test_rest_api_delete(self, stubbed_session): stubbed_session.stub('apigateway')\ .delete_rest_api(restApiId='name').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.delete_rest_api('name') is None stubbed_session.verify_stubs()
def test_lambda_delete_function(self, stubbed_session): stubbed_session.stub('lambda')\ .delete_function(FunctionName='name').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.delete_function('name') is None stubbed_session.verify_stubs()
def test_create_role_raises_error_on_failure(self, stubbed_session): arn = 'good_arn' * 3 role_id = 'abcd' * 4 today = datetime.datetime.today() stubbed_session.stub('iam').create_role( RoleName='role_name', AssumeRolePolicyDocument=json.dumps({'trust': 'policy'}) ).returns({'Role': { 'RoleName': 'No', 'Arn': arn, 'Path': '/', 'RoleId': role_id, 'CreateDate': today}} ) stubbed_session.stub('iam').put_role_policy( RoleName='role_name', PolicyName='role_name', PolicyDocument={'policy': 'document'} ).raises_error( error_code='MalformedPolicyDocumentException', message='MalformedPolicyDocument' ) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(botocore.exceptions.ClientError): awsclient.create_role( 'role_name', {'trust': 'policy'}, {'policy': 'document'}) stubbed_session.verify_stubs()
def generate_sdk(ctx, sdk_type, outdir): # type: (click.Context, str, str) -> None config = create_config_obj(ctx) session = create_botocore_session(profile=config.profile, debug=ctx.obj['debug']) client = TypedAWSClient(session) rest_api_id = client.get_rest_api_id(config.app_name) stage_name = config.stage if rest_api_id is None: click.echo("Could not find API ID, has this application " "been deployed?") raise click.Abort() zip_stream = client.get_sdk(rest_api_id, stage=stage_name, sdk_type=sdk_type) tmpdir = tempfile.mkdtemp() with open(os.path.join(tmpdir, 'sdk.zip'), 'wb') as f: f.write(zip_stream.read()) tmp_extract = os.path.join(tmpdir, 'extracted') with zipfile.ZipFile(os.path.join(tmpdir, 'sdk.zip')) as z: z.extractall(tmp_extract) # The extract zip dir will have a single directory: # ['apiGateway-js-sdk'] dirnames = os.listdir(tmp_extract) if len(dirnames) == 1: full_dirname = os.path.join(tmp_extract, dirnames[0]) if os.path.isdir(full_dirname): final_dirname = '%s-js-sdk' % config.app_name full_renamed_name = os.path.join(tmp_extract, final_dirname) os.rename(full_dirname, full_renamed_name) shutil.move(full_renamed_name, outdir) return click.echo("The downloaded SDK had an unexpected directory structure: %s" % (', '.join(dirnames))) raise click.Abort()
def test_update_function_code(stubbed_session): stubbed_session.stub('lambda').update_function_code( FunctionName='name', ZipFile=b'foo').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function_code('name', b'foo') stubbed_session.verify_stubs()
def test_delete_resource_for_api(stubbed_session): stubbed_session.stub('apigateway').delete_resource( restApiId='api_id', resourceId='resource_id').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.delete_resource_for_api('api_id', 'resource_id') stubbed_session.verify_stubs()
def test_create_function_is_retried_and_succeeds(self, stubbed_session): kwargs = { 'FunctionName': 'name', 'Runtime': 'python2.7', 'Code': {'ZipFile': b'foo'}, 'Handler': 'app.app', 'Role': 'myarn', } stubbed_session.stub('lambda').create_function( **kwargs).raises_error( error_code='InvalidParameterValueException', message=('The role defined for the function cannot ' 'be assumed by Lambda.')) stubbed_session.stub('lambda').create_function( **kwargs).raises_error( error_code='InvalidParameterValueException', message=('The role defined for the function cannot ' 'be assumed by Lambda.')) stubbed_session.stub('lambda').create_function( **kwargs).returns({'FunctionArn': 'arn:12345:name'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) assert awsclient.create_function( 'name', 'myarn', b'foo', 'python2.7', 'app.app') == 'arn:12345:name' stubbed_session.verify_stubs()
def test_update_function_is_retried_and_succeeds(self, stubbed_session): stubbed_session.stub('lambda').update_function_code( FunctionName='name', ZipFile=b'foo').returns( {'FunctionArn': 'arn'}) update_config_kwargs = { 'FunctionName': 'name', 'Role': 'role-arn' } # This should fail two times with retryable exceptions and # then succeed to update the lambda function. stubbed_session.stub('lambda').update_function_configuration( **update_config_kwargs).raises_error( error_code='InvalidParameterValueException', message=('The role defined for the function cannot ' 'be assumed by Lambda.')) stubbed_session.stub('lambda').update_function_configuration( **update_config_kwargs).raises_error( error_code='InvalidParameterValueException', message=('The role defined for the function cannot ' 'be assumed by Lambda.')) stubbed_session.stub('lambda').update_function_configuration( **update_config_kwargs).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) awsclient.update_function('name', b'foo', role_arn='role-arn') stubbed_session.verify_stubs()
def test_can_delete_role_policy(self, stubbed_session): stubbed_session.stub('iam').delete_role_policy( RoleName='myrole', PolicyName='mypolicy' ).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.delete_role_policy('myrole', 'mypolicy') stubbed_session.verify_stubs()
def test_can_add_permission_for_apigateway_not_needed(self, stubbed_session): source_arn = 'arn:aws:execute-api:us-west-2:123:rest-api-id/*' wrong_action = { 'Action': 'lambda:NotInvoke', 'Condition': { 'ArnLike': { 'AWS:SourceArn': source_arn, } }, 'Effect': 'Allow', 'Principal': {'Service': 'apigateway.amazonaws.com'}, 'Resource': 'arn:aws:lambda:us-west-2:account_id:function:name', 'Sid': 'e4755709-067e-4254-b6ec-e7f9639e6f7b', } wrong_service_name = { 'Action': 'lambda:Invoke', 'Condition': { 'ArnLike': { 'AWS:SourceArn': source_arn, } }, 'Effect': 'Allow', 'Principal': {'Service': 'NOT-apigateway.amazonaws.com'}, 'Resource': 'arn:aws:lambda:us-west-2:account_id:function:name', 'Sid': 'e4755709-067e-4254-b6ec-e7f9639e6f7b', } correct_statement = { 'Action': 'lambda:InvokeFunction', 'Condition': { 'ArnLike': { 'AWS:SourceArn': source_arn, } }, 'Effect': 'Allow', 'Principal': {'Service': 'apigateway.amazonaws.com'}, 'Resource': 'arn:aws:lambda:us-west-2:account_id:function:name', 'Sid': 'e4755709-067e-4254-b6ec-e7f9639e6f7b', } policy = { 'Id': 'default', 'Statement': [ wrong_action, wrong_service_name, correct_statement, ], 'Version': '2012-10-17' } stubbed_session.stub('lambda').get_policy( FunctionName='name').returns({'Policy': json.dumps(policy)}) # Because the policy above indicates that API gateway already has the # necessary permissions, we should not call add_permission. stubbed_session.activate_stubs() client = TypedAWSClient(stubbed_session) client.add_permission_for_apigateway_if_needed( 'name', 'us-west-2', '123', 'rest-api-id', 'random-id') stubbed_session.verify_stubs()
def test_unexpected_error_is_propagated(self, stubbed_session): stubbed_session.stub('iam').get_role(RoleName='Yes').raises_error( error_code='InternalError', message='Foo') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(botocore.exceptions.ClientError): awsclient.get_role_arn_for_name(name='Yes') stubbed_session.verify_stubs()
def test_get_role_raises_exception_when_no_exists(self, stubbed_session): stubbed_session.stub('iam').get_role(RoleName='Yes').raises_error( error_code='NoSuchEntity', message='Foo') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(ResourceDoesNotExistError): awsclient.get_role(name='Yes') stubbed_session.verify_stubs()
def test_deploy_rest_api(stubbed_session): stub_client = stubbed_session.stub('apigateway') stub_client.create_deployment( restApiId='api_id', stageName='stage').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.deploy_rest_api('api_id', 'stage') stubbed_session.verify_stubs()
def test_got_role_arn_not_found_raises_value_error(self, stubbed_session): stubbed_session.stub('iam').get_role(RoleName='Yes').raises_error( error_code='NoSuchEntity', message='Foo') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(ValueError): awsclient.get_role_arn_for_name(name='Yes') 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_lambda_delete_function_already_deleted(self, stubbed_session): stubbed_session.stub('lambda')\ .delete_function(FunctionName='name')\ .raises_error(error_code='ResourceNotFoundException', message='Unknown') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(ResourceDoesNotExistError): assert awsclient.delete_function('name')
def test_rest_api_delete_already_deleted(self, stubbed_session): stubbed_session.stub('apigateway')\ .delete_rest_api(restApiId='name')\ .raises_error(error_code='NotFoundException', message='Unknown') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(ResourceDoesNotExistError): assert awsclient.delete_rest_api('name')
def test_can_connect_rule_to_lambda(stubbed_session): events = stubbed_session.stub('events') events.put_targets( Rule='rule-name', Targets=[{'Id': '1', 'Arn': 'function-arn'}]).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.connect_rule_to_lambda('rule-name', 'function-arn') stubbed_session.verify_stubs()
def test_can_query_lambda_function_exists(self, stubbed_session): stubbed_session.stub('lambda').get_function(FunctionName='myappname')\ .returns({'Code': {}, 'Configuration': {}}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.lambda_function_exists(name='myappname') stubbed_session.verify_stubs()
def test_can_add_permission_for_apigateway_needed(self, stubbed_session): # An empty policy means we need to add permissions. lambda_stub = stubbed_session.stub('lambda') lambda_stub.get_policy(FunctionName='name').returns({'Policy': '{}'}) self.should_call_add_permission(lambda_stub) stubbed_session.activate_stubs() client = TypedAWSClient(stubbed_session) client.add_permission_for_apigateway_if_needed( 'name', 'us-west-2', '123', 'rest-api-id', 'random-id') stubbed_session.verify_stubs()
def test_update_function_code_with_timeout(self, stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code( FunctionName='name', ZipFile=b'foo').returns({}) lambda_client.update_function_configuration( FunctionName='name', Timeout=240).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', timeout=240) stubbed_session.verify_stubs()
def test_update_function_code_with_memory(self, stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code( FunctionName='name', ZipFile=b'foo').returns({}) lambda_client.update_function_configuration( FunctionName='name', MemorySize=256).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', memory_size=256) 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()
def test_can_delete_rule(stubbed_session): events = stubbed_session.stub('events') events.remove_targets( Rule='rule-name', Ids=['1']).returns({}) events.delete_rule(Name='rule-name').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.delete_rule('rule-name') stubbed_session.verify_stubs()
def test_raises_large_deployment_error_request_entity_to_large( self, stubbed_session): stubbed_session.stub('lambda').update_function_code( FunctionName='name', ZipFile=b'foo').raises_error( error_code='RequestEntityTooLargeException', message='') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) with pytest.raises(DeploymentPackageTooLargeError): awsclient.update_function('name', b'foo') stubbed_session.verify_stubs()
def test_raises_large_deployment_error_for_too_large_unzip( self, stubbed_session): stubbed_session.stub('lambda').update_function_code( FunctionName='name', ZipFile=b'foo').raises_error( error_code='InvalidParameterValueException', message='Unzipped size must be smaller than ...') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) with pytest.raises(DeploymentPackageTooLargeError): awsclient.update_function('name', b'foo') stubbed_session.verify_stubs()
def test_can_query_lambda_function_does_not_exist(self, stubbed_session): stubbed_session.stub('lambda').get_function(FunctionName='myappname')\ .raises_error(error_code='ResourceNotFoundException', message='ResourceNotFound') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert not awsclient.lambda_function_exists(name='myappname') stubbed_session.verify_stubs()
def test_put_role_policy(stubbed_session): stubbed_session.stub('iam').put_role_policy(RoleName='role_name', PolicyName='policy_name', PolicyDocument=json.dumps( {'foo': 'bar'}, indent=2)).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.put_role_policy('role_name', 'policy_name', {'foo': 'bar'}) stubbed_session.verify_stubs()
def test_rest_api_does_not_exist(self, stubbed_session): stubbed_session.stub('apigateway').get_rest_apis()\ .returns( {'items': [ {'createdDate': 1, 'id': 'wrongid1', 'name': 'wrong1'}, {'createdDate': 2, 'id': 'wrongid1', 'name': 'wrong2'}, {'createdDate': 3, 'id': 'wrongid3', 'name': 'wrong3'}, ]}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.get_rest_api_id('myappname') is None stubbed_session.verify_stubs()
def test_lambda_function_bad_error_propagates(self, stubbed_session): stubbed_session.stub('lambda').get_function(FunctionName='myappname')\ .raises_error(error_code='UnexpectedError', message='Unknown') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) with pytest.raises(botocore.exceptions.ClientError): awsclient.lambda_function_exists(name='myappname') stubbed_session.verify_stubs()
def test_get_sdk(self, stubbed_session): apig = stubbed_session.stub('apigateway') apig.get_sdk( restApiId='rest-api-id', stageName='dev', sdkType='javascript').returns({'body': 'foo'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) response = awsclient.get_sdk_download_stream( 'rest-api-id', 'dev', 'javascript') stubbed_session.verify_stubs() assert response == 'foo'
def url(ctx): # type: (click.Context) -> None config = create_config_obj(ctx) session = create_botocore_session(profile=config.profile, debug=ctx.obj['debug']) c = TypedAWSClient(session) rest_api_id = c.get_rest_api_id(config.app_name) stage_name = config.stage region_name = c.region_name click.echo( "https://{api_id}.execute-api.{region}.amazonaws.com/{stage}/".format( api_id=rest_api_id, region=region_name, stage=stage_name))
def test_update_api_from_swagger(self, stubbed_session): apig = stubbed_session.stub('apigateway') swagger_doc = {'swagger': 'doc'} apig.put_rest_api(restApiId='rest_api_id', mode='overwrite', body=json.dumps(swagger_doc, indent=2)).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_api_from_swagger('rest_api_id', swagger_doc) stubbed_session.verify_stubs()
def test_import_rest_api(self, stubbed_session): apig = stubbed_session.stub('apigateway') swagger_doc = {'swagger': 'doc'} apig.import_rest_api( body=json.dumps(swagger_doc, indent=2)).returns( {'id': 'rest_api_id'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) rest_api_id = awsclient.import_rest_api(swagger_doc) stubbed_session.verify_stubs() assert rest_api_id == 'rest_api_id'
def test_update_function_code_with_environment_vars(self, stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code( FunctionName='name', ZipFile=b'foo').returns({}) lambda_client.update_function_configuration( FunctionName='name', Environment={'Variables': {"FOO": "BAR"}}).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function( 'name', b'foo', {"FOO": "BAR"}) stubbed_session.verify_stubs()
def test_rest_api_exists(self, stubbed_session): desired_name = 'myappname' stubbed_session.stub('apigateway').get_rest_apis()\ .returns( {'items': [ {'createdDate': 1, 'id': 'wrongid1', 'name': 'wrong1'}, {'createdDate': 2, 'id': 'correct', 'name': desired_name}, {'createdDate': 3, 'id': 'wrongid3', 'name': 'wrong3'}, ]}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.get_rest_api_id(desired_name) == 'correct' stubbed_session.verify_stubs()
def test_can_pass_python_runtime(self, stubbed_session): stubbed_session.stub('lambda').create_function( FunctionName='name', Runtime='python3.6', Code={'ZipFile': b'foo'}, Handler='app.app', Role='myarn', ).returns({'FunctionArn': 'arn:12345:name'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.create_function( 'name', 'myarn', b'foo', runtime='python3.6') == 'arn:12345:name' stubbed_session.verify_stubs()
def test_can_get_function_configuration(stubbed_session): stubbed_session.stub('lambda').get_function_configuration( FunctionName='myfunction', ).returns({ "FunctionName": "myfunction", "MemorySize": 128, "Handler": "app.app", "Runtime": "python3.6", }) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert (awsclient.get_function_configuration('myfunction')['Runtime'] == 'python3.6')
def test_can_add_permission_when_policy_does_not_exist(self, stubbed_session): # It's also possible to receive a ResourceNotFoundException # if you call get_policy() on a lambda function with no policy. lambda_stub = stubbed_session.stub('lambda') lambda_stub.get_policy(FunctionName='name').raises_error( error_code='ResourceNotFoundException', message='Does not exist.') self.should_call_add_permission(lambda_stub) stubbed_session.activate_stubs() client = TypedAWSClient(stubbed_session) client.add_permission_for_apigateway_if_needed( 'name', 'us-west-2', '123', 'rest-api-id', 'random-id') stubbed_session.verify_stubs()
def test_can_get_or_create_rule_arn(stubbed_session): events = stubbed_session.stub('events') events.put_rule( Name='rule-name', ScheduleExpression='rate(1 hour)').returns({ 'RuleArn': 'rule-arn', }) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) result = awsclient.get_or_create_rule_arn('rule-name', 'rate(1 hour)') stubbed_session.verify_stubs() assert result == 'rule-arn'
def test_no_raise_large_deployment_error_when_small_deployment_size( self, stubbed_session): stubbed_session.stub('lambda').update_function_code( FunctionName='name', ZipFile=b'foo').raises_error( error=RequestsConnectionError()) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) with pytest.raises(LambdaClientError) as excinfo: awsclient.update_function('name', b'foo') stubbed_session.verify_stubs() assert not isinstance(excinfo.value, DeploymentPackageTooLargeError) assert isinstance( excinfo.value.original_error, RequestsConnectionError)
def generate_sdk(ctx, sdk_type, outdir): # type: (click.Context, str, str) -> None config = create_config_obj(ctx) session = create_botocore_session(profile=config.profile, debug=ctx.obj['debug']) client = TypedAWSClient(session) rest_api_id = client.get_rest_api_id(config.app_name) stage_name = config.stage if rest_api_id is None: click.echo("Could not find API ID, has this application " "been deployed?") raise click.Abort() client.download_sdk(rest_api_id, outdir, stage=stage_name, sdk_type=sdk_type)
def test_create_function_succeeds_first_try(self, stubbed_session): stubbed_session.stub('lambda').create_function( FunctionName='name', Runtime='python2.7', Code={'ZipFile': b'foo'}, Handler='app.app', Role='myarn', Timeout=60, ).returns({'FunctionArn': 'arn:12345:name'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.create_function( 'name', 'myarn', b'foo') == 'arn:12345:name' stubbed_session.verify_stubs()
def test_update_function_with_no_tag_updates_needed(self, stubbed_session): function_arn = 'arn' lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code( FunctionName='name', ZipFile=b'foo').returns( {'FunctionArn': function_arn}) lambda_client.list_tags( Resource=function_arn).returns({'Tags': {'MyKey': 'SameValue'}}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', tags={'MyKey': 'SameValue'}) stubbed_session.verify_stubs()
def test_delete_methods_from_root_resource(stubbed_session): resource_methods = { 'GET': 'foo', } stubbed_session.stub('apigateway').delete_method( restApiId='rest_api_id', resourceId='resource_id', httpMethod='GET').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.delete_methods_from_root_resource( 'rest_api_id', {'resourceMethods': resource_methods, 'id': 'resource_id'}) stubbed_session.verify_stubs()
def test_always_update_function_code(stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code(FunctionName='name', ZipFile=b'foo').returns({}) # Even if there's only a code change, we'll always call # update_function_configuration. lambda_client.update_function_configuration(FunctionName='name', Environment={ 'Variables': {} }).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo') stubbed_session.verify_stubs()
def test_no_runtime_arg_is_not_added_to_kwargs(stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code(FunctionName='name', ZipFile=b'foo').returns({}) lambda_client.update_function_configuration(FunctionName='name', Environment={ 'Variables': { "FOO": "BAR" } }).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', {"FOO": "BAR"}) stubbed_session.verify_stubs()
def __init__(self, config: Optional[Config], session: Optional[Session] = None): if session: self.client = TypedAWSClient(session) else: self.client = None self.layer_cache = {} self.layer_cache_dirty = False if config: self.load_layer_cache() self.download_layers(config.layers) self.write_layer_cache() if config.layers and os.path.exists('.opt/python'): sys.path.append('.opt/python')
def test_update_function_with_iam_role(self, stubbed_session): function_arn = 'arn' lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code( FunctionName='name', ZipFile=b'foo').returns( {'FunctionArn': function_arn}) lambda_client.update_function_configuration( FunctionName='name', Role='role-arn').returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', role_arn='role-arn') stubbed_session.verify_stubs()
def test_update_function_code_and_deploy(stubbed_session): lambda_client = stubbed_session.stub('lambda') lambda_client.update_function_code(FunctionName='name', ZipFile=b'foo').returns({}) lambda_client.update_function_configuration(FunctionName='name', Runtime='python3.6', Environment={ 'Variables': { "FOO": "BAR" } }).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.update_function('name', b'foo', {"FOO": "BAR"}, 'python3.6') stubbed_session.verify_stubs()
def test_create_function_with_environment_variables(self, stubbed_session): stubbed_session.stub('lambda').create_function( FunctionName='name', Runtime='python2.7', Code={'ZipFile': b'foo'}, Handler='app.app', Role='myarn', Environment={'Variables': {'FOO': 'BAR'}} ).returns({'FunctionArn': 'arn:12345:name'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.create_function( 'name', 'myarn', b'foo', 'python2.7', environment_variables={'FOO': 'BAR'}) == 'arn:12345:name' stubbed_session.verify_stubs()
def test_create_function_with_memory_size(self, stubbed_session): stubbed_session.stub('lambda').create_function( FunctionName='name', Runtime='python2.7', Code={'ZipFile': b'foo'}, Handler='app.app', Role='myarn', MemorySize=256 ).returns({'FunctionArn': 'arn:12345:name'}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) assert awsclient.create_function( 'name', 'myarn', b'foo', 'python2.7', memory_size=256) == 'arn:12345:name' stubbed_session.verify_stubs()
def create_lambda_invoke_handler(self, name, stage): # type: (str, str) -> LambdaInvokeHandler config = self.create_config_obj(stage) deployed = config.deployed_resources(stage) try: resource = deployed.resource_values(name) arn = resource['lambda_arn'] except (KeyError, ValueError): raise NoSuchFunctionError(name) function_scoped_config = config.scope(stage, name) # The session for max retries needs to be set to 0 for invoking a # lambda function because in the case of a timeout or other retriable # error the underlying client will call the function again. session = self.create_botocore_session( read_timeout=function_scoped_config.lambda_timeout, max_retries=0, ) client = TypedAWSClient(session) invoker = LambdaInvoker(arn, client) handler = LambdaInvokeHandler( invoker, LambdaResponseFormatter(), UI(), ) return handler
def test_get_resources_for_api(stubbed_session): expected = { 'id': 'id', 'parentId': 'parentId', 'pathPart': '/foo', 'path': '/foo', 'resourceMethods': {}, } stubbed_session.stub('apigateway').get_resources( restApiId='rest_api_id').returns({'items': [expected]}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) result = awsclient.get_resources_for_api('rest_api_id') assert result == [expected] stubbed_session.verify_stubs()
def test_can_add_permission_for_apigateway_not_needed( self, stubbed_session): source_arn = 'arn:aws:execute-api:us-west-2:123:rest-api-id/*' policy = { 'Id': 'default', 'Statement': [{ 'Action': 'lambda:InvokeFunction', 'Condition': { 'ArnLike': { 'AWS:SourceArn': source_arn, } }, 'Effect': 'Allow', 'Principal': { 'Service': 'apigateway.amazonaws.com' }, 'Resource': 'arn:aws:lambda:us-west-2:account_id:function:name', 'Sid': 'e4755709-067e-4254-b6ec-e7f9639e6f7b' }], 'Version': '2012-10-17' } stubbed_session.stub('lambda').get_policy(FunctionName='name').returns( {'Policy': json.dumps(policy)}) # Because the policy above indicates that API gateway already has the # necessary permissions, we should not call add_permission. stubbed_session.activate_stubs() TypedAWSClient( stubbed_session).add_permission_for_apigateway_if_needed( 'name', 'us-west-2', '123', 'rest-api-id', 'random-id') stubbed_session.verify_stubs()
def test_create_function_propagates_unknown_error(self, stubbed_session): kwargs = { 'FunctionName': 'name', 'Runtime': 'python2.7', 'Code': {'ZipFile': b'foo'}, 'Handler': 'app.app', 'Role': 'myarn', } stubbed_session.stub('lambda').create_function( **kwargs).raises_error( error_code='UnknownException', message='') stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session, mock.Mock(spec=time.sleep)) with pytest.raises(botocore.exceptions.ClientError): awsclient.create_function('name', 'myarn', b'foo', 'pytohn2.7') stubbed_session.verify_stubs()
def test_can_delete_role(self, stubbed_session): stubbed_session.stub('iam').list_role_policies( RoleName='myrole').returns({ 'PolicyNames': ['mypolicy'] }) stubbed_session.stub('iam').delete_role_policy( RoleName='myrole', PolicyName='mypolicy').returns({}) stubbed_session.stub('iam').delete_role( RoleName='myrole' ).returns({}) stubbed_session.activate_stubs() awsclient = TypedAWSClient(stubbed_session) awsclient.delete_role('myrole') stubbed_session.verify_stubs()