-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
TestRunner.js
446 lines (398 loc) · 14.1 KB
/
TestRunner.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
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
/**
* Copyright (c) 2014, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const fs = require('graceful-fs');
const os = require('os');
const path = require('path');
const utils = require('./lib/utils');
const workerFarm = require('worker-farm');
const Console = require('./Console');
const promisify = require('./lib/promisify');
const TEST_WORKER_PATH = require.resolve('./TestWorker');
const DEFAULT_OPTIONS = {
/**
* When true, runs all tests serially in the current process, rather than
* creating a worker pool of child processes.
*
* This can be useful for debugging, or when the environment limits to a
* single process.
*/
runInBand: false,
/**
* The maximum number of workers to run tests concurrently with.
*
* It's probably good to keep this at something close to the number of cores
* on the machine that's running the test.
*/
maxWorkers: Math.max(os.cpus().length, 1),
/**
* The path to the executable node binary.
*
* This is used in the process of booting each of the workers.
*/
nodePath: process.execPath,
/**
* The args to be passed to the node binary executable.
*
* This is used in the process of booting each of the workers.
* Passing --debug off to child processes can screw with socket connections
* of the parent process.
*/
nodeArgv: process.execArgv.filter(arg => arg !== '--debug'),
};
const HIDDEN_FILE_RE = /\/\.[^\/]*$/;
function optionPathToRegex(p) {
return utils.escapeStrForRegex(p.replace(/\//g, path.sep));
}
/**
* A class that takes a project's test config and provides various utilities for
* executing its tests.
*
* @param config The jest configuration
* @param options See DEFAULT_OPTIONS for descriptions on the various options
* and their defaults.
*/
class TestRunner {
constructor(config, options) {
this._config = Object.freeze(config);
this._configDeps = null;
// Maximum memory usage if `logHeapUsage` is enabled.
this._maxMemoryUsage = 0;
this._testPathDirsRegExp = new RegExp(
config.testPathDirs
.map(dir => optionPathToRegex(dir))
.join('|')
);
this._nodeHasteTestRegExp = new RegExp(
optionPathToRegex(path.sep + config.testDirectoryName + path.sep) +
'.*\\.(' +
config.testFileExtensions
.map(ext => utils.escapeStrForRegex(ext))
.join('|') +
')$'
);
// Map from testFilePath -> time it takes to run the test. Used to
// optimally schedule bigger test runs.
this._testPerformanceCache = null;
this._opts = Object.assign({}, DEFAULT_OPTIONS, options);
}
_constructModuleLoader(environment, customCfg) {
const config = customCfg || this._config;
const ModuleLoader = this._loadConfigDependencies().ModuleLoader;
return Promise.resolve(new ModuleLoader(config, environment));
}
_isTestFilePath(filePath) {
// get filePath into OS-appropriate format before testing patterns
filePath = path.normalize(filePath);
const testPathIgnorePattern =
this._config.testPathIgnorePatterns.length
? new RegExp(this._config.testPathIgnorePatterns.join('|'))
: null;
return (
this._nodeHasteTestRegExp.test(filePath)
&& !HIDDEN_FILE_RE.test(filePath)
&& (!testPathIgnorePattern || !testPathIgnorePattern.test(filePath))
&& this._testPathDirsRegExp.test(filePath)
);
}
_loadConfigDependencies() {
const config = this._config;
if (this._configDeps === null) {
this._configDeps = {
ModuleLoader: require(config.moduleLoader),
testEnvironment: require(config.testEnvironment),
testRunner: require(config.testRunner).bind(null),
};
}
return this._configDeps;
}
promiseTestPathsRelatedTo(changedPaths) {
// TODO switch this to use HasteResolver instead of a ModuleLoader instance.
return this._constructModuleLoader()
.then(moduleLoader => moduleLoader.getAllTestPaths().then(paths => {
const allTests = {};
return Promise.all(
paths.map(path => moduleLoader._resolver.getDependencies(path)
.then(deps => allTests[path] = deps)
)
).then(() => {
const relatedPaths = new Set();
for (const path in allTests) {
if (this._isTestFilePath(path)) {
for (const resourcePath in allTests[path].resources) {
if (changedPaths.has(resourcePath)) {
relatedPaths.add(path);
}
}
}
}
return Array.from(relatedPaths);
});
}));
}
promiseTestPathsMatching(pathPattern) {
// TODO switch this to use HasteResolver instead of a ModuleLoader instance.
return this._constructModuleLoader()
.then(moduleLoader => moduleLoader.getAllTestPaths())
.then(testPaths => testPaths.filter(
path => this._isTestFilePath(path) && pathPattern.test(path)
));
}
/**
* Run the given single test file path.
* This just contains logic for running a single test given it's file path.
*
* @param {String} testFilePath
* @return {Promise<Object>} Results of the test
*/
runTest(testFilePath) {
const config = this._config;
const configDeps = this._loadConfigDependencies();
const env = new configDeps.testEnvironment(config);
const testRunner = configDeps.testRunner;
// Intercept console logs to colorize.
env.global.console = new Console(
this._config.useStderr ? process.stderr : process.stdout,
process.stderr
);
// Pass the testFilePath into the runner, so it can be used to e.g.
// configure test reporter output.
env.testFilePath = testFilePath;
return this._constructModuleLoader(env, config)
.then(moduleLoader => moduleLoader.resolveDependencies(testFilePath))
.then(moduleLoader => {
if (config.setupEnvScriptFile) {
moduleLoader.requireModule(null, config.setupEnvScriptFile);
}
const testExecStats = {start: Date.now()};
return testRunner(config, env, moduleLoader, testFilePath)
.then(result => {
testExecStats.end = Date.now();
result.perfStats = testExecStats;
result.testFilePath = testFilePath;
result.coverage =
config.collectCoverage
? moduleLoader.getAllCoverageInfo()
: {};
return result;
});
})
.then(
result => Promise.resolve().then(() => {
env.dispose();
if (config.logHeapUsage) {
this._addMemoryUsage(result);
}
return result;
}),
err => Promise.resolve().then(() => {
env.dispose();
throw err;
})
);
}
_getTestPerformanceCachePath() {
return path.join(
this._config.cacheDirectory,
'perf-cache-' + this._config.name
);
}
_sortTests(testPaths) {
// When running more tests than we have workers available, sort the tests
// by size - big test files usually take longer to complete, so we run
// them first in an effort to minimize worker idle time at the end of a
// long test run.
//
// After a test run we store the time it took to run a test and on
// subsequent runs we use that to run the slowest tests first, yielding the
// fastest results.
try {
this._testPerformanceCache = JSON.parse(fs.readFileSync(
this._getTestPerformanceCachePath()
));
} catch (e) {}
const testPerformanceCache = this._testPerformanceCache;
if (testPaths.length > this._opts.maxWorkers) {
testPaths = testPaths
.map(path => [path, fs.statSync(path).size])
.sort((a, b) => {
const cacheA = testPerformanceCache && testPerformanceCache[a[0]];
const cacheB = testPerformanceCache && testPerformanceCache[b[0]];
if (cacheA !== null && cacheB !== null) {
return cacheA < cacheB ? 1 : -1;
}
return a[1] < b[1] ? 1 : -1;
})
.map(p => p[0]);
}
return testPaths;
}
_cacheTestResults(aggregatedResults) {
const performanceCacheFile = this._getTestPerformanceCachePath();
let testPerformanceCache = this._testPerformanceCache;
if (!testPerformanceCache) {
testPerformanceCache = this._testPerformanceCache = {};
}
aggregatedResults.testResults.forEach(test => {
const perf = test && test.perfStats;
if (perf && perf.end && perf.start) {
testPerformanceCache[test.testFilePath] = perf.end - perf.start;
}
});
return new Promise(resolve =>
fs.writeFile(
performanceCacheFile,
JSON.stringify(testPerformanceCache),
() => resolve(aggregatedResults)
)
);
}
/**
* Run all given test paths.
*
* @param {Array<String>} testPaths Array of paths to test files
* @param {Object} reporter Collection of callbacks called on test events
* @return {Promise<Object>} Fulfilled with information about test run:
* success: true if all tests passed
* runTime: elapsed time in seconds to run all tests
* numTotalTestSuites: total number of test suites considered
* numPassedTestSuites: number of test suites run and passed
* numFailedTestSuites: number of test suites run and failed
* numRuntimeErrorTestSuites: number of test suites failed to run
* numTotalTests: total number of tests executed
* numPassedTests: number of tests run and passed
* numFailedTests: number of tests run and failed
* testResults: the jest result info for all tests run
*/
runTests(testPaths, reporter) {
const config = this._config;
if (!reporter) {
const TestReporter = require(config.testReporter);
if (config.useStderr) {
/* eslint-disable fb-www/object-create-only-one-param */
reporter = new TestReporter(Object.create(
process,
{stdout: {value: process.stderr}}
));
/* eslint-enable fb-www/object-create-only-one-param */
} else {
reporter = new TestReporter();
}
}
testPaths = this._sortTests(testPaths);
const aggregatedResults = {
success: null,
startTime: null,
numTotalTestSuites: testPaths.length,
numPassedTestSuites: 0,
numFailedTestSuites: 0,
numRuntimeErrorTestSuites: 0,
numTotalTests: 0,
numPassedTests: 0,
numFailedTests: 0,
testResults: [],
postSuiteHeaders: [],
};
reporter.onRunStart && reporter.onRunStart(config, aggregatedResults);
const onTestResult = (testPath, testResult) => {
aggregatedResults.testResults.push(testResult);
aggregatedResults.numTotalTests +=
testResult.numPassingTests +
testResult.numFailingTests;
aggregatedResults.numFailedTests += testResult.numFailingTests;
aggregatedResults.numPassedTests += testResult.numPassingTests;
if (testResult.numFailingTests > 0) {
aggregatedResults.numFailedTestSuites++;
} else {
aggregatedResults.numPassedTestSuites++;
}
reporter.onTestResult && reporter.onTestResult(
config,
testResult,
aggregatedResults
);
};
const onRunFailure = (testPath, err) => {
const testResult = {
testFilePath: testPath,
testExecError: err,
suites: {},
tests: {},
testResults: {},
};
aggregatedResults.testResults.push(testResult);
aggregatedResults.numRuntimeErrorTestSuites++;
if (reporter.onTestResult) {
reporter.onTestResult(config, testResult, aggregatedResults);
}
};
aggregatedResults.startTime = Date.now();
const testRun = this._createTestRun(testPaths, onTestResult, onRunFailure);
return testRun
.then(() => {
aggregatedResults.success =
aggregatedResults.numFailedTests === 0 &&
aggregatedResults.numRuntimeErrorTestSuites === 0;
if (reporter.onRunComplete) {
reporter.onRunComplete(config, aggregatedResults);
}
return aggregatedResults;
})
.then(this._cacheTestResults.bind(this));
}
_createTestRun(testPaths, onTestResult, onRunFailure) {
if (this._opts.runInBand || testPaths.length <= 1) {
return this._createInBandTestRun(testPaths, onTestResult, onRunFailure);
} else {
return this._createParallelTestRun(testPaths, onTestResult, onRunFailure);
}
}
_createInBandTestRun(testPaths, onTestResult, onRunFailure) {
let testSequence = Promise.resolve();
testPaths.forEach(testPath =>
testSequence = testSequence
.then(this.runTest.bind(this, testPath))
.then(testResult => onTestResult(testPath, testResult))
.catch(err => onRunFailure(testPath, err))
);
return testSequence;
}
_createParallelTestRun(testPaths, onTestResult, onRunFailure) {
const farm = workerFarm({
maxConcurrentCallsPerWorker: 1,
maxRetries: 2, // Allow for a couple of transient errors.
maxConcurrentWorkers: this._opts.maxWorkers,
}, TEST_WORKER_PATH);
const runTest = promisify(farm);
return Promise.all(testPaths.map(
testFilePath => runTest({config: this._config, testFilePath})
.then(testResult => onTestResult(testFilePath, testResult))
.catch(err => {
onRunFailure(testFilePath, err);
if (err.type === 'ProcessTerminatedError') {
// Initialization error or some other uncaught error
console.error(
'A worker process has quit unexpectedly! ' +
'Most likely this an initialization error.'
);
process.exit(1);
}
})
)).then(() => workerFarm.end(farm));
}
_addMemoryUsage(result) {
if (global.gc) {
global.gc();
}
const memoryUsage = process.memoryUsage().heapUsed;
this._maxMemoryUsage = Math.max(this._maxMemoryUsage, memoryUsage);
result.maxMemoryUsage = this._maxMemoryUsage;
result.memoryUsage = memoryUsage;
}
}
module.exports = TestRunner;