/
3-dry-run-executor.ts
181 lines (162 loc) · 6.8 KB
/
3-dry-run-executor.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
import { EOL } from 'os';
import { Injector } from 'typed-inject';
import { I } from '@stryker-mutator/util';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { StrykerOptions, Mutant } from '@stryker-mutator/api/core';
import {
DryRunResult,
TestRunner,
DryRunStatus,
CompleteDryRunResult,
TestStatus,
TestResult,
FailedTestResult,
ErrorDryRunResult,
} from '@stryker-mutator/api/test-runner';
import { first } from 'rxjs/operators';
import { Checker } from '@stryker-mutator/api/check';
import { coreTokens } from '../di';
import { Sandbox } from '../sandbox/sandbox';
import Timer from '../utils/timer';
import { createTestRunnerFactory } from '../test-runner';
import { MutationTestReportHelper } from '../reporters/mutation-test-report-helper';
import { ConfigError } from '../errors';
import { findMutantTestCoverage } from '../mutants';
import { Pool, createTestRunnerPool } from '../concurrent/pool';
import { ConcurrencyTokenProvider } from '../concurrent';
import { MutationTestContext } from './4-mutation-test-executor';
import { MutantInstrumenterContext } from './2-mutant-instrumenter-executor';
const INITIAL_TEST_RUN_MARKER = 'Initial test run';
export interface DryRunContext extends MutantInstrumenterContext {
[coreTokens.sandbox]: Sandbox;
[coreTokens.mutants]: readonly Mutant[];
[coreTokens.checkerPool]: I<Pool<Checker>>;
[coreTokens.concurrencyTokenProvider]: I<ConcurrencyTokenProvider>;
}
/**
* A small object that keeps the timing variables of a test run.
*/
interface Timing {
/**
* The time that the test runner was actually executing tests in milliseconds.
*/
net: number;
/**
* the time that was spend not executing tests in milliseconds.
* So the time it took to start the test runner and to report the result.
*/
overhead: number;
/**
* The total time spent (net + overhead) in a human readable format
*/
humanReadableTimeElapsed: string;
}
function isFailedTest(testResult: TestResult): testResult is FailedTestResult {
return testResult.status === TestStatus.Failed;
}
export class DryRunExecutor {
private readonly dryRunTimeout: number;
public static readonly inject = tokens(
commonTokens.injector,
commonTokens.logger,
commonTokens.options,
coreTokens.timer,
coreTokens.concurrencyTokenProvider
);
constructor(
private readonly injector: Injector<DryRunContext>,
private readonly log: Logger,
private readonly options: StrykerOptions,
private readonly timer: I<Timer>,
private readonly concurrencyTokenProvider: I<ConcurrencyTokenProvider>
) {}
public async execute(): Promise<Injector<MutationTestContext>> {
const testRunnerInjector = this.injector
.provideFactory(coreTokens.testRunnerFactory, createTestRunnerFactory)
.provideValue(coreTokens.testRunnerConcurrencyTokens, this.concurrencyTokenProvider.testRunnerToken$)
.provideFactory(coreTokens.testRunnerPool, createTestRunnerPool);
const testRunnerPool = testRunnerInjector.resolve(coreTokens.testRunnerPool);
const testRunner = await testRunnerPool.worker$.pipe(first()).toPromise();
const { dryRunResult, timing } = await this.timeDryRun(testRunner);
this.logInitialTestRunSucceeded(dryRunResult.tests, timing);
if (!dryRunResult.tests.length) {
throw new ConfigError('No tests were executed. Stryker will exit prematurely. Please check your configuration.');
}
return testRunnerInjector
.provideValue(coreTokens.timeOverheadMS, timing.overhead)
.provideValue(coreTokens.dryRunResult, dryRunResult)
.provideClass(coreTokens.mutationTestReportHelper, MutationTestReportHelper)
.provideFactory(coreTokens.mutantsWithTestCoverage, findMutantTestCoverage);
}
private validateResultCompleted(runResult: DryRunResult): asserts runResult is CompleteDryRunResult {
switch (runResult.status) {
case DryRunStatus.Complete:
const failedTests = runResult.tests.filter(isFailedTest);
if (failedTests.length) {
this.logFailedTestsInInitialRun(failedTests);
throw new ConfigError('There were failed tests in the initial test run.');
}
return;
case DryRunStatus.Error:
this.logErrorsInInitialRun(runResult);
break;
case DryRunStatus.Timeout:
this.logTimeoutInitialRun();
break;
}
throw new Error('Something went wrong in the initial test run');
}
private async timeDryRun(testRunner: TestRunner): Promise<{ dryRunResult: CompleteDryRunResult; timing: Timing }> {
const dryRunTimeout = this.options.dryRunTimeoutMinutes * 1000 * 60;
this.timer.mark(INITIAL_TEST_RUN_MARKER);
this.log.info('Starting initial test run. This may take a while.');
this.log.debug(`Using timeout of ${this.dryRunTimeout} ms.`);
const dryRunResult = await testRunner.dryRun({ timeout: dryRunTimeout, coverageAnalysis: this.options.coverageAnalysis });
const grossTimeMS = this.timer.elapsedMs(INITIAL_TEST_RUN_MARKER);
const humanReadableTimeElapsed = this.timer.humanReadableElapsed(INITIAL_TEST_RUN_MARKER);
this.validateResultCompleted(dryRunResult);
const timing = this.calculateTiming(grossTimeMS, humanReadableTimeElapsed, dryRunResult.tests);
return { dryRunResult, timing };
}
private logInitialTestRunSucceeded(tests: TestResult[], timing: Timing) {
this.log.info(
'Initial test run succeeded. Ran %s tests in %s (net %s ms, overhead %s ms).',
tests.length,
timing.humanReadableTimeElapsed,
timing.net,
timing.overhead
);
}
/**
* Calculates the timing variables for the test run.
* grossTime = NetTime + overheadTime
*
* The overhead time is used to calculate exact timeout values during mutation testing.
* See timeoutMS setting in README for more information on this calculation
*/
private calculateTiming(grossTimeMS: number, humanReadableTimeElapsed: string, tests: readonly TestResult[]): Timing {
const netTimeMS = tests.reduce((total, test) => total + test.timeSpentMs, 0);
const overheadTimeMS = grossTimeMS - netTimeMS;
return {
net: netTimeMS,
overhead: overheadTimeMS < 0 ? 0 : overheadTimeMS,
humanReadableTimeElapsed,
};
}
private logFailedTestsInInitialRun(failedTests: FailedTestResult[]): void {
let message = 'One or more tests failed in the initial test run:';
failedTests.forEach((test) => {
message += `${EOL}\t${test.name}`;
message += `${EOL}\t\t${test.failureMessage}`;
});
this.log.error(message);
}
private logErrorsInInitialRun(runResult: ErrorDryRunResult) {
let message = `One or more tests resulted in an error:${EOL}\t${runResult.errorMessage}`;
this.log.error(message);
}
private logTimeoutInitialRun() {
this.log.error('Initial test run timed out!');
}
}