简体   繁体   中英

How to unit test multiple AWS Lambda functions in CDK?

I want to use CDK's built-in assertions to test multiple lambda functions in my stack. So far I was able to test only one lambda function.

def test_lambda_function():
app = core.App()
stack = RadBackendStack(app, "rad-backend")
template = assertions.Template.from_stack(stack)
print(template)
template.has_resource_properties("AWS::Lambda::Function", {
    "Architectures": ["arm64"],
    "Runtime": "python3.8",
    "Timeout": 1
})

This is the lambda testing function I wrote. And I expect it to test all the lambda functions in my stack.

self._lambda = _lambda.Function(
        self,
        "test_function",
        code=_lambda.AssetCode.from_asset('src'),
        handler="lambda.handler",
        architecture=_lambda.Architecture.ARM_64,
        runtime=_lambda.Runtime.PYTHON_3_8,
        timeout=Duration.seconds(1)
    )
self._lambda_2 = _lambda.Function(
        self,
        "test_function_2",
        code=_lambda.AssetCode.from_asset('src'),
        handler="lambda.handler",
        architecture=_lambda.Architecture.ARM_64,
        runtime=_lambda.Runtime.PYTHON_2_7,
        timeout=Duration.seconds(2)
    )

These are the lambda functions. I expect the second to fail but pytest is only testing the first one.

has_resource_properties tests whether a resource exists with those properties. It succeeds because there is a lambda with those properties. This is documented in the typescript implementation comments .

If both lambdas have the same properties you want to test, you can use template.resource_properties_count_is and assert the count is 2:

template.resource_properties_count_is("AWS::Lambda::Function", {
    "Architectures": ["arm64"],
    "Runtime": "python3.8",
    "Timeout": 1
}, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM