forked from aws/aws-cdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-resource.test.ts
248 lines (212 loc) · 8.31 KB
/
example-resource.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/*
* We write unit tests using the Jest framework
* (some modules might still use NodeUnit,
* but it's considered Names, and we want to migrate to Jest).
*/
import { Match, Template } from '@aws-cdk/assertions';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as core from '@aws-cdk/core';
// Always import the module you're testing qualified -
// don't import individual classes from it!
// Importing it qualified tests whether everything that needs to be exported
// from the module is.
import * as er from '../lib';
/* We allow quotes in the object keys used for CloudFormation template assertions */
/* eslint-disable quote-props */
const EXAMPLE_RESOURCE_NAME = {
'Fn::Select': [1, {
'Fn::Split': ['/', { 'Ref': 'ExampleResourceAC53F4AE' }],
}],
};
describe('Example Resource', () => {
let stack: core.Stack;
beforeEach(() => {
// try to factor out as much boilerplate test setup to before methods -
// makes the tests much more readable
stack = new core.Stack();
});
describe('created with default properties', () => {
let exampleResource: er.IExampleResource;
beforeEach(() => {
exampleResource = new er.ExampleResource(stack, 'ExampleResource');
});
test('creates a CFN WaitConditionHandle resource', () => {
// you can simply assert that a resource of a given type
// was generated in the resulting template
Template.fromStack(stack).resourceCountIs('AWS::CloudFormation::WaitConditionHandle', 1);
});
describe('creates a CFN WaitCondition resource', () => {
test('with count = 0 and timeout = 10', () => {
// you can also assert the properties of the resulting resource
Template.fromStack(stack).hasResourceProperties('AWS::CloudFormation::WaitCondition', {
'Count': 0,
'Timeout': '10',
'Handle': {
// Don't be afraid of using the generated logical IDs in your tests!
// While they look random, they are actually only dependent on the
// path constructs have in the tree.
// Since changing logical IDs as the library changes actually causes
// problems for their customers (their CloudFormation resources will be replaced),
// it's good for the unit tests to verify that the logical IDs are stable.
'Ref': 'ExampleResourceWaitConditionHandle9C53A8D3',
},
// this is how you can check a given property is _not_ set
'RandomProperty': Match.absent(),
});
});
test('with retention policy = Retain', () => {
// hasResource asserts _all_ properties of a resource,
// while hasResourceProperties only those within the 'Property' block
Template.fromStack(stack).hasResource('AWS::CloudFormation::WaitCondition', {
'DeletionPolicy': 'Retain',
'UpdateReplacePolicy': 'Retain',
// by default, haveResource and haveResourceLike only assert the properties of a resource -
// here's how you make them look at the entire resource definition
});
});
});
test('returns true from addToResourcePolicy', () => {
const result = exampleResource.addToRolePolicy(new iam.PolicyStatement({
actions: ['kms:*'],
resources: ['*'],
}));
expect(result).toBe(true);
});
test('correctly adds s3:Get* permissions when grantRead() is called', () => {
const role = new iam.Role(stack, 'Role', {
assumedBy: new iam.AnyPrincipal(),
});
exampleResource.grantRead(role);
Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', {
'PolicyDocument': {
'Statement': [
{
'Action': 's3:Get*',
'Effect': 'Allow',
'Resource': {
'Fn::Join': ['', [
'arn:',
{ 'Ref': 'AWS::Partition' },
':cloudformation:',
{ 'Ref': 'AWS::Region' },
':',
{ 'Ref': 'AWS::AccountId' },
':wait-condition/',
{ 'Ref': 'ExampleResourceAC53F4AE' },
]],
},
},
],
},
});
});
test('onEvent adds an Event Rule', () => {
exampleResource.onEvent('MyEvent');
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
EventPattern: {
detail: {
'example-resource-name': [EXAMPLE_RESOURCE_NAME],
},
},
});
});
test('metricCount returns a metric with correct dimensions', () => {
const countMetric = exampleResource.metricCount();
new cloudwatch.Alarm(stack, 'Alarm', {
metric: countMetric,
threshold: 10,
evaluationPeriods: 2,
});
Template.fromStack(stack).hasResourceProperties('AWS::CloudWatch::Alarm', {
EvaluationPeriods: 2,
Dimensions: [
{
Name: 'ExampleResource',
Value: EXAMPLE_RESOURCE_NAME,
},
],
MetricName: 'Count',
Namespace: 'AWS/ExampleResource',
});
});
});
describe('created with a VPC', () => {
let exampleResource: er.IExampleResource;
let vpc: ec2.IVpc;
beforeEach(() => {
vpc = new ec2.Vpc(stack, 'Vpc');
exampleResource = new er.ExampleResource(stack, 'ExampleResource', {
vpc,
});
});
test('allows manipulating its connections object', () => {
exampleResource.connections.allowToAnyIpv4(ec2.Port.allTcp());
});
test('correctly fills out the subnetIds property of the created VPC endpoint', () => {
Template.fromStack(stack).hasResourceProperties('AWS::EC2::VPCEndpoint', {
'SubnetIds': [
{ 'Ref': 'VpcPrivateSubnet1Subnet536B997A' },
{ 'Ref': 'VpcPrivateSubnet2Subnet3788AAA1' },
],
});
});
});
describe('imported by name', () => {
let exampleResource: er.IExampleResource;
beforeEach(() => {
exampleResource = er.ExampleResource.fromExampleResourceName(stack, 'ExampleResource',
'my-example-resource-name');
});
test('throws when accessing connections', () => {
expect(() => exampleResource.connections).toThrow();
});
test('has the same name as it was imported with', () => {
expect(exampleResource.exampleResourceName).toEqual('my-example-resource-name');
});
test('renders the correct ARN for Example Resource', () => {
// We can't simply compare the value we get from exampleResource.exampleResourceArn,
// as it will contain unresolved late-bound values
// (what we in the CDK call Tokens).
// So, use a utility method on Stack that allows you to resolve those Tokens
// into their correct values.
const arn = stack.resolve(exampleResource.exampleResourceArn);
expect(arn).toEqual({
'Fn::Join': ['', [
'arn:',
{ 'Ref': 'AWS::Partition' },
':cloudformation:',
{ 'Ref': 'AWS::Region' },
':',
{ 'Ref': 'AWS::AccountId' },
':wait-condition/my-example-resource-name',
]],
});
});
test('returns false from addToResourcePolicy', () => {
const result = exampleResource.addToRolePolicy(new iam.PolicyStatement({
actions: ['kms:*'],
resources: ['*'],
}));
expect(result).toEqual(false);
});
});
test('cannot be created with a physical name containing illegal characters', () => {
// this is how we write tests that expect an exception to be thrown
expect(() => {
new er.ExampleResource(stack, 'ExampleResource', {
waitConditionHandleName: 'a-1234',
});
// it's not enough to know an exception was thrown -
// we have to verify that its message is what we expected
}).toThrow(/waitConditionHandleName must be non-empty and contain only letters and underscores, got: 'a-1234'/);
});
test('does not fail validation if the physical name is a late-bound value', () => {
const parameter = new core.CfnParameter(stack, 'Parameter');
// no assertion necessary - the lack of an exception being thrown is all we need in this case
new er.ExampleResource(stack, 'ExampleResource', {
waitConditionHandleName: parameter.valueAsString,
});
});
});