Namespace Amazon.CDK.Assertions
Assertions
---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see the Migrating to AWS CDK v2 guide.
If you're migrating from the old assert
library, the migration guide can be found in
our GitHub repository.
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:
using Amazon.CDK;
using Amazon.CDK.Assertions;
var stack = new Stack();
// ...
var template = Template.FromStack(stack);
Alternatively, assertions can be run on an existing CloudFormation template -
var templateJson = "{ \"Resources\": ... }"; /* The CloudFormation template as JSON serialized string. */
var template = Template.FromString(templateJson);
Full Template Match
The simplest assertion would be to assert that the template matches a given template.
template.TemplateMatches(new Dictionary<string, IDictionary<string, IDictionary<string, object>>> {
{ "Resources", new Struct {
BarLogicalId = new Struct {
Type = "Foo::Bar",
Properties = new Struct {
Baz = "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.
template.ResourceCountIs("Foo::Bar", 2);
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 -
template.HasResourceProperties("Foo::Bar", new Dictionary<string, object> {
{ "Foo", "Bar" },
{ "Baz", 5 },
{ "Qux", new [] { "Waldo", "Fred" } }
});
Alternatively, if you would like to assert the entire resource definition, you
can use the hasResource()
API.
template.HasResource("Foo::Bar", new Dictionary<string, object> {
{ "Properties", new Struct { Foo = "Bar" } },
{ "DependsOn", new [] { "Waldo", "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.
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 -
IDictionary<string, object> expected = new Dictionary<string, object> {
{ "Value", "Bar" },
{ "Export", new Dictionary<string, string> { { "Name", "ExportBaz" } } }
};
template.HasOutput("Foo", expected);
If you want to match against all Outputs in the template, use *
as the logicalId
.
template.HasOutput("*", new Dictionary<string, object> {
{ "Value", "Bar" },
{ "Export", new Struct { Name = "ExportBaz" } }
});
findOutputs()
will return a set of outputs that match the logicalId
and props
,
and you can use the '*'
special case as well.
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" } });
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.
// 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" }
}) }
});
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.
// 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() }
}) }
});
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.
// 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()
} }
});
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.
// 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" }) }
}));
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.
// 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") }
});
Not Matcher
The not matcher inverts the search pattern and matches all patterns in the path that does not match the pattern specified.
// 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" }) }
}));
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.
// 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" } }
}) }
});
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.
// 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", new [] { "Qix", waldoCapture } }
});
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.
// 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();
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 -
// 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();
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
:
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());
}
}
We can then assert that the stack contains the expected Error:
// import { Annotations } from '@aws-cdk/assertions';
Annotations.FromStack(stack).HasError("/Default/Foo", "we do not want a Foo::Bar resource");
Here are the available APIs for Annotations
:
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 compatable with Matchers
for more fine-grained control.
For example, the following assertion works as well:
Annotations.FromStack(stack).HasError("/Default/Foo", Match.StringLikeRegexp(".*Foo::Bar.*"));
Classes
Annotations | Suite of assertions that can be run on a CDK Stack. |
Capture | Capture values while matching templates. |
Match | Partial and special matching during template assertions. |
MatchCapture | Information about a value captured during match. |
Matcher | Represents a matcher that can perform special data matching capabilities between a given pattern and a target. |
MatchFailure | Match failure details. |
MatchResult | The result of |
Template | Suite of assertions that can be run on a CDK stack. |
Interfaces
IMatchCapture | Information about a value captured during match. |
IMatchFailure | Match failure details. |