-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
index.ts
187 lines (168 loc) · 5.33 KB
/
index.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
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { parseSemver } from '@sentry/utils';
import { Express } from 'express';
import * as http from 'http';
import { RequestOptions } from 'https';
import nock from 'nock';
import * as path from 'path';
import { getPortPromise } from 'portfinder';
/**
* Returns`describe` or `describe.skip` depending on allowed major versions of Node.
*
* @param {{ min?: number; max?: number }} allowedVersion
* @return {*} {jest.Describe}
*/
export const conditionalTest = (allowedVersion: { min?: number; max?: number }): jest.Describe => {
const NODE_VERSION = parseSemver(process.versions.node).major;
if (!NODE_VERSION) {
return describe.skip;
}
return NODE_VERSION < (allowedVersion.min || -Infinity) || NODE_VERSION > (allowedVersion.max || Infinity)
? describe.skip
: describe;
};
/**
* Asserts against a Sentry Event ignoring non-deterministic properties
*
* @param {Record<string, unknown>} actual
* @param {Record<string, unknown>} expected
*/
export const assertSentryEvent = (actual: Record<string, unknown>, expected: Record<string, unknown>): void => {
expect(actual).toMatchObject({
event_id: expect.any(String),
timestamp: expect.any(Number),
...expected,
});
};
/**
* Asserts against a Sentry Transaction ignoring non-deterministic properties
*
* @param {Record<string, unknown>} actual
* @param {Record<string, unknown>} expected
*/
export const assertSentryTransaction = (actual: Record<string, unknown>, expected: Record<string, unknown>): void => {
expect(actual).toMatchObject({
event_id: expect.any(String),
timestamp: expect.any(Number),
start_timestamp: expect.any(Number),
spans: expect.any(Array),
type: 'transaction',
...expected,
});
};
/**
* Parses response body containing an Envelope
*
* @param {string} body
* @return {*} {Array<Record<string, unknown>>}
*/
export const parseEnvelope = (body: string): Array<Record<string, unknown>> => {
return body.split('\n').map(e => JSON.parse(e));
};
/**
* Intercepts and extracts up to a number of requests containing Sentry envelopes.
*
* @param url The url the intercepted requests will be directed to.
* @param count The expected amount of requests to the envelope endpoint. If
* the amount of sentrequests is lower than`count`, this function will not resolve.
* @returns The intercepted envelopes.
*/
export const getMultipleEnvelopeRequest = async (url: string, count: number): Promise<Record<string, unknown>[][]> => {
const envelopes: Record<string, unknown>[][] = [];
return new Promise(resolve => {
nock('https://dsn.ingest.sentry.io')
.post('/api/1337/envelope/', body => {
const envelope = parseEnvelope(body);
envelopes.push(envelope);
if (count === envelopes.length) {
resolve(envelopes);
}
return true;
})
.times(count)
.query(true) // accept any query params - used for sentry_key param
.reply(200);
http.get(url);
});
};
/**
* Sends a get request to given URL, with optional headers
*
* @param {URL} url
* @param {Record<string, string>} [headers]
* @return {*} {Promise<any>}
*/
export const getAPIResponse = async (url: URL, headers?: Record<string, string>): Promise<unknown> => {
return new Promise(resolve => {
http.get(
headers
? ({
protocol: url.protocol,
host: url.hostname,
path: url.pathname,
port: url.port,
headers,
} as RequestOptions)
: url,
response => {
let body = '';
response.on('data', function (chunk: string) {
body += chunk;
});
response.on('end', function () {
resolve(JSON.parse(body));
});
},
);
});
};
/**
* Intercepts and extracts a single request containing a Sentry envelope
*
* @param url The url the intercepted request will be directed to.
* @returns The extracted envelope.
*/
export const getEnvelopeRequest = async (url: string): Promise<Array<Record<string, unknown>>> => {
return (await getMultipleEnvelopeRequest(url, 1))[0];
};
/**
* Runs a test server
*
* @param {string} testDir
* @param {string} [serverPath]
* @param {string} [scenarioPath]
* @return {*} {Promise<string>}
*/
export async function runServer(testDir: string, serverPath?: string, scenarioPath?: string): Promise<string> {
const port = await getPortPromise();
const url = `http://localhost:${port}/test`;
const defaultServerPath = path.resolve(process.cwd(), 'utils', 'defaults', 'server');
await new Promise<void>(resolve => {
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-member-access
const app = require(serverPath || defaultServerPath).default as Express;
app.get('/test', (_req, res) => {
try {
require(scenarioPath || `${testDir}/scenario`);
} finally {
res.status(200).end();
}
});
const server = app.listen(port, () => {
resolve();
setTimeout(() => {
server.close();
}, 4000);
});
});
return url;
}
export async function runScenario(serverUrl: string): Promise<void> {
return new Promise<void>(resolve => {
http
.get(serverUrl, res => {
res.on('data', () => undefined);
res.on('end', resolve);
})
.end();
});
}