Ejemplo n.º 1
0
    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()
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
 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()
     TypedAWSClient(stubbed_session).add_permission_for_apigateway_if_needed(
         'name', 'us-west-2', '123', 'rest-api-id', 'random-id')
     stubbed_session.verify_stubs()
Ejemplo n.º 4
0
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))
Ejemplo n.º 5
0
    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()
Ejemplo n.º 6
0
 def create_log_retriever(self, session, lambda_arn, follow_logs):
     # type: (Session, str, bool) -> LogRetriever
     client = TypedAWSClient(session)
     if follow_logs:
         event_generator = cast(BaseLogEventGenerator,
                                FollowLogEventGenerator(client))
     else:
         event_generator = cast(BaseLogEventGenerator,
                                LogEventGenerator(client))
     retriever = LogRetriever.create_from_lambda_arn(event_generator,
                                                     lambda_arn)
     return retriever
Ejemplo n.º 7
0
 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()
Ejemplo n.º 8
0
 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'
Ejemplo n.º 9
0
    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'
Ejemplo n.º 10
0
 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()
Ejemplo n.º 11
0
 def test_can_add_permission_for_apigateway(self, stubbed_session):
     stubbed_session.stub('lambda').add_permission(
         Action='lambda:InvokeFunction',
         FunctionName='function_name',
         StatementId='random-id',
         Principal='apigateway.amazonaws.com',
         SourceArn='arn:aws:execute-api:us-west-2:123:rest-api-id/*',
     ).returns({})
     stubbed_session.activate_stubs()
     TypedAWSClient(stubbed_session).add_permission_for_apigateway(
         'function_name', 'us-west-2', '123', 'rest-api-id', 'random-id')
     stubbed_session.verify_stubs()
Ejemplo n.º 12
0
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()
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
0
 def test_invoke_does_forward_payload(self, stubbed_session):
     arn = 'arn:aws:lambda:region:id:function:name-dev'
     stubbed_session.stub('lambda').invoke(
         FunctionName=arn,
         InvocationType='RequestResponse',
         Payload=b'foobar',
     ).returns({})
     stubbed_session.activate_stubs()
     client = TypedAWSClient(stubbed_session)
     invoker = LambdaInvoker(arn, client)
     invoker.invoke(b'foobar')
     stubbed_session.verify_stubs()
Ejemplo n.º 15
0
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')
Ejemplo n.º 16
0
 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()
Ejemplo n.º 17
0
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'
Ejemplo n.º 18
0
def create_default_deployer(session, prompter=None):
    # type: (botocore.session.Session, NoPrompt) -> Deployer
    if prompter is None:
        prompter = NoPrompt()
    aws_client = TypedAWSClient(session)
    api_gateway_deploy = APIGatewayDeployer(aws_client)

    osutils = OSUtils()
    packager = LambdaDeploymentPackager(osutils=osutils)
    lambda_deploy = LambdaDeployer(
        aws_client, packager, prompter, osutils,
        ApplicationPolicyHandler(osutils, AppPolicyGenerator(osutils)))
    return Deployer(api_gateway_deploy, lambda_deploy)
Ejemplo n.º 19
0
def test_will_create_outdir_if_needed(tmpdir, stubbed_session):
    appdir = _create_app_structure(tmpdir)
    outdir = str(appdir.join('outdir'))
    default_params = {'autogen_policy': True}
    config = Config.create(project_dir=str(appdir),
                           chalice_app=sample_app(),
                           **default_params)
    options = PackageOptions(TypedAWSClient(session=stubbed_session))
    p = package.create_app_packager(config, options)
    p.package_app(config, str(outdir), 'dev')
    contents = os.listdir(str(outdir))
    assert 'deployment.zip' in contents
    assert 'sam.json' in contents
Ejemplo n.º 20
0
 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()
Ejemplo n.º 21
0
def create_default_deployer(session, prompter=None):
    # type: (botocore.session.Session, NoPrompt) -> Deployer
    if prompter is None:
        prompter = NoPrompt()
    aws_client = TypedAWSClient(session)
    api_gateway_deploy = APIGatewayDeployer(
        aws_client, session.create_client('apigateway'),
        session.create_client('lambda'))

    packager = LambdaDeploymentPackager()
    osutils = OSUtils()
    lambda_deploy = LambdaDeployer(aws_client, packager, prompter, osutils)
    return Deployer(api_gateway_deploy, lambda_deploy)
Ejemplo n.º 22
0
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()
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
    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()
Ejemplo n.º 26
0
 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()
Ejemplo n.º 27
0
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()
Ejemplo n.º 28
0
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()
Ejemplo n.º 29
0
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()
Ejemplo n.º 30
0
def test_can_specify_yaml_output(tmpdir, stubbed_session):
    appdir = _create_app_structure(tmpdir)

    outdir = tmpdir.mkdir('outdir')
    default_params = {'autogen_policy': True}
    config = Config.create(project_dir=str(appdir),
                           chalice_app=sample_app(),
                           **default_params)
    options = PackageOptions(TypedAWSClient(session=stubbed_session))
    p = package.create_app_packager(config, options, template_format='yaml')

    p.package_app(config, str(outdir), 'dev')
    contents = os.listdir(str(outdir))
    assert 'deployment.zip' in contents
    assert 'sam.yaml' in contents