-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhelpers.ts
404 lines (343 loc) · 11.2 KB
/
helpers.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
import type { Page, Request } from '@playwright/test';
import { parseEnvelope } from '@sentry/core';
import type {
Envelope,
EnvelopeItem,
EnvelopeItemType,
Event,
EventEnvelope,
EventEnvelopeHeaders,
TransactionEvent,
} from '@sentry/core';
export const envelopeUrlRegex = /\.sentry\.io\/api\/\d+\/envelope\//;
export const envelopeParser = (request: Request | null): unknown[] => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
// Third row of the envelop is the event payload.
return envelope.split('\n').map(line => {
try {
return JSON.parse(line);
} catch (error) {
return line;
}
});
};
export const envelopeRequestParser = <T = Event>(request: Request | null, envelopeIndex = 2): T => {
return envelopeParser(request)[envelopeIndex] as T;
};
/**
* The above envelope parser does not follow the envelope spec...
* ...but modifying it to follow the spec breaks a lot of the test which rely on the current indexing behavior.
*
* This parser is a temporary solution to allow us to test metrics with statsd envelopes.
*
* Eventually, all the tests should be migrated to use this 'proper' envelope parser!
*/
export const properEnvelopeParser = (request: Request | null): EnvelopeItem[] => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
const [, items] = parseEnvelope(envelope);
return items;
};
export type EventAndTraceHeader = [Event, EventEnvelopeHeaders['trace']];
/**
* Returns the first event item and `trace` envelope header from an envelope.
* This is particularly helpful if you want to test dynamic sampling and trace propagation-related cases.
*/
export const eventAndTraceHeaderRequestParser = (request: Request | null): EventAndTraceHeader => {
const envelope = properFullEnvelopeParser<EventEnvelope>(request);
return getEventAndTraceHeader(envelope);
};
const properFullEnvelopeParser = <T extends Envelope>(request: Request | null): T => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
return parseEnvelope(envelope) as T;
};
function getEventAndTraceHeader(envelope: EventEnvelope): EventAndTraceHeader {
const event = envelope[1][0]?.[1] as Event | undefined;
const trace = envelope[0]?.trace;
if (!event || !trace) {
throw new Error('Could not get event or trace from envelope');
}
return [event, trace];
}
export const properEnvelopeRequestParser = <T = Event>(request: Request | null, envelopeIndex = 1): T => {
return properEnvelopeParser(request)[0]?.[envelopeIndex] as T;
};
export const properFullEnvelopeRequestParser = <T extends Envelope>(request: Request | null): T => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
return parseEnvelope(envelope) as T;
};
export const envelopeHeaderRequestParser = (request: Request | null): EventEnvelopeHeaders => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
// First row of the envelop is the event payload.
return envelope.split('\n').map(line => JSON.parse(line))[0];
};
export const getEnvelopeType = (request: Request | null): EnvelopeItemType => {
const envelope = request?.postData() || '';
return (envelope.split('\n').map(line => JSON.parse(line))[1] as Record<string, unknown>).type as EnvelopeItemType;
};
export const countEnvelopes = async (
page: Page,
options?: {
url?: string;
timeout?: number;
envelopeType: EnvelopeItemType | EnvelopeItemType[];
},
): Promise<number> => {
const countPromise = new Promise<number>((resolve, reject) => {
let reqCount = 0;
const requestHandler = (request: Request): void => {
if (envelopeUrlRegex.test(request.url())) {
try {
if (options?.envelopeType) {
const envelopeTypeArray = options
? typeof options.envelopeType === 'string'
? [options.envelopeType]
: options.envelopeType || (['event'] as EnvelopeItemType[])
: (['event'] as EnvelopeItemType[]);
if (envelopeTypeArray.includes(getEnvelopeType(request))) {
reqCount++;
}
}
} catch (e) {
reject(e);
}
}
};
page.on('request', requestHandler);
setTimeout(() => {
page.off('request', requestHandler);
resolve(reqCount);
}, options?.timeout || 1000);
});
if (options?.url) {
await page.goto(options.url);
}
return countPromise;
};
/**
* Run script inside the test environment.
* This is useful for throwing errors in the test environment.
*
* Errors thrown from this function are not guaranteed to be captured by Sentry, especially in Webkit.
*
* @param {Page} page
* @param {{ path?: string; content?: string }} impl
* @return {*} {Promise<void>}
*/
async function runScriptInSandbox(
page: Page,
impl: {
path?: string;
content?: string;
},
): Promise<void> {
try {
await page.addScriptTag({ path: impl.path, content: impl.content });
} catch (e) {
// no-op
}
}
/**
* Get Sentry events at the given URL, or the current page.
*
* @param {Page} page
* @param {string} [url]
* @return {*} {Promise<Array<Event>>}
*/
async function getSentryEvents(page: Page, url?: string): Promise<Array<Event>> {
if (url) {
await page.goto(url);
}
const eventsHandle = await page.evaluateHandle<Array<Event>>('window.events');
return eventsHandle.jsonValue();
}
export async function waitForErrorRequestOnUrl(page: Page, url: string): Promise<Request> {
const [req] = await Promise.all([waitForErrorRequest(page), page.goto(url)]);
return req;
}
export async function waitForTransactionRequestOnUrl(page: Page, url: string): Promise<Request> {
const [req] = await Promise.all([waitForTransactionRequest(page), page.goto(url)]);
return req;
}
export function waitForErrorRequest(page: Page, callback?: (event: Event) => boolean): Promise<Request> {
return page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const event = envelopeRequestParser(req);
if (event.type) {
return false;
}
if (callback) {
return callback(event);
}
return true;
} catch {
return false;
}
});
}
export function waitForTransactionRequest(
page: Page,
callback?: (event: TransactionEvent) => boolean,
): Promise<Request> {
return page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const event = envelopeRequestParser(req);
if (event.type !== 'transaction') {
return false;
}
if (callback) {
return callback(event as TransactionEvent);
}
return true;
} catch {
return false;
}
});
}
/**
* We can only test tracing tests in certain bundles/packages:
* - NPM (ESM, CJS)
* - CDN bundles that contain Tracing
*
* @returns `true` if we should skip the tracing test
*/
export function shouldSkipTracingTest(): boolean {
const bundle = process.env.PW_BUNDLE as string | undefined;
return bundle != null && !bundle.includes('tracing') && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* Today we always run feedback tests, but this can be used to guard this if we ever need to.
*/
export function shouldSkipFeedbackTest(): boolean {
// We always run these, in bundles the pluggable integration is automatically added
return false;
}
/**
* We can only test metrics tests in certain bundles/packages:
* - NPM (ESM, CJS)
* - CDN bundles that include tracing
*
* @returns `true` if we should skip the metrics test
*/
export function shouldSkipMetricsTest(): boolean {
const bundle = process.env.PW_BUNDLE as string | undefined;
return bundle != null && !bundle.includes('tracing') && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* We only test feature flags integrations in certain bundles/packages:
* - NPM (ESM, CJS)
* - Not CDNs.
*
* @returns `true` if we should skip the feature flags test
*/
export function shouldSkipFeatureFlagsTest(): boolean {
const bundle = process.env.PW_BUNDLE as string | undefined;
return bundle != null && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* Waits until a number of requests matching urlRgx at the given URL arrive.
* If the timeout option is configured, this function will abort waiting, even if it hasn't received the configured
* amount of requests, and returns all the events received up to that point in time.
*/
async function getMultipleRequests<T>(
page: Page,
count: number,
urlRgx: RegExp,
requestParser: (req: Request) => T,
options?: {
url?: string;
timeout?: number;
envelopeType?: EnvelopeItemType | EnvelopeItemType[];
},
): Promise<T[]> {
const requests: Promise<T[]> = new Promise((resolve, reject) => {
let reqCount = count;
const requestData: T[] = [];
let timeoutId: NodeJS.Timeout | undefined = undefined;
function requestHandler(request: Request): void {
if (urlRgx.test(request.url())) {
try {
if (options?.envelopeType) {
const envelopeTypeArray = options
? typeof options.envelopeType === 'string'
? [options.envelopeType]
: options.envelopeType || (['event'] as EnvelopeItemType[])
: (['event'] as EnvelopeItemType[]);
if (!envelopeTypeArray.includes(getEnvelopeType(request))) {
return;
}
}
reqCount--;
requestData.push(requestParser(request));
if (reqCount === 0) {
if (timeoutId) {
clearTimeout(timeoutId);
}
page.off('request', requestHandler);
resolve(requestData);
}
} catch (err) {
reject(err);
}
}
}
page.on('request', requestHandler);
if (options?.timeout) {
timeoutId = setTimeout(() => {
resolve(requestData);
}, options.timeout);
}
});
if (options?.url) {
await page.goto(options.url);
}
return requests;
}
/**
* Wait and get multiple envelope requests at the given URL, or the current page
*/
async function getMultipleSentryEnvelopeRequests<T>(
page: Page,
count: number,
options?: {
url?: string;
timeout?: number;
envelopeType?: EnvelopeItemType | EnvelopeItemType[];
},
requestParser: (req: Request) => T = envelopeRequestParser as (req: Request) => T,
): Promise<T[]> {
return getMultipleRequests<T>(page, count, envelopeUrlRegex, requestParser, options) as Promise<T[]>;
}
/**
* Wait and get the first envelope request at the given URL, or the current page
*
* @template T
* @param {Page} page
* @param {string} [url]
* @return {*} {Promise<T>}
*/
async function getFirstSentryEnvelopeRequest<T>(
page: Page,
url?: string,
requestParser: (req: Request) => T = envelopeRequestParser as (req: Request) => T,
): Promise<T> {
const reqs = await getMultipleSentryEnvelopeRequests<T>(page, 1, { url }, requestParser);
const req = reqs[0];
if (!req) {
throw new Error('No request found');
}
return req;
}
export { runScriptInSandbox, getMultipleSentryEnvelopeRequests, getFirstSentryEnvelopeRequest, getSentryEvents };