Sub topic 18
Testing infrastructure with assertions
This chapter covers how to test a CDK app with the assertions module. It assumes you can define a stack (see the chapters on defining resources and custom constructs) and know basic Jest or pytest usage. Tests run on your machine and deploy nothing.
Why test infrastructure
A CDK app is code that produces a CloudFormation template. A bug in that code can remove encryption, drop a permission, or replace a database. Tests catch these changes before cdk deploy. They also document intent: a test named "bucket is versioned" records a decision that the code alone does not.
The CDK supports three kinds of test:
| Kind | What it checks | Speed |
|---|---|---|
| Fine-grained assertion | Specific properties of specific resources in the template | Fast |
| Snapshot | The whole template against a stored copy | Fast |
| Validation | That invalid props throw errors at synth time | Fast |
Integration tests that deploy real resources also exist, but this chapter covers only the three above. They are the right default because they need no AWS credentials.
How the tests work
Your test creates an App and a stack in memory. Template.fromStack(stack) synthesizes that stack and returns an object that wraps the generated CloudFormation template. You then query the template. Nothing is written to AWS, and the stack needs no real account or region.
A first test
This test uses the AppStack from the earlier chapter on defining resources. It assumes the project has Jest configured, as cdk init app --language typescript does.
import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import { AppStack } from '../lib/app-stack';
test('bucket is versioned and one function exists', () => {
const app = new cdk.App();
const stack = new AppStack(app, 'TestStack');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
VersioningConfiguration: { Status: 'Enabled' },
});
template.resourceCountIs('AWS::Lambda::Function', 1);
});Run it with npx jest. The two assertions do different jobs:
hasResourcePropertiespasses if at least one resource of that type contains the properties you list. Other properties are ignored.resourceCountIspasses only if the template holds exactly that number of resources of the type.
Matching rules
By default, hasResourceProperties does a partial, deep match. Objects match if they contain the keys you give. Arrays must match exactly, in order and length. Use the Match helpers when you need more control.
| Helper | Meaning |
|---|---|
| `Match.anyValue()` | Any value, as long as the key exists |
| `Match.absent()` | The key must not exist |
| `Match.objectLike({...})` | Partial match on an object, applied recursively |
| `Match.objectEquals({...})` | Exact match on an object |
| `Match.arrayWith([...])` | The array contains these items, in order, possibly among others |
| `Match.arrayEquals([...])` | Exact array match |
| `Match.stringLikeRegexp('...')` | String matching a regular expression |
For example, to check that a bucket blocks all public access and has no website configuration:
import * as cdk from 'aws-cdk-lib';
import { Match, Template } from 'aws-cdk-lib/assertions';
import { SecureBucket } from '../lib/secure-bucket';
test('secure bucket blocks public access', () => {
const stack = new cdk.Stack();
new SecureBucket(stack, 'Secure');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
PublicAccessBlockConfiguration: {
BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true,
},
WebsiteConfiguration: Match.absent(),
});
});Testing a custom construct this way needs only a bare cdk.Stack as its parent. This is why small, focused constructs are easy to test.
Testing the same stack in Python
The assertions module has the same API in Python, with snakecase names. With pytest, a test for the Python AppStack looks like this. The module path `app.appstack` is an assumption; adjust it to your project layout.
import aws_cdk as cdk
from aws_cdk.assertions import Template
from app.app_stack import AppStack
def test_bucket_is_versioned_and_one_function_exists():
app = cdk.App()
stack = AppStack(app, "TestStack")
template = Template.from_stack(stack)
template.has_resource_properties(
"AWS::S3::Bucket",
{"VersioningConfiguration": {"Status": "Enabled"}},
)
template.resource_count_is("AWS::Lambda::Function", 1)Other query methods
hasResourceProperties inspects only the Properties section. Several other methods cover the rest of the template.
hasResource(type, props)matches the whole resource definition, including attributes such asDeletionPolicy. Use it to check removal policies.findResources(type)returns every resource of a type so you can inspect them yourself.hasOutput(id, props),hasParameter(id, props)andhasMapping(...)check other template sections.templateMatches(expected)compares the whole template.toJSON()returns the template as a plain object.
A retention check for the uploads bucket from the earlier chapter looks like this:
template.hasResource('AWS::S3::Bucket', {
DeletionPolicy: 'Retain',
UpdateReplacePolicy: 'Retain',
});Testing IAM permissions
Grant methods produce AWS::IAM::Policy resources. Assert on them to confirm a function can read the bucket and nothing more:
import { Match } from 'aws-cdk-lib/assertions';
template.hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({
Action: Match.arrayWith(['s3:GetObject*']),
Effect: 'Allow',
}),
]),
},
});Keep these assertions loose. Grant methods may add or reorder actions between CDK versions, so asserting the exact action list makes the test fail on harmless upgrades.
Tokens in assertions
Some values in the template are not literals. A reference to another resource appears as an intrinsic function such as { "Ref": "UploadsBucket..." }. The logical ID contains a hash that changes when the construct path changes. Do not hard-code it. Match with Match.anyValue() or Match.objectLike({ Ref: Match.stringLikeRegexp('^UploadsBucket') }). You can also capture a value with Capture and use it in a later assertion.
Snapshot tests
A snapshot test stores the full template and fails when it changes:
test('template matches snapshot', () => {
const template = Template.fromStack(new AppStack(new cdk.App(), 'Snap'));
expect(template.toJSON()).toMatchSnapshot();
});Snapshots are cheap to write but noisy. Any CDK upgrade can change the template, and asset hashes change whenever Lambda code changes. Developers then update snapshots without reading them. Prefer fine-grained assertions for the properties you care about, and use snapshots sparingly.
Validation tests
Constructs can reject bad props with an error at construction or synthesis time. Test the failure path with toThrow:
test('rejects invalid configuration', () => {
expect(() => {
new MyConstruct(new cdk.Stack(), 'Bad', { retentionDays: -1 });
}).toThrow(/retentionDays/);
});MyConstruct stands for your own construct that validates its input.
Common errors
- Asserting on the wrong section.
hasResourcePropertiesignoresDeletionPolicyandDependsOn. UsehasResourcefor those. - Expecting arrays to match partially. Wrap the array in
Match.arrayWith. - Counting resources that CDK adds for you. Helper resources, such as the custom resources behind
autoDeleteObjects, change counts. Count by type and check the synthesized template withconsole.log(JSON.stringify(template.toJSON(), null, 2)). - Missing assets.
Code.fromAsset('lambda')needs that directory to exist when the test runs. Run tests from the project root, or useCode.fromInlinein test-only stacks. - Hard-coded logical IDs. They change when you move a construct.
Exercise
You want to check that a Lambda function's environment contains a BUCKET_NAME variable, whose value is a reference to the bucket that CloudFormation resolves at deploy time. Which assertion style do you use, and why not compare the exact value?
Show answer
Use hasResourceProperties on 'AWS::Lambda::Function' with Environment: { Variables: { BUCKET_NAME: Match.anyValue() } }, or Match.objectLike({ Ref: Match.stringLikeRegexp('^UploadsBucket') }) for the value. The value is a token that becomes a Ref intrinsic containing a hashed logical ID, so an exact literal would break whenever the construct path changes.
Exercise
A test uses template.hasResourceProperties('AWS::S3::Bucket', { DeletionPolicy: 'Retain' }) and fails even though the bucket is retained. What is wrong, and how do you fix it?
Show answer
DeletionPolicy is a resource attribute, not an entry under Properties, and hasResourceProperties only inspects Properties. Use template.hasResource('AWS::S3::Bucket', { DeletionPolicy: 'Retain' }).