-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
run-mocha-tests.js
369 lines (324 loc) · 12.1 KB
/
run-mocha-tests.js
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
/**
* @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
/**
* @fileoverview
* CLI tool for running mocha tests. Run with `yarn mocha`
*/
import fs from 'fs';
import path from 'path';
import {Worker, isMainThread, parentPort, workerData} from 'worker_threads';
import {once} from 'events';
import Mocha from 'mocha';
import yargs from 'yargs';
import * as yargsHelpers from 'yargs/helpers';
import glob from 'glob';
import {LH_ROOT} from '../../../root.js';
import {mochaGlobalSetup, mochaGlobalTeardown} from '../test-env/mocha-setup.js';
const failedTestsDir = `${LH_ROOT}/.tmp/failing-tests`;
if (!isMainThread && parentPort) {
// Worker.
const {test, mochaArgs, numberMochaInvocations} = workerData;
const numberFailures = await runMocha([test], mochaArgs, numberMochaInvocations);
parentPort?.postMessage({type: 'result', numberFailures});
process.exit(0);
}
/** @param {string} text */
function escapeRegex(text) {
return text.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&');
}
function getFailedTests() {
const allFailedTests = [];
for (const file of glob.sync('*.json', {cwd: failedTestsDir, absolute: true})) {
allFailedTests.push(...JSON.parse(fs.readFileSync(file, 'utf-8')));
}
return allFailedTests;
}
// Some tests replace real modules with mocks in the global scope of the test file
// (outside 'before' lifecycle / a test unit). Before doing any lifecycle stuff, Mocha will load
// all test files (everything if --no-parallel, else each worker will load a subset of the files
// all at once). This results in unexpected mocks contaminating other test files.
//
// For now, we isolate a number of tests until they can be refactored.
//
// To run tests without isolation, and all in one process:
// yarn mocha --no-isolation --no-parallel core/test
//
// Because mocha workers can divide up test files that mess with global scope in a way that
// _just happens_ to not cause anything to fail, use this command to verify that
// all necessary tests are isolated:
// yarn mocha --no-parallel
// (also, just comment out the `testsToRunIsolated` below, as they won't impact this verification)
const testsToIsolate = new Set([
// grep -lRE '^await td\.replace' --include='*-test.*' --exclude-dir=node_modules
'core/test/gather/snapshot-runner-test.js',
'core/test/gather/timespan-runner-test.js',
'core/test/user-flow-test.js',
'core/test/gather/driver/prepare-test.js',
'core/test/gather/gatherers/link-elements-test.js',
'core/test/gather/gatherers/service-worker-test.js',
'core/test/runner-test.js',
// grep -lRE --include='-test.js' 'mockDriverSubmodules|mockRunnerModule|mockDriverModule|mockDriverSubmodules|makeMocksForGatherRunner' --include='*-test.*' --exclude-dir=node_modules
'core/test/gather/navigation-runner-test.js',
'core/test/gather/snapshot-runner-test.js',
'core/test/gather/timespan-runner-test.js',
'core/test/user-flow-test.js',
'core/test/gather/gatherers/dobetterweb/response-compression-test.js',
'core/test/gather/gatherers/script-elements-test.js',
'core/test/runner-test.js',
// These tend to timeout in puppeteer when run in parallel with other tests.
'core/test/scenarios/api-test-pptr.js',
'core/test/scenarios/cross-origin-test-pptr.js',
'core/test/scenarios/disconnect-test-pptr.js',
// ?
'clients/test/lightrider/lightrider-entry-test.js', // Runner overrides.
'flow-report/test/flow-report-pptr-test.ts',
'cli/test/cli/bin-test.js',
'cli/test/cli/run-test.js',
'core/test/config/config-test.js',
'core/test/lib/emulation-test.js',
'core/test/lib/sentry-test.js',
'report/test/clients/bundle-test.js',
'report/test/clients/bundle-test.js',
'shared/test/localization/format-test.js',
]);
const y = yargs(yargsHelpers.hideBin(process.argv));
// TODO: -t => --fgrep
const rawArgv = y
.help('help')
.usage('node $0 [<options>] <paths>')
.parserConfiguration({'unknown-options-as-args': true})
.option('_', {
array: true,
type: 'string',
})
.options({
'testMatch': {
type: 'string',
describe: 'Glob pattern for collecting test files',
},
'update': {
alias: 'u',
type: 'boolean',
default: false,
describe: 'Update snapshots',
},
'isolation': {
type: 'boolean',
default: true,
},
'parallel': {
type: 'boolean',
// Although much faster, mocha's parallel test runner defers printing errors until
// all tests have finished. This may be undesired for local development, so enable
// parallel mode by default only in CI.
// Also, good to default to false locally because that avoids missing cross-file
// test contamination by chance of mocha splitting up the work in a way that hides it.
default: Boolean(process.env.CI),
},
'bail': {
alias: 'b',
type: 'boolean',
default: false,
},
't': {
type: 'string',
describe: 'an alias for --grep, to run only tests with matching titles',
},
'onlyFailures': {
type: 'boolean',
},
'require': {
type: 'string',
},
})
.wrap(y.terminalWidth())
.argv;
const argv =
/** @type {Awaited<typeof rawArgv> & LH.Util.CamelCasify<Awaited<typeof rawArgv>>} */ (rawArgv);
// This captures all of our mocha tests except for:
// * flow-report, because it needs to provide additional mocha flags
// * various *-test-pptr.js integration tests, which are long so are handled explicitly in
// specific package.json scripts
const defaultTestMatches = [
'build/**/*-test.js',
'clients/test/**/*-test.js',
'cli/**/*-test.js',
'core/**/*-test.js',
'core/test/**/*-test-pptr.js',
'report/**/*-test.js',
'shared/**/*-test.js',
'third-party/**/*-test.js',
'treemap/**/*-test.js',
'viewer/**/*-test.js',
];
const filterFilePatterns = argv._.filter(arg => !(typeof arg !== 'string' || arg.startsWith('--')))
.map(pattern => {
if (path.isAbsolute(pattern)) {
// Allows this to work:
// yarn mocha /Users/cjamcl/src/lighthouse/core/test/runner-test.js
return path.relative(LH_ROOT, pattern);
} else {
return pattern;
}
});
function getTestFiles() {
// Collect all the possible test files, based off the provided testMatch glob pattern
// or the default patterns defined above.
const testsGlob = argv.testMatch || `{${defaultTestMatches.join(',')}}`;
const allTestFiles = glob.sync(testsGlob, {cwd: LH_ROOT});
// If provided, filter the test files using a basic string includes on the absolute path of
// each test file.
let filteredTests = filterFilePatterns.length ?
allTestFiles.filter((file) => filterFilePatterns.some(pattern => file.includes(pattern))) :
allTestFiles;
let grep;
if (argv.onlyFailures) {
const failedTests = getFailedTests();
if (failedTests.length === 0) throw new Error('no tests failed');
const titles = failedTests.map(failed => failed.title);
grep = new RegExp(titles.map(escapeRegex).join('|'));
filteredTests = filteredTests.filter(file => failedTests.some(failed => failed.file === file));
} else if (argv.t) {
grep = argv.t;
}
if (filterFilePatterns.length) {
console.log(`applied test filters: ${JSON.stringify(filterFilePatterns, null, 2)}`);
}
console.log(`running ${filteredTests.length} test files`);
return {filteredTests, grep};
}
/**
* @param {{numberFailures: number, numberMochaInvocations: number}} params
*/
function exit({numberFailures, numberMochaInvocations}) {
if (!numberFailures) {
console.log('Tests passed');
process.exit(0);
}
if (numberMochaInvocations === 1) {
console.log('Tests failed');
process.exit(1);
}
// If running many instances of mocha, failed results can get lost in the output.
// So keep track of failures and re-print them at the very end.
// See mocha-setup.js afterAll.
const allFailedTests = getFailedTests();
const groupedByFile = new Map();
for (const failedTest of allFailedTests) {
const failedTests = groupedByFile.get(failedTest.file) || [];
failedTests.push(failedTest);
groupedByFile.set(failedTest.file, failedTests);
}
console.log(`${allFailedTests.length} tests failed`);
console.log('Printing failing tests:\n===========\n');
for (const [file, failedTests] of groupedByFile) {
console.log(`${file}\n`);
for (const failedTest of failedTests) {
console.log(`= ${failedTest.title}\n`);
console.log(`${failedTest.error}\n`);
}
}
process.exit(1);
}
/**
* @typedef OurMochaArgs
* @property {RegExp | string | undefined} grep
* @property {boolean} bail
* @property {boolean} parallel
* @property {string | undefined} require
*/
/**
* @param {string[]} tests
* @param {OurMochaArgs} mochaArgs
* @param {number} invocationNumber
*/
async function runMocha(tests, mochaArgs, invocationNumber) {
process.env.LH_FAILED_TESTS_FILE = `${failedTestsDir}/output-${invocationNumber}.json`;
const rootHooksPath = mochaArgs.require || '../test-env/mocha-setup.js';
const {rootHooks} = await import(rootHooksPath);
try {
const mocha = new Mocha({
rootHooks,
timeout: 20_000,
bail: mochaArgs.bail,
grep: mochaArgs.grep,
// TODO: not working
// parallel: tests.length > 1 && mochaArgs.parallel,
parallel: false,
});
// @ts-expect-error - not in types.
mocha.lazyLoadFiles(true);
for (const test of tests) mocha.addFile(test);
await mocha.loadFilesAsync();
return await new Promise(resolve => mocha.run(resolve));
} catch (err) {
console.error(err);
return 1;
}
}
async function main() {
process.env.SNAPSHOT_UPDATE = argv.update ? '1' : '';
const {filteredTests: testsToRun, grep} = getTestFiles();
const testsToRunTogether = [];
const testsToRunIsolated = [];
for (const test of testsToRun) {
if (argv.isolation && testsToIsolate.has(test)) {
testsToRunIsolated.push(test);
} else {
testsToRunTogether.push(test);
}
}
// If running only a single test file, no need for isolation at all. Move
// the singular test to `testsToRunTogether` so that it's run in-process,
// allowing for better DX when doing a `node --inspect-brk` workflow.
if (testsToRunTogether.length === 0 && testsToRunIsolated.length === 1) {
testsToRunTogether.push(testsToRunIsolated[0]);
testsToRunIsolated.splice(0, 1);
}
fs.rmSync(failedTestsDir, {recursive: true, force: true});
fs.mkdirSync(failedTestsDir, {recursive: true});
/** @type {OurMochaArgs} */
const mochaArgs = {
grep,
bail: argv.bail,
parallel: argv.parallel,
require: argv.require,
};
mochaGlobalSetup();
let numberMochaInvocations = 0;
let numberFailures = 0;
try {
if (testsToRunTogether.length) {
numberFailures += await runMocha(testsToRunTogether, mochaArgs, numberMochaInvocations);
numberMochaInvocations += 1;
if (numberFailures && argv.bail) exit({numberFailures, numberMochaInvocations});
}
for (const test of testsToRunIsolated) {
console.log(`Running test in isolation: ${test}`);
const worker = new Worker(new URL(import.meta.url), {
workerData: {
test,
mochaArgs,
numberMochaInvocations,
},
});
try {
const [workerResponse] = await once(worker, 'message');
numberFailures += workerResponse.numberFailures;
} catch (err) {
// `once` throws an error if the underlying event emitter produces an 'error' message.
console.error(err);
numberFailures += 1;
}
numberMochaInvocations += 1;
if (numberFailures && argv.bail) exit({numberFailures, numberMochaInvocations});
}
} finally {
mochaGlobalTeardown();
}
exit({numberFailures, numberMochaInvocations});
}
await main();