-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmocks.ts
More file actions
578 lines (539 loc) · 16.7 KB
/
Copy pathmocks.ts
File metadata and controls
578 lines (539 loc) · 16.7 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
// 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 { DEFAULT_SITE } from '@dd/core/constants';
import {
checkFile,
getFile,
readFileSync,
readFile,
existsSync,
outputFileSync,
} from '@dd/core/helpers/fs';
import { getAbsolutePath } from '@dd/core/helpers/paths';
import { getUniqueId } from '@dd/core/helpers/strings';
import type {
AuthOptionsWithDefaults,
BuildReport,
FileReport,
GetPluginsArg,
GlobalContext,
GlobalData,
GlobalStores,
Logger,
LogLevel,
Options,
OptionsWithDefaults,
RepositoryData,
TimeLogger,
TimingsReport,
} from '@dd/core/types';
import type {
Metadata,
MultipartValue,
Payload,
} from '@dd/error-tracking-plugin/sourcemaps/payload';
import type {
SourcemapsOptions,
SourcemapsOptionsWithDefaults,
Sourcemap,
} from '@dd/error-tracking-plugin/types';
import { TrackedFilesMatcher } from '@dd/internal-git-plugin/trackedFilesMatcher';
import type { Compilation, Module, MetricsOptions } from '@dd/metrics-plugin/types';
import { File } from 'buffer';
import type { PluginBuild, Metafile } from 'esbuild';
import esbuild from 'esbuild';
import type { PathLike, Stats } from 'fs';
import path from 'path';
import { getTempWorkingDir } from './env';
export const easyProjectEntry = './easy_project/main.js';
export const easyProjectWithCSSEntry = './easy_project_with_css/main.js';
export const hardProjectEntries = {
app1: './hard_project/main1.js',
app2: './hard_project/main2.js',
};
export const defaultAuth: AuthOptionsWithDefaults = {
apiKey: '123',
appKey: '123',
site: DEFAULT_SITE,
};
export const defaultPluginOptions: OptionsWithDefaults = {
auth: defaultAuth,
enableGit: true,
logLevel: 'debug',
metadata: {},
};
export const getMockBundler = (
overrides: Partial<BuildReport['bundler']> = {},
): BuildReport['bundler'] => ({
name: 'esbuild',
version: 'FAKE_VERSION',
...overrides,
});
export const getMockData = (overrides: Partial<GlobalData> = {}): GlobalData => ({
env: 'test',
metadata: {},
bundler: getMockBundler(overrides.bundler),
packageName: '@datadog/esbuild-plugin',
version: 'FAKE_VERSION',
...overrides,
});
export const getMockStores = (overrides: Partial<GlobalStores> = {}): GlobalStores => ({
debugIds: new Map(),
logs: [],
errors: [],
warnings: [],
metrics: new Set(),
queue: [],
timings: [],
...overrides,
});
export const getMockTimer = (
overrides: Partial<TimeLogger['timer']> = {},
): TimeLogger['timer'] => ({
pluginName: 'mock-plugin',
label: 'mock-label',
spans: [],
tags: [],
logLevel: 'debug',
total: 0,
...overrides,
});
export const getMockTimeLogger = (overrides: Partial<TimeLogger> = {}): TimeLogger => {
const mockTimer: TimeLogger = {
end: jest.fn(),
resume: jest.fn(),
pause: jest.fn(),
tag: jest.fn(),
...overrides,
timer: getMockTimer(overrides.timer),
};
return mockTimer;
};
export const mockLogFn = jest.fn((text: any, level: LogLevel) => {});
export const getMockLogger = (overrides: Partial<Logger> = {}): Logger => ({
getLogger: jest.fn(),
time: jest.fn(() => getMockTimeLogger()),
error: (text: any) => {
mockLogFn(text, 'error');
},
warn: (text: any) => {
mockLogFn(text, 'warn');
},
info: (text: any) => {
mockLogFn(text, 'info');
},
debug: (text: any) => {
mockLogFn(text, 'debug');
},
...overrides,
});
export const mockLogger: Logger = getMockLogger();
export const getEsbuildMock = (
overrides: Partial<PluginBuild> = {},
cwd: string = process.cwd(),
): PluginBuild => {
return {
resolve: async (filepath) => {
return {
errors: [],
warnings: [],
external: false,
sideEffects: false,
namespace: '',
suffix: '',
pluginData: {},
path: getAbsolutePath(cwd, filepath),
};
},
onStart: jest.fn(),
onEnd: jest.fn(),
onResolve: jest.fn(),
onLoad: jest.fn(),
onDispose: jest.fn(),
...overrides,
esbuild: {
context: jest.fn(),
build: jest.fn(),
buildSync: jest.fn(),
transform: jest.fn(),
transformSync: jest.fn(),
formatMessages: jest.fn(),
formatMessagesSync: jest.fn(),
analyzeMetafile: jest.fn(),
analyzeMetafileSync: jest.fn(),
initialize: jest.fn(),
version: '1.0.0',
...(overrides.esbuild || {}),
},
initialOptions: {
...(overrides.initialOptions || {}),
},
};
};
export const mockTimingsReport: TimingsReport = {
tapables: new Map(),
loaders: new Map(),
modules: new Map(),
};
export const getMockBuildReport = (overrides: Partial<BuildReport> = {}): BuildReport => ({
errors: [],
warnings: [],
metadata: {},
logs: [],
timings: [],
...overrides,
bundler: getMockBundler(overrides.bundler),
});
export const getGetPluginsArg = (
optionsOverrides: Partial<OptionsWithDefaults> = {},
contextOverrides: Partial<GlobalContext> = {},
): GetPluginsArg => {
return {
options: {
...defaultPluginOptions,
...optionsOverrides,
auth: { ...defaultAuth, ...optionsOverrides.auth },
},
context: getContextMock(contextOverrides),
data: getMockData(),
stores: getMockStores(),
bundler: {},
};
};
export const getContextMock = (overrides: Partial<GlobalContext> = {}): GlobalContext => {
return {
auth: defaultAuth,
bundler: {
...getMockBundler(overrides.bundler),
outDir: '/cwd/path',
},
build: getMockBuildReport(),
buildRoot: '/cwd/path',
env: 'test',
getLogger: jest.fn(() => getMockLogger()),
asyncHook: jest.fn(),
addMetric: jest.fn(),
hook: jest.fn(),
inject: jest.fn(),
pluginNames: [],
sendLog: jest.fn(),
plugins: [],
queue: jest.fn(),
start: Date.now(),
version: 'FAKE_VERSION',
...overrides,
};
};
// Return a plugin configuration including all the features.
export const getFullPluginConfig = (overrides: Partial<Options> = {}): Options => {
return {
...defaultPluginOptions,
errorTracking: {
sourcemaps: getSourcemapsConfiguration(),
},
rum: {
sdk: {
applicationId: '123',
clientToken: '123',
},
privacy: {},
},
metrics: getMetricsConfiguration(),
...overrides,
};
};
// Filter out stuff from the build report.
export const filterOutParticularities = (input: FileReport) =>
// Vite injects its own preloader helper.
!input.filepath.includes('vite/preload-helper') &&
// Exclude ?commonjs-* files, which are coming from the rollup/vite commonjs plugin.
!input.filepath.includes('?commonjs-') &&
// Exclude webpack buildin modules, which are webpack internal dependencies.
!input.filepath.includes('webpack/buildin') &&
// Exclude webpack's fake entry point.
!input.filepath.includes('fixtures/empty.js');
export const getMockPluginBuild = (overrides: Partial<PluginBuild>): PluginBuild => {
return {
initialOptions: {},
esbuild,
resolve: jest.fn(),
onStart: jest.fn(),
onEnd: jest.fn(),
onResolve: jest.fn(),
onDispose: jest.fn(),
onLoad: jest.fn(),
...overrides,
};
};
const mockTapable = { tap: jest.fn() };
export const mockModule: Module = {
name: 'module',
userRequest: '',
size: 123,
loaders: [],
chunks: [],
_chunks: new Set(),
dependencies: [],
};
export const getMockModule = (overrides: Partial<Module>): Module => ({
...mockModule,
...overrides,
});
export const mockCompilation: Compilation = {
options: {
context: '/default/context',
},
moduleGraph: {
getIssuer: () => mockModule,
getModule: () => mockModule,
issuer: mockModule,
},
hooks: {
buildModule: mockTapable,
succeedModule: mockTapable,
failedModule: mockTapable,
afterOptimizeTree: mockTapable,
},
};
export const getMockCompilation = (overrides: Partial<Compilation>): Compilation => ({
options: {
...mockCompilation.options,
...overrides.options,
},
moduleGraph: {
...mockCompilation.moduleGraph!,
...overrides.moduleGraph!,
},
hooks: {
...mockCompilation.hooks,
...overrides.hooks,
},
});
export const mockMetaFile: Metafile = {
inputs: {
module1: {
bytes: 1,
imports: [],
},
module2: {
bytes: 1,
imports: [],
},
},
outputs: {
module1: {
imports: [],
exports: [],
inputs: { module2: { bytesInOutput: 0 } },
bytes: 0,
},
module2: {
imports: [],
exports: [],
inputs: { module1: { bytesInOutput: 0 } },
bytes: 0,
},
},
};
export const getMetricsConfiguration = (
overrides: Partial<MetricsOptions> = {},
): MetricsOptions => ({
enableDefaultPrefix: true,
enableTracing: true,
prefix: 'prefix',
tags: ['tag'],
timestamp: new Date().getTime(),
...overrides,
});
export const getMinimalSourcemapsConfiguration = (
options: Partial<SourcemapsOptions> = {},
): SourcemapsOptions => {
return {
minifiedPathPrefix: '/prefix',
releaseVersion: '1.0.0',
service: 'error-tracking-build-plugin-sourcemaps',
...options,
};
};
export const getSourcemapsConfiguration = (
options: Partial<SourcemapsOptions> = {},
): SourcemapsOptionsWithDefaults => {
return {
bailOnError: false,
dryRun: false,
maxConcurrency: 10,
minifiedPathPrefix: '/prefix',
releaseVersion: '1.0.0',
service: 'error-tracking-build-plugin-sourcemaps',
...options,
};
};
export const getSourcemapMock = (options: Partial<Sourcemap> = {}): Sourcemap => {
return {
minifiedFilePath: '/path/to/minified.min.js',
minifiedPathPrefix: '/prefix',
minifiedUrl: '/prefix/path/to/minified.js',
relativePath: 'path/to/minified.min.js',
sourcemapFilePath: '/path/to/sourcemap.js.map',
...options,
};
};
export const getMetadataMock = (options: Partial<Metadata> = {}): Metadata => {
return {
plugin_version: '1.0.0',
project_path: '/path/to/project',
service: 'error-tracking-build-plugin-sourcemaps',
type: 'js_sourcemap',
version: '1.0.0',
...options,
};
};
export const getRepositoryDataMock = (options: Partial<RepositoryData> = {}): RepositoryData => {
return {
commit: {
hash: 'hash',
message: 'message',
author: {
name: 'author',
email: 'author@example.com',
date: '2021-01-01',
},
committer: {
name: 'committer',
email: 'committer@example.com',
date: '2021-01-01',
},
},
hash: 'hash',
branch: 'branch',
remote: 'remote',
trackedFilesMatcher: new TrackedFilesMatcher(['/path/to/minified.min.js']),
...options,
};
};
export const getPayloadMock = (
options: Partial<Payload> = {},
content: [string, MultipartValue][] = [],
): Payload => {
return {
content: new Map<string, MultipartValue>([
[
'source_map',
{
type: 'file',
path: '/path/to/sourcemap.js.map',
options: { filename: 'source_map', contentType: 'application/json' },
},
],
[
'minified_file',
{
type: 'file',
path: '/path/to/minified.min.js',
options: {
filename: 'minified_file',
contentType: 'application/javascript',
},
},
],
...content,
]),
errors: [],
warnings: [],
...options,
};
};
// Mocking files in fs.
const mockGetFile = jest.mocked(getFile);
const mockCheckFile = jest.mocked(checkFile);
const mockReadFileSync = jest.mocked(readFileSync);
const mockReadFile = jest.mocked(readFile);
const mockExistsSync = jest.mocked(existsSync);
const mockStat = jest.mocked(require('fs/promises').stat);
const mockGlobSync = jest.mocked(require('glob').glob.sync);
export const addFixtureFiles = (files: Record<string, string>, buildRoot: string = __dirname) => {
let toReturnBuildRoot = buildRoot;
const getENOENTError = () => {
const err = new Error(`File not found`);
(err as any).code = 'ENOENT';
return err;
};
// Convert relative paths to absolute paths based on the provided buildRoot.
const absoluteFiles: Record<string, string> = {};
for (const [relativePath, content] of Object.entries(files)) {
const absolutePath = path.resolve(buildRoot, relativePath);
absoluteFiles[absolutePath] = content;
}
// Default readFile mock
const readFileImplementation = (filePath: string) => {
const resolvedPath = path.resolve(buildRoot, filePath);
if (absoluteFiles[resolvedPath] === undefined) {
throw getENOENTError();
}
return absoluteFiles[resolvedPath] || '';
};
if (typeof mockCheckFile.mockImplementation === 'function') {
mockCheckFile.mockImplementation(async (filePath) => {
const resolvedPath = path.resolve(buildRoot, filePath);
return {
empty: !absoluteFiles[resolvedPath],
exists: !!absoluteFiles[resolvedPath],
};
});
}
if (typeof mockGetFile.mockImplementation === 'function') {
mockGetFile.mockImplementation(async (filePath, options) => {
const resolvedPath = path.resolve(buildRoot, filePath);
if (absoluteFiles[resolvedPath] === undefined) {
throw getENOENTError();
}
const filecontent = new Blob([absoluteFiles[resolvedPath] || '']);
return new File([filecontent], options.filename, { type: options.contentType });
});
}
if (typeof mockReadFileSync.mockImplementation === 'function') {
mockReadFileSync.mockImplementation(readFileImplementation);
}
if (typeof mockReadFile.mockImplementation === 'function') {
mockReadFile.mockImplementation(async (filePath: string) =>
readFileImplementation(filePath),
);
}
if (typeof mockStat.mockImplementation === 'function') {
mockStat.mockImplementation(async (filePath: PathLike) => {
const resolvedPath = path.resolve(buildRoot, filePath.toString());
if (absoluteFiles[resolvedPath] === undefined) {
throw getENOENTError();
}
return {
size: absoluteFiles[resolvedPath].length,
} as Stats;
});
}
if (typeof mockExistsSync.mockImplementation === 'function') {
mockExistsSync.mockImplementation((filePath: string) => {
const resolvedPath = path.resolve(buildRoot, filePath);
return absoluteFiles[resolvedPath] !== undefined;
});
}
if (typeof mockGlobSync.mockImplementation === 'function') {
// Create a temp directory to store the files we want to fixture.
const seed: string = `${Math.abs(jest.getSeed())}.${getUniqueId()}`;
const workingDir = getTempWorkingDir(seed);
toReturnBuildRoot = workingDir;
// Create the files in the temp directory.
for (const [relativePath, content] of Object.entries(files)) {
const absolutePath = path.resolve(workingDir, relativePath);
outputFileSync(absolutePath, content);
}
mockGlobSync.mockImplementation((pattern: string) => {
const original = jest.requireActual('glob');
// Re-orient glob to the temp directory.
return original.glob.sync(pattern, {
cwd: workingDir,
});
});
}
return toReturnBuildRoot;
};