-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
TestScheduler.ts
401 lines (355 loc) · 11.7 KB
/
TestScheduler.ts
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
/**
* Copyright (c) Facebook, Inc. and its affiliates. 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.
*/
import chalk = require('chalk');
import {formatExecError} from 'jest-message-util';
import type {Config} from '@jest/types';
import snapshot = require('jest-snapshot');
import TestRunner = require('jest-runner');
import type {Context} from 'jest-runtime';
import {
CoverageReporter,
DefaultReporter,
NotifyReporter,
Reporter,
SummaryReporter,
VerboseReporter,
} from '@jest/reporters';
import exit = require('exit');
import {
AggregatedResult,
SerializableError,
TestResult,
addResult,
buildFailureTestResult,
makeEmptyAggregatedTestResult,
} from '@jest/test-result';
import {interopRequireDefault} from 'jest-util';
import ReporterDispatcher from './ReporterDispatcher';
import type TestWatcher from './TestWatcher';
import {shouldRunInBand} from './testSchedulerHelper';
// 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: Config.GlobalConfig) => void;
};
export type TestSchedulerContext = {
firstRun: boolean;
previousSuccess: boolean;
changedFiles?: Set<Config.Path>;
sourcesRelatedToTestsInChangedFiles?: Set<Config.Path>;
};
export default class TestScheduler {
private _dispatcher: ReporterDispatcher;
private _globalConfig: Config.GlobalConfig;
private _options: TestSchedulerOptions;
private _context: TestSchedulerContext;
constructor(
globalConfig: Config.GlobalConfig,
options: TestSchedulerOptions,
context: TestSchedulerContext,
) {
this._dispatcher = new ReporterDispatcher();
this._globalConfig = globalConfig;
this._options = options;
this._context = context;
this._setupReporters();
}
addReporter(reporter: Reporter): void {
this._dispatcher.register(reporter);
}
removeReporter(ReporterClass: Function): void {
this._dispatcher.unregister(ReporterClass);
}
async scheduleTests(
tests: Array<TestRunner.Test>,
watcher: TestWatcher,
): Promise<AggregatedResult> {
const onStart = this._dispatcher.onTestStart.bind(this._dispatcher);
const timings: Array<number> = [];
const contexts = new Set<Context>();
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,
);
const runInBand = shouldRunInBand(tests, timings, this._globalConfig);
const onResult = async (test: TestRunner.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 executing a 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: TestRunner.Test,
error: SerializableError,
) => {
if (watcher.isInterrupted()) {
return;
}
const testResult = buildFailureTestResult(test.path, error);
testResult.failureMessage = formatExecError(
testResult.testExecError,
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,
snapshot.buildSnapshotResolver(context.config),
context.config.testPathIgnorePatterns,
);
aggregatedResults.snapshot.filesRemoved += status.filesRemoved;
aggregatedResults.snapshot.filesRemovedList = (
aggregatedResults.snapshot.filesRemovedList || []
).concat(status.filesRemovedList);
});
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: {[key: string]: TestRunner} = Object.create(null);
contexts.forEach(({config}) => {
if (!testRunners[config.runner]) {
const Runner: typeof TestRunner = require(config.runner);
testRunners[config.runner] = new Runner(this._globalConfig, {
changedFiles: this._context?.changedFiles,
sourcesRelatedToTestsInChangedFiles: this._context
?.sourcesRelatedToTestsInChangedFiles,
});
}
});
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 || Boolean(testRunners[runner].isSerial),
},
);
}
} 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;
}
private _partitionTests(
testRunners: Record<string, TestRunner>,
tests: Array<TestRunner.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;
}
}
private _shouldAddDefaultReporters(
reporters?: Array<string | Config.ReporterConfig>,
): boolean {
return (
!reporters ||
!!reporters.find(
reporter => this._getReporterProps(reporter).path === 'default',
)
);
}
private _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, {
changedFiles: this._context?.changedFiles,
sourcesRelatedToTestsInChangedFiles: this._context
?.sourcesRelatedToTestsInChangedFiles,
}),
);
}
if (notify) {
this.addReporter(
new NotifyReporter(
this._globalConfig,
this._options.startRun,
this._context,
),
);
}
if (reporters && Array.isArray(reporters)) {
this._addCustomReporters(reporters);
}
}
private _setupDefaultReporters(collectCoverage: boolean) {
this.addReporter(
this._globalConfig.verbose
? new VerboseReporter(this._globalConfig)
: new DefaultReporter(this._globalConfig),
);
if (collectCoverage) {
this.addReporter(
new CoverageReporter(this._globalConfig, {
changedFiles: this._context?.changedFiles,
sourcesRelatedToTestsInChangedFiles: this._context
?.sourcesRelatedToTestsInChangedFiles,
}),
);
}
this.addReporter(new SummaryReporter(this._globalConfig));
}
private _addCustomReporters(
reporters: Array<string | Config.ReporterConfig>,
) {
reporters.forEach(reporter => {
const {options, path} = this._getReporterProps(reporter);
if (path === 'default') return;
try {
// TODO: Use `requireAndTranspileModule` for Jest 26
const Reporter = interopRequireDefault(require(path)).default;
this.addReporter(new Reporter(this._globalConfig, options));
} catch (error) {
error.message =
'An error occurred while adding the reporter at path "' +
chalk.bold(path) +
'".' +
error.message;
throw error;
}
});
}
/**
* Get properties of a reporter in an object
* to make dealing with them less painful.
*/
private _getReporterProps(
reporter: string | Config.ReporterConfig,
): {path: string; options: Record<string, unknown>} {
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');
}
private _bailIfNeeded(
contexts: Set<Context>,
aggregatedResults: AggregatedResult,
watcher: TestWatcher,
): Promise<void> {
if (
this._globalConfig.bail !== 0 &&
aggregatedResults.numFailedTests >= this._globalConfig.bail
) {
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: Array<number>, workers: number) => {
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);
};