forked from open-telemetry/opentelemetry-js
/
utils.test.ts
483 lines (433 loc) · 15.1 KB
/
utils.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
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
SpanAttributes,
SpanStatusCode,
ROOT_CONTEXT,
SpanKind,
TraceFlags,
context,
} from '@opentelemetry/api';
import { BasicTracerProvider, Span } from '@opentelemetry/sdk-trace-base';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import * as assert from 'assert';
import * as http from 'http';
import { IncomingMessage, ServerResponse } from 'http';
import { Socket } from 'net';
import * as sinon from 'sinon';
import * as url from 'url';
import { IgnoreMatcher } from '../../src/types';
import * as utils from '../../src/utils';
import { AttributeNames } from '../../src/enums/AttributeNames';
import { RPCType, setRPCMetadata } from '@opentelemetry/core';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
describe('Utility', () => {
describe('parseResponseStatus()', () => {
it('should return ERROR code by default', () => {
const status = utils.parseResponseStatus(
(undefined as unknown) as number
);
assert.deepStrictEqual(status, { code: SpanStatusCode.ERROR });
});
it('should return OK for Success HTTP status code', () => {
for (let index = 100; index < 400; index++) {
const status = utils.parseResponseStatus(index);
assert.deepStrictEqual(status, { code: SpanStatusCode.OK });
}
});
it('should not return OK for Bad HTTP status code', () => {
for (let index = 400; index <= 600; index++) {
const status = utils.parseResponseStatus(index);
assert.notStrictEqual(status.code, SpanStatusCode.OK);
}
});
});
describe('hasExpectHeader()', () => {
it('should throw if no option', () => {
try {
utils.hasExpectHeader('' as http.RequestOptions);
assert.fail();
} catch (ignore) {}
});
it('should not throw if no headers', () => {
const result = utils.hasExpectHeader({} as http.RequestOptions);
assert.strictEqual(result, false);
});
it('should return true on Expect (no case sensitive)', () => {
for (const headers of [{ Expect: 1 }, { expect: 1 }, { ExPect: 1 }]) {
const result = utils.hasExpectHeader({
headers,
} as http.RequestOptions);
assert.strictEqual(result, true);
}
});
});
describe('getRequestInfo()', () => {
it('should get options object', () => {
const webUrl = 'http://u:p@google.fr/aPath?qu=ry';
const urlParsed = url.parse(webUrl);
const urlParsedWithoutPathname = {
...urlParsed,
pathname: undefined,
};
const whatWgUrl = new url.URL(webUrl);
for (const param of [
webUrl,
urlParsed,
urlParsedWithoutPathname,
whatWgUrl,
]) {
const result = utils.getRequestInfo(param);
assert.strictEqual(result.optionsParsed.hostname, 'google.fr');
assert.strictEqual(result.optionsParsed.protocol, 'http:');
assert.strictEqual(result.optionsParsed.path, '/aPath?qu=ry');
assert.strictEqual(result.pathname, '/aPath');
assert.strictEqual(result.origin, 'http://google.fr');
}
});
});
describe('satisfiesPattern()', () => {
it('string pattern', () => {
const answer1 = utils.satisfiesPattern('/test/1', '/test/1');
assert.strictEqual(answer1, true);
const answer2 = utils.satisfiesPattern('/test/1', '/test/11');
assert.strictEqual(answer2, false);
});
it('regex pattern', () => {
const answer1 = utils.satisfiesPattern('/TeSt/1', /\/test/i);
assert.strictEqual(answer1, true);
const answer2 = utils.satisfiesPattern('/2/tEst/1', /\/test/);
assert.strictEqual(answer2, false);
});
it('should throw if type is unknown', () => {
try {
utils.satisfiesPattern('/TeSt/1', (true as unknown) as IgnoreMatcher);
assert.fail();
} catch (error) {
assert.strictEqual(error instanceof TypeError, true);
}
});
it('function pattern', () => {
const answer1 = utils.satisfiesPattern(
'/test/home',
(url: string) => url === '/test/home'
);
assert.strictEqual(answer1, true);
const answer2 = utils.satisfiesPattern(
'/test/home',
(url: string) => url !== '/test/home'
);
assert.strictEqual(answer2, false);
});
});
describe('isIgnored()', () => {
beforeEach(() => {
sinon.spy(utils, 'satisfiesPattern');
});
afterEach(() => {
sinon.restore();
});
it('should call isSatisfyPattern, n match', () => {
const answer1 = utils.isIgnored('/test/1', ['/test/11']);
assert.strictEqual(answer1, false);
assert.strictEqual(
(utils.satisfiesPattern as sinon.SinonSpy).callCount,
1
);
});
it('should call isSatisfyPattern, match for function', () => {
const answer1 = utils.isIgnored('/test/1', [
url => url.endsWith('/test/1'),
]);
assert.strictEqual(answer1, true);
});
it('should not re-throw when function throws an exception', () => {
const onException = (e: Error) => {
// Do nothing
};
for (const callback of [undefined, onException]) {
assert.doesNotThrow(() =>
utils.isIgnored(
'/test/1',
[
() => {
throw new Error('test');
},
],
callback
)
);
}
});
it('should call onException when function throws an exception', () => {
const onException = sinon.spy();
assert.doesNotThrow(() =>
utils.isIgnored(
'/test/1',
[
() => {
throw new Error('test');
},
],
onException
)
);
assert.strictEqual((onException as sinon.SinonSpy).callCount, 1);
});
it('should not call isSatisfyPattern', () => {
utils.isIgnored('/test/1', []);
assert.strictEqual(
(utils.satisfiesPattern as sinon.SinonSpy).callCount,
0
);
});
it('should return false on empty list', () => {
const answer1 = utils.isIgnored('/test/1', []);
assert.strictEqual(answer1, false);
});
it('should not throw and return false when list is undefined', () => {
const answer2 = utils.isIgnored('/test/1', undefined);
assert.strictEqual(answer2, false);
});
});
describe('getAbsoluteUrl()', () => {
it('should return absolute url with localhost', () => {
const path = '/test/1';
const result = utils.getAbsoluteUrl(url.parse(path), {});
assert.strictEqual(result, `http://localhost${path}`);
});
it('should return absolute url', () => {
const absUrl = 'http://www.google/test/1?query=1';
const result = utils.getAbsoluteUrl(url.parse(absUrl), {});
assert.strictEqual(result, absUrl);
});
it('should return default url', () => {
const result = utils.getAbsoluteUrl(null, {});
assert.strictEqual(result, 'http://localhost/');
});
it("{ path: '/helloworld', port: 8080 } should return http://localhost:8080/helloworld", () => {
const result = utils.getAbsoluteUrl(
{ path: '/helloworld', port: 8080 },
{}
);
assert.strictEqual(result, 'http://localhost:8080/helloworld');
});
});
describe('setSpanWithError()', () => {
it('should have error attributes', () => {
const errorMessage = 'test error';
for (const obj of [undefined, { statusCode: 400 }]) {
const span = new Span(
new BasicTracerProvider().getTracer('default'),
ROOT_CONTEXT,
'test',
{ spanId: '', traceId: '', traceFlags: TraceFlags.SAMPLED },
SpanKind.INTERNAL
);
/* tslint:disable-next-line:no-any */
utils.setSpanWithError(span, new Error(errorMessage), obj as any);
const attributes = span.attributes;
assert.strictEqual(
attributes[AttributeNames.HTTP_ERROR_MESSAGE],
errorMessage
);
assert.ok(attributes[AttributeNames.HTTP_ERROR_NAME]);
}
});
});
describe('isValidOptionsType()', () => {
['', false, true, 1, 0, []].forEach(options => {
it(`should return false with the following value: ${JSON.stringify(
options
)}`, () => {
assert.strictEqual(utils.isValidOptionsType(options), false);
});
});
for (const options of ['url', url.parse('http://url.com'), {}]) {
it(`should return true with the following value: ${JSON.stringify(
options
)}`, () => {
assert.strictEqual(utils.isValidOptionsType(options), true);
});
}
});
describe('getIncomingRequestAttributesOnResponse()', () => {
it('should correctly parse the middleware stack if present', done => {
context.setGlobalContextManager(new AsyncHooksContextManager().enable());
const request = {
socket: {},
} as IncomingMessage;
context.with(
setRPCMetadata(context.active(), {
type: RPCType.HTTP,
route: '/user/:id',
span: (null as unknown) as Span,
}),
() => {
const attributes = utils.getIncomingRequestAttributesOnResponse(
request,
{} as ServerResponse
);
assert.deepStrictEqual(
attributes[SemanticAttributes.HTTP_ROUTE],
'/user/:id'
);
context.disable();
return done();
}
);
});
it('should succesfully process without middleware stack', () => {
const request = {
socket: {},
} as IncomingMessage;
const attributes = utils.getIncomingRequestAttributesOnResponse(request, {
socket: {},
} as ServerResponse & { socket: Socket });
assert.deepEqual(attributes[SemanticAttributes.HTTP_ROUTE], undefined);
});
});
// Verify the key in the given attributes is set to the given value,
// and that no other HTTP Content Length attributes are set.
function verifyValueInAttributes(
attributes: SpanAttributes,
key: string | undefined,
value: number
) {
const SemanticAttributess = [
SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH,
SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH,
];
for (const attr of SemanticAttributess) {
if (attr === key) {
assert.strictEqual(attributes[attr], value);
} else {
assert.strictEqual(attributes[attr], undefined);
}
}
}
describe('setRequestContentLengthAttributes()', () => {
it('should set request content-length uncompressed attribute with no content-encoding header', () => {
const attributes: SpanAttributes = {};
const request = {} as IncomingMessage;
request.headers = {
'content-length': '1200',
};
utils.setRequestContentLengthAttribute(request, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
1200
);
});
it('should set request content-length uncompressed attribute with "identity" content-encoding header', () => {
const attributes: SpanAttributes = {};
const request = {} as IncomingMessage;
request.headers = {
'content-length': '1200',
'content-encoding': 'identity',
};
utils.setRequestContentLengthAttribute(request, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
1200
);
});
it('should set request content-length compressed attribute with "gzip" content-encoding header', () => {
const attributes: SpanAttributes = {};
const request = {} as IncomingMessage;
request.headers = {
'content-length': '1200',
'content-encoding': 'gzip',
};
utils.setRequestContentLengthAttribute(request, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH,
1200
);
});
});
describe('setResponseContentLengthAttributes()', () => {
it('should set response content-length uncompressed attribute with no content-encoding header', () => {
const attributes: SpanAttributes = {};
const response = {} as IncomingMessage;
response.headers = {
'content-length': '1200',
};
utils.setResponseContentLengthAttribute(response, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
1200
);
});
it('should set response content-length uncompressed attribute with "identity" content-encoding header', () => {
const attributes: SpanAttributes = {};
const response = {} as IncomingMessage;
response.headers = {
'content-length': '1200',
'content-encoding': 'identity',
};
utils.setResponseContentLengthAttribute(response, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
1200
);
});
it('should set response content-length compressed attribute with "gzip" content-encoding header', () => {
const attributes: SpanAttributes = {};
const response = {} as IncomingMessage;
response.headers = {
'content-length': '1200',
'content-encoding': 'gzip',
};
utils.setResponseContentLengthAttribute(response, attributes);
verifyValueInAttributes(
attributes,
SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH,
1200
);
});
it('should set no attributes with no content-length header', () => {
const attributes: SpanAttributes = {};
const message = {} as IncomingMessage;
message.headers = {
'content-encoding': 'gzip',
};
utils.setResponseContentLengthAttribute(message, attributes);
verifyValueInAttributes(attributes, undefined, 1200);
});
});
describe('getIncomingRequestAttributes()', () => {
it('should not set http.route in http span attributes', () => {
const request = {
url: 'http://hostname/user/:id',
method: 'GET'
} as IncomingMessage;
request.headers = {
'user-agent': 'chrome',
'x-forwarded-for': '<client>, <proxy1>, <proxy2>'
}
const attributes = utils.getIncomingRequestAttributes(request, { component: 'http'})
assert.strictEqual(attributes[SemanticAttributes.HTTP_ROUTE], undefined)
});
})
});