我正在 ts 中重构一个已经达到资源限制的 cdk 堆栈。由于它包含有状态资源,我想确保重构的堆栈引用相同的资源,而不是新资源,这可能会触发不良结果,例如孤立或删除。
为了解决这个问题,我希望编写一个单元测试,断言从堆栈生成的模板包含具有给定逻辑 ID 集的资源。我已经看到了断言具有给定属性的资源存在的方法,但不存在具有给定 id 的资源。
如何检查堆栈是否包含具有给定逻辑 ID 的资源?我想做如下的事情:
describe('MyStack', () => {
test('synthesizes with expected logical IDs', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'MyStackDev', {
deploymentEnvironment: 'dev',
});
const template = Template.fromStack(stack);
const expectedLogicalIds = [
apiGatewayDev,
lambdaDev,
webSocketLambdaDev,
devLambdaWithConcurrentProvisioning,
neptuneBastionHostDev,
neptuneClusterDev,
auroraClusterDev,
sevenndevimages,
sevenndevprivate,
sparkQueryLogs,
shareLinks,
webSocketInstances,
flowInteractionLog,
];
expectedLogicalIds.forEach((logicalId) => {
// NOTE: if I need to apply the type, then I'll need to do some more work
// to make sure the right type is matched with the right logical id
// either way, I don't expect it to work as written because I don't
// believe this is proper usage of hasResourceProperties, as the
// logical id is actually the key of the resource object
expect(
template.hasResourceProperties('AWS::Lambda::Function', { LogicalId: logicalId }),
).toBeTruthy();
});
});
});
我认为,如果你想安全的话,你确实需要确保资源类型也匹配。
.templateMatches()
来检查逻辑ID:
expect(
template.templateMatches({
Resources: {
// This is your logical ID, which is the key of the resource object
[lambdaDev]: {
Type: "AWS::Lambda::Function",
},
},
}),
).toBeTruthy();
这会起作用,因为您可以指定模板的子集。来自文档:
默认情况下,templateMatches() API 将使用“类对象”比较,这意味着它将允许实际模板成为给定期望的超集。