-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
test_scheduler.js
374 lines (326 loc) · 10.8 KB
/
test_scheduler.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
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {AggregatedResult, TestResult} from 'types/TestResult';
import type {GlobalConfig, ReporterConfig} from 'types/Config';
import type {Context} from 'types/Context';
import type {Reporter, Test} from 'types/TestRunner';
import chalk from 'chalk';
import {formatExecError} from 'jest-message-util';
import {
addResult,
buildFailureTestResult,
makeEmptyAggregatedTestResult,
} from './test_result_helpers';
import CoverageReporter from './reporters/coverage_reporter';
import DefaultReporter from './reporters/default_reporter';
import exit from 'exit';
import NotifyReporter from './reporters/notify_reporter';
import ReporterDispatcher from './reporter_dispatcher';
import snapshot from 'jest-snapshot';
import SummaryReporter from './reporters/summary_reporter';
import TestRunner from 'jest-runner';
import TestWatcher from './test_watcher';
import VerboseReporter from './reporters/verbose_reporter';
const SLOW_TEST_TIME = 3000;
// The default jest-runner is required because it is the default test runner
// and required implicitly through the `runner` ProjectConfig option.
TestRunner;
export type TestSchedulerOptions = {|
startRun: (globalConfig: GlobalConfig) => *,
|};
export type TestSchedulerContext = {|
firstRun: boolean,
previousSuccess: boolean,
|};
export default class TestScheduler {
_dispatcher: ReporterDispatcher;
_globalConfig: GlobalConfig;
_options: TestSchedulerOptions;
_context: TestSchedulerContext;
constructor(
globalConfig: GlobalConfig,
options: TestSchedulerOptions,
context: TestSchedulerContext,
) {
this._dispatcher = new ReporterDispatcher();
this._globalConfig = globalConfig;
this._options = options;
this._context = context;
this._setupReporters();
}
addReporter(reporter: Reporter) {
this._dispatcher.register(reporter);
}
removeReporter(ReporterClass: Function) {
this._dispatcher.unregister(ReporterClass);
}
async scheduleTests(tests: Array<Test>, watcher: TestWatcher) {
const onStart = this._dispatcher.onTestStart.bind(this._dispatcher);
const timings = [];
const contexts = new Set();
tests.forEach(test => {
contexts.add(test.context);
if (test.duration) {
timings.push(test.duration);
}
});
const aggregatedResults = createAggregatedResults(tests.length);
const estimatedTime = Math.ceil(
getEstimatedTime(timings, this._globalConfig.maxWorkers) / 1000,
);
// Run in band if we only have one test or one worker available.
// If we are confident from previous runs that the tests will finish quickly
// we also run in band to reduce the overhead of spawning workers.
const runInBand =
this._globalConfig.maxWorkers <= 1 ||
tests.length <= 1 ||
(tests.length <= 20 &&
timings.length > 0 &&
timings.every(timing => timing < SLOW_TEST_TIME));
const onResult = async (test: Test, testResult: TestResult) => {
if (watcher.isInterrupted()) {
return Promise.resolve();
}
if (testResult.testResults.length === 0) {
const message = 'Your test suite must contain at least one test.';
return onFailure(test, {
message,
stack: new Error(message).stack,
});
}
// Throws when the context is leaked after executinga test.
if (testResult.leaks) {
const message =
chalk.red.bold('EXPERIMENTAL FEATURE!\n') +
'Your test suite is leaking memory. Please ensure all references are cleaned.\n' +
'\n' +
'There is a number of things that can leak memory:\n' +
' - Async operations that have not finished (e.g. fs.readFile).\n' +
' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' +
' - Keeping references to the global scope.';
return onFailure(test, {
message,
stack: new Error(message).stack,
});
}
addResult(aggregatedResults, testResult);
await this._dispatcher.onTestResult(test, testResult, aggregatedResults);
return this._bailIfNeeded(contexts, aggregatedResults, watcher);
};
const onFailure = async (test, error) => {
if (watcher.isInterrupted()) {
return;
}
const testResult = buildFailureTestResult(test.path, error);
testResult.failureMessage = formatExecError(
testResult,
test.context.config,
this._globalConfig,
test.path,
);
addResult(aggregatedResults, testResult);
await this._dispatcher.onTestResult(test, testResult, aggregatedResults);
};
const updateSnapshotState = () => {
contexts.forEach(context => {
const status = snapshot.cleanup(
context.hasteFS,
this._globalConfig.updateSnapshot,
);
aggregatedResults.snapshot.filesRemoved += status.filesRemoved;
});
const updateAll = this._globalConfig.updateSnapshot === 'all';
aggregatedResults.snapshot.didUpdate = updateAll;
aggregatedResults.snapshot.failure = !!(
!updateAll &&
(aggregatedResults.snapshot.unchecked ||
aggregatedResults.snapshot.unmatched ||
aggregatedResults.snapshot.filesRemoved)
);
};
await this._dispatcher.onRunStart(aggregatedResults, {
estimatedTime,
showStatus: !runInBand,
});
const testRunners = Object.create(null);
contexts.forEach(({config}) => {
if (!testRunners[config.runner]) {
// $FlowFixMe
testRunners[config.runner] = new (require(config.runner): TestRunner)(
this._globalConfig,
);
}
});
const testsByRunner = this._partitionTests(testRunners, tests);
if (testsByRunner) {
try {
for (const runner of Object.keys(testRunners)) {
await testRunners[runner].runTests(
testsByRunner[runner],
watcher,
onStart,
onResult,
onFailure,
{
serial: runInBand,
},
);
}
} catch (error) {
if (!watcher.isInterrupted()) {
throw error;
}
}
}
updateSnapshotState();
aggregatedResults.wasInterrupted = watcher.isInterrupted();
await this._dispatcher.onRunComplete(contexts, aggregatedResults);
const anyTestFailures = !(
aggregatedResults.numFailedTests === 0 &&
aggregatedResults.numRuntimeErrorTestSuites === 0
);
const anyReporterErrors = this._dispatcher.hasErrors();
aggregatedResults.success = !(
anyTestFailures ||
aggregatedResults.snapshot.failure ||
anyReporterErrors
);
return aggregatedResults;
}
_partitionTests(
testRunners: {[key: string]: TestRunner, __proto__: null},
tests: Array<Test>,
) {
if (Object.keys(testRunners).length > 1) {
return tests.reduce((testRuns, test) => {
const runner = test.context.config.runner;
if (!testRuns[runner]) {
testRuns[runner] = [];
}
testRuns[runner].push(test);
return testRuns;
}, Object.create(null));
} else if (tests.length > 0 && tests[0] != null) {
// If there is only one runner, don't partition the tests.
return Object.assign(Object.create(null), {
[tests[0].context.config.runner]: tests,
});
} else {
return null;
}
}
_shouldAddDefaultReporters(reporters?: Array<ReporterConfig>): boolean {
return (
!reporters ||
!!reporters.find(reporterConfig => reporterConfig[0] === 'default')
);
}
_setupReporters() {
const {collectCoverage, notify, reporters} = this._globalConfig;
const isDefault = this._shouldAddDefaultReporters(reporters);
if (isDefault) {
this._setupDefaultReporters(collectCoverage);
}
if (!isDefault && collectCoverage) {
this.addReporter(new CoverageReporter(this._globalConfig));
}
if (notify) {
this.addReporter(
new NotifyReporter(
this._globalConfig,
this._options.startRun,
this._context,
),
);
}
if (reporters && Array.isArray(reporters)) {
this._addCustomReporters(reporters);
}
}
_setupDefaultReporters(collectCoverage: boolean) {
this.addReporter(
this._globalConfig.verbose
? new VerboseReporter(this._globalConfig)
: new DefaultReporter(this._globalConfig),
);
if (collectCoverage) {
this.addReporter(new CoverageReporter(this._globalConfig));
}
this.addReporter(new SummaryReporter(this._globalConfig));
}
_addCustomReporters(reporters: Array<ReporterConfig>) {
const customReporters = reporters.filter(
reporterConfig => reporterConfig[0] !== 'default',
);
customReporters.forEach((reporter, index) => {
const {options, path} = this._getReporterProps(reporter);
try {
// $FlowFixMe
const Reporter = require(path);
this.addReporter(new Reporter(this._globalConfig, options));
} catch (error) {
throw new Error(
'An error occurred while adding the reporter at path "' +
path +
'".' +
error.message,
);
}
});
}
/**
* Get properties of a reporter in an object
* to make dealing with them less painful.
*/
_getReporterProps(
reporter: ReporterConfig,
): {path: string, options?: Object} {
if (typeof reporter === 'string') {
return {options: this._options, path: reporter};
} else if (Array.isArray(reporter)) {
const [path, options] = reporter;
return {options, path};
}
throw new Error('Reporter should be either a string or an array');
}
_bailIfNeeded(
contexts: Set<Context>,
aggregatedResults: AggregatedResult,
watcher: TestWatcher,
): Promise<void> {
if (this._globalConfig.bail && aggregatedResults.numFailedTests !== 0) {
if (watcher.isWatchMode()) {
watcher.setState({interrupted: true});
} else {
const failureExit = () => exit(1);
return this._dispatcher
.onRunComplete(contexts, aggregatedResults)
.then(failureExit)
.catch(failureExit);
}
}
return Promise.resolve();
}
}
const createAggregatedResults = (numTotalTestSuites: number) => {
const result = makeEmptyAggregatedTestResult();
result.numTotalTestSuites = numTotalTestSuites;
result.startTime = Date.now();
result.success = false;
return result;
};
const getEstimatedTime = (timings, workers) => {
if (!timings.length) {
return 0;
}
const max = Math.max.apply(null, timings);
return timings.length <= workers
? max
: Math.max(timings.reduce((sum, time) => sum + time) / workers, max);
};