What are unit tests?
In AWS CDK, unit tests are tests that are used to verify what the CDK code synthesizes.
They do not test what is currently running in AWS.
Unit tests are defined under the tests/ folder, inside the CDK project.
What types of unit test does CDK provide?
CDK provides a few different types of unit tests, such as:
Fine-grained assertion tests
These are the most common type of unit tests.
They extract part of the generated CloudFormation template and analyze it.
This allows for detailed testing on components, such as, what kind of resources are generated.
For example, using this type of tests, it is possible to check if a Lambda is being generated with the Python runtime 3.12:
def test_api_props(get_tpl):
"""
Verify that the stack defines a Lambda function with the expected runtime configuration.
:param get_tpl: The synthesized CDK app. (Output of get_tpl()).
"""
get_tpl.has_resource_properties("AWS::Lambda::Function", {
"Runtime": "python3.12"
})Snapshot tests
Snapshot tests are a type of tests that output the synthesized CloudFormation template from the CDK code and compare it with a previously generated template from another test run to detect template differences between them.
In short, snapshot tests compare the entire synthesized template against a saved “golden” file.
They are especially useful when upgrading CDK or when refactoring code, as they ensure that no unexpected changes have occurred in the stack.
Here is a practical example:
def test_snapshot(get_tpl):
"""
Tests the synthesized template against the last snapshot in order to ensure that no unexpected changes have occurred.
:param get_tpl: The synthesized CDK app. (Output of get_tpl()).
"""
SNAPSHOT = Path(__file__).parent / "snapshot.json"
# If snapshot does not exist, create it.
if not SNAPSHOT.exists():
SNAPSHOT.write_text(json.dumps(get_tpl.to_json(), indent=2))
assert False, "Snapshot created. Re-run test."
# Load the previously saved snapshot.
EXPECTED = json.loads(SNAPSHOT.read_text())
# Compare current template with stored snapshot.
# Test fails if anything in the infrastructure has changed.
assert get_tpl.to_json() == EXPECTEDTesting advice
In order to improve performance, while testing, make sure that the generated template is only generated once during the testing session.
This can be achieved with a function similar to this one:
# This is used to generate the template only once
# per session, improving performance while testing.
@pytest.fixture(scope="session")
def get_tpl():
app = core.App()
stack = LambdaApiStack(app, "py-testing")
tpl = assertions.Template.from_stack(stack)
return tpl