-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsender.test.ts
More file actions
293 lines (253 loc) · 10 KB
/
Copy pathsender.test.ts
File metadata and controls
293 lines (253 loc) · 10 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
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.
import { doRequest } from '@dd/core/helpers/request';
import {
getData,
getIntakeUrl,
sendSourcemaps,
upload,
SOURCEMAPS_API_SUBDOMAIN,
SOURCEMAPS_API_PATH,
} from '@dd/error-tracking-plugin/sourcemaps/sender';
import { SOURCEMAP_UPLOAD_METRIC_PREFIX } from '@dd/error-tracking-plugin/sourcemaps/upload-metrics';
import {
getContextMock,
mockLogFn,
mockLogger,
getPayloadMock,
getSourcemapMock,
getSourcemapsConfiguration,
addFixtureFiles,
} from '@dd/tests/_jest/helpers/mocks';
jest.mock('@dd/core/helpers/fs', () => {
const original = jest.requireActual('@dd/core/helpers/fs');
return {
...original,
checkFile: jest.fn(),
getFile: jest.fn(),
};
});
jest.mock('@dd/core/helpers/request', () => {
const original = jest.requireActual('@dd/core/helpers/request');
return {
...original,
doRequest: jest.fn(),
};
});
const doRequestMock = jest.mocked(doRequest);
const contextMock = getContextMock();
const uploadContextMock = {
addMetric: contextMock.addMetric,
apiKey: contextMock.auth.apiKey,
bundlerName: contextMock.bundler.name,
site: contextMock.auth.site,
version: contextMock.version,
outDir: contextMock.bundler.outDir,
};
const senderContextMock = {
...uploadContextMock,
debugIds: new Map(),
git: contextMock.git,
};
describe('Error Tracking Plugin Sourcemaps', () => {
describe('getIntakeUrl', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
});
afterEach(() => {
process.env = originalEnv;
});
test('Should return correct intake URL for US3 site', () => {
expect(getIntakeUrl('us3.datadoghq.com')).toBe(
`https://${SOURCEMAPS_API_SUBDOMAIN}.us3.datadoghq.com/${SOURCEMAPS_API_PATH}`,
);
});
test('Should use DATADOG_SOURCEMAP_INTAKE_URL env var when set', () => {
const customUrl = 'https://custom.intake.url/api/v2/srcmap';
process.env.DATADOG_SOURCEMAP_INTAKE_URL = customUrl;
expect(getIntakeUrl('datadoghq.com')).toBe(customUrl);
expect(getIntakeUrl('datadoghq.eu')).toBe(customUrl);
});
});
describe('getData', () => {
test('Should return the correct data and headers', async () => {
// Add some fixtures.
addFixtureFiles({
'/path/to/minified.min.js': 'Some JS File with some content.',
'/path/to/sourcemap.js.map': '{"version":3,"sources":["/path/to/minified.min.js"]}',
});
const payload = getPayloadMock();
const { data, headers } = await getData(payload)();
const unzippedData = await new Response(
data.pipeThrough(new DecompressionStream('gzip')),
).text();
const dataLines = unzippedData.split(/[\r\n]/g).filter(Boolean);
const boundary = headers['content-type']
.split('boundary=')
.pop()!
.replace(/^(-)+/g, '');
expect(boundary).toBeTruthy();
expect(dataLines[0]).toMatch(boundary);
expect(dataLines[dataLines.length - 1]).toMatch(boundary);
});
});
describe('sendSourcemaps', () => {
test('Should upload sourcemaps.', async () => {
// Add some fixtures.
addFixtureFiles({
'/path/to/minified.min.js': 'Some JS File with some content.',
'/path/to/sourcemap.js.map': '{"version":3,"sources":["/path/to/minified.min.js"]}',
});
await sendSourcemaps(
[getSourcemapMock()],
getSourcemapsConfiguration(),
senderContextMock,
mockLogger,
);
expect(doRequestMock).toHaveBeenCalledTimes(1);
});
test('Should alert in case of payload issues', async () => {
// Add some fixtures.
addFixtureFiles({
'/path/to/minified.min.js': '',
});
await sendSourcemaps(
[getSourcemapMock()],
getSourcemapsConfiguration(),
senderContextMock,
mockLogger,
);
expect(mockLogFn).toHaveBeenCalledTimes(1);
expect(mockLogFn).toHaveBeenCalledWith(
expect.stringMatching('Failed to prepare payloads, aborting upload'),
'error',
);
expect(doRequestMock).not.toHaveBeenCalled();
});
test('Should throw in case of payload issues and bailOnError', async () => {
// Add some fixtures.
addFixtureFiles({
'/path/to/minified.min.js': '',
});
await expect(async () => {
await sendSourcemaps(
[getSourcemapMock()],
getSourcemapsConfiguration({ bailOnError: true }),
senderContextMock,
mockLogger,
);
}).rejects.toThrow('Failed to prepare payloads, aborting upload');
expect(doRequestMock).not.toHaveBeenCalled();
});
});
describe('upload', () => {
beforeEach(() => {
doRequestMock.mockReset();
jest.mocked(contextMock.addMetric).mockReset();
// Add some fixtures.
addFixtureFiles({
'/path/to/minified.min.js': 'Some JS File with some content.',
'/path/to/sourcemap.js.map': '{"version":3,"sources":["/path/to/minified.min.js"]}',
});
});
test('Should not throw', async () => {
doRequestMock.mockResolvedValue(undefined);
const payloads = [getPayloadMock()];
const { warnings, errors } = await upload(
payloads,
getSourcemapsConfiguration(),
uploadContextMock,
mockLogger,
);
expect(warnings).toHaveLength(0);
expect(errors).toHaveLength(0);
expect(doRequestMock).toHaveBeenCalledTimes(1);
});
test('Should alert in case of errors', async () => {
doRequestMock.mockRejectedValueOnce(new Error('Fake Error'));
const payloads = [getPayloadMock()];
const { warnings, errors } = await upload(
payloads,
getSourcemapsConfiguration(),
uploadContextMock,
mockLogger,
);
expect(errors).toHaveLength(1);
expect(errors[0]).toMatchObject({
metadata: {
sourcemap: '/path/to/sourcemap.js.map',
file: '/path/to/minified.min.js',
},
error: new Error('Fake Error'),
});
expect(warnings).toHaveLength(0);
expect(doRequestMock).toHaveBeenCalledTimes(1);
});
test('Should throw in case of errors with bailOnError', async () => {
doRequestMock.mockRejectedValueOnce(new Error('Fake Error'));
const payloads = [getPayloadMock()];
await expect(
upload(
payloads,
getSourcemapsConfiguration({ bailOnError: true }),
uploadContextMock,
mockLogger,
),
).rejects.toThrow('Fake Error');
});
test('Should add retry metrics for temporary upload failures', async () => {
const retryError = new Error('HTTP 408 Request Timeout\nstream timeout');
doRequestMock.mockImplementation(async (opts) => {
opts.onRetry?.(retryError, 1);
});
const payloads = [getPayloadMock()];
const { warnings, errors } = await upload(
payloads,
getSourcemapsConfiguration(),
{ ...uploadContextMock, sendMetrics: true },
mockLogger,
);
expect(warnings).toHaveLength(1);
expect(errors).toHaveLength(0);
expect(doRequestMock).toHaveBeenCalledTimes(1);
expect(uploadContextMock.addMetric).toHaveBeenCalledWith({
metric: `${SOURCEMAP_UPLOAD_METRIC_PREFIX}.retry`,
type: 'count',
points: [[expect.any(Number), 1]],
tags: expect.arrayContaining([
'service:error-tracking-build-plugin-sourcemaps',
'attempt:1',
'status_code:408',
'error_type:http_408',
]),
});
});
test('Should add final failure metrics for exhausted upload retries', async () => {
doRequestMock
.mockRejectedValueOnce(new Error('HTTP 408 Request Timeout\nstream timeout'))
.mockResolvedValueOnce(undefined);
const payloads = [getPayloadMock()];
const { warnings, errors } = await upload(
payloads,
getSourcemapsConfiguration(),
{ ...uploadContextMock, sendMetrics: true },
mockLogger,
);
expect(warnings).toHaveLength(0);
expect(errors).toHaveLength(1);
expect(doRequestMock).toHaveBeenCalledTimes(1);
expect(uploadContextMock.addMetric).toHaveBeenCalledWith({
metric: `${SOURCEMAP_UPLOAD_METRIC_PREFIX}.failure`,
type: 'count',
points: [[expect.any(Number), 1]],
tags: expect.arrayContaining([
'service:error-tracking-build-plugin-sourcemaps',
'status_code:408',
'error_type:http_408',
]),
});
});
});
});