-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.test.ts
422 lines (379 loc) · 12.1 KB
/
index.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
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
/**
* Copyright 2018 Google LLC
*
* Distributed under MIT license.
* See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
import * as assert from 'assert';
import {beforeEach, afterEach, describe, it} from 'mocha';
import * as nock from 'nock';
import * as gcp from '../src';
// the metadata IP entry:
const HOST = gcp.HOST_ADDRESS;
// the metadata DNS entry:
const SECONDARY_HOST = gcp.SECONDARY_HOST_ADDRESS;
const PATH = gcp.BASE_PATH;
const TYPE = 'instance';
const PROPERTY = 'property';
// NOTE: nodejs switches all incoming header names to lower case.
const HEADERS = {
[gcp.HEADER_NAME.toLowerCase()]: gcp.HEADER_VALUE,
};
nock.disableNetConnect();
beforeEach(() => {
gcp.resetIsAvailableCache();
});
afterEach(() => {
nock.cleanAll();
});
it('should create the correct accessors', async () => {
assert(typeof gcp.instance, 'function');
assert(typeof gcp.project, 'function');
});
it('should access all the metadata properly', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`, undefined, HEADERS)
.reply(200, {}, HEADERS);
await gcp.instance();
scope.done();
});
it('should access a specific metadata property', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(200, {}, HEADERS);
await gcp.instance(PROPERTY);
scope.done();
});
it('should set custom headers when supplied', async () => {
const headers = {human: 'phone', monkey: 'banana'};
const scope = nock(HOST, {reqheaders: headers})
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(200, {}, HEADERS);
await gcp.instance({property: PROPERTY, headers});
scope.done();
});
it('should return large numbers as BigNumber values', async () => {
const BIG_NUMBER_STRING = `3279739563200103600`;
const scope = nock(HOST)
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(200, BIG_NUMBER_STRING, HEADERS);
const property = await gcp.instance(PROPERTY);
// property should be a BigNumber.
assert.strictEqual(property.valueOf(), BIG_NUMBER_STRING);
scope.done();
});
it('should return small numbers normally', async () => {
const NUMBER = 32797;
const scope = nock(HOST)
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(200, `${NUMBER}`, HEADERS);
const property = await gcp.instance(PROPERTY);
assert.strictEqual(typeof property, 'number');
assert.strictEqual(property, NUMBER);
scope.done();
});
it('should deal with nested large numbers', async () => {
const BIG_NUMBER_STRING = `3279739563200103600`;
const RESPONSE = `{ "v1": true, "v2": ${BIG_NUMBER_STRING} }`;
const scope = nock(HOST)
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(200, RESPONSE, HEADERS);
const response = await gcp.instance(PROPERTY);
assert.strictEqual(response.v2.valueOf(), BIG_NUMBER_STRING);
scope.done();
});
it('should accept an object with property and query fields', async () => {
const QUERY = {key: 'value'};
const scope = nock(HOST)
.get(`${PATH}/project/${PROPERTY}`)
.query(QUERY)
.reply(200, {}, HEADERS);
await gcp.project({property: PROPERTY, params: QUERY});
scope.done();
});
it('should return the request error', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.times(4)
.reply(500, undefined, HEADERS);
await assert.rejects(gcp.instance(), /Unsuccessful response status code/);
scope.done();
});
it('should return error when res is empty', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, undefined, HEADERS);
await assert.rejects(gcp.instance());
scope.done();
});
it('should return error when flavor header is incorrect', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, {[gcp.HEADER_NAME.toLowerCase()]: 'Hazelnut'});
await assert.rejects(
gcp.instance(),
/Invalid response from metadata service: incorrect Metadata-Flavor header./
);
scope.done();
});
it('should return error if statusCode is not 200', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(418, {}, HEADERS);
await assert.rejects(gcp.instance(), /Unsuccessful response status code/);
scope.done();
});
it('should retry if the initial request fails', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.times(2)
.reply(500)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
await gcp.instance();
scope.done();
});
it('should throw if request options are passed', async () => {
await assert.rejects(
// tslint:disable-next-line no-any
gcp.instance({qs: {one: 'two'}} as any),
/'qs' is not a valid configuration option. Please use 'params' instead\./
);
});
it('should throw if invalid options are passed', async () => {
await assert.rejects(
// tslint:disable-next-line no-any
gcp.instance({fake: 'news'} as any),
/'fake' is not a valid/
);
});
it('should retry on DNS errors', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: 'ETIMEDOUT'})
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
const data = await gcp.instance();
scope.done();
assert(data);
});
async function secondaryHostRequest(
delay: number,
responseType = 'success'
): Promise<void> {
let secondary: nock.Scope;
if (responseType === 'success') {
secondary = nock(SECONDARY_HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(delay)
.reply(200, {}, HEADERS);
} else {
secondary = nock(SECONDARY_HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(delay)
.replyWithError({code: responseType});
}
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
secondary.done();
return resolve();
} catch (err) {
return reject(err);
}
}, delay + 50);
});
}
it('should report isGCE if primary server returns 500 followed by 200', async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(500)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(isGCE, true);
});
it('should log error if DEBUG_AUTH is set', async () => {
process.env.DEBUG_AUTH = 'true';
const info = console.info;
let err: Error | null = null;
console.info = (_err: Error) => {
err = _err;
};
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: 'ENOTFOUND'});
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
console.info = info;
delete process.env.DEBUG_AUTH;
assert.strictEqual(/failed, reason/.test(err!.message), true);
});
[
'EHOSTDOWN',
'EHOSTUNREACH',
'ENETUNREACH',
'ENOENT',
'ENOTFOUND',
'ECONNREFUSED',
].forEach(errorCode => {
it(`should fail fast on isAvailable if ${errorCode} is returned`, async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: errorCode});
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(false, isGCE);
});
});
it(`should fail fast on isAvailable if 404 status code is returned`, async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(404);
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(false, isGCE);
});
it('should fail on isAvailable if request times out', async () => {
const secondary = secondaryHostRequest(5000);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(3500)
// this should never get called, as the 3000 timeout will trigger.
.reply(200, {}, HEADERS);
const isGCE = await gcp.isAvailable();
// secondary is allowed to simply timeout in the aether, to avoid
// having a test that waits 5000 ms.
primary.done();
assert.strictEqual(false, isGCE);
});
it('should report isGCE if secondary responds before primary', async () => {
const secondary = secondaryHostRequest(10);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(3500)
// this should never get called, as the 3000 timeout will trigger.
.reply(200, {}, HEADERS);
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(isGCE, true);
});
it('should fail fast on isAvailable if ENOENT is returned by secondary', async () => {
const secondary = secondaryHostRequest(10, 'ENOENT');
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(250)
.replyWithError({code: 'ENOENT'});
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(false, isGCE);
});
it('should throw on unexpected errors', async () => {
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: '🤡'});
const secondary = nock(SECONDARY_HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: '🤡'});
assert.rejects(gcp.isAvailable());
primary.done();
secondary.done();
});
it('should report isGCE if secondary succeeds before primary fails', async () => {
const secondary = secondaryHostRequest(10);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.delayConnection(200)
// this should never get called, as the 3000 timeout will trigger.
.reply(500, {}, HEADERS);
const isGCE = await gcp.isAvailable();
await secondary;
await new Promise((resolve, reject) => {
setTimeout(() => {
primary.done();
return resolve();
}, 500);
});
});
it('should retry environment detection if DETECT_GCP_RETRIES >= 2', async () => {
process.env.DETECT_GCP_RETRIES = '2';
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: 'ENETUNREACH'})
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
const isGCE = await gcp.isAvailable();
primary.done();
assert.strictEqual(true, isGCE);
delete process.env.DETECT_GCP_RETRIES;
});
it('should cache response from first isAvailable() call', async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
await gcp.isAvailable();
// because we haven't created additional mocks, we expect this to fail
// if we were not caching the first isAvailable() call:
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(isGCE, true);
});
it('should only make one outbound request, if isAvailable() called in rapid succession', async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS);
gcp.isAvailable();
// because we haven't created additional mocks, we expect this to fail
// if we were not caching the first isAvailable() call:
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(isGCE, true);
});
it('resets cache when resetIsAvailableCache() is called', async () => {
// we will attempt to hit the secondary and primary server twice,
// mock accordingly.
const secondary = secondaryHostRequest(250);
const secondary2 = secondaryHostRequest(500);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: 'ENOENT'});
// Check whether we're in a GCP environment twice, resetting the cache
// inbetween:
await gcp.isAvailable();
gcp.resetIsAvailableCache();
const isGCE = await gcp.isAvailable();
await secondary;
await secondary2;
primary.done();
assert.strictEqual(isGCE, false);
});
it('returns request timeout of 3000ms, when not GCF', () => {
assert.strictEqual(gcp.requestTimeout(), 3000);
});
it('returns request timeout of 0, when FUNCTION_NAME set', () => {
process.env.FUNCTION_NAME = 'my-function';
assert.strictEqual(gcp.requestTimeout(), 0);
delete process.env.FUNCTION_NAME;
});
it('returns request timeout of 0, when K_SERVICE set', () => {
process.env.K_SERVICE = 'my-function';
assert.strictEqual(gcp.requestTimeout(), 0);
delete process.env.K_SERVICE;
});