アサーションとは

プログラミング一般の用語で「ある条件が真であることを検証する」こと

CDK 固有の概念ではなく、Jest、Pytest、JUnit など一般的なテストフレームワークで使われる

CDK Assertions モジュール

CDK が生成する CloudFormation テンプレートに対してテストを書くためのライブラリ

出典: Test AWS CDK applications

“The standard approach to testing AWS CDK apps uses the AWS CDK’s assertions module and popular test frameworks like Jest for TypeScript and JavaScript or Pytest for Python.”

2種類のテスト

出典: Test AWS CDK applications

“Fine-grained assertions test specific aspects of the generated AWS CloudFormation template, such as ‘this resource has this property with this value.’ These tests can detect regressions.” “Snapshot tests test the synthesized AWS CloudFormation template against a previously stored baseline template.”

種類内容
Fine-grained assertions特定のリソースが特定のプロパティを持つか検証
Snapshot tests生成されたテンプレート全体を過去のベースラインと比較

import { Template } from 'aws-cdk-lib/assertions';
 
const template = Template.fromStack(myStack);
 
// S3 バケットが暗号化されているか検証
template.hasResourceProperties('AWS::S3::Bucket', {
  BucketEncryption: {
    ServerSideEncryptionConfiguration: [
      { ServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' } }
    ]
  }
});