forked from open-telemetry/opentelemetry-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.test.ts
More file actions
917 lines (828 loc) · 26.8 KB
/
fetch.test.ts
File metadata and controls
917 lines (828 loc) · 26.8 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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
/*
* 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 * as api from '@opentelemetry/api';
import * as core from '@opentelemetry/core';
import {
isWrapped,
registerInstrumentations,
} from '@opentelemetry/instrumentation';
import {
B3Propagator,
B3InjectEncoding,
X_B3_TRACE_ID,
X_B3_SPAN_ID,
X_B3_SAMPLED,
} from '@opentelemetry/propagator-b3';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import * as tracing from '@opentelemetry/sdk-trace-base';
import {
PerformanceTimingNames as PTN,
WebTracerProvider,
} from '@opentelemetry/sdk-trace-web';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {
FetchInstrumentation,
FetchInstrumentationConfig,
FetchCustomAttributeFunction,
} from '../src';
import { AttributeNames } from '../src/enums/AttributeNames';
import {
SEMATTRS_HTTP_HOST,
SEMATTRS_HTTP_METHOD,
SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,
SEMATTRS_HTTP_SCHEME,
SEMATTRS_HTTP_STATUS_CODE,
SEMATTRS_HTTP_URL,
SEMATTRS_HTTP_USER_AGENT,
} from '@opentelemetry/semantic-conventions';
class DummySpanExporter implements tracing.SpanExporter {
export(spans: any) {}
shutdown() {
return Promise.resolve();
}
forceFlush(): Promise<void> {
return Promise.resolve();
}
}
const getData = (url: string, method?: string) => {
return fetch(url, {
method: method || 'GET',
headers: {
foo: 'bar',
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
};
const CUSTOM_ATTRIBUTE_KEY = 'span kind';
const defaultResource = {
connectEnd: 15,
connectStart: 13,
decodedBodySize: 0,
domainLookupEnd: 12,
domainLookupStart: 11,
encodedBodySize: 0,
fetchStart: 10.1,
initiatorType: 'fetch',
nextHopProtocol: '',
redirectEnd: 0,
redirectStart: 0,
requestStart: 16,
responseEnd: 20.5,
responseStart: 17,
secureConnectionStart: 14,
transferSize: 0,
workerStart: 0,
duration: 0,
entryType: '',
name: '',
startTime: 0,
};
function createResource(resource = {}): PerformanceResourceTiming {
return Object.assign(
{},
defaultResource,
resource
) as PerformanceResourceTiming;
}
function createMainResource(resource = {}): PerformanceResourceTiming {
const mainResource: any = createResource(resource);
Object.keys(mainResource).forEach((key: string) => {
if (typeof mainResource[key] === 'number') {
mainResource[key] = mainResource[key] + 30;
}
});
return mainResource;
}
function createFakePerformanceObs(url: string) {
class FakePerfObs implements PerformanceObserver {
constructor(private readonly cb: PerformanceObserverCallback) {}
observe() {
const absoluteUrl = url.startsWith('http') ? url : location.origin + url;
const resources: PerformanceObserverEntryList = {
getEntries(): PerformanceEntryList {
return [
createMainResource({ name: absoluteUrl }) as any,
];
},
getEntriesByName(): PerformanceEntryList {
return [];
},
getEntriesByType(): PerformanceEntryList {
return [];
},
};
this.cb(resources, this);
}
disconnect() {}
takeRecords(): PerformanceEntryList {
return [];
}
}
return FakePerfObs;
}
function testForCorrectEvents(
events: tracing.TimedEvent[],
eventNames: string[]
) {
for (let i = 0; i < events.length; i++) {
assert.strictEqual(
events[i].name,
eventNames[i],
`event ${eventNames[i]} is not defined`
);
}
}
describe('fetch', () => {
let contextManager: ZoneContextManager;
let lastResponse: any | undefined;
let webTracerWithZone: api.Tracer;
let webTracerProviderWithZone: WebTracerProvider;
let dummySpanExporter: DummySpanExporter;
let exportSpy: any;
let clearResourceTimingsSpy: any;
let rootSpan: api.Span;
let fakeNow = 0;
let fetchInstrumentation: FetchInstrumentation;
const url = 'http://localhost:8090/get';
const secureUrl = 'https://localhost:8090/get';
const badUrl = 'http://foo.bar.com/get';
const clearData = () => {
sinon.restore();
lastResponse = undefined;
};
const prepareData = async (
fileUrl: string,
config: FetchInstrumentationConfig,
method?: string,
disablePerfObserver?: boolean,
disableGetEntries?: boolean
) => {
sinon.useFakeTimers();
sinon.stub(core.otperformance, 'timeOrigin').value(0);
sinon.stub(core.otperformance, 'now').callsFake(() => fakeNow);
function fakeFetch(input: RequestInfo | Request, init: RequestInit = {}) {
return new Promise((resolve, reject) => {
const response: any = {
args: {},
url: fileUrl,
};
response.headers = Object.assign({}, init.headers);
if (init instanceof Request) {
// Passing request as 2nd argument causes missing body bug (#2411)
response.status = 400;
response.statusText = 'Bad Request (Request object as 2nd argument)';
reject(new window.Response(JSON.stringify(response), response));
} else if (init.method === 'DELETE') {
response.status = 405;
response.statusText = 'OK';
resolve(new window.Response('foo', response));
} else if (
(input instanceof Request && input.url === url) ||
input === url
) {
response.status = 200;
response.statusText = 'OK';
resolve(new window.Response(JSON.stringify(response), response));
} else {
response.status = 404;
response.statusText = 'Bad request';
reject(new window.Response(JSON.stringify(response), response));
}
});
}
sinon.stub(window, 'fetch').callsFake(fakeFetch as any);
const resources: PerformanceResourceTiming[] = [];
resources.push(
createMainResource({
name: fileUrl,
})
);
if (disablePerfObserver) {
sinon.stub(window, 'PerformanceObserver').value(undefined);
} else {
sinon
.stub(window, 'PerformanceObserver')
.value(createFakePerformanceObs(fileUrl));
}
if (disableGetEntries) {
sinon.stub(performance, 'getEntriesByType').value(undefined);
} else {
const spyEntries = sinon.stub(performance, 'getEntriesByType');
spyEntries.withArgs('resource').returns(resources);
}
fetchInstrumentation = new FetchInstrumentation(config);
webTracerProviderWithZone = new WebTracerProvider();
registerInstrumentations({
tracerProvider: webTracerProviderWithZone,
instrumentations: [fetchInstrumentation],
});
webTracerWithZone = webTracerProviderWithZone.getTracer('fetch-test');
dummySpanExporter = new DummySpanExporter();
exportSpy = sinon.stub(dummySpanExporter, 'export');
clearResourceTimingsSpy = sinon.stub(performance, 'clearResourceTimings');
webTracerProviderWithZone.addSpanProcessor(
new tracing.SimpleSpanProcessor(dummySpanExporter)
);
// endSpan is called after the whole response body is read
// this process is scheduled at the same time the fetch promise is resolved
// due to this we can't rely on getData resolution to know that the span has ended
let resolveEndSpan: (value: unknown) => void;
const spanEnded = new Promise(r => (resolveEndSpan = r));
const readSpy = sinon.spy(
window.ReadableStreamDefaultReader.prototype,
'read'
);
const endSpanStub: sinon.SinonStub<any> = sinon
.stub(FetchInstrumentation.prototype, '_endSpan' as any)
.callsFake(async function (this: FetchInstrumentation, ...args: any[]) {
resolveEndSpan({});
return endSpanStub.wrappedMethod.apply(this, args);
});
rootSpan = webTracerWithZone.startSpan('root');
await api.context.with(
api.trace.setSpan(api.context.active(), rootSpan),
async () => {
fakeNow = 0;
try {
const responsePromise = getData(fileUrl, method);
fakeNow = 300;
const response = await responsePromise;
// if the url is not ignored, body.read should be called by now
// awaiting for the span to end
if (readSpy.callCount > 0) await spanEnded;
// this is a bit tricky as the only way to get all request headers from
// fetch is to use json()
lastResponse = await response.json();
const headers: { [key: string]: string } = {};
Object.keys(lastResponse.headers).forEach(key => {
headers[key.toLowerCase()] = lastResponse.headers[key];
});
lastResponse.headers = headers;
} catch (e) {
lastResponse = undefined;
}
await sinon.clock.runAllAsync();
}
);
};
beforeEach(() => {
contextManager = new ZoneContextManager().enable();
api.context.setGlobalContextManager(contextManager);
});
afterEach(() => {
api.context.disable();
});
before(() => {
api.propagation.setGlobalPropagator(
new B3Propagator({
injectEncoding: B3InjectEncoding.MULTI_HEADER,
})
);
});
describe('when request is successful', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = [url];
await prepareData(url, { propagateTraceHeaderCorsUrls });
});
afterEach(() => {
clearData();
});
it('should wrap methods', () => {
assert.ok(isWrapped(window.fetch));
fetchInstrumentation.enable();
assert.ok(isWrapped(window.fetch));
});
it('should unwrap methods', () => {
assert.ok(isWrapped(window.fetch));
fetchInstrumentation.disable();
assert.ok(!isWrapped(window.fetch));
});
it('should create a span with correct root span', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.strictEqual(
span.parentSpanId,
rootSpan.spanContext().spanId,
'parent span is not root span'
);
});
it('span should have correct name', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.strictEqual(span.name, 'HTTP GET', 'span has wrong name');
});
it('span should have correct kind', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.strictEqual(span.kind, api.SpanKind.CLIENT, 'span has wrong kind');
});
it('span should have correct attributes', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const attributes = span.attributes;
const keys = Object.keys(attributes);
assert.ok(
attributes[keys[0]] !== '',
`attributes ${AttributeNames.COMPONENT} is not defined`
);
assert.strictEqual(
attributes[keys[1]],
'GET',
`attributes ${SEMATTRS_HTTP_METHOD} is wrong`
);
assert.strictEqual(
attributes[keys[2]],
url,
`attributes ${SEMATTRS_HTTP_URL} is wrong`
);
assert.strictEqual(
attributes[keys[3]],
200,
`attributes ${SEMATTRS_HTTP_STATUS_CODE} is wrong`
);
assert.ok(
attributes[keys[4]] === 'OK' || attributes[keys[4]] === '',
`attributes ${AttributeNames.HTTP_STATUS_TEXT} is wrong`
);
assert.ok(
(attributes[keys[5]] as string).indexOf('localhost') === 0,
`attributes ${SEMATTRS_HTTP_HOST} is wrong`
);
assert.ok(
attributes[keys[6]] === 'http' || attributes[keys[6]] === 'https',
`attributes ${SEMATTRS_HTTP_SCHEME} is wrong`
);
assert.ok(
attributes[keys[7]] !== '',
`attributes ${SEMATTRS_HTTP_USER_AGENT} is not defined`
);
assert.ok(
(attributes[keys[8]] as number) > 0,
`attributes ${SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH} is <= 0`
);
assert.strictEqual(keys.length, 9, 'number of attributes is wrong');
});
it('span should have correct events', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(events.length, 8, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
it('should set trace headers', () => {
const span: api.Span = exportSpy.args[0][0][0];
assert.strictEqual(
lastResponse.headers[X_B3_TRACE_ID],
span.spanContext().traceId,
`trace header '${X_B3_TRACE_ID}' not set`
);
assert.strictEqual(
lastResponse.headers[X_B3_SPAN_ID],
span.spanContext().spanId,
`trace header '${X_B3_SPAN_ID}' not set`
);
assert.strictEqual(
lastResponse.headers[X_B3_SAMPLED],
String(span.spanContext().traceFlags),
`trace header '${X_B3_SAMPLED}' not set`
);
});
it('should set trace headers with a request object', () => {
const r = new Request('url');
window.fetch(r).catch(() => {});
assert.ok(typeof r.headers.get(X_B3_TRACE_ID) === 'string');
});
it('should keep custom headers with a request object and a headers object', () => {
const r = new Request('url', {
headers: new Headers({ foo: 'bar' }),
});
window.fetch(r).catch(() => {});
assert.ok(r.headers.get('foo') === 'bar');
});
it('should keep custom headers with url, untyped request object and typed (Headers) headers object', () => {
const url = 'url';
const init = {
headers: new Headers({ foo: 'bar' }),
};
window.fetch(url, init).catch(() => {});
assert.ok(init.headers.get('foo') === 'bar');
});
it('should keep custom headers with url, untyped request object and untyped headers object', () => {
const url = 'url';
const init = {
headers: { foo: 'bar' },
};
window.fetch(url, init).catch(() => {});
assert.ok(init.headers['foo'] === 'bar');
});
it('should keep custom headers with url, untyped request object and typed (Map) headers object', () => {
const url = 'url';
const init = {
headers: new Map().set('foo', 'bar'),
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore variable init not of RequestInit type
window.fetch(url, init).catch(() => {});
assert.ok(init.headers.get('foo') === 'bar');
});
it('should pass request object as first parameter to the original function (#2411)', () => {
const r = new Request(url);
return window.fetch(r).then(
() => {
assert.ok(true);
},
(response: Response) => {
assert.fail(response.statusText);
}
);
});
it('should NOT clear the resources', () => {
assert.strictEqual(
clearResourceTimingsSpy.args.length,
0,
'resources have been cleared'
);
});
describe('when propagateTraceHeaderCorsUrls does NOT MATCH', () => {
let spyDebug: sinon.SinonSpy;
beforeEach(async () => {
const diagLogger = new api.DiagConsoleLogger();
spyDebug = sinon.spy();
diagLogger.debug = spyDebug;
api.diag.setLogger(diagLogger, api.DiagLogLevel.ALL);
clearData();
await prepareData(url, {});
});
afterEach(() => {
sinon.restore();
});
it('should NOT set trace headers', () => {
assert.strictEqual(
lastResponse.headers[X_B3_TRACE_ID],
undefined,
`trace header '${X_B3_TRACE_ID}' should not be set`
);
assert.strictEqual(
lastResponse.headers[X_B3_SPAN_ID],
undefined,
`trace header '${X_B3_SPAN_ID}' should not be set`
);
assert.strictEqual(
lastResponse.headers[X_B3_SAMPLED],
undefined,
`trace header '${X_B3_SAMPLED}' should not be set`
);
});
it('should debug info that injecting headers was skipped', () => {
assert.strictEqual(
spyDebug.lastCall.args[1],
'headers inject skipped due to CORS policy'
);
});
});
});
describe('when request is secure and successful', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = [secureUrl];
await prepareData(secureUrl, { propagateTraceHeaderCorsUrls });
});
afterEach(() => {
clearData();
});
it('span should have correct events', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(events.length, 9, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.SECURE_CONNECTION_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
it('preflight request span should have correct events', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(events.length, 9, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.SECURE_CONNECTION_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
});
describe('applyCustomAttributesOnSpan option', () => {
const prepare = async (
url: string,
applyCustomAttributesOnSpan: FetchCustomAttributeFunction
) => {
const propagateTraceHeaderCorsUrls = [url];
await prepareData(url, {
propagateTraceHeaderCorsUrls,
applyCustomAttributesOnSpan,
});
};
afterEach(() => {
clearData();
});
it('applies attributes when the request is successful', async () => {
await prepare(url, span => {
span.setAttribute(CUSTOM_ATTRIBUTE_KEY, 'custom value');
});
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const attributes = span.attributes;
assert.ok(attributes[CUSTOM_ATTRIBUTE_KEY] === 'custom value');
});
it('applies custom attributes when the request fails', async () => {
await prepare(badUrl, span => {
span.setAttribute(CUSTOM_ATTRIBUTE_KEY, 'custom value');
});
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const attributes = span.attributes;
assert.ok(attributes[CUSTOM_ATTRIBUTE_KEY] === 'custom value');
});
it('has request and response objects in callback arguments', async () => {
let request: any;
let response: any;
const applyCustomAttributes: FetchCustomAttributeFunction = (
span,
req,
res
) => {
request = req;
response = res;
};
await prepare(url, applyCustomAttributes);
assert.ok(request.method === 'GET');
assert.ok(response.status === 200);
});
it('get response body from callback arguments response', async () => {
let response: any;
const applyCustomAttributes: FetchCustomAttributeFunction = async (
span,
req,
res
) => {
if (res instanceof Response) {
response = res;
}
};
await prepare(url, applyCustomAttributes);
const rsp = await response.json();
assert.deepStrictEqual(rsp.args, {});
});
});
describe('when url is ignored', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = url;
await prepareData(url, {
propagateTraceHeaderCorsUrls,
ignoreUrls: [propagateTraceHeaderCorsUrls],
});
});
afterEach(() => {
clearData();
});
it('should NOT create any span', () => {
assert.strictEqual(exportSpy.args.length, 0, "span shouldn't b exported");
});
it('should pass request object as the first parameter to the original function (#2411)', () => {
const r = new Request(url);
return window.fetch(r).then(
() => {
assert.ok(true);
},
(response: Response) => {
assert.fail(response.statusText);
}
);
});
});
describe('when clearTimingResources is TRUE', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = url;
await prepareData(url, {
propagateTraceHeaderCorsUrls,
clearTimingResources: true,
});
});
afterEach(() => {
clearData();
});
it('should clear the resources', () => {
assert.strictEqual(
clearResourceTimingsSpy.args.length,
1,
"resources haven't been cleared"
);
});
});
describe('when request is NOT successful (wrong url)', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = badUrl;
await prepareData(badUrl, { propagateTraceHeaderCorsUrls });
});
afterEach(() => {
clearData();
});
it('should create a span with correct root span', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.strictEqual(
span.parentSpanId,
rootSpan.spanContext().spanId,
'parent span is not root span'
);
});
});
describe('when request is NOT successful (405)', () => {
beforeEach(async () => {
const propagateTraceHeaderCorsUrls = url;
await prepareData(url, { propagateTraceHeaderCorsUrls }, 'DELETE');
});
afterEach(() => {
clearData();
});
it('should create a span with correct root span', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
assert.strictEqual(
span.parentSpanId,
rootSpan.spanContext().spanId,
'parent span is not root span'
);
});
});
describe('when PerformanceObserver is used by default', () => {
beforeEach(async () => {
// All above tests test it already but just in case
// lets explicitly turn getEntriesByType off so we can be sure
// that the perf entries come from the observer.
await prepareData(url, {}, undefined, false, true);
});
afterEach(() => {
clearData();
});
it('should create both spans with network events', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(
exportSpy.args.length,
1,
`Wrong number of spans: ${exportSpy.args.length}`
);
assert.strictEqual(events.length, 8, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
});
describe('when fetching with relative url', () => {
beforeEach(async () => {
await prepareData('/get', {}, undefined, false, true);
});
afterEach(() => {
clearData();
});
it('should create spans with network info', () => {
// no prefetch span because mock observer uses location.origin as url when relative
// and prefetch span finding compares url origins
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(
exportSpy.args.length,
1,
`Wrong number of spans: ${exportSpy.args.length}`
);
assert.strictEqual(events.length, 8, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
it('should have an absolute http.url attribute', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const attributes = span.attributes;
assert.strictEqual(
attributes[SEMATTRS_HTTP_URL],
location.origin + '/get',
`attributes ${SEMATTRS_HTTP_URL} is wrong`
);
});
});
describe('when PerformanceObserver is undefined', () => {
beforeEach(async () => {
await prepareData(url, {}, undefined, true, false);
});
afterEach(() => {
clearData();
});
it('should fallback to getEntries', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(
exportSpy.args.length,
1,
`Wrong number of spans: ${exportSpy.args.length}`
);
assert.strictEqual(events.length, 8, 'number of events is wrong');
testForCorrectEvents(events, [
PTN.FETCH_START,
PTN.DOMAIN_LOOKUP_START,
PTN.DOMAIN_LOOKUP_END,
PTN.CONNECT_START,
PTN.CONNECT_END,
PTN.REQUEST_START,
PTN.RESPONSE_START,
PTN.RESPONSE_END,
]);
});
});
describe('when PerformanceObserver and performance.getEntriesByType are undefined', () => {
beforeEach(async () => {
await prepareData(url, {}, undefined, true, true);
});
afterEach(() => {
clearData();
});
it('should still capture fetch with basic attributes', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
const attributes = span.attributes;
const keys = Object.keys(attributes);
assert.strictEqual(
exportSpy.args.length,
1,
`Wrong number of spans: ${exportSpy.args.length}`
);
assert.strictEqual(
exportSpy.args[0][0][0].name,
'HTTP GET',
'wrong span captured'
);
assert.strictEqual(events.length, 0, 'Should not have any events');
// should still have basic attributes
assert.strictEqual(
attributes[keys[3]],
200,
`Missing basic attribute ${SEMATTRS_HTTP_STATUS_CODE}`
);
});
});
describe('when network events are ignored', () => {
beforeEach(async () => {
await prepareData(url, {
ignoreNetworkEvents: true,
});
});
afterEach(() => {
clearData();
});
it('should NOT add network events', () => {
const span: tracing.ReadableSpan = exportSpy.args[0][0][0];
const events = span.events;
assert.strictEqual(events.length, 0, 'number of events is wrong');
});
});
});