cdktn init so that you can start writing tests right away.
Add Testing to Your Application
If you would like to add testing to an existing project, refer the following resources according to your chosen language:-
TypeScript: Follow TypeScript’s Getting Started guide for testing with Jest. Then, add these lines in a setup file:
-
Python: Follow the Get Started guide for pytest. The assertions for CDKTN are available in the
cdktnpackage underTesting. -
Java: Follow the Using JUnit documentation. The assertions for CDKTN specific are available in the
cdktnpackage underTesting. -
C#: Follow the Getting Started with xUnit.net guide. The assertions for CDKTN are available in the
cdktnpackage underTesting. -
Go: Follow the Add a Test guide in the Go documentation. The assertions for CDKTN specific are available in the
cdktnpackage underTesting.
Write Assertions
The following Typescript example usesTesting.synth to test a part of the application. Given the desired scope to test, a JSON string representing the synthesized HCL-JSON is returned. Then the custom assertions under Testing in the cdktn package can be used to verify the code acts as intended. Testing.synth can test the Stack that extends the TerraformStack.
The other examples use Testing.synthScope to test a part of the application. This creates a scope to test a subset of the application and returns a JSON string representing the synthesized HCL-JSON. Then it uses custom matchers to verify the code acts as intended. Testing.synthScope can test the Constructs that extends the IConstruct.
CDK Terrain v0.20 introduces support for a
Testing.synthHcl function. However, that is not compatible with other assertions, like toHaveResourceWithProperties etc. and should not be used.toHaveResource: Checks if a certain resource existstoHaveResourceWithProperties: Checks if a certain resource exists with all properties passedtoHaveDataSource: Checks if a certain data source existstoHaveDataSourceWithProperties: Checks if a certain data source exists with all properties passedtoHaveProvider: Checks if a certain provider existstoHaveProviderWithProperties: Checks if a certain provider exists with all properties passed
Snapshot Testing
Snapshot tests are useful when you want to make sure your infrastructure does not change unexpectedly. Snapshot Testing is only supported in Typescript with Jest. Refer to the Jest docs for details.Integration with Terraform
You can produce invalid Terraform configuration if you are using escape hatches in your CDK Terrain application. You may use an escape hatch when setting up a remote backend or when overriding resource attributes To test this, you can assert thatterraform validate or terraform plan run successfully on all or part of your application before running cdktn plan or cdktn deploy.
Currently only Typescript is capable of testing for successful plans, while all languages are capable of testing for validity of the Terraform produced.