Skip to content
v2.274.0

Assertions ​

If you're migrating from the old @aws-cdk/assert library, first use this migration guide to migrate from @aws-cdk/assert to @aws-cdk/assertions found in our GitHub repository. Then, you can migrate your application to AWS CDK v2 in order to use this library using this guide.

Functions for writing test asserting against CDK applications, with focus on CloudFormation templates.

The Template class includes a set of methods for writing assertions against CloudFormation templates. Use one of the Template.fromXxx() static methods to create an instance of this class.

To create Template from CDK stack, start off with:

ts
import { Stack } from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';

const stack = new Stack(/* ... */);
// ...
const template = Template.fromStack(stack);
python
from aws_cdk import Stack
from aws_cdk.assertions import Template

stack = Stack()
# ...
template = Template.from_stack(stack)
java
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.assertions.Template;

Stack stack = new Stack();
// ...
Template template = Template.fromStack(stack);
csharp
using Amazon.CDK;
using Amazon.CDK.Assertions;

var stack = new Stack();
// ...
var template = Template.FromStack(stack);
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

stack := awscdk.NewStack()
// ...
template := awscdk.Template_FromStack(stack)

Alternatively, assertions can be run on an existing CloudFormation template -

ts
const templateJson = '{ "Resources": ... }'; /* The CloudFormation template as JSON serialized string. */
const template = Template.fromString(templateJson);
python
template_json = "{ \"Resources\": ... }" # The CloudFormation template as JSON serialized string.
template = Template.from_string(template_json)
java
String templateJson = "{ \"Resources\": ... }"; /* The CloudFormation template as JSON serialized string. */
Template template = Template.fromString(templateJson);
csharp
var templateJson = "{ \"Resources\": ... }"; /* The CloudFormation template as JSON serialized string. */
var template = Template.FromString(templateJson);
go
templateJson := "{ \"Resources\": ... }" /* The CloudFormation template as JSON serialized string. */
template := awscdk.Template_FromString(templateJson)

Cyclical Resources Note

If allowing cyclical references is desired, for example in the case of unprocessed Transform templates, supply TemplateParsingOptions and set skipCyclicalDependenciesCheck to true. In all other cases, will fail on detecting cyclical dependencies.

Cleaning up temporary output in Jest ​

Synthesizing a stack without an explicit output directory can create a temporary cdk.out* directory. CDK normally removes these directories when the Node.js process exits, but Jest does not trigger the exit event used for that cleanup. When using Template.fromStack() in Jest tests, add the cleanup helper to setupFilesAfterEnv so temporary assemblies are removed after each test file. For example, in a CommonJS Jest configuration (jest.config.cjs):

js
module.exports = {
  setupFilesAfterEnv: [
    // Include any existing setup files here as well.
    'aws-cdk-lib/testhelpers/jest-autoclean',
  ],
};

The helper calls CloudAssembly.cleanupTemporaryDirectories() from an afterAll hook. It removes registered temporary assembly directories; explicitly configured output directories are retained. To keep temporary assemblies for debugging, set CDK_NO_CLEAN_TESTS=1 when running Jest.

Full Template Match ​

The simplest assertion would be to assert that the template matches a given template.

ts
template.templateMatches({
  Resources: {
    BarLogicalId: {
      Type: 'Foo::Bar',
      Properties: {
        Baz: 'Qux',
      },
    },
  },
});
python
template.template_matches({
    "Resources": {
        "BarLogicalId": {
            "Type": "Foo::Bar",
            "Properties": {
                "Baz": "Qux"
            }
        }
    }
})
java
template.templateMatches(Map.of(
        "Resources", Map.of(
                "BarLogicalId", Map.of(
                        "Type", "Foo::Bar",
                        "Properties", Map.of(
                                "Baz", "Qux")))));
csharp
template.TemplateMatches(new Dictionary<string, IDictionary<string, IDictionary<string, object>>> {
    { "Resources", new Struct {
        BarLogicalId = new Struct {
            Type = "Foo::Bar",
            Properties = new Struct {
                Baz = "Qux"
            }
        }
    } }
});
go
template.TemplateMatches(map[string]map[string]map[string]interface{}{
	"Resources": map[string]map[string]interface{}{
		"BarLogicalId": map[string]interface{}{
			"Type": jsii.String("Foo::Bar"),
			"Properties": map[string]*string{
				"Baz": jsii.String("Qux"),
			},
		},
	},
})

By default, the templateMatches() API will use the an 'object-like' comparison, which means that it will allow for the actual template to be a superset of the given expectation. See Special Matchers for details on how to change this.

Snapshot testing is a common technique to store a snapshot of the output and compare it during future changes. Since CloudFormation templates are human readable, they are a good target for snapshot testing.

The toJSON() method on the Template can be used to produce a well formatted JSON of the CloudFormation template that can be used as a snapshot.

See Snapshot Testing in Jest and Snapshot Testing in Java.

Counting Resources ​

This module allows asserting the number of resources of a specific type found in a template.

ts
template.resourceCountIs('Foo::Bar', 2);
python
template.resource_count_is("Foo::Bar", 2)
java
template.resourceCountIs("Foo::Bar", 2);
csharp
template.ResourceCountIs("Foo::Bar", 2);
go
template.ResourceCountIs(jsii.String("Foo::Bar"), jsii.Number(2))

You can also count the number of resources of a specific type whose Properties section contains the specified properties:

ts
template.resourcePropertiesCountIs('Foo::Bar', {
  Foo: 'Bar',
  Baz: 5,
  Qux: [ 'Waldo', 'Fred' ],
}, 1);
python
template.resource_properties_count_is("Foo::Bar", {
    "Foo": "Bar",
    "Baz": 5,
    "Qux": ["Waldo", "Fred"]
}, 1)
java
template.resourcePropertiesCountIs("Foo::Bar", Map.of(
        "Foo", "Bar",
        "Baz", 5,
        "Qux", List.of("Waldo", "Fred")), 1);
csharp
template.ResourcePropertiesCountIs("Foo::Bar", new Dictionary<string, object> {
    { "Foo", "Bar" },
    { "Baz", 5 },
    { "Qux", new [] { "Waldo", "Fred" } }
}, 1);
go
template.ResourcePropertiesCountIs(jsii.String("Foo::Bar"), map[string]interface{}{
	"Foo": jsii.String("Bar"),
	"Baz": jsii.Number(5),
	"Qux": []*string{
		jsii.String("Waldo"),
		jsii.String("Fred"),
	},
}, jsii.Number(1))

Resource Matching & Retrieval ​

Beyond resource counting, the module also allows asserting that a resource with specific properties are present.

The following code asserts that the Properties section of a resource of type Foo::Bar contains the specified properties -

ts
template.hasResourceProperties('Foo::Bar', {
  Lorem: 'Ipsum',
  Baz: 5,
  Qux: [ 'Waldo', 'Fred' ],
});
python
template.has_resource_properties("Foo::Bar", {
    "Lorem": "Ipsum",
    "Baz": 5,
    "Qux": ["Waldo", "Fred"]
})
java
template.hasResourceProperties("Foo::Bar", Map.of(
        "Lorem", "Ipsum",
        "Baz", 5,
        "Qux", List.of("Waldo", "Fred")));
csharp
template.HasResourceProperties("Foo::Bar", new Dictionary<string, object> {
    { "Lorem", "Ipsum" },
    { "Baz", 5 },
    { "Qux", new [] { "Waldo", "Fred" } }
});
go
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]interface{}{
	"Lorem": jsii.String("Ipsum"),
	"Baz": jsii.Number(5),
	"Qux": []*string{
		jsii.String("Waldo"),
		jsii.String("Fred"),
	},
})

You can also assert that the Properties section of all resources of type Foo::Bar contains the specified properties -

ts
template.allResourcesProperties('Foo::Bar', {
  Lorem: 'Ipsum',
  Baz: 5,
  Qux: [ 'Waldo', 'Fred' ],
});
python
template.all_resources_properties("Foo::Bar", {
    "Lorem": "Ipsum",
    "Baz": 5,
    "Qux": ["Waldo", "Fred"]
})
java
template.allResourcesProperties("Foo::Bar", Map.of(
        "Lorem", "Ipsum",
        "Baz", 5,
        "Qux", List.of("Waldo", "Fred")));
csharp
template.AllResourcesProperties("Foo::Bar", new Dictionary<string, object> {
    { "Lorem", "Ipsum" },
    { "Baz", 5 },
    { "Qux", new [] { "Waldo", "Fred" } }
});
go
template.AllResourcesProperties(jsii.String("Foo::Bar"), map[string]interface{}{
	"Lorem": jsii.String("Ipsum"),
	"Baz": jsii.Number(5),
	"Qux": []*string{
		jsii.String("Waldo"),
		jsii.String("Fred"),
	},
})

Alternatively, if you would like to assert the entire resource definition, you can use the hasResource() API.

ts
template.hasResource('Foo::Bar', {
  Properties: { Lorem: 'Ipsum' },
  DependsOn: [ 'Waldo', 'Fred' ],
});
python
template.has_resource("Foo::Bar", {
    "Properties": {"Lorem": "Ipsum"},
    "DependsOn": ["Waldo", "Fred"]
})
java
template.hasResource("Foo::Bar", Map.of(
        "Properties", Map.of("Lorem", "Ipsum"),
        "DependsOn", List.of("Waldo", "Fred")));
csharp
template.HasResource("Foo::Bar", new Dictionary<string, object> {
    { "Properties", new Struct { Lorem = "Ipsum" } },
    { "DependsOn", new [] { "Waldo", "Fred" } }
});
go
template.HasResource(jsii.String("Foo::Bar"), map[string]interface{}{
	"Properties": map[string]*string{
		"Lorem": jsii.String("Ipsum"),
	},
	"DependsOn": []*string{
		jsii.String("Waldo"),
		jsii.String("Fred"),
	},
})

You can also assert the definitions of all resources of a type using the allResources() API.

ts
template.allResources('Foo::Bar', {
  Properties: { Lorem: 'Ipsum' },
  DependsOn: [ 'Waldo', 'Fred' ],
});
python
template.all_resources("Foo::Bar", {
    "Properties": {"Lorem": "Ipsum"},
    "DependsOn": ["Waldo", "Fred"]
})
java
template.allResources("Foo::Bar", Map.of(
        "Properties", Map.of("Lorem", "Ipsum"),
        "DependsOn", List.of("Waldo", "Fred")));
csharp
template.AllResources("Foo::Bar", new Dictionary<string, object> {
    { "Properties", new Struct { Lorem = "Ipsum" } },
    { "DependsOn", new [] { "Waldo", "Fred" } }
});
go
template.AllResources(jsii.String("Foo::Bar"), map[string]interface{}{
	"Properties": map[string]*string{
		"Lorem": jsii.String("Ipsum"),
	},
	"DependsOn": []*string{
		jsii.String("Waldo"),
		jsii.String("Fred"),
	},
})

Beyond assertions, the module provides APIs to retrieve matching resources. The findResources() API is complementary to the hasResource() API, except, instead of asserting its presence, it returns the set of matching resources.

Similarly, the getResourceId() API is complementary to the findResources() API, except it expects only one matching resource, and returns the matched resource's resource id. Useful for asserting that certain cloudformation resources correlate expectedly.

ts
// Assert that a certain bucket denies unsecure communication
const bucket = template.getResourceId('AWS::S3::Bucket', {
  Properties: {
    BucketName: 'my-bucket',
  }
})

template.hasResourceProperties('AWS::S3::BucketPolicy', {
  Bucket: {
    Ref: bucket,
  },
  PolicyDocument: {
    Statement: [
      {
        Effect: 'Deny',
        Action: 's3:*',
        Principal: { AWS: '*' },
        Condition: { Bool: { 'aws:SecureTransport': 'false' } },
      },
    ],
  }
})
python
# Assert that a certain bucket denies unsecure communication
bucket = template.get_resource_id("AWS::S3::Bucket", {
    "Properties": {
        "BucketName": "my-bucket"
    }
})

template.has_resource_properties("AWS::S3::BucketPolicy", {
    "Bucket": {
        "Ref": bucket
    },
    "PolicyDocument": {
        "Statement": [{
            "Effect": "Deny",
            "Action": "s3:*",
            "Principal": {"AWS": "*"},
            "Condition": {"Bool": {"aws:secure_transport": "false"}}
        }
        ]
    }
})
java
// Assert that a certain bucket denies unsecure communication
String bucket = template.getResourceId("AWS::S3::Bucket", Map.of(
        "Properties", Map.of(
                "BucketName", "my-bucket")));

template.hasResourceProperties("AWS::S3::BucketPolicy", Map.of(
        "Bucket", Map.of(
                "Ref", bucket),
        "PolicyDocument", Map.of(
                "Statement", List.of(Map.of(
                        "Effect", "Deny",
                        "Action", "s3:*",
                        "Principal", Map.of("AWS", "*"),
                        "Condition", Map.of("Bool", Map.of("aws:SecureTransport", "false")))))));
csharp
// Assert that a certain bucket denies unsecure communication
var bucket = template.GetResourceId("AWS::S3::Bucket", new Dictionary<string, IDictionary<string, string>> {
    { "Properties", new Struct {
        BucketName = "my-bucket"
    } }
});

template.HasResourceProperties("AWS::S3::BucketPolicy", new Dictionary<string, IDictionary<string, string>> {
    { "Bucket", new Struct {
        Ref = bucket
    } },
    { "PolicyDocument", new Struct {
        Statement = new [] { new Struct {
            Effect = "Deny",
            Action = "s3:*",
            Principal = new Struct { AWS = "*" },
            Condition = new Struct { Bool = new Struct { Aws:SecureTransport = "false" } }
        } }
    } }
});
go
// Assert that a certain bucket denies unsecure communication
bucket := template.GetResourceId(jsii.String("AWS::S3::Bucket"), map[string]map[string]*string{
	"Properties": map[string]*string{
		"BucketName": jsii.String("my-bucket"),
	},
})

template.HasResourceProperties(jsii.String("AWS::S3::BucketPolicy"), map[string]map[string]*string{
	"Bucket": map[string]*string{
		"Ref": bucket,
	},
	"PolicyDocument": map[string][]map[string]interface{}{
		"Statement": []map[string]interface{}{
			map[string]interface{}{
				"Effect": jsii.String("Deny"),
				"Action": jsii.String("s3:*"),
				"Principal": map[string]*string{
					"AWS": jsii.String("*"),
				},
				"Condition": map[string]map[string]*string{
					"Bool": map[string]*string{
						"aws:SecureTransport": jsii.String("false"),
					},
				},
			},
		},
	},
})

By default, the hasResource() and hasResourceProperties() APIs perform deep partial object matching. This behavior can be configured using matchers. See subsequent section on special matchers.

Output and Mapping sections ​

The module allows you to assert that the CloudFormation template contains an Output that matches specific properties. The following code asserts that a template contains an Output with a logicalId of Foo and the specified properties -

ts
const expected = {
  Value: 'Bar',
  Export: { Name: 'ExportBaz' },
};
template.hasOutput('Foo', expected);
python
expected = {
    "Value": "Bar",
    "Export": {"Name": "ExportBaz"}
}
template.has_output("Foo", expected)
java
Map<String, Object> expected = Map.of(
        "Value", "Bar",
        "Export", Map.of("Name", "ExportBaz"));
template.hasOutput("Foo", expected);
csharp
IDictionary<string, object> expected = new Dictionary<string, object> {
    { "Value", "Bar" },
    { "Export", new Dictionary<string, string> { { "Name", "ExportBaz" } } }
};
template.HasOutput("Foo", expected);
go
expected := map[string]interface{}{
	"Value": jsii.String("Bar"),
	"Export": map[string]*string{
		"Name": jsii.String("ExportBaz"),
	},
}
template.HasOutput(jsii.String("Foo"), expected)

If you want to match against all Outputs in the template, use * as the logicalId.

ts
template.hasOutput('*', {
  Value: 'Bar',
  Export: { Name: 'ExportBaz' },
});
python
template.has_output("*", {
    "Value": "Bar",
    "Export": {"Name": "ExportBaz"}
})
java
template.hasOutput("*", Map.of(
        "Value", "Bar",
        "Export", Map.of("Name", "ExportBaz")));
csharp
template.HasOutput("*", new Dictionary<string, object> {
    { "Value", "Bar" },
    { "Export", new Struct { Name = "ExportBaz" } }
});
go
template.HasOutput(jsii.String("*"), map[string]interface{}{
	"Value": jsii.String("Bar"),
	"Export": map[string]*string{
		"Name": jsii.String("ExportBaz"),
	},
})

findOutputs() will return a set of outputs that match the logicalId and props, and you can use the '*' special case as well.

ts
const result = template.findOutputs('*', { Value: 'Fred' });
expect(result.Foo).toEqual({ Value: 'Fred', Description: 'FooFred' });
expect(result.Bar).toEqual({ Value: 'Fred', Description: 'BarFred' });
python
result = template.find_outputs("*", {"Value": "Fred"})
expect(result.Foo).to_equal({"Value": "Fred", "Description": "FooFred"})
expect(result.Bar).to_equal({"Value": "Fred", "Description": "BarFred"})
java
Map<String, Map<String, Object>> result = template.findOutputs("*", Map.of("Value", "Fred"));
expect(result.Foo).toEqual(Map.of("Value", "Fred", "Description", "FooFred"));
expect(result.Bar).toEqual(Map.of("Value", "Fred", "Description", "BarFred"));
csharp
IDictionary<string, IDictionary<string, object>> result = template.FindOutputs("*", new Dictionary<string, string> { { "Value", "Fred" } });
Expect(result.Foo).ToEqual(new Dictionary<string, string> { { "Value", "Fred" }, { "Description", "FooFred" } });
Expect(result.Bar).ToEqual(new Dictionary<string, string> { { "Value", "Fred" }, { "Description", "BarFred" } });
go
result := template.FindOutputs(jsii.String("*"), map[string]*string{
	"Value": jsii.String("Fred"),
})
expect(result.foo).toEqual(map[string]*string{
	"Value": jsii.String("Fred"),
	"Description": jsii.String("FooFred"),
})
expect(result.bar).toEqual(map[string]*string{
	"Value": jsii.String("Fred"),
	"Description": jsii.String("BarFred"),
})

The APIs hasMapping(), findMappings(), hasCondition(), and hasCondtions() provide similar functionalities.

Special Matchers ​

The expectation provided to the hasXxx(), findXxx() and templateMatches() APIs, besides carrying literal values, as seen in the above examples, also accept special matchers.

They are available as part of the Match class.

Object Matchers ​

The Match.objectLike() API can be used to assert that the target is a superset object of the provided pattern. This API will perform a deep partial match on the target. Deep partial matching is where objects are matched partially recursively. At each level, the list of keys in the target is a subset of the provided pattern.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//           "Bob": "Cat"
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    Wobble: 'Flob',
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    Brew: 'Coffee',
  }),
});
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": "Flob",
#           "Bob": "Cat"
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.object_like({
        "Wobble": "Flob"
    })
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.object_like({
        "Brew": "Coffee"
    })
})
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//           "Bob": "Cat"
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.objectLike(Map.of(
                "Wobble", "Flob"))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.objectLike(Map.of(
                "Brew", "Coffee"))));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//           "Bob": "Cat"
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.ObjectLike(new Dictionary<string, object> {
        { "Wobble", "Flob" }
    }) }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.ObjectLike(new Dictionary<string, object> {
        { "Brew", "Coffee" }
    }) }
});
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//           "Bob": "Cat"
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_objectLike(map[string]interface{}{
		"Wobble": jsii.String("Flob"),
	}),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_objectLike(map[string]interface{}{
		"Brew": jsii.String("Coffee"),
	}),
})

The Match.objectEquals() API can be used to assert a target as a deep exact match.

Presence and Absence ​

The Match.absent() matcher can be used to specify that a specific value should not exist on the target. This can be used within Match.objectLike() or outside of any matchers.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    Bob: Match.absent(),
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    Wobble: Match.absent(),
  }),
});
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": "Flob",
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.object_like({
        "Bob": Match.absent()
    })
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.object_like({
        "Wobble": Match.absent()
    })
})
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.objectLike(Map.of(
                "Bob", Match.absent()))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.objectLike(Map.of(
                "Wobble", Match.absent()))));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.ObjectLike(new Dictionary<string, object> {
        { "Bob", Match.Absent() }
    }) }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.ObjectLike(new Dictionary<string, object> {
        { "Wobble", Match.Absent() }
    }) }
});
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": "Flob",
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_objectLike(map[string]interface{}{
		"Bob": awscdk.Match_absent(),
	}),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_objectLike(map[string]interface{}{
		"Wobble": awscdk.Match_absent(),
	}),
})

The Match.anyValue() matcher can be used to specify that a specific value should be found at the location. This matcher will fail if when the target location has null-ish values (i.e., null or undefined).

This matcher can be combined with any of the other matchers.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": ["Flob", "Flib"],
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: {
    Wobble: [ Match.anyValue(), Match.anyValue() ],
  },
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: {
    Wimble: Match.anyValue(),
  },
});
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": ["Flob", "Flib"],
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": {
        "Wobble": [Match.any_value(), Match.any_value()]
    }
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": {
        "Wimble": Match.any_value()
    }
})
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": ["Flob", "Flib"],
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Map.of(
                "Wobble", List.of(Match.anyValue(), Match.anyValue()))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Map.of(
                "Wimble", Match.anyValue())));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": ["Flob", "Flib"],
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, IDictionary<string, Matcher[]>> {
    { "Fred", new Struct {
        Wobble = new [] { Match.AnyValue(), Match.AnyValue() }
    } }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, IDictionary<string, Matcher>> {
    { "Fred", new Struct {
        Wimble = Match.AnyValue()
    } }
});
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": {
//           "Wobble": ["Flob", "Flib"],
//         }
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]map[string][]Matcher{
	"Fred": map[string][]Matcher{
		"Wobble": []Matcher{
			awscdk.Match_anyValue(),
			awscdk.Match_anyValue(),
		},
	},
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]map[string]Matcher{
	"Fred": map[string]Matcher{
		"Wimble": awscdk.Match_anyValue(),
	},
})

Array Matchers ​

The Match.arrayWith() API can be used to assert that the target is equal to or a subset of the provided pattern array. This API will perform subset match on the target.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.arrayWith(['Flob']),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', Match.objectLike({
  Fred: Match.arrayWith(['Wobble']),
}));
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"]
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.array_with(["Flob"])
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", Match.object_like({
    "Fred": Match.array_with(["Wobble"])
}))
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.arrayWith(List.of("Flob"))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Match.objectLike(Map.of(
        "Fred", Match.arrayWith(List.of("Wobble")))));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.ArrayWith(new [] { "Flob" }) }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", Match.ObjectLike(new Dictionary<string, object> {
    { "Fred", Match.ArrayWith(new [] { "Wobble" }) }
}));
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_arrayWith([]interface{}{
		jsii.String("Flob"),
	}),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), awscdk.Match_ObjectLike(map[string]interface{}{
	"Fred": awscdk.Match_arrayWith([]interface{}{
		jsii.String("Wobble"),
	}),
}))

Note: The list of items in the pattern array should be in order as they appear in the target array. Out of order will be recorded as a match failure.

Alternatively, the Match.arrayEquals() API can be used to assert that the target is exactly equal to the pattern array.

String Matchers ​

The Match.stringLikeRegexp() API can be used to assert that the target matches the provided regular expression.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Template": "const includeHeaders = true;"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Template: Match.stringLikeRegexp('includeHeaders = (true|false)'),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Template: Match.stringLikeRegexp('includeHeaders = null'),
});
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Template": "const includeHeaders = true;"
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Template": Match.string_like_regexp("includeHeaders = (true|false)")
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Template": Match.string_like_regexp("includeHeaders = null")
})
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Template": "const includeHeaders = true;"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Template", Match.stringLikeRegexp("includeHeaders = (true|false)")));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Template", Match.stringLikeRegexp("includeHeaders = null")));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Template": "const includeHeaders = true;"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Template", Match.StringLikeRegexp("includeHeaders = (true|false)") }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Template", Match.StringLikeRegexp("includeHeaders = null") }
});
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Template": "const includeHeaders = true;"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Template": awscdk.Match_stringLikeRegexp(jsii.String("includeHeaders = (true|false)")),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Template": awscdk.Match_stringLikeRegexp(jsii.String("includeHeaders = null")),
})

Not Matcher ​

The not matcher inverts the search pattern and matches all patterns in the path that does not match the pattern specified.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.not(['Flob']),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', Match.objectLike({
  Fred: Match.not(['Flob', 'Cat']),
}));
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"]
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Fred": Match.not(["Flob"])
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", Match.object_like({
    "Fred": Match.not(["Flob", "Cat"])
}))
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", Match.not(List.of("Flob"))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Match.objectLike(Map.of(
        "Fred", Match.not(List.of("Flob", "Cat")))));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Fred", Match.Not(new [] { "Flob" }) }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", Match.ObjectLike(new Dictionary<string, object> {
    { "Fred", Match.Not(new [] { "Flob", "Cat" }) }
}));
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"]
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Fred": awscdk.Match_not([]interface{}{
		jsii.String("Flob"),
	}),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), awscdk.Match_ObjectLike(map[string]interface{}{
	"Fred": awscdk.Match_not([]interface{}{
		jsii.String("Flob"),
		jsii.String("Cat"),
	}),
}))

Serialized JSON ​

Often, we find that some CloudFormation Resource types declare properties as a string, but actually expect JSON serialized as a string. For example, the BuildSpec property of AWS::CodeBuild::Project, the Definition property of AWS::StepFunctions::StateMachine, to name a couple.

The Match.serializedJson() matcher allows deep matching within a stringified JSON.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Baz: Match.serializedJson({
    Fred: Match.arrayWith(["Waldo"]),
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Baz: Match.serializedJson({
    Fred: ["Waldo", "Johnny"],
  }),
});
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Baz": Match.serialized_json({
        "Fred": Match.array_with(["Waldo"])
    })
})

# The following will throw an assertion error
template.has_resource_properties("Foo::Bar", {
    "Baz": Match.serialized_json({
        "Fred": ["Waldo", "Johnny"]
    })
})
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Baz", Match.serializedJson(Map.of(
                "Fred", Match.arrayWith(List.of("Waldo"))))));

// The following will throw an assertion error
template.hasResourceProperties("Foo::Bar", Map.of(
        "Baz", Match.serializedJson(Map.of(
                "Fred", List.of("Waldo", "Johnny")))));
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Baz", Match.SerializedJson(new Dictionary<string, Matcher> {
        { "Fred", Match.ArrayWith(new [] { "Waldo" }) }
    }) }
});

// The following will throw an assertion error
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Matcher> {
    { "Baz", Match.SerializedJson(new Dictionary<string, string[]> {
        { "Fred", new [] { "Waldo", "Johnny" } }
    }) }
});
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
//       }
//     }
//   }
// }

// The following will NOT throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Baz": awscdk.Match_serializedJson(map[string]Matcher{
		"Fred": awscdk.Match_arrayWith([]interface{}{
			jsii.String("Waldo"),
		}),
	}),
})

// The following will throw an assertion error
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Matcher{
	"Baz": awscdk.Match_serializedJson(map[string][]*string{
		"Fred": []*string{
			jsii.String("Waldo"),
			jsii.String("Johnny"),
		},
	}),
})

Capturing Values ​

The matcher APIs documented above allow capturing values in the matching entry (Resource, Output, Mapping, etc.). The following code captures a string from a matching resource.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//         "Waldo": ["Qix", "Qux"],
//       }
//     }
//   }
// }

const fredCapture = new Capture();
const waldoCapture = new Capture();
template.hasResourceProperties('Foo::Bar', {
  Fred: fredCapture,
  Waldo: ["Qix", waldoCapture] as any[],
});

fredCapture.asArray(); // returns ["Flob", "Cat"]
waldoCapture.asString(); // returns "Qux"
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"],
#         "Waldo": ["Qix", "Qux"],
#       }
#     }
#   }
# }

fred_capture = Capture()
waldo_capture = Capture()
template.has_resource_properties("Foo::Bar", {
    "Fred": fred_capture,
    "Waldo": ["Qix", waldo_capture]
})

fred_capture.as_array() # returns ["Flob", "Cat"]
waldo_capture.as_string()
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//         "Waldo": ["Qix", "Qux"],
//       }
//     }
//   }
// }

Capture fredCapture = new Capture();
Capture waldoCapture = new Capture();
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", fredCapture,
        "Waldo", (Object[])List.of("Qix", waldoCapture)));

fredCapture.asArray(); // returns ["Flob", "Cat"]
waldoCapture.asString();
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//         "Waldo": ["Qix", "Qux"],
//       }
//     }
//   }
// }

var fredCapture = new Capture();
var waldoCapture = new Capture();
template.HasResourceProperties("Foo::Bar", new Dictionary<string, object> {
    { "Fred", fredCapture },
    { "Waldo", (object[])new [] { "Qix", waldoCapture } }
});

fredCapture.AsArray(); // returns ["Flob", "Cat"]
waldoCapture.AsString();
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//         "Waldo": ["Qix", "Qux"],
//       }
//     }
//   }
// }

fredCapture := awscdk.NewCapture()
waldoCapture := awscdk.NewCapture()
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]interface{}{
	"Fred": fredCapture,
	"Waldo": []interface{}{
		jsii.String("Qix"),
		waldoCapture,
	}.([]interface{}),
})

fredCapture.AsArray() // returns ["Flob", "Cat"]
waldoCapture.AsString()

With captures, a nested pattern can also be specified, so that only targets that match the nested pattern will be captured. This pattern can be literals or further Matchers.

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar1": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//       }
//     }
//     "MyBar2": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Qix", "Qux"],
//       }
//     }
//   }
// }

const capture = new Capture(Match.arrayWith(['Cat']));
template.hasResourceProperties('Foo::Bar', {
  Fred: capture,
});

capture.asArray(); // returns ['Flob', 'Cat']
python
# Given a template -
# {
#   "Resources": {
#     "MyBar1": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"],
#       }
#     }
#     "MyBar2": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Qix", "Qux"],
#       }
#     }
#   }
# }

capture = Capture(Match.array_with(["Cat"]))
template.has_resource_properties("Foo::Bar", {
    "Fred": capture
})

capture.as_array()
java
// Given a template -
// {
//   "Resources": {
//     "MyBar1": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//       }
//     }
//     "MyBar2": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Qix", "Qux"],
//       }
//     }
//   }
// }

Capture capture = new Capture(Match.arrayWith(List.of("Cat")));
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", capture));

capture.asArray();
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar1": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//       }
//     }
//     "MyBar2": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Qix", "Qux"],
//       }
//     }
//   }
// }

var capture = new Capture(Match.ArrayWith(new [] { "Cat" }));
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Capture> {
    { "Fred", capture }
});

capture.AsArray();
go
// Given a template -
// {
//   "Resources": {
//     "MyBar1": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Flob", "Cat"],
//       }
//     }
//     "MyBar2": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": ["Qix", "Qux"],
//       }
//     }
//   }
// }

capture := awscdk.NewCapture(awscdk.Match_ArrayWith([]interface{}{
	jsii.String("Cat"),
}))
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Capture{
	"Fred": capture,
})

capture.AsArray()

When multiple resources match the given condition, each Capture defined in the condition will capture all matching values. They can be paged through using the next() API. The following example illustrates this -

ts
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Flob",
//       }
//     },
//     "MyBaz": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Quib",
//       }
//     }
//   }
// }

const fredCapture = new Capture();
template.hasResourceProperties('Foo::Bar', {
  Fred: fredCapture,
});

fredCapture.asString(); // returns "Flob"
fredCapture.next();     // returns true
fredCapture.asString(); // returns "Quib"
python
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": "Flob",
#       }
#     },
#     "MyBaz": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": "Quib",
#       }
#     }
#   }
# }

fred_capture = Capture()
template.has_resource_properties("Foo::Bar", {
    "Fred": fred_capture
})

fred_capture.as_string() # returns "Flob"
fred_capture.next() # returns true
fred_capture.as_string()
java
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Flob",
//       }
//     },
//     "MyBaz": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Quib",
//       }
//     }
//   }
// }

Capture fredCapture = new Capture();
template.hasResourceProperties("Foo::Bar", Map.of(
        "Fred", fredCapture));

fredCapture.asString(); // returns "Flob"
fredCapture.next(); // returns true
fredCapture.asString();
csharp
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Flob",
//       }
//     },
//     "MyBaz": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Quib",
//       }
//     }
//   }
// }

var fredCapture = new Capture();
template.HasResourceProperties("Foo::Bar", new Dictionary<string, Capture> {
    { "Fred", fredCapture }
});

fredCapture.AsString(); // returns "Flob"
fredCapture.Next(); // returns true
fredCapture.AsString();
go
// Given a template -
// {
//   "Resources": {
//     "MyBar": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Flob",
//       }
//     },
//     "MyBaz": {
//       "Type": "Foo::Bar",
//       "Properties": {
//         "Fred": "Quib",
//       }
//     }
//   }
// }

fredCapture := awscdk.NewCapture()
template.HasResourceProperties(jsii.String("Foo::Bar"), map[string]Capture{
	"Fred": fredCapture,
})

fredCapture.AsString() // returns "Flob"
fredCapture.Next() // returns true
fredCapture.AsString()

Asserting Annotations ​

In addition to template matching, we provide an API for annotation matching. Annotations can be added via the Aspects API. You can learn more about Aspects here.

Say you have a MyAspect and a MyStack that uses MyAspect:

ts
import * as cdk from 'aws-cdk-lib';
import { Construct, IConstruct } from 'constructs';

class MyAspect implements cdk.IAspect {
  public visit(node: IConstruct): void {
    if (node instanceof cdk.CfnResource && node.cfnResourceType === 'Foo::Bar') {
      this.error(node, 'we do not want a Foo::Bar resource');
    }
  }

  protected error(node: IConstruct, message: string): void {
    cdk.Annotations.of(node).addError(message);
  }
}

class MyStack extends cdk.Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const stack = new cdk.Stack();
    new cdk.CfnResource(stack, 'Foo', {
      type: 'Foo::Bar',
      properties: {
        Fred: 'Thud',
      },
    });
    cdk.Aspects.of(stack).add(new MyAspect());
  }
}
python
import aws_cdk as cdk
from constructs import Construct, IConstruct

@jsii.implements(cdk.IAspect)
class MyAspect:
    def visit(self, node):
        if node instanceof cdk.CfnResource && node.cfn_resource_type == "Foo::Bar":
            self.error(node, "we do not want a Foo::Bar resource")

    def error(self, node, message):
        cdk.Annotations.of(node).add_error(message)

class MyStack(cdk.Stack):
    def __init__(self, scope, id):
        super().__init__(scope, id)

        stack = cdk.Stack()
        cdk.CfnResource(stack, "Foo",
            type="Foo::Bar",
            properties={
                "Fred": "Thud"
            }
        )
        cdk.Aspects.of(stack).add(MyAspect())
java
import software.amazon.awscdk.*;
import software.constructs.Construct;
import software.constructs.IConstruct;

public class MyAspect implements IAspect {
    public void visit(IConstruct node) {
        if (node instanceof CfnResource && node.getCfnResourceType() == "Foo::Bar") {
            this.error(node, "we do not want a Foo::Bar resource");
        }
    }

    public void error(IConstruct node, String message) {
        Annotations.of(node).addError(message);
    }
}

public class MyStack extends Stack {
    public MyStack(Construct scope, String id) {
        super(scope, id);

        Stack stack = new Stack();
        CfnResource.Builder.create(stack, "Foo")
                .type("Foo::Bar")
                .properties(Map.of(
                        "Fred", "Thud"))
                .build();
        Aspects.of(stack).add(new MyAspect());
    }
}
csharp
using Amazon.CDK;
using Constructs;

class MyAspect : IAspect
{
    public void Visit(IConstruct node)
    {
        if (node instanceof CfnResource && node.CfnResourceType == "Foo::Bar")
        {
            Error(node, "we do not want a Foo::Bar resource");
        }
    }

    protected void Error(IConstruct node, string message)
    {
        Annotations.Of(node).AddError(message);
    }
}

class MyStack : Stack
{
    public MyStack(Construct scope, string id) : base(scope, id)
    {

        var stack = new Stack();
        new CfnResource(stack, "Foo", new CfnResourceProps {
            Type = "Foo::Bar",
            Properties = new Dictionary<string, object> {
                { "Fred", "Thud" }
            }
        });
        Aspects.Of(stack).Add(new MyAspect());
    }
}
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/constructs-go/constructs"

type myAspect struct {
}

func (this *myAspect) visit(node IConstruct) {
	if *node instanceof cdk.CfnResource && *node.CfnResourceType == "Foo::Bar" {
		this.error(*node, jsii.String("we do not want a Foo::Bar resource"))
	}
}

func (this *myAspect) error(node IConstruct, message *string) {
	cdk.Annotations_Of(*node).AddError(*message)
}

type myStack struct {
	Stack
}

func newMyStack(scope Construct, id *string) *myStack {
	this := &myStack{}
	cdk.NewStack_Override(this, scope, id)

	stack := cdk.NewStack()
	cdk.NewCfnResource(stack, jsii.String("Foo"), &CfnResourceProps{
		Type: jsii.String("Foo::Bar"),
		Properties: map[string]interface{}{
			"Fred": jsii.String("Thud"),
		},
	})
	cdk.Aspects_Of(stack).Add(NewMyAspect())
	return this
}

We can then assert that the stack contains the expected Error:

ts
// import { Annotations } from '@aws-cdk/assertions';

Annotations.fromStack(stack).hasError(
  '/Default/Foo',
  'we do not want a Foo::Bar resource',
);
python
# import { Annotations } from '@aws-cdk/assertions';

Annotations.from_stack(stack).has_error("/Default/Foo", "we do not want a Foo::Bar resource")
java
// import { Annotations } from '@aws-cdk/assertions';

Annotations.fromStack(stack).hasError("/Default/Foo", "we do not want a Foo::Bar resource");
csharp
// import { Annotations } from '@aws-cdk/assertions';

Annotations.FromStack(stack).HasError("/Default/Foo", "we do not want a Foo::Bar resource");
go
// import { Annotations } from '@aws-cdk/assertions';

awscdk.Annotations_FromStack(stack).HasError(jsii.String("/Default/Foo"), jsii.String("we do not want a Foo::Bar resource"))

Here are the available APIs for Annotations:

  • hasError(), hasNoError(), and findError()
  • hasWarning(), hasNoWarning(), and findWarning()
  • hasInfo(), hasNoInfo(), and findInfo()

The corresponding findXxx() API is complementary to the hasXxx() API, except instead of asserting its presence, it returns the set of matching messages.

In addition, this suite of APIs is compatible with Matchers for more fine-grained control. For example, the following assertion works as well:

ts
Annotations.fromStack(stack).hasError(
  '/Default/Foo',
  Match.stringLikeRegexp('.*Foo::Bar.*'),
);
python
Annotations.from_stack(stack).has_error("/Default/Foo",
    Match.string_like_regexp(".*Foo::Bar.*"))
java
Annotations.fromStack(stack).hasError("/Default/Foo", Match.stringLikeRegexp(".*Foo::Bar.*"));
csharp
Annotations.FromStack(stack).HasError("/Default/Foo", Match.StringLikeRegexp(".*Foo::Bar.*"));
go
awscdk.Annotations_FromStack(stack).HasError(jsii.String("/Default/Foo"), awscdk.Match_StringLikeRegexp(jsii.String(".*Foo::Bar.*")))

Asserting Stack tags ​

Tags applied to a Stack are not part of the rendered template: instead, they are included as properties in the Cloud Assembly Manifest. To test that stacks are tagged as expected, simple assertions can be written.

Given the following setup:

ts
import { App, Stack } from 'aws-cdk-lib';
import { Tags } from 'aws-cdk-lib/assertions';

const app = new App();
const stack = new Stack(app, 'MyStack', {
  tags: {
    'tag-name': 'tag-value',
  },
});
python
from aws_cdk import App, Stack
from aws_cdk.assertions import Tags

app = App()
stack = Stack(app, "MyStack",
    tags={
        "tag-name": "tag-value"
    }
)
java
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.assertions.Tags;

App app = new App();
Stack stack = Stack.Builder.create(app, "MyStack")
        .tags(Map.of(
                "tag-name", "tag-value"))
        .build();
csharp
using Amazon.CDK;
using Amazon.CDK.Assertions;

var app = new App();
var stack = new Stack(app, "MyStack", new StackProps {
    Tags = new Dictionary<string, string> {
        { "tag-name", "tag-value" }
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

app := awscdk.NewApp()
stack := awscdk.NewStack(app, jsii.String("MyStack"), &StackProps{
	Tags: map[string]*string{
		"tag-name": jsii.String("tag-value"),
	},
})

It is possible to test against these values:

ts
const tags = Tags.fromStack(stack);

// using a default 'objectLike' Matcher
tags.hasValues({
  'tag-name': 'tag-value',
});

// ... with Matchers embedded
tags.hasValues({
  'tag-name': Match.stringLikeRegexp('value'),
});

// or another object Matcher at the top level
tags.hasValues(Match.objectEquals({
  'tag-name': Match.anyValue(),
}));
python
tags = Tags.from_stack(stack)

# using a default 'objectLike' Matcher
tags.has_values({
    "tag-name": "tag-value"
})

# ... with Matchers embedded
tags.has_values({
    "tag-name": Match.string_like_regexp("value")
})

# or another object Matcher at the top level
tags.has_values(Match.object_equals({
    "tag-name": Match.any_value()
}))
java
Tags tags = Tags.fromStack(stack);

// using a default 'objectLike' Matcher
tags.hasValues(Map.of(
        "tag-name", "tag-value"));

// ... with Matchers embedded
tags.hasValues(Map.of(
        "tag-name", Match.stringLikeRegexp("value")));

// or another object Matcher at the top level
tags.hasValues(Match.objectEquals(Map.of(
        "tag-name", Match.anyValue())));
csharp
var tags = Tags.FromStack(stack);

// using a default 'objectLike' Matcher
tags.HasValues(new Dictionary<string, string> {
    { "tag-name", "tag-value" }
});

// ... with Matchers embedded
tags.HasValues(new Dictionary<string, Matcher> {
    { "tag-name", Match.StringLikeRegexp("value") }
});

// or another object Matcher at the top level
tags.HasValues(Match.ObjectEquals(new Dictionary<string, object> {
    { "tag-name", Match.AnyValue() }
}));
go
tags := awscdk.Tags_FromStack(stack)

// using a default 'objectLike' Matcher
tags.HasValues(map[string]*string{
	"tag-name": jsii.String("tag-value"),
})

// ... with Matchers embedded
tags.HasValues(map[string]Matcher{
	"tag-name": awscdk.Match_stringLikeRegexp(jsii.String("value")),
})

// or another object Matcher at the top level
tags.HasValues(awscdk.Match_ObjectEquals(map[string]interface{}{
	"tag-name": awscdk.Match_anyValue(),
}))

When tags are not defined on the stack, it is represented as an empty object rather than undefined. To make this more obvious, there is a hasNone() method that can be used in place of Match.exactly({}). If Match.absent() is passed, an error will result.

ts
// no tags present
Tags.fromStack(stack).hasNone();

// don't use absent() at the top level, it won't work
expect(() => { Tags.fromStack(stack).hasValues(Match.absent()); }).toThrow(/will never match/i);
python
# no tags present
Tags.from_stack(stack).has_none()

# don't use absent() at the top level, it won't work
expect(() => { Tags.fromStack(stack).hasValues(Match.absent()); }).to_throw(/will never match/i)
java
// no tags present
Tags.fromStack(stack).hasNone();

// don't use absent() at the top level, it won't work
expect(() => { Tags.fromStack(stack).hasValues(Match.absent()); }).toThrow(/will never match/i);
csharp
// no tags present
Tags.FromStack(stack).HasNone();

// don't use absent() at the top level, it won't work
Expect(() => { Tags.fromStack(stack).hasValues(Match.absent()); }).ToThrow(/will never match/i);
go
// no tags present
awscdk.Tags_FromStack(stack).HasNone()

// don't use absent() at the top level, it won't work
expect(() => { Tags.fromStack(stack).hasValues(Match.absent()); }).toThrow(/will never match/i)

Types ​

NameKindSummary
AnnotationsClassSuite of assertions that can be run on a CDK Stack.
CaptureClassCapture values while matching templates.
MatchClassPartial and special matching during template assertions.
MatchCaptureStructInformation about a value captured during match.
MatcherClassRepresents a matcher that can perform special data matching capabilities between a given pattern and a target.
MatchFailureStructMatch failure details.
MatchResultClassThe result of Match.test().
TagsClassAllows assertions on the tags associated with a synthesized CDK stack's manifest.
TemplateClassSuite of assertions that can be run on a CDK stack.
TemplateParsingOptionsStructOptions to configure template parsing behavior, such as disregarding circular dependencies.