-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtestHelper.ts
More file actions
452 lines (406 loc) · 16.9 KB
/
testHelper.ts
File metadata and controls
452 lines (406 loc) · 16.9 KB
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import * as sinon from "sinon";
import { AppConfigurationClient, ConfigurationSetting, featureFlagContentType, secretReferenceContentType } from "@azure/app-configuration";
import { ClientSecretCredential } from "@azure/identity";
import { KeyVaultSecret, SecretClient } from "@azure/keyvault-secrets";
import * as uuid from "uuid";
import { RestError } from "@azure/core-rest-pipeline";
import { ConfigurationClientManager } from "../../src/configurationClientManager.js";
import { ConfigurationClientWrapper } from "../../src/configurationClientWrapper.js";
const sleepInMs = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
// Async, browser-safe SHA-256 using native crypto.subtle when available; falls back to tiny FNV-1a for Node without subtle.
async function _sha256(input: string): Promise<string> {
let crypto;
if (typeof window !== "undefined" && window.crypto && window.crypto.subtle) {
crypto = window.crypto;
}
else {
crypto = global.crypto;
}
const data = new TextEncoder().encode(input);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return btoa(String.fromCharCode(...new Uint8Array(hashBuffer)));
}
function _filterKVs(unfilteredKvs: ConfigurationSetting[], listOptions: any) {
const keyFilter = listOptions?.keyFilter ?? "*";
const labelFilter = listOptions?.labelFilter ?? "*";
const tagsFilter = listOptions?.tagsFilter ?? [];
if (tagsFilter.length > 5) {
throw new RestError("Invalid request parameter 'tags'. Maximum number of tag filters is 5.", { statusCode: 400 });
}
return unfilteredKvs.filter(kv => {
const keyMatched = keyFilter.endsWith("*") ? kv.key.startsWith(keyFilter.slice(0, -1)) : kv.key === keyFilter;
let labelMatched = false;
if (labelFilter === "*") {
labelMatched = true;
} else if (labelFilter === "\0") {
labelMatched = kv.label === undefined;
} else if (labelFilter.endsWith("*")) {
labelMatched = kv.label !== undefined && kv.label.startsWith(labelFilter.slice(0, -1));
} else {
labelMatched = kv.label === labelFilter;
}
let tagsMatched = true;
if (tagsFilter.length > 0) {
tagsMatched = tagsFilter.every(tag => {
const [tagName, tagValue] = tag.split("=");
if (tagValue === "\0") {
return kv.tags && kv.tags[tagName] === null;
}
return kv.tags && kv.tags[tagName] === tagValue;
});
}
return keyMatched && labelMatched && tagsMatched;
});
}
function getMockedIterator(pages: ConfigurationSetting[][], kvs: ConfigurationSetting[], listOptions: any) {
const mockIterator: AsyncIterableIterator<any> & { byPage(): AsyncIterableIterator<any> } = {
[Symbol.asyncIterator](): AsyncIterableIterator<any> {
kvs = _filterKVs(pages.flat(), listOptions);
return this;
},
next() {
const value = kvs.shift();
return Promise.resolve({ done: !value, value });
},
byPage(): AsyncIterableIterator<any> {
let remainingPages;
const pageEtags = listOptions?.pageEtags ? [...listOptions.pageEtags] : undefined; // a copy of the original list
return {
[Symbol.asyncIterator](): AsyncIterableIterator<any> {
remainingPages = [...pages];
return this;
},
async next() {
const pageItems = remainingPages.shift();
const pageEtag = pageEtags?.shift();
if (pageItems === undefined) {
return { done: true, value: undefined };
} else {
const items = _filterKVs(pageItems ?? [], listOptions);
const etag = await _sha256(JSON.stringify(items));
const statusCode = pageEtag === etag ? 304 : 200;
return {
done: false,
value: {
items,
etag,
_response: { status: statusCode }
}
};
}
}
};
}
};
return mockIterator as any;
}
function getCachedIterator(pages: Array<{
items: ConfigurationSetting[];
response?: any;
}>) {
const iterator: AsyncIterableIterator<any> & { byPage(): AsyncIterableIterator<any> } = {
[Symbol.asyncIterator](): AsyncIterableIterator<any> {
return this;
},
next() {
while (pages.length > 0) {
pages.shift();
}
if (pages.length === 0) {
return Promise.resolve({ done: true, value: undefined });
}
const value = pages[0].items.shift();
return Promise.resolve({ done: !value, value });
},
byPage(): AsyncIterableIterator<any> {
return {
[Symbol.asyncIterator](): AsyncIterableIterator<any> { return this; },
next() {
const page = pages.shift();
if (!page) {
return Promise.resolve({ done: true, value: undefined });
}
const etag = _sha256(JSON.stringify(page.items));
return Promise.resolve({
done: false,
value: {
items: page.items,
etag,
_response: page.response
}
});
}
};
}
};
return iterator as any;
}
function getMockedHeadIterator(pages: ConfigurationSetting[][], listOptions: any) {
const mockIterator: AsyncIterableIterator<any> & { byPage(): AsyncIterableIterator<any> } = {
[Symbol.asyncIterator](): AsyncIterableIterator<any> {
return this;
},
next() {
return Promise.resolve({ done: true, value: undefined });
},
byPage(): AsyncIterableIterator<any> {
let remainingPages;
const pageEtags = listOptions?.pageEtags ? [...listOptions.pageEtags] : undefined;
return {
[Symbol.asyncIterator](): AsyncIterableIterator<any> {
remainingPages = [...pages];
return this;
},
async next() {
const pageItems = remainingPages.shift();
const pageEtag = pageEtags?.shift();
if (pageItems === undefined) {
return { done: true, value: undefined };
} else {
const items = _filterKVs(pageItems ?? [], listOptions);
const etag = await _sha256(JSON.stringify(items));
const statusCode = pageEtag === etag ? 304 : 200;
return {
done: false,
value: {
items: [], // HEAD request returns no items
etag,
_response: { status: statusCode }
}
};
}
}
};
}
};
return mockIterator as any;
}
/**
* Mocks the listConfigurationSettings method of AppConfigurationClient to return the provided pages of ConfigurationSetting.
* E.g.
* - mockAppConfigurationClientListConfigurationSettings([item1, item2, item3]) // single page
*
* @param pages List of pages, each page is a list of ConfigurationSetting
*/
function mockAppConfigurationClientListConfigurationSettings(pages: ConfigurationSetting[][], customCallback?: (listOptions) => any) {
sinon.stub(AppConfigurationClient.prototype, "listConfigurationSettings").callsFake((listOptions) => {
if (customCallback) {
customCallback(listOptions);
}
const kvs = _filterKVs(pages.flat(), listOptions);
return getMockedIterator(pages, kvs, listOptions);
});
sinon.stub(AppConfigurationClient.prototype, "checkConfigurationSettings").callsFake((listOptions) => {
if (customCallback) {
customCallback(listOptions);
}
return getMockedHeadIterator(pages, listOptions);
});
}
function mockAppConfigurationClientLoadBalanceMode(pages: ConfigurationSetting[][], clientWrapper: ConfigurationClientWrapper, countObject: { count: number }) {
sinon.stub(clientWrapper.client, "listConfigurationSettings").callsFake((listOptions) => {
countObject.count += 1;
const kvs = _filterKVs(pages.flat(), listOptions);
return getMockedIterator(pages, kvs, listOptions);
});
sinon.stub(clientWrapper.client, "checkConfigurationSettings").callsFake((listOptions) => {
countObject.count += 1;
return getMockedHeadIterator(pages, listOptions);
});
}
function mockConfigurationManagerGetClients(fakeClientWrappers: ConfigurationClientWrapper[], isFailoverable: boolean, ...pages: ConfigurationSetting[][]) {
// Stub the getClients method on the class prototype
sinon.stub(ConfigurationClientManager.prototype, "getClients").callsFake(async () => {
if (fakeClientWrappers?.length > 0) {
return fakeClientWrappers;
}
const clients: ConfigurationClientWrapper[] = [];
const fakeEndpoint = createMockedEndpoint("fake");
const fakeStaticClientWrapper = new ConfigurationClientWrapper(fakeEndpoint, new AppConfigurationClient(createMockedConnectionString(fakeEndpoint)));
sinon.stub(fakeStaticClientWrapper.client, "listConfigurationSettings").callsFake(() => {
throw new RestError("Internal Server Error", { statusCode: 500 });
});
sinon.stub(fakeStaticClientWrapper.client, "checkConfigurationSettings").callsFake(() => {
throw new RestError("Internal Server Error", { statusCode: 500 });
});
clients.push(fakeStaticClientWrapper);
if (!isFailoverable) {
return clients;
}
const fakeReplicaEndpoint = createMockedEndpoint("fake-replica");
const fakeDynamicClientWrapper = new ConfigurationClientWrapper(fakeReplicaEndpoint, new AppConfigurationClient(createMockedConnectionString(fakeReplicaEndpoint)));
clients.push(fakeDynamicClientWrapper);
sinon.stub(fakeDynamicClientWrapper.client, "listConfigurationSettings").callsFake((listOptions) => {
const kvs = _filterKVs(pages.flat(), listOptions);
return getMockedIterator(pages, kvs, listOptions);
});
sinon.stub(fakeDynamicClientWrapper.client, "checkConfigurationSettings").callsFake((listOptions) => {
return getMockedHeadIterator(pages, listOptions);
});
return clients;
});
}
function mockAppConfigurationClientGetConfigurationSetting(kvList: any[], customCallback?: (options) => any) {
sinon.stub(AppConfigurationClient.prototype, "getConfigurationSetting").callsFake((settingId, options) => {
if (customCallback) {
customCallback(options);
}
const found = kvList.find(elem => elem.key === settingId.key && elem.label === settingId.label);
if (found) {
if (options?.onlyIfChanged && settingId.etag === found.etag) {
return { statusCode: 304 };
} else {
return { statusCode: 200, ...found };
}
} else {
throw new RestError("", { statusCode: 404 });
}
});
}
function mockAppConfigurationClientGetSnapshot(snapshotResponses: Map<string, any>, customCallback?: (options) => any) {
sinon.stub(AppConfigurationClient.prototype, "getSnapshot").callsFake((name, options) => {
if (customCallback) {
customCallback(options);
}
if (snapshotResponses.has(name)) {
return snapshotResponses.get(name);
} else {
throw new RestError("", { statusCode: 404 });
}
});
}
function mockAppConfigurationClientListConfigurationSettingsForSnapshot(snapshotResponses: Map<string, ConfigurationSetting[][]>, customCallback?: (options) => any) {
sinon.stub(AppConfigurationClient.prototype, "listConfigurationSettingsForSnapshot").callsFake((name, listOptions) => {
if (customCallback) {
customCallback(listOptions);
}
if (snapshotResponses.has(name)) {
const kvs = _filterKVs(snapshotResponses.get(name)!.flat(), listOptions);
return getMockedIterator(snapshotResponses.get(name)!, kvs, listOptions);
} else {
throw new RestError("", { statusCode: 404 });
}
});
}
// uriValueList: [["<secretUri>", "value"], ...]
function mockSecretClientGetSecret(uriValueList: [string, string][]) {
const dict = new Map();
for (const [uri, value] of uriValueList) {
dict.set(uri, value);
}
sinon.stub(SecretClient.prototype, "getSecret").callsFake(async function (secretName, options) {
const url = new URL(this.vaultUrl);
url.pathname = `/secrets/${secretName}`;
if (options?.version) {
url.pathname += `/${options.version}`;
}
return {
name: secretName,
value: dict.get(url.toString())
} as KeyVaultSecret;
});
}
function restoreMocks() {
sinon.restore();
}
const createMockedEndpoint = (name = "azure") => `https://${name}.azconfig.io`;
const createMockedAzureFrontDoorEndpoint = (name = "appconfig") => `https://${name}.b01.azurefd.net`;
const createMockedConnectionString = (endpoint = createMockedEndpoint(), secret = "secret", id = "123456") => {
return `Endpoint=${endpoint};Id=${id};Secret=${secret}`;
};
const createMockedTokenCredential = () => {
const effectiveTenantId = uuid.v4();
const effectiveClientId = uuid.v4();
const effectiveClientSecret = uuid.v4();
return new ClientSecretCredential(effectiveTenantId, effectiveClientId, effectiveClientSecret);
};
const createMockedKeyVaultReference = (key: string, vaultUri: string): ConfigurationSetting => ({
// https://${vaultName}.vault.azure.net/secrets/${secretName}
value: `{"uri":"${vaultUri}"}`,
key,
contentType: secretReferenceContentType,
lastModified: new Date(),
tags: {},
etag: uuid.v4(),
isReadOnly: false,
});
const createMockedJsonKeyValue = (key: string, value: any): ConfigurationSetting => ({
value: value,
key: key,
contentType: "application/json",
lastModified: new Date(),
tags: {},
etag: uuid.v4(),
isReadOnly: false
});
const createMockedKeyValue = (props: { [key: string]: any }): ConfigurationSetting => (Object.assign({
value: "TestValue",
key: "TestKey",
contentType: "",
lastModified: new Date(),
tags: {},
etag: uuid.v4(),
isReadOnly: false
}, props));
const createMockedFeatureFlag = (name: string, flagProps?: any, props?: any) => (Object.assign({
key: `.appconfig.featureflag/${name}`,
value: JSON.stringify(Object.assign({
"id": name,
"description": "",
"enabled": true,
"conditions": {
"client_filters": []
}
}, flagProps)),
contentType: featureFlagContentType,
lastModified: new Date(),
tags: {},
etag: uuid.v4(),
isReadOnly: false
}, props));
const createMockedSnapshotReference = (key: string, snapshotName: string): ConfigurationSetting => ({
value: `{"snapshot_name":"${snapshotName}"}`,
key,
contentType: "application/json; profile=\"https://azconfig.io/mime-profiles/snapshot-ref\"; charset=utf-8",
lastModified: new Date(),
tags: {},
etag: uuid.v4(),
isReadOnly: false,
});
class HttpRequestHeadersPolicy {
headers: any;
name: string;
constructor() {
this.headers = {};
this.name = "HttpRequestHeadersPolicy";
}
sendRequest(req, next) {
this.headers = req.headers;
return next(req).then(resp => resp);
}
}
export {
sinon,
mockAppConfigurationClientListConfigurationSettings,
mockAppConfigurationClientGetConfigurationSetting,
mockAppConfigurationClientGetSnapshot,
mockAppConfigurationClientListConfigurationSettingsForSnapshot,
mockAppConfigurationClientLoadBalanceMode,
mockConfigurationManagerGetClients,
mockSecretClientGetSecret,
getCachedIterator,
restoreMocks,
createMockedEndpoint,
createMockedAzureFrontDoorEndpoint,
createMockedConnectionString,
createMockedTokenCredential,
createMockedKeyVaultReference,
createMockedJsonKeyValue,
createMockedKeyValue,
createMockedFeatureFlag,
createMockedSnapshotReference,
sleepInMs,
HttpRequestHeadersPolicy
};