@aws-cdk/assertions

中文文档
1.204.0发布于 2023/06/20Apache-2.0TypeScriptCommonJS近 30 天下载 9196

An assertion library for use with CDK Apps

此软件包已被标记为弃用

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 https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

原始使用文档
文档目录13 节
  1. Full Template Match
  2. Counting Resources
  3. Resource Matching & Retrieval
  4. Output and Mapping sections
  5. Special Matchers
  6. Object Matchers
  7. Presence and Absence
  8. Array Matchers
  9. String Matchers
  10. Not Matcher
  11. Serialized JSON
  12. Capturing Values
  13. Asserting Annotations

Assertions


End-of-Support

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:

import { Stack } from '@aws-cdk/core';
import { Template } from '@aws-cdk/assertions';

const stack = new Stack(/* ... */);
// ...
const template = Template.fromStack(stack);

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

const templateJson = '{ "Resources": ... }'; /* The CloudFormation template as JSON serialized string. */
const template = Template.fromString(templateJson);

Full Template Match

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

template.templateMatches({
  Resources: {
    BarLogicalId: {
      Type: 'Foo::Bar',
      Properties: {
        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', {
  Foo: 'Bar',
  Baz: 5,
  Qux: [ 'Waldo', 'Fred' ],
});

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

template.hasResource('Foo::Bar', {
  Properties: { Foo: 'Bar' },
  DependsOn: [ '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 -

const expected = { 
  Value: 'Bar',
  Export: { Name: 'ExportBaz' }, 
};
template.hasOutput('Foo', expected);

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

template.hasOutput('*', {
  Value: 'Bar',
  Export: { Name: 'ExportBaz' },
});

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

const result = template.findOutputs('*', { Value: 'Fred' });
expect(result.Foo).toEqual({ Value: 'Fred', Description: 'FooFred' });
expect(result.Bar).toEqual({ 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', {
  Fred: Match.objectLike({
    Wobble: 'Flob',
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    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', {
  Fred: Match.objectLike({
    Bob: Match.absent(),
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: Match.objectLike({
    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', {
  Fred: {
    Wobble: [ Match.anyValue(), Match.anyValue() ],
  },
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Fred: {
    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', {
  Fred: Match.arrayWith(['Flob']),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', Match.objectLike({
  Fred: Match.arrayWith(['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', {
  Template: Match.stringLikeRegexp('includeHeaders = (true|false)'),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  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', {
  Fred: Match.not(['Flob']),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', Match.objectLike({
  Fred: Match.not(['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', {
  Baz: Match.serializedJson({
    Fred: Match.arrayWith(["Waldo"]),
  }),
});

// The following will throw an assertion error
template.hasResourceProperties('Foo::Bar', {
  Baz: Match.serializedJson({
    Fred: ["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"],
//       }
//     }
//   }
// }

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

fredCapture.asArray(); // returns ["Flob", "Cat"]
waldoCapture.asString(); // returns "Qux"

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"],
//       }
//     }
//   }
// }

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

capture.asArray(); // returns ['Flob', 'Cat']

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",
//       }
//     }
//   }
// }

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

fredCapture.asString(); // returns "Flob"
fredCapture.next();     // returns true
fredCapture.asString(); // returns "Quib"

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:

import * as cdk from '@aws-cdk/core';
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());
  }
}

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:

  • 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 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.*'),
);

版本与发布记录

@aws-cdk/assertions 共发布 107 个版本,首次发布于 2021/06/24;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.204.0latest2023/06/203 年前
1.203.02023/06/013 年前
1.202.02023/05/223 年前
1.201.02023/05/113 年前
1.200.02023/04/273 年前
1.199.02023/04/213 年前

关于 @aws-cdk/assertions 的常见问题

@aws-cdk/assertions 是什么?

An assertion library for use with CDK Apps注意:该包已被作者标记为弃用——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 https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

如何安装 @aws-cdk/assertions?

在项目目录运行 npm install @aws-cdk/assertions,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@aws-cdk/cloud-assembly-schema(1.204.0)、@aws-cdk/core(1.204.0)、@aws-cdk/cx-api(1.204.0)、constructs(^3.3.69)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-cdk/assertions 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-cdk/assertions 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws-cdk/assertions 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14.15.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws-cdk/assertions 可以商用吗?

@aws-cdk/assertions 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-cdk/assertions 的下载量有多少?

根据 npm 官方下载统计,@aws-cdk/assertions 在 2026/10/07 – 2026/11/05 这 30 天内被下载 9,196 次,日均约 307 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-cdk/assertions 还在维护吗?

最新版本 1.204.0 发布于 2023/06/20(3 年前);至今共发布 107 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/06/24。作者已将其标记为弃用,新项目建议寻找替代方案。