This repository was archived by the owner on Dec 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy patharmService.test.ts
397 lines (339 loc) · 17.9 KB
/
armService.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import Serverless from "serverless";
import { MockFactory } from "../test/mockFactory";
import { ArmService } from "./armService";
import { ArmResourceTemplate, ArmTemplateType, ArmDeployment, ArmTemplateProvisioningState, ArmParamType } from "../models/armTemplates";
import { ArmTemplateConfig, ServerlessAzureOptions } from "../models/serverless";
import {vol} from "memfs"
import jsonpath from "jsonpath";
import { Deployments } from "@azure/arm-resources";
import { Deployment, DeploymentExtended } from "@azure/arm-resources/esm/models";
import { ResourceService } from "./resourceService";
import { DeploymentExtendedError } from "../models/azureProvider";
import { Runtime } from "../config/runtime";
describe("Arm Service", () => {
let sls: Serverless
let service: ArmService;
let options: ServerlessAzureOptions;
function createService() {
return new ArmService(sls, options);
}
beforeEach(() => {
sls = MockFactory.createTestServerless();
sls.service.provider["prefix"] = "myapp";
sls.service.provider.region = "westus";
sls.service.provider.stage = "dev";
sls.variables = {
...sls.variables,
azureCredentials: MockFactory.createTestAzureCredentials(),
subscriptionId: "ABC123",
};
service = createService();
ResourceService.prototype.getDeployments = jest.fn(() => Promise.resolve(MockFactory.createTestDeployments())) as any;
ResourceService.prototype.getDeploymentTemplate = jest.fn(() => {
return {
template: MockFactory.createTestArmTemplate()
}
}) as any;
})
afterEach(() => {
vol.reset();
})
describe("Creating Templates", () => {
it("Creates an ARM template from a specified file", async () => {
const armTemplateConfig: ArmTemplateConfig = {
file: "armTemplates/custom-template.json",
parameters: MockFactory.createTestParameters(),
};
const testTemplate: ArmResourceTemplate = MockFactory.createTestArmTemplate();
vol.fromNestedJSON({
"armTemplates": {
"custom-template.json": JSON.stringify(testTemplate),
},
});
sls.service.provider["armTemplate"] = armTemplateConfig;
const deployment = await service.createDeploymentFromConfig(sls.service.provider["armTemplate"]);
expect(deployment).not.toBeNull();
expect(deployment.template.parameters).toEqual(testTemplate.parameters);
expect(deployment.template.resources).toEqual(testTemplate.resources);
expect(deployment.parameters).toEqual(armTemplateConfig.parameters);
});
it("Creates a custom ARM template from well-known type", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType("premium");
expect(deployment).not.toBeNull();
expect(Object.keys(deployment.parameters).length).toBeGreaterThan(0);
expect(deployment.template.resources.length).toBeGreaterThan(0);
});
it("Creates a custom ARM template (with APIM support) from well-known type", async () => {
sls.service.provider["apim"] = MockFactory.createTestApimConfig();
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.Premium);
expect(deployment).not.toBeNull();
expect(Object.keys(deployment.parameters).length).toBeGreaterThan(0);
expect(deployment.template.resources.length).toBeGreaterThan(0);
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.ApiManagement/service")).not.toBeNull();
});
it("throws error when specified type is not found", async () => {
await expect(service.createDeploymentFromType("not-found")).rejects.not.toBeNull();
});
it("Premium template includes correct resources", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.Premium);
expect(deployment.template.parameters.appServicePlanSkuTier.defaultValue).toEqual("ElasticPremium");
expect(deployment.template.parameters.appServicePlanSkuName.defaultValue).toEqual("EP1");
// Should not contain
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/hostingEnvironments")).toBeUndefined();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Network/virtualNetworks")).toBeUndefined();
// Should contain
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/serverfarms")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/sites")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Storage/storageAccounts")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "microsoft.insights/components")).not.toBeNull();
// Verify the ARM template includes the linkage to the correct server farm
const functionApp = deployment.template.resources.find((res) => res.type === "Microsoft.Web/sites");
expect(functionApp.dependsOn).toContain("[concat('Microsoft.Web/serverfarms/', parameters('appServicePlanName'))]");
expect(functionApp.properties.serverFarmId).toEqual("[resourceId('Microsoft.Web/serverfarms', parameters('appServicePlanName'))]");
});
it("ASE template includes correct resources", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.AppServiceEnvironment);
expect(deployment.template.parameters.appServicePlanSkuTier.defaultValue).toEqual("Isolated");
expect(deployment.template.parameters.appServicePlanSkuName.defaultValue).toEqual("I1");
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/hostingEnvironments")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Network/virtualNetworks")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/serverfarms")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/sites")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Storage/storageAccounts")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "microsoft.insights/components")).not.toBeNull();
// Verify the ARM template includes the linkage to the correct server farm
const appServicePlan = deployment.template.resources.find((res) => res.type === "Microsoft.Web/serverfarms");
expect(appServicePlan.dependsOn).toContain("[resourceId('Microsoft.Web/hostingEnvironments', parameters('hostingEnvironmentName'))]");
expect(appServicePlan.properties.hostingEnvironmentProfile.id).toEqual("[resourceId('Microsoft.Web/hostingEnvironments', parameters('hostingEnvironmentName'))]");
// Verify the ARM template includes the linkage to the correct hosting environment
const functionApp = deployment.template.resources.find((res) => res.type === "Microsoft.Web/sites");
expect(functionApp.dependsOn).toContain("[concat('Microsoft.Web/serverfarms/', parameters('appServicePlanName'))]");
expect(functionApp.properties.serverFarmId).toEqual("[resourceId('Microsoft.Web/serverfarms', parameters('appServicePlanName'))]");
expect(functionApp.properties.hostingEnvironmentProfile.id).toEqual("[resourceId('Microsoft.Web/hostingEnvironments', parameters('hostingEnvironmentName'))]");
});
it("Consumption template includes correct resources", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.Consumption);
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/hostingEnvironments")).toBeUndefined();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Network/virtualNetworks")).toBeUndefined();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/serverfarms")).toBeUndefined();
// Should contain
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Web/sites")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "Microsoft.Storage/storageAccounts")).not.toBeNull();
expect(deployment.template.resources.find((resource) => resource.type === "microsoft.insights/components")).not.toBeNull();
});
});
describe("Deploying Templates", () => {
beforeEach(() => {
Deployments.prototype.createOrUpdate = jest.fn(() => Promise.resolve(null));
});
it("Does not deploy if previously deployed template is the same", async () => {
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).not.toBeCalled();
});
it("Does not crash if deployment parameters are undefined", async () => {
const deployment: ArmDeployment = {
parameters: undefined,
template: MockFactory.createTestArmTemplate(),
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).toBeCalled();
});
it("Does not deploy if identity is only difference between deployments", async () => {
const template = MockFactory.createTestArmTemplate();
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: {
...template,
resources: template.resources.map((item) => {
return {
...item,
identity: {
"type": ArmParamType.SystemAssigned
}
}
})
}
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).not.toBeCalled()
});
it("Calls deploy if previous template is the same but failed", async () => {
const deployments = MockFactory.createTestDeployments();
const failedDeployment: DeploymentExtended = {
...deployments[0],
properties: {
...deployments[0].properties,
provisioningState: ArmTemplateProvisioningState.FAILED
}
}
deployments[0] = failedDeployment;
ResourceService.prototype.getDeployments = jest.fn(() => Promise.resolve(deployments))
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).toBeCalled();
});
it("Calls deploy if parameters have changed from deployed template", async () => {
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
deployment.parameters.param1.value = "3";
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).toBeCalled();
});
it("Calls deploy if previously deployed template is different", async () => {
ResourceService.prototype.getDeploymentTemplate = jest.fn(() => {
return {
template: {
resources: []
}
}
}) as any;
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).toBeCalled()
});
it("Calls deploy if running first deployment", async () => {
ResourceService.prototype.getDeployments = jest.fn(() => {
return []
}) as any;
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
await service.deployTemplate(deployment);
expect(Deployments.prototype.createOrUpdate).toBeCalled()
});
it("Appends environment variables into app settings of ARM template", async () => {
const environmentConfig: any = {
PARAM_1: "1",
PARAM_2: "2",
PARAM_3: "3",
};
sls.service.provider["environment"] = environmentConfig
sls.service.provider.runtime = Runtime.NODE10;
sls.service.provider["os"] = "windows";
const deployment = await service.createDeploymentFromType(ArmTemplateType.Consumption);
await service.deployTemplate(deployment);
const appSettings: any[] = jsonpath.query(deployment.template, "$.resources[?(@.type==\"Microsoft.Web/sites\")].properties.siteConfig.appSettings[*]");
expect(appSettings.find((setting) => setting.name === "PARAM_1")).toEqual({ name: "PARAM_1", value: environmentConfig.PARAM_1 });
expect(appSettings.find((setting) => setting.name === "PARAM_2")).toEqual({ name: "PARAM_2", value: environmentConfig.PARAM_2 });
expect(appSettings.find((setting) => setting.name === "PARAM_3")).toEqual({ name: "PARAM_3", value: environmentConfig.PARAM_3 });
});
it("Deploys ARM template via resources REST API", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.Consumption);
await service.deployTemplate(deployment);
const expectedResourceGroup = sls.service.provider["resourceGroup"];
const expectedDeploymentName = sls.service.provider["deploymentName"] || `${this.resourceGroup}-deployment`;
const expectedDeploymentNameRegex = new RegExp(expectedDeploymentName + "-t([0-9]+)")
const expectedDeployment: Deployment = {
properties: {
mode: "Incremental",
...deployment
},
};
const call = (Deployments.prototype.createOrUpdate as any).mock.calls[0];
expect(call[0]).toEqual(expectedResourceGroup);
expect(call[1]).toMatch(expectedDeploymentNameRegex);
expect(call[2]).toEqual(expectedDeployment);
});
it("Throws more detailed error message upon failed ARM deployment", async () => {
Deployments.prototype.createOrUpdate = jest.fn(() => Promise.reject(null));
const previousDeploymentError: DeploymentExtendedError = {
code: "DeploymentFailed",
message: "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.",
details: [
{
code: "ServiceAlreadyExists",
message: "Api service already exists: abc-123-apim"
},
{
code: "StorageAccountAlreadyTaken",
message: "The storage account named ABC123 is already taken."
}
]
}
ResourceService.prototype.getPreviousDeployment = jest.fn(() => Promise.resolve({
properties: {
error: previousDeploymentError
}
})) as any;
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
deployment.parameters.param1.value = "3"
const { code, message, details } = previousDeploymentError;
const errorPattern = [
code,
message,
details[0].code,
details[0].message,
details[1].code,
details[1].message
].join(".*")
await expect(service.deployTemplate(deployment))
.rejects
.toThrowError(
new RegExp(`.*${errorPattern}.*`, "s")
);
});
it("Does not try to include paramaters with a value that is undefined", async () => {
sls.service.provider.runtime = Runtime.NODE10;
const deployment = await service.createDeploymentFromType(ArmTemplateType.Consumption);
expect(deployment.parameters.functionAppExtensionVersion).not.toBeUndefined();
expect(deployment.parameters.functionAppExtensionVersion.value).toBeUndefined();
await service.deployTemplate(deployment);
expect(deployment.parameters.functionAppExtensionVersion).toBeUndefined();
const paramKeys = Object.keys(deployment.parameters);
paramKeys.forEach((key) => {
const paramValue = deployment.parameters[key];
if (paramValue) {
expect(paramValue.value).not.toBeUndefined();
}
})
const expectedResourceGroup = sls.service.provider["resourceGroup"];
const expectedDeploymentName = sls.service.provider["deploymentName"] || `${this.resourceGroup}-deployment`;
const expectedDeploymentNameRegex = new RegExp(expectedDeploymentName + "-t([0-9]+)")
const expectedDeployment: Deployment = {
properties: {
mode: "Incremental",
...deployment
},
};
const call = (Deployments.prototype.createOrUpdate as any).mock.calls[0];
expect(call[0]).toEqual(expectedResourceGroup);
expect(call[1]).toMatch(expectedDeploymentNameRegex);
expect(call[2]).toEqual(expectedDeployment);
});
it("Throws original error when there has not been a previous deployment", async () => {
const originalError = new Error("original error message");
Deployments.prototype.createOrUpdate = jest.fn(() => Promise.reject(originalError));
ResourceService.prototype.getPreviousDeployment = jest.fn(() => Promise.resolve(undefined)) as any;
const deployment: ArmDeployment = {
parameters: MockFactory.createTestParameters(),
template: MockFactory.createTestArmTemplate()
};
deployment.parameters.param1.value = "3"
await expect(service.deployTemplate(deployment))
.rejects
.toThrowError(originalError);
});
});
});