Infrastructure Tests with CDK
Tags: aws, cloud, devops, cdk
Published: 2022-03-09 10:23:31

Written by Kristine Jetzke
_Originally published on July 29th 2021_

**This article gives an overview of the main testing functionalities provided by the AWS Cloud Development Kit (CDK) and shares some of our recent learnings and findings.**

<p>
I come from a software development background. Well, actually a testing one. I used to be a tester and have carried this mindset with me for over a decade now while I moved first into development and then later into more ops and infrastructure related topics. 
</p>
<p>
What has always annoyed me about infrastructure automation were the long feedback cycles. As a developer - especially one with a Java background - I was so used to getting immediate feedback because writing unit tests and running them all the time is second nature. I don’t even remember the last time I wrote a piece of backend code and manually started the application to see that it works. It is just not something that you ever do as a backend developer. What a waste of time. And much too risky as well. Why would I trust myself to be able to perform the same mundane step in the worst case dozens of times over a longer period of time, while mentally keeping track of every single change I made. I’m doomed to make a small mistake at some point and not catch the bug. Also, the mental overhead of remembering all the different test cases is just not worth it. But I digress...
</p>
<p>
Lately, I have been using the <a href="https://aws.amazon.com/cdk">AWS Cloud Development Kit</a> (CDK) a lot to set up infrastructure on AWS, and I am so happy about the build-in test support. Not only did it save a lot of time already, but I also really like that there is now (finally) a way to actually document intent. In this article I want to share some of my learnings and findings with you about how to use the testing capabilities of the CDK. 
</p>
<p>
Note that this article is not an introduction to CDK itself. If you are new to CDK, you might want to check out our <a href="https://kreuzwerker.de/post/brief-primer-on-cdk">brief primer on CDK</a>, published as a companion piece to this article. It should give you enough background information to be able to follow this article even without prior CDK knowledge. I do assume basic familiarity with <a href="https://aws.amazon.com/de/cloudformation/">AWS CloudFormation</a> though. 
</p>
<p>
Before diving in, a brief clarification of the terminology used in this article for the different types of tests. 
</p>
<h2>Test Terminology</h2>

<p>
There are three different ways of testing in CDK according to the <a href="https://docs.aws.amazon.com/cdk/latest/guide/testing.html">AWS documentation</a>: fine-grained assertions tests, validation tests and snapshot tests. I personally find the difference between the fine-grained assertions tests and the validation tests a little bit obsolete. They both test certain aspects of the code, and for my way of thinking it doesn’t matter so much if the code under test is code that only uses the CDK API (fine-grained assertions tests) or “regular” code that is used to parameterize the calls to the API (validation tests). On top I can imagine other functionality that needs to be tested, e.g. loops that don’t fall neatly into either of those two categories. Thus, I will not distinguish between those two types of tests going forward and will just call them <em>unit tests </em>in order to differentiate them from the<em> snapshot tests</em>. 
</p>
<h2>Our Example</h2>

<p>
We are going to use a simple S3 bucket throughout this article to show the available testing methods and their use cases. We will set some basic properties on the bucket (e.g. the name), apply some tags to it and configure the removal policy. I have tried to always choose the most minimal example I could think of since the focus of this article is to show the testing capabilities of the CDK, not the CDK itself.
</p>
<p>
Our language of choice is TypeScript. It is at the time of writing the only language that supports testing.<sup id="fnref1"><a href="#fn1" rel="footnote">1</a></sup> Just for this fact alone, I would always recommend to treat TypeScript as the first choice when deciding on the CDK language and only use another language if you have strong reasons for it. The testing library used is <a href="https://jestjs.io/">Jest</a>.  
</p>
<p>
So, let’s finally see some code! Below is the CDK snippet that creates the S3 bucket. I’m showing the complete stack here for context but going forward will only show the relevant part. You can find the complete code in <a href="https://github.com/kreuzwerker/blog-testing-with-cdk">this repository</a> which also contains a <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tags">dedicated tag </a>for each section of this article. 
</p>
<p>
Note that all examples use Version 1 of the AWS CDK because Version 2 is still in <a href="https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-v2.html">Developer Preview</a> at the time of writing.
</p>

```TypeScript
import * as cdk from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3';

export class BucketStack extends cdk.Stack {
 constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
   super(scope, id, props);

   new s3.Bucket(this, 'Bucket');

 }
}
```

<p>
In the remainder of the article I will show how to write unit tests and snapshot tests for this bucket, making configuration changes to it as we go along and explaining the different testing methods available in the CDK; and starting with some very simple assertions of single properties, moving on to test different kinds of attributes and ending with testing the complete template. 
</p>
<p>
Before we start though - a brief interlude: What I found quite confusing in the beginning (might be me, might be my Spring Boot background fighting Node ecosystem or bad CDK documentation...) is that the <a href="https://docs.aws.amazon.com/cdk/latest/guide/testing.html#testing_fine_grained">official AWS documentation</a> uses different methods for the assertions than the sample code that is auto-generated when creating a new CDK app via <code><a href="https://docs.aws.amazon.com/cdk/latest/guide/cli.html#cli-init">cdk init</a></code>.

<p>
In case I’m not the only one confused by this - here is an explanation. The main library used for assertions is <a href="https://www.npmjs.com/package/@aws-cdk/assert">@aws-cdk/assert</a>. It provides all functionality that can be used inside CDK unit tests with this format <code>expect(stack).to(someExpectation(...))</code> This library is used directly by the auto-generated sample code e.g.
</p>

```TypeScript
expectCDK(stack).to(matchTemplate({
     "Resources": {}
   }, MatchStyle.EXACT))
```

<p>
The examples in the official documentation use custom matchers defined in <code>@aws-cdk/assert/jest</code> which basically provide some syntactic sugar on top of the other ones, e.g. instead of writing   <code>expectCDK(stack).to(matchTemplate(...))</code> you can write <code>expect(stack).toMatchTemplate(...)</code>. I will cover their different use cases in more detail later. But let’s start with writing the most simple test first.
</p>

<h2>Unit Tests</h2>

<h3>How to Write A First Simple Test</h3>

<p>
Starting off there is not yet much to test. So, let’s add the test skeleton:
</p>

```TypeScript
import '@aws-cdk/assert/jest';
import * as cdk from '@aws-cdk/core';
import { BucketStack } from '../lib/bucket-stack';

test('Stack contains bucket', () => {
  const app = new cdk.App();
  const stack = new BucketStack(app, 'MyTestStack');

  expect(stack).toHaveResource('AWS::S3::Bucket');
});
```

<p>
All this test does is to verify that the stack actually contains an S3 bucket by using the <code><a href="https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/assert-internal/lib/assertions/have-resource.ts#L26">toHaveResource </a></code> method. It does not check any attributes yet. However, it at least ensures that the stack contains an S3 bucket and will fail with the following message if someone deletes it from the stack:
</p>
<p>

![Blog Infrastructure Tests with CDK](//images.contentful.com/hqu2g0tau160/7nozcakOboz3xO8xAdmsdZ/2e253405d6496657813dc0122ba8c693/Blog-1.png)

</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/first-simple-test">here</a>.
</p>

<h3>How to Test Resource Properties</h3>

<p>
Let’s move on and write an actual test testing a property. For the sake of simplicity, let’s write a test that checks the bucket name. Let’s do some TDD-style programming and first write a test for the expected behavior. 
</p>

```TypeScript
test('Bucket name', () => {
  const app = new cdk.App();
  const stack = new BucketStack(app, 'MyTestStack');

  expect(stack).toHaveResource('AWS::S3::Bucket', {
     BucketName: 'my-bucket'
  });
});
```

<p>
As expected - the test fails because we haven’t set the bucket name in our example code yet 
</p>

![Blog Infrastructure Tests with CDK](//images.contentful.com/hqu2g0tau160/3VA2oyMVdxsM9AHuQ7LAKH/8c66d88c257c38091ce1d1673bbcd202/Blog-2.png)

<p>
As a side note: What you can see here - and might consider a limitation - is that the test checks only the generated CloudFormation output. It does not check the actual bucket name that would get assigned if the bucket gets deployed. It is a unit test after all. 
</p>
<p>
Now let’s add the bucket name in our stack:
</p>

```TypeScript
new s3.Bucket(this, 'Bucket', {
     bucketName: 'my-bucket'
   });
```

<p>
And tada - success!
</p>

![Blog-Infrastructure Tests with CDK](//images.contentful.com/hqu2g0tau160/7A8gHVWz2Vo4oBLiQji6As/9bbaafaa70fc408fce8fb0989136c032/Blog-Infrastructure_Tests_with_CDK.png)

<p>
What would happen if we picked a bucket name that is not allowed by S3, e.g. one containing upper case letters? 
</p>

```TypeScript
new s3.Bucket(this, 'Bucket', {
     bucketName: 'MyBucket'
   });
```

<p>
The test fails with a quite detailed error message.
</p>

![Blog-Infrastructure Tests with CDK-1](//images.contentful.com/hqu2g0tau160/190BlvheA2Xz47lpIjvJBd/0acd3611d66462c61762ef053ddcd98b/Blog-Infrastructure_Tests_with_CDK-1.png)

<p>
This is in my opinion one of the huge benefits of using CDK. Fast feedback! Getting this feedback took 23 milliseconds. Compare that with pure CloudFormation which would take several minutes: you have to upload the template, wait for the deployment to start and finally fail. And on top of that even with a less detailed error message.<sup id="fnref2"><a href="#fn2" rel="footnote">2</a></sup> 
</p>

![Blog-Infrastructure Tests with CDK-2](//images.contentful.com/hqu2g0tau160/6uCn0BtV59uJ6iM0sHNuBR/2be32e2bbac46773f3b361aefe10f2f4/Blog-Infrastructure_Tests_with_CDK-2.png)

<p>
Since bucket names are often not static but contain some dynamic values, let’s next set the bucket name dynamically by including the environment<sup id="fnref3"><a href="#fn3" rel="footnote">3</a></sup> name in it e.g. <code>my-bucket-production</code>. The environment name will be passed as the first parameter to the bucket stack (btw I’d love to learn more about how different people parameterize. I’ve tried several approaches now but am not completely satisfied with any of them so far.). 
</p>
<p>
I extended the test with the expected behavior and - as expected - it fails because the actual name and the expected name don’t match (yes, I admit I'm not a TDD purist, I already extended the constructor).
</p>

```TypeScript
const stack = new BucketStack('foo', app, 'MyTestStack');

  expect(stack).toHaveResource('AWS::S3::Bucket', {
     BucketName: 'my-bucket-foo'
  });
```

![Blog-Infrastructure Tests with CDK-3](//images.contentful.com/hqu2g0tau160/4ra4IDLHEnOL0xW2M6MTBf/6d60996265a75a6475c2fce498bab0e3/Blog-Infrastructure_Tests_with_CDK-3.png)

<p>
The test passes after adapting the code to set the bucket name to the desired format. 
</p>

```TypeScript
export class BucketStack extends cdk.Stack {
 constructor(environment: string, scope: cdk.Construct, id: string, props?: cdk.StackProps) {
   super(scope, id, props);

   new s3.Bucket(this, 'Bucket', {
     bucketName: `my-bucket-${environment}`
   });

 }
}
```

<p>
And even though this example is quite simple so far, it already gives a first glimpse into how powerful the CDK with its actual programming capabilities can be.
</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/test-simple-attribute">here</a>.
</p>

<h3>How to Test Array Resource Properties</h3>

<p>
While we’re at it and messing with the environment - let’s add the environment name as a tag as well. This will be used to show different ways of how to test array properties.
</p>
<p>
Let’s add a new test for testing the tags. I’ll take the chance and refactor a little and introduce a section for all tests that are related to environment-specific settings that contains the previously created test for the bucket name and the new test for the tags.
</p>

```TypeScript
describe('Environment name applied', () => {

  test('Bucket name contains environment name', () => {
    ...
  });

  test('Environment name applied as tag', () => {
     const app = new cdk.App();
     const stack = new BucketStack('foo', app, 'MyTestStack');

     expect(stack).toHaveResource('AWS::S3::Bucket', {
        Tags: [
           {
              Key: 'environment',
              Value: 'foo'
           }
        ]
     });
  });
});
```

<p>
The new test for the tags is at this point almost identical to the test for the bucket name; it just tests a different property. What you can clearly see here is that each test only tests the properties specified and ignores the rest, i.e. the tag test does not care about the bucket name and vice versa.
</p>
<p>
The new test fails as expected since we did not assign any tags yet to the bucket. But what is actually quite nice is that because of the way the tests are structured now, you can see immediately that something is wrong with the tags and not the bucket name:
</p>

![Blog-Infrastructure Tests with CDK-4](//images.contentful.com/hqu2g0tau160/vs4qm7vq2BdC8BPjtbDNT/fc0884de7e4bc1460c8aaeced9727c87/Blog-Infrastructure_Tests_with_CDK-4.png)

<p>
After adapting the code<sup id="fnref4"><a href="#fn4" rel="footnote">4</a></sup> the test passed as expected:
</p>

```TypeScript
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `my-bucket-${environment}`
   });
   cdk.Tags.of(bucket).add('environment', environment)
```

![Blog-Infrastructure Tests with CDK-5](//images.contentful.com/hqu2g0tau160/5SR4nj4FTON74JFReDVz1w/bbf08f1fae21fa7c549ccb02fd57fc85/Blog-Infrastructure_Tests_with_CDK-5.png)

<p>
Another side note: In this example you can see a limitation of the CDK’s testing capabilities. Or at least something that becomes annoying over time. The code assigning the tags provides a nice abstraction layer over the underlying CloudFormation resource representation. You don’t need to know how tags are represented in CloudFormation. However, in order to write the test, you need to know that the CDK tags are represented internally in CloudFormation as an array of objects with <code>Key</code> and <code>Value</code> attributes. Otherwise, you cannot verify that they get assigned correctly. This is actually one area where I would love for improvement in the testing support and have similar abstraction layers as in the main CDK code. 
</p>

<p>
But coming back to our example. We added a tag for the environment and the corresponding test passed. So far, so good. What happens if someone changes the tag, removes the tag or adds another one? Have a look at the different outcomes. 
</p>

<table>
  <tr>
   <td>Tag Key or Value Changed
   </td>
   <td>

![Blog-Infrastructure Tests with CDK-6](//images.contentful.com/hqu2g0tau160/2MlxF4CQdHSqAaK1fwLde9/9ca82917ca4ec0219eaf5e4b91ebbc16/Blog-Infrastructure_Tests_with_CDK-6.png)

   </td>
  </tr>
  <tr>
   <td>Tag Removed
   </td>
   <td>

![Blog-Infrastructure Tests with CDK-7](//images.contentful.com/hqu2g0tau160/6Fh5fDxXrRbdTzLHc6YWgd/e104de510a0fd58d9299b01a4361ad64/Blog-Infrastructure_Tests_with_CDK-7.png)

   </td>
  </tr>
  <tr>
   <td>Tag Added 
   </td>
   <td>

![Blog-Infrastructure Tests with CDK-8](//images.contentful.com/hqu2g0tau160/1FGTVQTjjbFtFzCJngvM8N/3285fcc87db1224a000a79cd7a22f8ba/Blog-Infrastructure_Tests_with_CDK-8.png)

   </td>
  </tr>
</table>

<p>
Is this the expected behavior? For the first two cases (change and removal) for sure. The error messages could be improved a little bit maybe. You need to look at the details to really understand what is going on. But other than that - it’s fine. But what about the failure when adding another tag? We actually only want to be sure that the environment is included in the list of tags. If additional tags exist, we don’t care. And we definitely don’t want to update our tag test with every change in the tag array.
</p>
<p>
For a case like this, the method <code><a href="https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/assert-internal/lib/assertions/have-resource.ts#L37">toHaveResourceLike</a></code> comes in handy. It passes if the actual values are a superset of the expected values, whereas <code>toHaveResource</code> only passes if the values are an exact match.

<p>
Thus, when we change the test to use this method instead, it passes:
</p>

```TypeScript
expect(stack).toHaveResourceLike('AWS::S3::Bucket', {
        Tags: [
           {
              Key: 'environment',
              Value: 'foo'
           }
        ]
     });
```

<p>
However, there is yet another shortcoming: the order of the elements in the array matters. If the additional tag is not added <strong>after</strong> but <strong>before</strong> our environment tag<sup id="fnref5"><a href="#fn5" rel="footnote">5</a></sup>, the test fails even when  <code>toHaveResourceLike</code> is used:
</p>

![Blog-Infrastructure Tests with CDK-9](//images.contentful.com/hqu2g0tau160/3qiUIUV21q6hW9SzZfyQc2/25aee58d4d45806db7ad53ec8d447146/Blog-Infrastructure_Tests_with_CDK-9.png)

<p>
This is the point where switching to the underlying assertions from <code>@aws-cdk/assert </code>makes sense. It provides a lot more functionality when it comes to matching content inside the resources. E.g. in this case the <code>arrayWith</code> matcher can be used. It checks that the array contains the given element. Now the test will only fail if either the environment tag gets completely removed or if it contains wrong values. Anything else can happen with the tags property and the test won’t be affected. 
</p>

```TypeScript
import { expect as expectCDK, haveResourceLike, arrayWith } from '@aws-cdk/assert'
...
expectCDK(stack).to(haveResourceLike('AWS::S3::Bucket', {
        Tags: arrayWith(
           {
              Key: 'environment',
              Value: 'foo'
           }
        )
     }));
```

<p>
There are several more matchers available and also the option to capture output. Maybe something for another blog post...
</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/test-complete-resource">here</a>.
</p>

<h3>How to Test Other Resource Attributes</h3>

<p>
Until now we have only verified resource properties such as the bucket name or the bucket tags, and that’s where most of the action is anyway. However, sometimes you want to test other resource attributes as well. 
</p>
<p>
Something I have been doing quite often is to change the default removal policy, which is by the way something I had to get used to when switching from CloudFormation. In fact, the default in CloudFormation is that resources get deleted, whereas in CDK it is the reverse: resources get retained. And it is a sensible default for production environments. However, for other environments it may not always make sense that way. E.g. imagine an ephemeral environment (a.k.a. feature environment a.k.a. review environment) that gets automatically created for each pull request and gets destroyed again after the pull request has been merged. In that case, all resources of the stack should always be destroyed when the stack gets destroyed and not be retained. 
</p>
<p>
So let’s assume we want to always delete our bucket and thus the two relevant removal policy attributes <code>DeletionPolicy</code> and <code>UpdateReplacePolicy</code> should be set to <code>Delete</code>. The naive way to test for this is to just add the attributes with the desired values to the expected outcome of the test. However, the test fails with the error message <code>Field UpdateReplacePolicy missing, Field DeletionPolicy missing</code> as shown below.
</p>

```TypeScript
test('Retention settings, () => {
  ...
  expect(stack).toHaveResource('AWS::S3::Bucket', {
     UpdateReplacePolicy: 'Delete',
     DeletionPolicy: 'Delete',
  });
});
```

<p>

![Blog-Infrastructure Tests with CDK-10](//images.contentful.com/hqu2g0tau160/B88rcCJoBWCO52wunC5JO/9a317bd4f86a7780b94bec9a88297d03/Blog-Infrastructure_Tests_with_CDK-10.png)

</p>
<p>
Why this happens becomes apparent when looking at the generated CloudFormation template. It looks like this:
</p>

```TypeScript
Resources:
  Bucket83908E77:
	Type: AWS::S3::Bucket
	Properties:
  	  BucketName: my-bucket-foo
       Tags:
         - Key: environment
           Value: foo
	UpdateReplacePolicy: Retain
	DeletionPolicy: Retain
```

<p>
You can see that the two relevant attributes <code>DeletionPolicy</code> and <code>UpdateReplacePolicy</code> are not part of the Properties section of the template, which is the section considered by default by the <code>toHaveResource</code> method. Other sections are ignored. Luckily, this can easily be changed by setting the <a href="https://docs.aws.amazon.com/cdk/api/latest/typescript/api/assert/resourcepart.html#assert_ResourcePart">ResourcePart</a> parameter to <code>CompleteDefinition</code>. Now the complete resource will be verified.
</p>

```TypeScript
expect(stack).toHaveResource('AWS::S3::Bucket', {
     UpdateReplacePolicy: 'Delete',
     DeletionPolicy: 'Delete',
  }, ResourcePart.CompleteDefinition);
```

<p>

![Blog-Infrastructure Tests with CDK-11](//images.contentful.com/hqu2g0tau160/13D4FyWjAMg2nBrT8VfeGp/7bbb7004ca3c46f6bbfb5b987d11b45c/Blog-Infrastructure_Tests_with_CDK-11.png)

</p>
<p>
And after the stack is changed accordingly, the test passes:
</p>

```TypeScript
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `my-bucket-${environment}`,
     removalPolicy: cdk.RemovalPolicy.DESTROY
   });
```

<p>

![Blog-Infrastructure Tests with CDK-12](//images.contentful.com/hqu2g0tau160/7w9ubZjodpfVXM7XqhSK7t/ddae3d035fdd9ccc7d583798dfaa6700/Blog-Infrastructure_Tests_with_CDK-12.png)

</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/snapshot-test">here</a>.
</p>
<h3>How to Test (Parts of) the Template</h3>

<p>
One last unit test method I want to discuss before moving on to the snapshot tests is the <code>toMatchTemplate</code> one, which lets you verify the complete synthesized template or a subset of it. To be honest I haven’t yet had too many use cases in which I used it because its usage seems to lead to quite some maintenance effort down the road. 
</p>
<p>
The two use cases I came up with so far are
</p>
<ol>

<li>Verify the logical resource ID in case there is some custom code for it.

<li>Verify that the template contains no resources that require a replacement.
</li>
</ol>
<p>
This is what a test looks like that verifies the complete template:
</p>

```TypeScript
test('Test template', () => {
  const app = new cdk.App();
  const stack = new BucketStack('foo', app, 'MyTestStack');
  expect(stack).toMatchTemplate({
     "Resources": {
        "Bucket83908E77": {
           "Type": "AWS::S3::Bucket",
           "Properties": {
              "BucketName": "my-bucket-foo",
              "Tags": [
                 {
                    "Key": "abc",
                    "Value": "123"
                 },
                 {
                    "Key": "environment",
                    "Value": "foo"
                 }
              ]
           },
           "UpdateReplacePolicy": "Delete",
           "DeletionPolicy": "Delete"
        }
     }
  }, MatchStyle.EXACT)
});
```

<p>
There are three configuration options that configure how strict the matching is performed: <code>MatchStyle.EXACT</code> (the default), <code>MatchStyle.SUPERSET</code> and <code>MatchStyle.NO_REPLACES</code>.
</p>
<p>
With <code>MatchStyle.EXACT</code>, the test will fail if the actual template and the expected one are not an exact match, i.e. when you change anything in the template such as adding another resource, modifying the existing one or removing an existing one.
</p>
<p>
Examples:
</p>
<ul>

<li>When an additional resource <code>new s3.Bucket(this, 'OtherBucket') </code>is added, the test fails and shows this diff: 

![Blog-Infrastructure Tests with CDK-13](//images.contentful.com/hqu2g0tau160/2T1ivUTh7ByiIbZVbHVsAX/c6dd27ef5f83ee5990c592f97df7c7a0/Blog-Infrastructure_Tests_with_CDK-13.png)

<li>When the existing bucket is deleted it fails and shows that it is removed and that it will be destroyed: 

![Blog-Infrastructure Tests with CDK-14](//images.contentful.com/hqu2g0tau160/4aWm99l86bqH2Tyk3QSehq/3033adc8aff7d7ec7ab3cc3fca320e83/Blog-Infrastructure_Tests_with_CDK-14.png)

<li>When an attribute is changed it fails and shows the difference:

<li>

![Blog-Infrastructure Tests with CDK-15](//images.contentful.com/hqu2g0tau160/Wbwj7yq3b78kXGjp2fWva/2ddf39700a46ff73a42c6fa05171ce9f/Blog-Infrastructure_Tests_with_CDK-15.png)

<li>When an attribute is changed that leads to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">the replacement </a>of the whole resource e.g. the bucket name it fails and indicates this as well: 

![Blog-Infrastructure Tests with CDK-16](//images.contentful.com/hqu2g0tau160/63UjrlDSKYZVw60mtEj0Mh/5b81d068c328d677888017fe2014c9d7/Blog-Infrastructure_Tests_with_CDK-16.png)

</li>
</ul>
<p>
The behavior is almost similar to <code>MatchStyle.SUPERSET</code>. The only difference is when an additional resource is added. In that case it will continue to pass since it only verifies<code> </code>sub-sections of the template. Note though that the complete resource is always verified, i.e. it is  not possible to verify a subset of attributes of a resource. This is the main difference to the previously described <code>toHaveResource</code> method.
</p>
<p>
And then there is the third option <code>MatchStyle.NO_REPLACES</code> which will only cause the test to fail if there is a change that causes the resource to be replaced.  
</p>
<p>
Let’s assume you make a lot of changes to this stack:
</p>

```TypeScript
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `my-bucket-${environment}`,
     removalPolicy: cdk.RemovalPolicy.DESTROY
   });
   cdk.Tags.of(bucket).add('abc', '123')
   cdk.Tags.of(bucket).add('environment', environment)
```

<p>
And remove all attributes except the name and add another bucket to the stack, resulting in this one:
</p>

```TypeScript
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `my-bucket-${environment}`
   });

   new s3.Bucket(this, 'OtherBucket');
```

<p>
With <code>MatchStyle.NO_REPLACES </code>the test will continue to pass.
</p>
<p>

![Blog-Infrastructure Tests with CDK-17](//images.contentful.com/hqu2g0tau160/5CKJKyJ0O2tK4jeMUSdWs7/3fb6e0817f6e649af96d0f55a7bef39e/Blog-Infrastructure_Tests_with_CDK-17.png)

</p>
<p>
But if you change the bucket name afterwards- <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-name">which causes a replacement</a> -  it will fail:
</p>

```TypeScript
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `your-bucket-${environment}`
   });

   new s3.Bucket(this, 'OtherBucket');
```

<p>

![Blog-Infrastructure Tests with CDK-18](//images.contentful.com/hqu2g0tau160/1fb8yyf0LTI73MV05hJl8A/a1eef6a207d774c8b4c95d14a37c6b09/Blog-Infrastructure_Tests_with_CDK-18.png)

</p>
<p>
I find this setting the most useful. Having an early warning about a replacement can be quite helpful indeed! And compared to the other settings it doesn’t result in too much maintenance effort. You can have one test per stack that contains all the resources with only the properties that require a replacement. This test will fail if you make a change and force you to conscientiously accept the replacement by fixing the test. I would love to see this feature actually integrated into the snapshot tests because it would remove the need to manually create a copy of the template. And talking about snapshot tests… let’s close this section about the unit tests and move to snapshot tests next.
</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/test-template">here</a>.
</p>

<h2>Snapshot Tests</h2>

<p>
Snapshot tests - as the name suggests - take a snapshot of the stack and compare it to the stored version. Under the hood it uses the <a href="https://jestjs.io/docs/snapshot-testing">snapshot testing feature of jest</a>. There is no abstraction layer on top so the functionality is quite limited.
</p>
<p>
It is quite straightforward to write a snapshot test since all assertions are done automatically.
</p>

```TypeScript
import { SynthUtils } from '@aws-cdk/assert';
import * as cdk from '@aws-cdk/core';

import { BucketStack } from '../lib/bucket-stack';

test('bucket stack', () => {
 const app = new cdk.App();
 const stack = new BucketStack('foo', app, 'TestBucketStack');
 expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot();
});
```

<p>
The first time you run it, a new folder called <code>__snapshots__</code> will be created and the snapshot will be stored in it. 

![Blog-Infrastructure Tests with CDK-19](//images.contentful.com/hqu2g0tau160/3mkrOeTytBz5942RwyWobM/946740fac83246f4dac0d38a7b9421eb/Blog-Infrastructure_Tests_with_CDK-19.png)

</p>
<p>
On each subsequent run, the synthesized template is compared against the stored snapshot. 
</p>
<p>

![Blog-Infrastructure Tests with CDK-20](//images.contentful.com/hqu2g0tau160/S5yXcDi2dNgmQC68R07hb/8d9458a4006b37611ecd058aae198eaf/Blog-Infrastructure_Tests_with_CDK-20.png)

</p>
<p>
If you change the template, the snapshot test will fail
</p>

```TypeScript   
const bucket = new s3.Bucket(this, 'Bucket', {
     bucketName: `your-bucket-${environment}`,
     removalPolicy: cdk.RemovalPolicy.DESTROY
   });
```

<p>

![Blog-Infrastructure Tests with CDK-21](//images.contentful.com/hqu2g0tau160/46rYUXVIEg7ZdknvIvQlAO/f2da66164e632ebd3bcae4c3647d9987/Blog-Infrastructure_Tests_with_CDK-21.png)

</p>
<p>
You can review the change and if it’s ok, you can automatically update the snapshot by running again with the <code>-u</code> option:
</p>
<p>

![Blog-Infrastructure Tests with CDK-22](//images.contentful.com/hqu2g0tau160/sxfRDju9Q84wtZm9mq406/dc64972239a84fd85d42bb340080f530/Blog-Infrastructure_Tests_with_CDK-22.png)

</p>
<p>
And that’s basically all there is to say about the snapshot tests. I do think that they could be vastly improved, e.g. by adding an abstraction layer and - as stated in the previous section - providing an option to only fail if one of the resources requires a replacement. Right now they are quite basic and should be used sparingly since they are very broad, don’t really document intent and might result in quite some maintenance effort. However, they can be considered a last safety net. In theory they can also be used for TDD style development. However, I found it hard to manually update the snapshot beforehand because the readability of the generated snapshot is not that good due to the serialization format and the file length. 
</p>
<p>
Code until here can be found <a href="https://github.com/kreuzwerker/blog-testing-with-cdk/tree/snapshot-test">here</a>.
</p>

<h2>Conclusion</h2>

<p>
This article gave an overview of the main testing functionalities provided by <a href="https://kreuzwerker.de/post/brief-primer-on-cdk">CDK</a>. Some key takeaways:
</p>
<ul>

<li>Having tests in place allows for fast feedback loops and ensures better maintainability down the road. 

<li>The main methods to test resource properties and other resource attributes are <code>toHaveResource</code> and <code>toHaveResourceLike</code>. For more advanced use cases, matchers and captures provided by <code>@aws-cdk/assert</code> can be used.

<li>Use <code>toMatchTemplate</code> or snapshot tests to test the whole template or a complete subsection of it.
</li>
</ul>
<p>
And while I’m super happy about the fact that those testing capabilities exist, I do see room for improvements, namely:
</p>
<ul>

<li>Provide an abstraction layer for the testing library as well. You don’t need to know how CDK attributes map to the underlying CloudFormation attributes when defining the stack. However, once you move to the tests, you suddenly do need to know. This makes the tests harder to write, maintain and understand. 

<li>Provide additional functionality to the snapshot tests, e.g. allow a setting that causes the test only to fail if a resource requires replacement.

<li>Better documentation. 
</li>
</ul>
<p>
Are you completely satisfied with the testing capabilities of the CDK or are you also looking for improvements? How is your experience with it in general? Looking forward to hearing your thoughts!
</p>

<!-- Footnotes themselves at the bottom. -->

<h2>Notes</h2>
<div class="footnotes">
<hr>
<ol><li id="fn1">
<p>
     This might very soon become obsolete. A new module <code>@aws-cdk/assertions</code> providing testing support for all languages <a href="https://github.com/aws/aws-cdk/pull/15173">was very recently made experimentally available</a>.&nbsp;<a href="#fnref1" rev="footnote">&#8617;</a><li id="fn2">
<p>
     <a href="https://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.html">Validate-template</a> is of no help either because it only checks syntax.&nbsp;<a href="#fnref2" rev="footnote">&#8617;</a><li id="fn3">
<p>
     Not to be confused with the <a href="https://docs.aws.amazon.com/cdk/latest/guide/environments.html">CDK term environment</a> which describes the account/region target&nbsp;<a href="#fnref3" rev="footnote">&#8617;</a><li id="fn4">
<p>
      This is actually not how you should do it in real life. I only used it here because I was looking for a simple array example. Instead, you should use the <a href="https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stackprops.html#core_StackProps_tags">tags attribute of StackProps</a>. All tags defined there get automatically applied to the stack itself and all its resources (except for when they don’t due to <a href="https://github.com/aws/aws-cdk/issues/14127">some bug</a>…). &nbsp;<a href="#fnref4" rev="footnote">&#8617;</a><li id="fn5">
<p>
     By default, the tags are sorted alphabetically by <code>Key</code> inside the array. &nbsp;<a href="#fnref5" rev="footnote">&#8617;</a>

</ol></div>