Exemplo n.º 1
0
    def test_add_parameter_resource_output(self):
        from troposphere_mate import apigateway

        tpl = Template()
        param_project_name = Parameter("ProjectName", Type="String")

        rest_api = apigateway.RestApi(
            "RestApi",
            template=tpl,
            Name=Ref(param_project_name),
            EndpointConfiguration=apigateway.EndpointConfiguration(
                Types=["REGIONAL"]))

        output_rest_api_id = Output("RestApiId", Value=Ref(rest_api))

        # test ignore_duplicate argument
        tpl.add_parameter(param_project_name)
        with raises(ValueError):
            tpl.add_parameter(param_project_name)
        tpl.add_parameter(param_project_name, ignore_duplicate=True)

        with raises(ValueError):
            tpl.add_resource(rest_api)
        tpl.add_resource(rest_api, ignore_duplicate=True)

        tpl.add_output(output_rest_api_id)
        with raises(ValueError):
            tpl.add_output(output_rest_api_id)
        tpl.add_output(output_rest_api_id, ignore_duplicate=True)
Exemplo n.º 2
0
def test_package():
    tpl_tier11 = Template(Metadata={"Description": "Tier 1-1"}, )
    restapi = apigateway.RestApi(
        "RestApi",
        template=tpl_tier11,
        Name="troposphere-mate-test",
    )

    tpl_tier1 = Template(Metadata={"Description": "Tier 1"}, )
    nest_stack_tier11 = cloudformation.Stack(
        "NestedTemplate",
        template=tpl_tier1,
        TemplateURL="",
    )
    link_stack_template(
        stack=nest_stack_tier11,
        template=tpl_tier11,
    )

    tpl_master = Template(Metadata={"Description": "Master Tier"}, )
    nest_stack_tier1 = cloudformation.Stack(
        "NestedTemplate",
        template=tpl_master,
        TemplateURL="",
    )
    link_stack_template(
        stack=nest_stack_tier1,
        template=tpl_tier1,
    )

    template_url = package(s3_client=s3_client,
                           template=tpl_master,
                           bucket_name=bucket_name,
                           verbose=True)
    print(template_url)
def test_property_method():
    """
    If the resource is RestApi, then the ``.iam_role_arn`` property method
    should not be called.
    """
    rest_api = apigateway.RestApi("RestApi", Name="my-test-api")
    _ = rest_api.apigw_restapi_id

    with pytest.raises(TypeError):
        _ = rest_api.iam_role_arn
Exemplo n.º 4
0
def test_deploy_stack():
    # tier11
    tpl_tier11 = Template(Metadata={"Description": "Tier 1-1"}, )
    restapi = apigateway.RestApi(
        "RestApi",
        template=tpl_tier11,
        Name="troposphere-mate-test",
    )

    # tier1
    tpl_tier1 = Template(Metadata={"Description": "Tier 1"}, )
    nest_stack_tier11 = cloudformation.Stack(
        "NestedStackTier11",
        template=tpl_tier1,
        TemplateURL="",
    )

    # link
    link_stack_template(
        stack=nest_stack_tier11,
        template=tpl_tier11,
    )

    # master
    tpl_master = Template(Metadata={"Description": "Master Tier"}, )
    nest_stack_tier1 = cloudformation.Stack(
        "NestedStackTier1",
        template=tpl_master,
        TemplateURL="",
    )

    link_stack_template(
        stack=nest_stack_tier1,
        template=tpl_tier1,
    )

    stack_manager = StackManager(
        boto_ses=boto_ses,
        cft_bucket=bucket_name,
    )
    stack_manager.deploy(template=tpl_master, )

    template_url = package(s3_client=s3_client,
                           template=tpl_master,
                           bucket_name=bucket_name,
                           verbose=True)

    deploy_stack(
        cf_client=cf_client,
        stack_name="troposphere-mate-stack-deploy-test",
        template_url=template_url,
        stack_tags={"Creator": "Sanhe"},
    )
Exemplo n.º 5
0
    def __init__(self):
        self.tpl = Template()

        self.param_env_name = Parameter("EnvName", Type="String")

        self.rest_api_x = apigateway.RestApi(
            "RestApiX",
            template=self.tpl,
            Name="MyRestApiX",
        )
        self.rest_api_y = apigateway.RestApi(
            "RestApiY",
            template=self.tpl,
            Name="MyRestApiY",
            DependsOn=self.rest_api_x,
        )
        self.rest_api_z = apigateway.RestApi("RestApiZ",
                                             template=self.tpl,
                                             Name="MyRestApiZ",
                                             DependsOn=self.rest_api_y)

        self.output_rest_api_x_id = Output(
            "RestApiXId",
            Value=Ref(self.rest_api_x),
            DependsOn=self.rest_api_x,
        )
        self.tpl.add_output(self.output_rest_api_x_id)
        self.output_rest_api_y_id = Output(
            "RestApiYId",
            Value=Ref(self.rest_api_y),
            DependsOn=self.rest_api_y,
        )
        self.tpl.add_output(self.output_rest_api_y_id)
        self.output_rest_api_z_id = Output(
            "RestApiZId",
            Value=Ref(self.rest_api_z),
            DependsOn=self.rest_api_z,
        )
        self.tpl.add_output(self.output_rest_api_z_id)
Exemplo n.º 6
0
def test_initiate_default_resource_metadata():
    rest_api = apigateway.RestApi("RestApi", Name="MyRestApi")
    mtdt.initiate_default_resource_metadata(rest_api)
    validate_resource_level_basic_fields(rest_api)

    rest_api = apigateway.RestApi("RestApi",
                                  Name="MyRestApi",
                                  Metadata={"Key": "Value"})
    mtdt.initiate_default_resource_metadata(rest_api)
    validate_resource_level_basic_fields(rest_api)
    assert rest_api.Metadata["Key"] == "Value"

    rest_api = apigateway.RestApi(
        "RestApi",
        Name="MyRestApi",
        Metadata={mtdt.TROPOSPHERE_METADATA_FIELD_NAME: {
            "Key": "Value"
        }},
    )
    mtdt.initiate_default_resource_metadata(rest_api)
    validate_resource_level_basic_fields(rest_api)
    assert rest_api.Metadata[
        mtdt.TROPOSPHERE_METADATA_FIELD_NAME]["Key"] == "Value"
Exemplo n.º 7
0
def test_package_with_simple_template():
    template = Template()
    restapi = apigateway.RestApi(
        "RestApi",
        template=template,
        Name="troposphere-mate-test",
    )

    template_url = package(
        s3_client=s3_client,
        template=template,
        bucket_name=bucket_name,
    )

    print(template_url)
Exemplo n.º 8
0
def test_upload_template():
    template = Template()
    restapi = apigateway.RestApi(
        "RestApi",
        template=template,
        Name="troposphere-mate-test",
    )

    template_url = upload_template(
        s3_client=s3_client,
        template_content=template.to_json(indent=4, sort_keys=True),
        bucket_name=bucket_name,
    )

    print(template_url)
Exemplo n.º 9
0
def test_stack_manager():
    """
    First time, run stack_manager.deploy, comment out stack_manager.delete
    Second time, comment out stack_manager.deploy, run stack_manager.delete.
    """
    stack_name = "troposphere-mate-stack-manager-test"
    template = Template()
    apigateway.RestApi(
        "RestApi",
        template=template,
        Name="troposphere-mate-test",
    )
    stack_manager.deploy(
        template,
        stack_name=stack_name,
    )
    def test(self):
        lbd_permission = awslambda.Permission("LbdPermission",
                                              Action="",
                                              FunctionName="",
                                              Principal="")

        lbd_func = awslambda.Function(
            "LbdFunc",
            Code=awslambda.Code(
                S3Bucket="my-bucket",
                S3Key="0.0.1.zip",
            ),
            Handler="my_func.handler",
            Role="arn:aws:iam::111122223333:role/todo",
            Runtime="python3.6")

        authorizer = apigateway.Authorizer(
            "Authorizer",
            Name="MyAuthorizer",
            Type="",
            AuthorizerUri="",
            IdentitySource="",
        )

        rest_api = apigateway.RestApi("RestApi", )

        associate(rest_api,
                  authorizer,
                  lbd_func,
                  lbd_permission,
                  authorizer_type_is_token=True)

        assert lbd_permission.Action == "lambda:InvokeFunction"
        assert isinstance(lbd_permission.FunctionName, GetAtt)
        assert lbd_permission.Principal == "apigateway.amazonaws.com"
        assert isinstance(lbd_permission.SourceArn, Sub)
        assert len(lbd_permission.DependsOn) == 3

        assert authorizer.Type == "TOKEN"
        assert authorizer.IdentitySource == "method.request.header.auth"
        assert isinstance(authorizer.RestApiId, Ref)
        assert isinstance(authorizer.AuthorizerUri, Sub)
        assert len(authorizer.DependsOn) == 2
Exemplo n.º 11
0
    def test_create_resource_type_label(self):
        from troposphere_mate import s3, apigateway
        tpl = Template()
        s3_bucket = s3.Bucket(
            "Bucket",
            template=tpl,
            BucketName="my-bucket",
        )
        rest_api = apigateway.RestApi("RestApi",
                                      template=tpl,
                                      DependsOn=[
                                          s3_bucket,
                                      ])
        tpl.create_resource_type_label()
        tpl.create_resource_type_label()  # see if second call raise exception

        assert len(tpl.to_dict()["Resources"]["Bucket"]["Metadata"]
                   [DEFAULT_LABELS_FIELD]) == 1
        assert len(tpl.to_dict()["Resources"]["RestApi"]["Metadata"]
                   [DEFAULT_LABELS_FIELD]) == 1
Exemplo n.º 12
0
def test_is_x_depends_on_y():
    res1 = apigateway.RestApi("Res1", Name="MyRestApi1")
    res2 = apigateway.RestApi("Res2", Name="MyRestApi2", DependsOn=res1)
    assert is_x_depends_on_y(res1, res2) is False
    assert is_x_depends_on_y(res2, res1) is True

    res1 = apigateway.RestApi("Res1", Name="MyRestApi1")
    res2 = apigateway.RestApi("Res2", Name="MyRestApi2", DependsOn=[
        res1,
    ])
    assert is_x_depends_on_y(res1, res2) is False
    assert is_x_depends_on_y(res2, res1) is True

    res1 = apigateway.RestApi("Res1", Name="MyRestApi1")
    res2 = apigateway.RestApi("Res2", Name="MyRestApi2")
    assert is_x_depends_on_y(res1, res2) is False
    assert is_x_depends_on_y(res2, res1) is False

    res1 = apigateway.RestApi("Res1", Name="MyRestApi1")
    res2 = apigateway.RestApi("Res2", Name="MyRestApi2", DependsOn=set())
    assert is_x_depends_on_y(res1, res2) is False
    assert is_x_depends_on_y(res2, res1) is False
Exemplo n.º 13
0
    def test_init(self):
        rest_api = apigateway.RestApi("RestApi", Name="MyRestApi")
        output_rest_api_id = Output(
            "RestApiId",
            Value=Ref(rest_api),
            DependsOn=rest_api,
        )
        assert output_rest_api_id.depends_on_resources == [
            "RestApi",
        ]

        output_rest_api_id = Output(
            "RestApiId",
            Value=Ref(rest_api),
            DependsOn=[
                rest_api,
            ],
        )
        assert output_rest_api_id.depends_on_resources == [
            "RestApi",
        ]
Exemplo n.º 14
0
    def test_iter_nested_template(self):
        from troposphere_mate import apigateway, cloudformation, link_stack_template

        tpl_1_1 = Template(Metadata={"id": "11"})
        apigateway.RestApi("RestApi", template=tpl_1_1, Name="MyRestApi")

        tpl_1_2 = Template(Metadata={"id": "12"})
        apigateway.RestApi("RestApi", template=tpl_1_2, Name="MyRestApi")

        tpl_2_1 = Template(Metadata={"id": "21"})
        apigateway.RestApi("RestApi", template=tpl_2_1, Name="MyRestApi")

        tpl_2_2 = Template(Metadata={"id": "22"})
        apigateway.RestApi("RestApi", template=tpl_2_2, Name="MyRestApi")

        tpl_1 = Template(Metadata={"id": "1"})
        stack11 = cloudformation.Stack(
            "Stack11",
            template=tpl_1,
            TemplateURL="",
        )
        stack12 = cloudformation.Stack(
            "Stack12",
            template=tpl_1,
            TemplateURL="",
        )
        link_stack_template(stack=stack11, template=tpl_1_1)
        link_stack_template(stack=stack12, template=tpl_1_2)

        tpl_2 = Template(Metadata={"id": "2"})
        stack21 = cloudformation.Stack(
            "Stack21",
            template=tpl_2,
            TemplateURL="",
        )
        stack22 = cloudformation.Stack(
            "Stack22",
            template=tpl_2,
            TemplateURL="",
        )
        link_stack_template(stack=stack21, template=tpl_2_1)
        link_stack_template(stack=stack22, template=tpl_2_2)

        tpl = Template(Metadata={"id": "0"})
        stack1 = cloudformation.Stack(
            "Stack1",
            template=tpl,
            TemplateURL="",
        )
        stack2 = cloudformation.Stack(
            "Stack2",
            template=tpl,
            TemplateURL="",
        )
        link_stack_template(stack=stack1, template=tpl_1)
        link_stack_template(stack=stack2, template=tpl_2)

        assert stack1.Metadata[mtdt.TROPOSPHERE_METADATA_FIELD_NAME] \
                   [mtdt.ResourceLevelField.CftStack.IS_NESTED_STACK] is True
        assert stack2.Metadata[mtdt.TROPOSPHERE_METADATA_FIELD_NAME] \
                   [mtdt.ResourceLevelField.CftStack.IS_NESTED_STACK] is True

        import sys
        if sys.version_info.major >= 3:
            ids = [
                template.metadata["id"]
                for template in tpl.iter_nested_template(depth_first=True)
            ]
            assert ids == ["1", "11", "12", "2", "21", "22"]

            ids = [
                template.metadata["id"]
                for template in tpl.iter_nested_template(depth_first=False)
            ]
            assert ids == ["1", "2", "11", "12", "21", "22"]
Exemplo n.º 15
0
# -*- coding: utf-8 -*-

import pytest
from troposphere import Ref, GetAtt, Sub

from troposphere_mate import awslambda, apigateway, mtdt
from troposphere_mate.associate import LinkerApi, associate

rest_api = apigateway.RestApi("RestApi")


class TestApiResourceWithRestApi(object):
    linker = LinkerApi.ApiResourceWithRestApi

    def test(self):
        api_resource = apigateway.Resource(
            "ApiResource",
            ParentId="",
            PathPart="users",
            RestApiId="",
        )
        associate(api_resource, rest_api, has_parent_resource=False)
        assert isinstance(api_resource.RestApiId, Ref)
        assert isinstance(api_resource.ParentId, GetAtt)
        assert api_resource.Metadata[mtdt.TROPOSPHERE_METADATA_FIELD_NAME][
            mtdt.ResourceLevelField.ApiResource.FULL_PATH] == "users"


class TestApiResourceWithParentApiResource(object):
    linker = LinkerApi.ApiResourceWithParentApiResource
Exemplo n.º 16
0
from troposphere_mate import apigateway, awslambda, iam
from troposphere_mate.canned.iam import AWSManagedPolicyArn, AWSServiceName, create_assume_role_policy_document
from .app_config_init import app_config

template = tm.Template()

param_env_name = tm.Parameter(
    "EnvironmentName",
    Type="String",
)
template.add_parameter(param_env_name)

rest_api = apigateway.RestApi(
    "RestApi",
    template=template,
    Name=tm.helper_fn_sub("{}", param_env_name),
    EndpointConfiguration=apigateway.EndpointConfiguration(Types=[
        "REGIONAL",
    ]))

lambda_code = awslambda.Code(
    S3Bucket=app_config.LAMBDA_CODE_S3_BUCKET.get_value(),
    S3Key=app_config.LAMBDA_CODE_S3_KEY.get_value(),
)

iam_role = iam.Role(
    "IamRoleForLbdFunc",
    template=template,
    RoleName=tm.helper_fn_sub("{}-lbd-func", param_env_name),
    AssumeRolePolicyDocument=create_assume_role_policy_document(
        [AWSServiceName.aws_Lambda]),