/
request.test.ts
438 lines (347 loc) · 14.9 KB
/
request.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
import { BrowserClient } from '@sentry/browser';
import { Hub, makeMain } from '@sentry/core';
import * as utils from '@sentry/utils';
import { Span, spanStatusfromHttpCode, Transaction } from '../../src';
import {
fetchCallback,
FetchData,
instrumentOutgoingRequests,
shouldAttachHeaders,
xhrCallback,
XHRData,
} from '../../src/browser/request';
import { addExtensionMethods } from '../../src/hubextensions';
import * as tracingUtils from '../../src/utils';
import { getDefaultBrowserClientOptions } from '../testutils';
beforeAll(() => {
addExtensionMethods();
// @ts-ignore need to override global Request because it's not in the jest environment (even with an
// `@jest-environment jsdom` directive, for some reason)
global.Request = {};
});
const hasTracingEnabled = jest.spyOn(tracingUtils, 'hasTracingEnabled');
const addInstrumentationHandler = jest.spyOn(utils, 'addInstrumentationHandler');
const setRequestHeader = jest.fn();
describe('instrumentOutgoingRequests', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('instruments fetch and xhr requests', () => {
instrumentOutgoingRequests();
expect(addInstrumentationHandler).toHaveBeenCalledWith('fetch', expect.any(Function));
expect(addInstrumentationHandler).toHaveBeenCalledWith('xhr', expect.any(Function));
});
it('does not instrument fetch requests if traceFetch is false', () => {
instrumentOutgoingRequests({ traceFetch: false });
expect(addInstrumentationHandler).not.toHaveBeenCalledWith('fetch', expect.any(Function));
});
it('does not instrument xhr requests if traceXHR is false', () => {
instrumentOutgoingRequests({ traceXHR: false });
expect(addInstrumentationHandler).not.toHaveBeenCalledWith('xhr', expect.any(Function));
});
});
describe('callbacks', () => {
let hub: Hub;
let transaction: Transaction;
const alwaysCreateSpan = () => true;
const alwaysAttachHeaders = () => true;
const startTimestamp = 1356996072000;
const endTimestamp = 1356996072000;
beforeAll(() => {
const options = getDefaultBrowserClientOptions({ tracesSampleRate: 1 });
hub = new Hub(new BrowserClient(options));
makeMain(hub);
});
beforeEach(() => {
transaction = hub.startTransaction({ name: 'organizations/users/:userid', op: 'pageload' }) as Transaction;
hub.configureScope(scope => scope.setSpan(transaction));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('fetchCallback()', () => {
let fetchHandlerData: FetchData;
const fetchSpan = {
data: {
method: 'GET',
url: 'http://dogs.are.great/',
type: 'fetch',
},
description: 'GET http://dogs.are.great/',
op: 'http.client',
parentSpanId: expect.any(String),
spanId: expect.any(String),
startTimestamp: expect.any(Number),
traceId: expect.any(String),
};
beforeEach(() => {
fetchHandlerData = {
args: ['http://dogs.are.great/', {}],
fetchData: { url: 'http://dogs.are.great/', method: 'GET' },
startTimestamp,
};
});
it.each([
// each case is [shouldCreateSpanReturnValue, shouldAttachHeadersReturnValue, expectedSpan, expectedHeaderKeys]
[true, true, expect.objectContaining(fetchSpan), ['sentry-trace', 'baggage']],
[true, false, expect.objectContaining(fetchSpan), []],
// If there's no span then there's no parent span id to stick into a header, so no headers, even if there's a
// `tracingOrigins` match
[false, true, undefined, []],
[false, false, undefined, []],
])(
'span creation/header attachment interaction - shouldCreateSpan: %s, shouldAttachHeaders: %s',
(shouldCreateSpanReturnValue, shouldAttachHeadersReturnValue, expectedSpan, expectedHeaderKeys) => {
fetchCallback(
fetchHandlerData,
() => shouldCreateSpanReturnValue,
() => shouldAttachHeadersReturnValue,
{},
);
// spans[0] is the transaction itself
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toEqual(expectedSpan);
const headers = (fetchHandlerData.args[1].headers as Record<string, string>) || {};
expect(Object.keys(headers)).toEqual(expectedHeaderKeys);
},
);
it('adds neither fetch request spans nor fetch request headers if there is no fetch data in handler data', () => {
delete fetchHandlerData.fetchData;
const spans = {};
fetchCallback(fetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(spans).toEqual({});
const headers = (fetchHandlerData.args[1].headers as Record<string, string>) || {};
expect(Object.keys(headers)).toEqual([]);
});
it('adds neither fetch request spans nor fetch request headers if tracing is disabled', () => {
hasTracingEnabled.mockReturnValueOnce(false);
const spans = {};
fetchCallback(fetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(spans).toEqual({});
const headers = (fetchHandlerData.args[1].headers as Record<string, string>) || {};
expect(Object.keys(headers)).toEqual([]);
});
it('creates and finishes fetch span on active transaction', () => {
const spans = {};
// triggered by request being sent
fetchCallback(fetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toBeDefined();
expect(newSpan).toBeInstanceOf(Span);
expect(newSpan.data).toEqual({
method: 'GET',
type: 'fetch',
url: 'http://dogs.are.great/',
});
expect(newSpan.description).toBe('GET http://dogs.are.great/');
expect(newSpan.op).toBe('http.client');
expect(fetchHandlerData.fetchData?.__span).toBeDefined();
const postRequestFetchHandlerData = {
...fetchHandlerData,
endTimestamp,
};
// triggered by response coming back
fetchCallback(postRequestFetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(newSpan.endTimestamp).toBeDefined();
});
it('sets response status on finish', () => {
const spans: Record<string, Span> = {};
// triggered by request being sent
fetchCallback(fetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toBeDefined();
const postRequestFetchHandlerData = {
...fetchHandlerData,
endTimestamp,
response: { status: 404 } as Response,
};
// triggered by response coming back
fetchCallback(postRequestFetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(newSpan.status).toBe(spanStatusfromHttpCode(404));
});
it('ignores response with no associated span', () => {
// the request might be missed somehow. E.g. if it was sent before tracing gets enabled.
const postRequestFetchHandlerData = {
...fetchHandlerData,
endTimestamp,
response: { status: 404 } as Response,
};
// in that case, the response coming back will be ignored
fetchCallback(postRequestFetchHandlerData, alwaysCreateSpan, alwaysAttachHeaders, {});
const newSpan = transaction.spanRecorder?.spans[1];
expect(newSpan).toBeUndefined();
});
it('records outgoing propogations', () => {
const firstReqData = { ...fetchHandlerData };
const secondReqData = { ...fetchHandlerData };
expect(transaction.metadata.propagations).toBe(0);
fetchCallback(firstReqData, alwaysCreateSpan, alwaysAttachHeaders, {});
expect(transaction.metadata.propagations).toBe(1);
fetchCallback(secondReqData, alwaysCreateSpan, alwaysAttachHeaders, {});
expect(transaction.metadata.propagations).toBe(2);
});
});
describe('xhrCallback()', () => {
let xhrHandlerData: XHRData;
const xhrSpan = {
data: {
method: 'GET',
url: 'http://dogs.are.great/',
type: 'xhr',
},
description: 'GET http://dogs.are.great/',
op: 'http.client',
parentSpanId: expect.any(String),
spanId: expect.any(String),
startTimestamp: expect.any(Number),
traceId: expect.any(String),
};
beforeEach(() => {
xhrHandlerData = {
xhr: {
__sentry_xhr__: {
method: 'GET',
url: 'http://dogs.are.great/',
status_code: 200,
data: {},
},
__sentry_xhr_span_id__: '1231201211212012',
setRequestHeader,
},
startTimestamp,
};
});
it.each([
// each case is [shouldCreateSpanReturnValue, shouldAttachHeadersReturnValue, expectedSpan, expectedHeaderKeys]
[true, true, expect.objectContaining(xhrSpan), ['sentry-trace', 'baggage']],
[true, false, expect.objectContaining(xhrSpan), []],
// If there's no span then there's no parent span id to stick into a header, so no headers, even if there's a
// `tracingOrigins` match
[false, true, undefined, []],
[false, false, undefined, []],
])(
'span creation/header attachment interaction - shouldCreateSpan: %s, shouldAttachHeaders: %s',
(shouldCreateSpanReturnValue, shouldAttachHeadersReturnValue, expectedSpan, expectedHeaderKeys) => {
xhrCallback(
xhrHandlerData,
() => shouldCreateSpanReturnValue,
() => shouldAttachHeadersReturnValue,
{},
);
// spans[0] is the transaction itself
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toEqual(expectedSpan);
const headerKeys = setRequestHeader.mock.calls.map(header => header[0]);
expect(headerKeys).toEqual(expectedHeaderKeys);
},
);
it('adds neither xhr request spans nor xhr request headers if tracing is disabled', () => {
hasTracingEnabled.mockReturnValueOnce(false);
const spans = {};
xhrCallback(xhrHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(spans).toEqual({});
expect(setRequestHeader).not.toHaveBeenCalled();
});
it('creates and finishes XHR span on active transaction', () => {
const spans = {};
// triggered by request being sent
xhrCallback(xhrHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toBeInstanceOf(Span);
expect(newSpan.data).toEqual({
method: 'GET',
type: 'xhr',
url: 'http://dogs.are.great/',
});
expect(newSpan.description).toBe('GET http://dogs.are.great/');
expect(newSpan.op).toBe('http.client');
expect(xhrHandlerData.xhr?.__sentry_xhr_span_id__).toBeDefined();
expect(xhrHandlerData.xhr?.__sentry_xhr_span_id__).toEqual(newSpan?.spanId);
const postRequestXHRHandlerData = {
...xhrHandlerData,
endTimestamp,
};
// triggered by response coming back
xhrCallback(postRequestXHRHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(newSpan.endTimestamp).toBeDefined();
});
it('sets response status on finish', () => {
const spans = {};
// triggered by request being sent
xhrCallback(xhrHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
const newSpan = transaction.spanRecorder?.spans[1] as Span;
expect(newSpan).toBeDefined();
const postRequestXHRHandlerData = {
...xhrHandlerData,
endTimestamp,
};
postRequestXHRHandlerData.xhr!.__sentry_xhr__!.status_code = 404;
// triggered by response coming back
xhrCallback(postRequestXHRHandlerData, alwaysCreateSpan, alwaysAttachHeaders, spans);
expect(newSpan.status).toBe(spanStatusfromHttpCode(404));
});
it('ignores response with no associated span', () => {
// the request might be missed somehow. E.g. if it was sent before tracing gets enabled.
const postRequestXHRHandlerData = {
...{
xhr: {
__sentry_xhr__: xhrHandlerData.xhr?.__sentry_xhr__,
},
},
startTimestamp,
endTimestamp,
};
// in that case, the response coming back will be ignored
xhrCallback(postRequestXHRHandlerData, alwaysCreateSpan, alwaysAttachHeaders, {});
const newSpan = transaction.spanRecorder?.spans[1];
expect(newSpan).toBeUndefined();
});
it('records outgoing propogations', () => {
const firstReqData = { ...xhrHandlerData };
const secondReqData = { ...xhrHandlerData };
expect(transaction.metadata.propagations).toBe(0);
xhrCallback(firstReqData, alwaysCreateSpan, alwaysAttachHeaders, {});
expect(transaction.metadata.propagations).toBe(1);
xhrCallback(secondReqData, alwaysCreateSpan, alwaysAttachHeaders, {});
expect(transaction.metadata.propagations).toBe(2);
});
});
});
// TODO (v8): Adapt these tests once we remove `tracingOrigins`
describe('[pre-v8]: shouldAttachHeaders', () => {
describe('prefer `tracePropagationTargets` over `tracingOrigins`', () => {
it('should return `true` if the url matches the new tracePropagationTargets', () => {
expect(shouldAttachHeaders('http://example.com', ['example.com'], undefined)).toBe(true);
});
it('should return `false` if tracePropagationTargets array is empty', () => {
expect(shouldAttachHeaders('http://localhost:3000/test', [], ['localhost'])).toBe(false);
});
it("should return `false` if tracePropagationTargets array doesn't match", () => {
expect(shouldAttachHeaders('http://localhost:3000/test', ['example.com'], ['localhost'])).toBe(false);
});
});
describe('tracingOrigins backwards compatibility (tracePropagationTargets not defined)', () => {
it('should return `true` if the url matches tracingOrigns', () => {
expect(shouldAttachHeaders('http://example.com', undefined, ['example.com'])).toBe(true);
});
it('should return `false` if tracePropagationTargets array is empty', () => {
expect(shouldAttachHeaders('http://localhost:3000/test', undefined, [])).toBe(false);
});
it("should return `false` if tracePropagationTargets array doesn't match", () => {
expect(shouldAttachHeaders('http://localhost:3000/test', undefined, ['example.com'])).toBe(false);
});
});
describe('should fall back to defaults if no options are specified', () => {
it.each([
'/api/test',
'http://localhost:3000/test',
'http://somewhere.com/test/localhost/123',
'http://somewhere.com/test?url=localhost:3000&test=123',
])('return `true` for urls matching defaults (%s)', url => {
expect(shouldAttachHeaders(url, undefined, undefined)).toBe(true);
});
it.each(['notmydoman/api/test', 'example.com'])('return `false` for urls not matching defaults (%s)', url => {
expect(shouldAttachHeaders(url, undefined, undefined)).toBe(false);
});
});
});