targeted-mutation 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +148 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { appendFileSync } from 'node:fs';
|
|
2
|
+
import { vi } from 'vitest';
|
|
3
|
+
import { VitestTestRunner } from 'vitest/runners';
|
|
4
|
+
|
|
5
|
+
const sessionKey = Symbol.for('targeted-mutation-ts/session');
|
|
6
|
+
const trialKey = Symbol.for('targeted-mutation-ts/trial');
|
|
7
|
+
const unhandledKey = Symbol.for('targeted-mutation-ts/unhandled');
|
|
8
|
+
const immediate = setImmediate;
|
|
9
|
+
const base = VitestTestRunner.prototype;
|
|
10
|
+
const runs = task => task.mode === 'run' || task.mode === 'queued';
|
|
11
|
+
const timeoutMessage = /^(?:Hook|Test) timed out in \d+ms\./;
|
|
12
|
+
const vitestModule = /\/vitest\/dist\/|vitest-virtual-\w+\/dist|@vitest\/dist/;
|
|
13
|
+
const timedOut = error => timeoutMessage.test(error?.message ?? '');
|
|
14
|
+
|
|
15
|
+
function watchUnhandled() {
|
|
16
|
+
if (globalThis[unhandledKey]) return globalThis[unhandledKey];
|
|
17
|
+
const counter = globalThis[unhandledKey] = { count: 0 };
|
|
18
|
+
process.on('unhandledRejection', () => { counter.count++; });
|
|
19
|
+
process.on('uncaughtException', () => { counter.count++; });
|
|
20
|
+
return counter;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Leaves only the chosen tests runnable. A suite with nothing left to run is skipped, so its hooks stay quiet.
|
|
24
|
+
function choose(suite, selected) {
|
|
25
|
+
let any = false;
|
|
26
|
+
for (const task of suite.tasks) {
|
|
27
|
+
if (task.type !== 'test') any = choose(task, selected) || any;
|
|
28
|
+
else if (runs(task)) {
|
|
29
|
+
if (selected.has(task.id)) any = true;
|
|
30
|
+
else task.mode = 'skip';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!any && runs(suite)) suite.mode = 'skip';
|
|
34
|
+
return any;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `expected` holds the tests the baseline ran for this entry. A test outside it that ran, or one of them that is
|
|
38
|
+
// no longer registered, means the file now holds different tests, which only a fresh run can judge.
|
|
39
|
+
function summarize(suite, summary, expected) {
|
|
40
|
+
for (const error of suite.result?.errors ?? []) summary.errors.push(String(error.message ?? error));
|
|
41
|
+
for (const task of suite.tasks) {
|
|
42
|
+
if (task.type !== 'test') summarize(task, summary, expected);
|
|
43
|
+
else if (expected.has(task.id)) summary.missing--;
|
|
44
|
+
if (task.type === 'test' && (task.result?.state === 'pass' || task.result?.state === 'fail')) {
|
|
45
|
+
if (!expected.has(task.id)) summary.foreign++;
|
|
46
|
+
if (task.result.state === 'pass') summary.passed++;
|
|
47
|
+
else {
|
|
48
|
+
summary.failed.push(task.id);
|
|
49
|
+
summary.timeout ||= (task.result.errors ?? []).some(timedOut);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return summary;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export default class StandardMutationRunner extends VitestTestRunner {
|
|
57
|
+
// Every mutation planned for this test file runs here, in the worker that would otherwise run the file once.
|
|
58
|
+
// A control run follows each mutation. When it differs from the baseline the file stops, and the session
|
|
59
|
+
// gives that mutation and the remaining ones a fresh Vitest run each.
|
|
60
|
+
async onBeforeCollect(paths) {
|
|
61
|
+
const state = this.injectValue('tmtSession');
|
|
62
|
+
if (state?.phase !== 'trials') return;
|
|
63
|
+
// Vitest's own run of these files has nothing left to decide. Its tests are skipped, so a worker that the
|
|
64
|
+
// mutations changed cannot fail it and end the run for the other test files.
|
|
65
|
+
this.cancelRun = true;
|
|
66
|
+
for (const path of paths) {
|
|
67
|
+
const module = JSON.stringify([this.config.name ?? '', path]);
|
|
68
|
+
const plans = state.plans[module] ?? [];
|
|
69
|
+
const emit = event => appendFileSync(state.events, JSON.stringify({ module, ...event }) + '\n');
|
|
70
|
+
if (!plans.length) continue;
|
|
71
|
+
try {
|
|
72
|
+
const { startTests } = await import(state.runnerEntry);
|
|
73
|
+
const inner = this.#engine(startTests, path);
|
|
74
|
+
for (const plan of plans) {
|
|
75
|
+
// Past the deadline the session takes the rest back and decides how many workers it is worth.
|
|
76
|
+
if (state.deadline !== undefined && Date.now() > state.deadline) {
|
|
77
|
+
emit({ yielded: true });
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
const began = Date.now();
|
|
81
|
+
emit({ start: plan.id });
|
|
82
|
+
const expected = plan.tests.length;
|
|
83
|
+
const selected = plan.static ? undefined : plan.tests;
|
|
84
|
+
const active = plan.active ?? plan.id;
|
|
85
|
+
const trial = await inner({ phase: 'trial', active, shift: plan.shift, hitLimit: plan.hitLimit, staticActivation: plan.static }, selected, plan.tests);
|
|
86
|
+
const hits = globalThis.__stryker__.hitCount;
|
|
87
|
+
// For an edit whose tests all passed, the switches each test reached say what the edit changed on the way.
|
|
88
|
+
const reachedIds = counts => Object.entries(counts ?? {}).filter(([, count]) => count).map(([id]) => id);
|
|
89
|
+
const coverage = globalThis.__stryker__.mutantCoverage;
|
|
90
|
+
// A test that ran and reached no switch at all is listed with none.
|
|
91
|
+
const reached = plan.effects && !trial.failed.length ? { ...Object.fromEntries(plan.tests.map(test => [test, []])),
|
|
92
|
+
...Object.fromEntries(Object.entries(coverage?.perTest ?? {}).map(([test, counts]) => [test, reachedIds(counts)])),
|
|
93
|
+
'': reachedIds(coverage?.static) } : undefined;
|
|
94
|
+
// From here on a silent worker is a failed control, not a mutation that never returns.
|
|
95
|
+
emit({ control: plan.id });
|
|
96
|
+
// The same tests without the mutation, directly afterwards. They must behave as in the baseline, or the
|
|
97
|
+
// trial ran in an environment that an earlier run, or the trial itself, had changed.
|
|
98
|
+
const control = await inner({ phase: 'control' }, selected, plan.tests);
|
|
99
|
+
const controlHits = globalThis.__stryker__.mutantCoverage?.static?.[active] ?? 0;
|
|
100
|
+
if (control.unhandled || control.errors.length || control.failed.length || control.foreign || control.missing || control.passed !== expected ||
|
|
101
|
+
controlHits !== plan.hits) {
|
|
102
|
+
emit({ stop: plan.id, reason: 'control' });
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
emit({ id: plan.id, expected, ...trial, hits, elapsed: Date.now() - began, ...(reached ? { reached } : {}) });
|
|
106
|
+
}
|
|
107
|
+
await inner.reset();
|
|
108
|
+
} catch (error) {
|
|
109
|
+
emit({ stop: null, reason: String(error?.message ?? error) });
|
|
110
|
+
} finally {
|
|
111
|
+
delete globalThis[trialKey];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#engine(startTests, path) {
|
|
117
|
+
const unhandled = watchUnhandled();
|
|
118
|
+
const quiet = Object.create(this);
|
|
119
|
+
let selected;
|
|
120
|
+
// The worker reports nothing of these runs to Vitest.
|
|
121
|
+
Object.assign(quiet, {
|
|
122
|
+
config: { ...this.config, bail: 0 },
|
|
123
|
+
onTaskUpdate: async () => {},
|
|
124
|
+
onTestAnnotate: async (_test, annotation) => annotation,
|
|
125
|
+
onTestArtifactRecord: async (_test, artifact) => artifact,
|
|
126
|
+
onCollectStart: file => base.onCollectStart.call(quiet, file),
|
|
127
|
+
onCollected: files => { if (selected) for (const file of files) choose(file, selected); },
|
|
128
|
+
onBeforeCollect: () => {},
|
|
129
|
+
onAfterRunFiles: () => base.onAfterRunFiles.call(quiet),
|
|
130
|
+
onAfterRunTask: test => {
|
|
131
|
+
if (test.result?.state === 'fail') quiet.cancelRun = true;
|
|
132
|
+
return base.onAfterRunTask.call(quiet, test);
|
|
133
|
+
},
|
|
134
|
+
onAfterRunSuite: async suite => {
|
|
135
|
+
if (suite.mode !== 'skip' && 'filepath' in suite) await quiet.snapshotClient.finish(suite.file.filepath);
|
|
136
|
+
quiet.workerState.current = suite.suite || suite.file;
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
const reset = async trial => {
|
|
140
|
+
const namespace = globalThis.__stryker__ ??= {};
|
|
141
|
+
vi.useRealTimers();
|
|
142
|
+
vi.restoreAllMocks();
|
|
143
|
+
vi.unstubAllGlobals();
|
|
144
|
+
vi.unstubAllEnvs();
|
|
145
|
+
vi.resetConfig();
|
|
146
|
+
this.moduleRunner.mocker.reset();
|
|
147
|
+
for (const [id, node] of this.workerState.evaluatedModules.idToModuleMap) {
|
|
148
|
+
if (vitestModule.test(id)) continue;
|
|
149
|
+
node.promise = undefined;
|
|
150
|
+
node.exports = undefined;
|
|
151
|
+
node.evaluated = false;
|
|
152
|
+
node.importers.clear();
|
|
153
|
+
}
|
|
154
|
+
Object.assign(namespace, { activeMutant: undefined, currentTestId: undefined, hitCount: 0, hitLimit: undefined, shift: 0,
|
|
155
|
+
mutantCoverage: { static: {}, perTest: {} } });
|
|
156
|
+
if (trial) globalThis[trialKey] = trial;
|
|
157
|
+
else delete globalThis[trialKey];
|
|
158
|
+
};
|
|
159
|
+
const inner = async (trial, tests, baselineTests) => {
|
|
160
|
+
await reset(trial);
|
|
161
|
+
selected = tests && new Set(tests);
|
|
162
|
+
const expected = new Set(baselineTests);
|
|
163
|
+
quiet.cancelRun = false;
|
|
164
|
+
const before = unhandled.count;
|
|
165
|
+
const files = await startTests([path], quiet);
|
|
166
|
+
await new Promise(resolve => immediate(resolve));
|
|
167
|
+
const summary = { passed: 0, failed: [], errors: [], timeout: false, foreign: 0, missing: expected.size };
|
|
168
|
+
for (const file of files) summarize(file, summary, expected);
|
|
169
|
+
return { ...summary, unhandled: unhandled.count - before };
|
|
170
|
+
};
|
|
171
|
+
inner.reset = () => reset();
|
|
172
|
+
return inner;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
onAfterRunFiles(files) {
|
|
176
|
+
super.onAfterRunFiles(files);
|
|
177
|
+
const state = globalThis[sessionKey];
|
|
178
|
+
if (!state || state.phase === 'trials') return;
|
|
179
|
+
const { mutantCoverage, hitCount, observed } = globalThis.__stryker__;
|
|
180
|
+
appendFileSync(state.destination, JSON.stringify({
|
|
181
|
+
modules: files.map(file => [file.projectName ?? '', file.filepath]),
|
|
182
|
+
coverage: mutantCoverage, hits: hitCount, observed,
|
|
183
|
+
}) + '\n');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import { appendFileSync, closeSync, existsSync, openSync, readFileSync, readSync, realpathSync, rmSync } from 'node:fs';
|
|
2
|
+
import { createRequire, enableCompileCache } from 'node:module';
|
|
3
|
+
import { relative, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { failedTests, snapshotVitestRun, timeVitestRun } from './vitest-reporter.mjs';
|
|
6
|
+
import { changedReach, indexAgreement, indexCoverage, indexReach, reachOfRecords, assessTrial, cheapestFirst, openReasons, planInThread, sampleSettled, settleInThread, sharePlans, unanswered, withoutMutations } from './standard-plan.mjs';
|
|
7
|
+
import { inside } from './vitest.mjs';
|
|
8
|
+
|
|
9
|
+
// Vitest and Vite are loaded on every run. Node keeps their compiled code between runs when it can.
|
|
10
|
+
try { enableCompileCache?.(); } catch { /* The cache is an optimisation only. */ }
|
|
11
|
+
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
12
|
+
const { workspace, config, files, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
|
|
13
|
+
const destination = resolve(temporary, 'coverage.jsonl');
|
|
14
|
+
const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
|
|
15
|
+
const lanes = [];
|
|
16
|
+
let supportsIds;
|
|
17
|
+
let createContext;
|
|
18
|
+
let runnerEntry;
|
|
19
|
+
|
|
20
|
+
const shiftSwitches = new Map(mutants.filter(mutant => mutant.parametric).map(mutant => [`${mutant.parametric.file}:${mutant.parametric.at}`, mutant.id]));
|
|
21
|
+
|
|
22
|
+
// The parent writes the list when the focused analysis has planned its trials, or an empty one when it has none.
|
|
23
|
+
async function extrasFromParent() {
|
|
24
|
+
const path = resolve(temporary, 'extras.json');
|
|
25
|
+
for (let waited = 0; waited < 600_000 && !existsSync(path); waited += 25) await new Promise(resolveWait => setTimeout(resolveWait, 25));
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
28
|
+
} catch {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Reads the lines appended since the last call, so a long trial log is never read twice.
|
|
34
|
+
function follow(path) {
|
|
35
|
+
let position = 0;
|
|
36
|
+
let rest = '';
|
|
37
|
+
return () => {
|
|
38
|
+
if (!existsSync(path)) return [];
|
|
39
|
+
const descriptor = openSync(path, 'r');
|
|
40
|
+
try {
|
|
41
|
+
const chunks = [];
|
|
42
|
+
const buffer = Buffer.alloc(65536);
|
|
43
|
+
for (let read; (read = readSync(descriptor, buffer, 0, buffer.length, position)) > 0; position += read) {
|
|
44
|
+
chunks.push(Buffer.from(buffer.subarray(0, read)));
|
|
45
|
+
}
|
|
46
|
+
const lines = (rest + Buffer.concat(chunks).toString('utf8')).split('\n');
|
|
47
|
+
rest = lines.pop();
|
|
48
|
+
return lines.filter(Boolean).map(line => JSON.parse(line));
|
|
49
|
+
} finally {
|
|
50
|
+
closeSync(descriptor);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// A lane is one Vitest instance with its own worker. The first lane also runs the baseline and the isolated trials.
|
|
56
|
+
async function openLane(index, serial = false) {
|
|
57
|
+
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial };
|
|
58
|
+
lane.context = await createContext(lane);
|
|
59
|
+
lane.specs = await lane.context.globTestSpecifications(files);
|
|
60
|
+
return lane;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Runs a lane's share of the planned mutations inside its worker, one Vitest run per round. A worker that stops
|
|
64
|
+
// answering is replaced, its mutation is a timeout, and the rest continue in the next round.
|
|
65
|
+
async function runInThread(lane, plans, limit, deadline) {
|
|
66
|
+
const events = [];
|
|
67
|
+
let remaining = plans;
|
|
68
|
+
while (Object.keys(remaining).length) {
|
|
69
|
+
rmSync(lane.events, { force: true });
|
|
70
|
+
lane.snapshot = null;
|
|
71
|
+
lane.context.provide('tmtSession', { phase: 'trials', plans: remaining, events: lane.events, runnerEntry, deadline });
|
|
72
|
+
const chosen = lane.specs.filter(spec => remaining[JSON.stringify([spec.project.name, spec.moduleId])]);
|
|
73
|
+
if (!chosen.length) break;
|
|
74
|
+
const read = follow(lane.events);
|
|
75
|
+
const started = new Map();
|
|
76
|
+
const round = [];
|
|
77
|
+
let finished = false;
|
|
78
|
+
let stuck;
|
|
79
|
+
const running = lane.context.runTestSpecifications(chosen).then(() => { finished = true; }, () => { finished = true; });
|
|
80
|
+
while (!stuck) {
|
|
81
|
+
const ended = finished;
|
|
82
|
+
for (const event of read()) {
|
|
83
|
+
round.push(event);
|
|
84
|
+
if (event.start !== undefined) started.set(event.module, { id: event.start, at: Date.now() });
|
|
85
|
+
else if (event.control !== undefined) started.set(event.module, { id: event.control, at: Date.now(), control: true });
|
|
86
|
+
else started.delete(event.module);
|
|
87
|
+
}
|
|
88
|
+
if (ended) break;
|
|
89
|
+
stuck = [...started].find(([, { at }]) => Date.now() - at > limit);
|
|
90
|
+
if (!stuck) await Promise.race([running, new Promise(resolvePoll => setTimeout(resolvePoll, 50))]);
|
|
91
|
+
}
|
|
92
|
+
if (!stuck) {
|
|
93
|
+
const flagged = round.reduce((sum, event) => sum + (event.unhandled ?? 0), 0);
|
|
94
|
+
// An unhandled error nobody attributed to a mutation leaves this round's verdicts without a clean environment.
|
|
95
|
+
// A test file that fails outside its trials loses its own answers, unless it had already stopped: a worker
|
|
96
|
+
// that a mutation changed can fail Vitest's own load of the file afterwards, and its earlier answers each
|
|
97
|
+
// passed their control.
|
|
98
|
+
const stopped = new Set(round.filter(event => event.stop !== undefined).map(event => event.module));
|
|
99
|
+
const distrusted = new Set((lane.failedModules ?? []).filter(module => !stopped.has(module)));
|
|
100
|
+
if (lane.snapshot && lane.unhandled <= flagged) events.push(...round.filter(event => !distrusted.has(event.module)));
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
// A worker that hangs in the control run says nothing about the mutation, which then gets a fresh run.
|
|
104
|
+
events.push(...round, { module: stuck[0], id: stuck[1].id, ...(stuck[1].control ? { stuckControl: true } : { stuck: true }) });
|
|
105
|
+
const answered = new Set(round.filter(event => event.id !== undefined).map(event => JSON.stringify([event.module, event.id])));
|
|
106
|
+
const stopped = new Set(round.filter(event => event.stop !== undefined).map(event => event.module));
|
|
107
|
+
remaining = Object.fromEntries(Object.entries(remaining).filter(([module]) => !stopped.has(module))
|
|
108
|
+
.map(([module, list]) => [module, list.filter(plan => plan.id !== stuck[1].id && !answered.has(JSON.stringify([module, plan.id])))])
|
|
109
|
+
.filter(([, list]) => list.length));
|
|
110
|
+
await Promise.race([lane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
111
|
+
lane.context = await createContext(lane);
|
|
112
|
+
lane.specs = await lane.context.globTestSpecifications(files);
|
|
113
|
+
}
|
|
114
|
+
return events;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function run(specs, state, lane = lanes[0]) {
|
|
118
|
+
lane.snapshot = null;
|
|
119
|
+
rmSync(destination, { force: true });
|
|
120
|
+
lane.context.provide('tmtSession', { ...state, destination });
|
|
121
|
+
const timeout = setTimeout(() => {
|
|
122
|
+
record(state.id === undefined
|
|
123
|
+
? { baseline: { status: 'timeout' } }
|
|
124
|
+
: { id: state.id, status: 'timeout', statusReason: 'Vitest did not finish before its deadline' });
|
|
125
|
+
process.exit(124);
|
|
126
|
+
}, runTimeout);
|
|
127
|
+
try {
|
|
128
|
+
await lane.context.runTestSpecifications(specs);
|
|
129
|
+
if (!lane.snapshot) throw new Error('Vitest did not report a completed run');
|
|
130
|
+
const records = existsSync(destination)
|
|
131
|
+
? readFileSync(destination, 'utf8').trim().split('\n').filter(Boolean).map(row => JSON.parse(row)) : [];
|
|
132
|
+
return { snapshot: lane.snapshot, records };
|
|
133
|
+
} finally {
|
|
134
|
+
clearTimeout(timeout);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function subjectKey(project, file) {
|
|
139
|
+
return JSON.stringify([project, file]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function chooseTests(specs, tests, plan) {
|
|
143
|
+
if (plan.staticActivation || !supportsIds) return specs;
|
|
144
|
+
const byModule = new Map();
|
|
145
|
+
for (const id of plan.covered) {
|
|
146
|
+
const { file, project } = tests.get(id);
|
|
147
|
+
const key = subjectKey(project, file);
|
|
148
|
+
if (!byModule.has(key)) byModule.set(key, []);
|
|
149
|
+
byModule.get(key).push(id);
|
|
150
|
+
}
|
|
151
|
+
return specs.flatMap(spec => {
|
|
152
|
+
const ids = byModule.get(subjectKey(spec.project.name, relative(workspace, spec.moduleId)));
|
|
153
|
+
return ids ? [spec.project.createSpecification(spec.moduleId, { testIds: ids })] : [];
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let exitStatus = 1;
|
|
158
|
+
try {
|
|
159
|
+
const require = createRequire(resolve(workspace, 'package.json'));
|
|
160
|
+
const { createVitest } = await import(pathToFileURL(require.resolve('vitest/node')).href);
|
|
161
|
+
const version = require('vitest/package.json').version;
|
|
162
|
+
if (!version.startsWith('4.')) throw new Error(`The Vitest session requires Vitest 4, found ${version}`);
|
|
163
|
+
supportsIds = !version.startsWith('4.0.');
|
|
164
|
+
runnerEntry = pathToFileURL(realpathSync(createRequire(require.resolve('vitest/package.json')).resolve('@vitest/runner'))).href;
|
|
165
|
+
// Test files run beside each other when the project allows it: each has its own worker, and its coverage and
|
|
166
|
+
// its mutations are kept per file.
|
|
167
|
+
const oneByOne = { maxWorkers: 1, fileParallelism: false };
|
|
168
|
+
const beside = concurrency === 1 || isolatedTrials ? oneByOne : { maxWorkers: concurrency };
|
|
169
|
+
createContext = async lane => {
|
|
170
|
+
const workers = lane.serial ? oneByOne : beside;
|
|
171
|
+
const created = await createVitest('test', {
|
|
172
|
+
root: workspace, config, watch: false, api: false, ui: false, cache: false,
|
|
173
|
+
pool: 'threads', isolate: true, maxConcurrency: 1, ...workers,
|
|
174
|
+
coverage: { enabled: false }, onConsoleLog: () => false, bail: 1,
|
|
175
|
+
reporters: [{ onTestRunEnd(modules, errors, reason) {
|
|
176
|
+
lane.snapshot = snapshotVitestRun(workspace, modules, errors, reason);
|
|
177
|
+
lane.timing = timeVitestRun(modules);
|
|
178
|
+
lane.unhandled = errors.length;
|
|
179
|
+
lane.failedModules = modules.filter(module => module.errors().length).map(module => JSON.stringify([module.project.name, module.moduleId]));
|
|
180
|
+
} }],
|
|
181
|
+
});
|
|
182
|
+
for (const project of created.projects) {
|
|
183
|
+
if (project.config.browser?.enabled || project.config.typecheck?.enabled || project.config.runner) {
|
|
184
|
+
throw new Error('The Vitest session requires the default Vitest runner without browser mode or type checking');
|
|
185
|
+
}
|
|
186
|
+
Object.assign(project.config, { setupFiles: [setup, ...project.config.setupFiles],
|
|
187
|
+
runner: workerRunner, pool: 'threads', isolate: true, maxConcurrency: 1, ...workers, bail: 1 });
|
|
188
|
+
}
|
|
189
|
+
return created;
|
|
190
|
+
};
|
|
191
|
+
lanes.push(await openLane(0));
|
|
192
|
+
const { specs } = lanes[0];
|
|
193
|
+
const discovered = new Set(specs.map(spec => inside(workspace, spec.moduleId)));
|
|
194
|
+
if (files.length && (files.some(file => !discovered.has(file)) || discovered.size !== files.length)) {
|
|
195
|
+
throw new Error('Vitest test selection mismatch');
|
|
196
|
+
}
|
|
197
|
+
const baselineState = { phase: 'baseline' };
|
|
198
|
+
const baselineStarted = Date.now();
|
|
199
|
+
const baseline = await run(specs, baselineState);
|
|
200
|
+
const baselineTiming = lanes[0].timing;
|
|
201
|
+
const baselineTime = Date.now() - baselineStarted;
|
|
202
|
+
const passed = baseline.snapshot.tests.filter(test => test.status === 'passed');
|
|
203
|
+
const tests = new Map(passed.map(test => [test.id, test]));
|
|
204
|
+
const coveredModules = new Set(baseline.records.flatMap(record => record.modules.map(([project, file]) =>
|
|
205
|
+
subjectKey(project, relative(workspace, file)))));
|
|
206
|
+
if (!passed.length || tests.size !== passed.length || passed.some(test => !coveredModules.has(subjectKey(test.project, test.file))) ||
|
|
207
|
+
baseline.snapshot.errors.length || baseline.snapshot.reason !== 'passed') {
|
|
208
|
+
record({ baseline: { status: 'error', errors: baseline.snapshot.errors,
|
|
209
|
+
output: baseline.snapshot.tests.flatMap(test => test.failures).join('\n'),
|
|
210
|
+
failedTests: failedTests(baseline.snapshot) } });
|
|
211
|
+
} else {
|
|
212
|
+
record({ baseline: { status: 'passed', tests: baseline.snapshot.tests.length } });
|
|
213
|
+
const baselineCoverage = indexCoverage(baseline.records, tests);
|
|
214
|
+
const agreement = indexAgreement(baseline.records, tests);
|
|
215
|
+
const reach = indexReach(baseline.records);
|
|
216
|
+
if (agreement.size) {
|
|
217
|
+
const named = ids => [...ids].map(id => tests.get(id)).map(({ id, project, file, name }) => ({ id, project, file, name }));
|
|
218
|
+
record({ observed: Object.fromEntries([...agreement].map(([id, seen]) => [id, { agreeing: seen.agreeing.size,
|
|
219
|
+
differing: named(seen.differing), unsure: named(seen.unsure), outside: seen.outside, outsideUnsure: seen.outsideUnsure, differ: seen.differ, agree: seen.agree,
|
|
220
|
+
unknown: seen.unknown, ...(seen.realCopy ? { realCopy: true } : {}), ...(seen.nonArray ? { nonArray: true } : {}), ...(seen.nonPlain ? { nonPlain: true } : {}) }])) });
|
|
221
|
+
}
|
|
222
|
+
const pending = [];
|
|
223
|
+
for (const mutant of mutants.filter(candidate => !candidate.parametric)) {
|
|
224
|
+
const { id } = mutant;
|
|
225
|
+
const plan = baselineCoverage(id);
|
|
226
|
+
if (!plan.hits) {
|
|
227
|
+
record({ id, status: 'unreached' });
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
// `??` and `||` give the same for null, undefined and every object. Where no test gave the left side a value
|
|
231
|
+
// of a type that has a falsy one, the two are taken for the same code and the edit is not tried.
|
|
232
|
+
const seen = agreement.get(id);
|
|
233
|
+
if (mutant.evidence && seen && !seen.differing.size && !seen.unsure.size && !seen.outside && !seen.outsideUnsure && !seen.typed) {
|
|
234
|
+
record({ id, status: 'ignored', statusReason: 'No test gives the left side a number, a string or a boolean, so both operators are taken to behave alike here' });
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
// `expr[0]` on a plain map or `arguments` object is not a sequence: mutating to `.at(-1)` would only raise
|
|
238
|
+
// a TypeError noise kill. Never skip if any baseline evaluation threw (exception behavior is unverified).
|
|
239
|
+
if (mutant.sequenceIndex && seen && !seen.sequence && seen.nonSequence && !seen.threw && !seen.differing.size && !seen.outside) {
|
|
240
|
+
record({ id, status: 'ignored', statusReason: 'No test passes a sequence (array, string, or typed array) to this index expression' });
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
pending.push({ mutant, plan });
|
|
244
|
+
}
|
|
245
|
+
let fresh;
|
|
246
|
+
const totals = { inWorker: 0, isolated: 0, sampled: 0, mismatches: [], inWorkerUsed: false };
|
|
247
|
+
// Decides a list of reached trials: inside workers where that holds, in fresh runs for the rest.
|
|
248
|
+
// What a surviving edit changed in the code its tests run, with the tests by name.
|
|
249
|
+
const effectsOf = runs => {
|
|
250
|
+
const named = list => list.map(({ test, id }) => ({ id, ...(tests.has(test) ? { test: tests.get(test).name } : {}) }));
|
|
251
|
+
const { now, gone } = changedReach(reach, runs);
|
|
252
|
+
return { now: named(now), gone: named(gone) };
|
|
253
|
+
};
|
|
254
|
+
const decide = async (pending, report) => {
|
|
255
|
+
const plans = isolatedTrials ? null : planInThread(baseline.records, tests, pending, workspace, baselineTiming);
|
|
256
|
+
let settled = new Map();
|
|
257
|
+
let reasons = new Map();
|
|
258
|
+
const effects = new Map();
|
|
259
|
+
// A sample of the workers' verdicts is run again in fresh runs when asked for. A difference is reported and
|
|
260
|
+
// the fresh run's verdict is the one kept.
|
|
261
|
+
const sampled = new Set();
|
|
262
|
+
if (plans) {
|
|
263
|
+
const limit = 15_000 + 3 * baselineTime;
|
|
264
|
+
// The first lane starts alone with a deadline. Most plans end within it. What is left is timed by then, and a
|
|
265
|
+
// further lane, which costs a Vitest instance, its transforms and an environment per test file, opens for
|
|
266
|
+
// every six seconds of measured work in the longest test file.
|
|
267
|
+
const inLanes = async step => {
|
|
268
|
+
const events = await runInThread(lanes[0], step, limit, Date.now() + 2_000);
|
|
269
|
+
// Each further round takes what is left: entries the deadline cut off, and test files that start again
|
|
270
|
+
// in a new worker after a control run differed.
|
|
271
|
+
for (let round = 0; round < 12; round++) {
|
|
272
|
+
const left = unanswered(step, events, 8);
|
|
273
|
+
const entries = Object.values(left).flat();
|
|
274
|
+
if (!entries.length) break;
|
|
275
|
+
const timed = events.filter(event => event.elapsed !== undefined);
|
|
276
|
+
const planned = new Map(Object.entries(step).flatMap(([module, list]) => list.map(plan => [JSON.stringify([module, plan.id]), plan])));
|
|
277
|
+
const paid = timed.reduce((sum, event) => sum + planned.get(JSON.stringify([event.module, event.id])).cost + 1, 0);
|
|
278
|
+
// Before anything was timed, an entry is taken as its baseline cost twice: a trial and a control run.
|
|
279
|
+
const rate = timed.length ? timed.reduce((sum, event) => sum + event.elapsed, 0) / paid : 2;
|
|
280
|
+
// Test files already run beside each other inside a lane. A further lane only helps the longest file.
|
|
281
|
+
const work = Math.max(...Object.values(left).map(list => list.reduce((sum, plan) => sum + (plan.cost + 1) * rate, 0)));
|
|
282
|
+
const wanted = Math.max(1, Math.min(concurrency, Math.ceil(work / 6_000)));
|
|
283
|
+
const opened = await Promise.all(Array.from({ length: Math.max(0, wanted - lanes.length) },
|
|
284
|
+
(_, index) => openLane(lanes.length + index).catch(() => null)));
|
|
285
|
+
lanes.push(...opened.filter(Boolean));
|
|
286
|
+
const shares = sharePlans(left, Math.min(wanted, lanes.length));
|
|
287
|
+
const answered = (await Promise.all(shares.map((share, index) => runInThread(lanes[index], share, limit)))).flat();
|
|
288
|
+
if (!answered.some(event => event.id !== undefined || event.stop !== undefined)) break;
|
|
289
|
+
events.push(...answered);
|
|
290
|
+
}
|
|
291
|
+
return events;
|
|
292
|
+
};
|
|
293
|
+
const { first, rest } = cheapestFirst(plans);
|
|
294
|
+
const firstEvents = await inLanes(first);
|
|
295
|
+
const killed = new Set([...settleInThread(first, firstEvents, tests)].filter(([, verdict]) => verdict.status === 'killed').map(([id]) => id));
|
|
296
|
+
const restEvents = await inLanes(withoutMutations(rest, killed));
|
|
297
|
+
// A mutation killed in the first step is settled by that step alone. The others need every test file's answer.
|
|
298
|
+
const decisive = Object.fromEntries(Object.entries(plans).map(([module, list]) =>
|
|
299
|
+
[module, list.filter(plan => !killed.has(plan.id) || first[module]?.includes(plan))]).filter(([, list]) => list.length));
|
|
300
|
+
settled = settleInThread(decisive, [...firstEvents, ...restEvents], tests);
|
|
301
|
+
reasons = openReasons(decisive, [...firstEvents, ...restEvents]);
|
|
302
|
+
// What each surviving edit of the targeted rules changed in the code its tests run.
|
|
303
|
+
const runs = new Map();
|
|
304
|
+
for (const event of [...firstEvents, ...restEvents]) {
|
|
305
|
+
if (!event.reached || settled.get(event.id)?.status !== 'survived') continue;
|
|
306
|
+
if (!runs.has(event.id)) runs.set(event.id, []);
|
|
307
|
+
runs.get(event.id).push({ module: event.module, reached: event.reached });
|
|
308
|
+
}
|
|
309
|
+
for (const [id, list] of runs) effects.set(id, effectsOf(list));
|
|
310
|
+
}
|
|
311
|
+
for (const id of sampleSettled(pending.map(({ mutant }) => mutant.id).filter(id => settled.has(id)), Math.max(0, verifyTrials - totals.sampled))) sampled.add(id);
|
|
312
|
+
for (const { mutant, plan } of pending) {
|
|
313
|
+
const { id } = mutant;
|
|
314
|
+
const expected = plan.staticActivation || !supportsIds ? tests : new Map([...plan.covered].map(id => [id, tests.get(id)]));
|
|
315
|
+
if (settled.has(id) && !sampled.has(id)) {
|
|
316
|
+
report(mutant, { ...settled.get(id), ...(effects.has(id) ? { effects: effects.get(id) } : {}) });
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (!sampled.has(id)) totals.isolated++;
|
|
320
|
+
// A fresh run stops at its first failing test. Beside each other, test files would be cut off mid-run,
|
|
321
|
+
// so these runs take the files one by one.
|
|
322
|
+
fresh ??= beside === oneByOne ? lanes[0] : await openLane('fresh', true).then(lane => (lanes.push(lane), lane));
|
|
323
|
+
const selected = chooseTests(fresh.specs, tests, plan);
|
|
324
|
+
const hitLimit = plan.hits * 100;
|
|
325
|
+
const trial = await run(selected, { id, phase: 'trial', active: mutant.active ?? id, shift: mutant.shift, hitLimit,
|
|
326
|
+
staticActivation: plan.staticActivation }, fresh);
|
|
327
|
+
const assessed = assessTrial(trial, expected, hitLimit);
|
|
328
|
+
if (sampled.has(id) && assessed.status !== settled.get(id).status) totals.mismatches.push({ id, worker: settled.get(id).status, fresh: assessed.status });
|
|
329
|
+
const changed = mutant.effects && assessed.status === 'survived' ? { effects: effectsOf(reachOfRecords(trial.records, expected.keys())) } : {};
|
|
330
|
+
report(mutant, { ...assessed, ...changed, ...(reasons.has(id) ? { fallback: reasons.get(id) } : {}) });
|
|
331
|
+
}
|
|
332
|
+
totals.inWorker += settled.size;
|
|
333
|
+
totals.sampled += sampled.size;
|
|
334
|
+
totals.inWorkerUsed ||= plans !== null;
|
|
335
|
+
};
|
|
336
|
+
await decide(pending, (mutant, result) => record({ id: mutant.id, ...result }));
|
|
337
|
+
if (awaitsExtras) {
|
|
338
|
+
// Threshold edits of the focused analysis: each names a comparison and how far its right side moves.
|
|
339
|
+
const extras = [];
|
|
340
|
+
for (const [index, extra] of (await extrasFromParent()).entries()) {
|
|
341
|
+
const active = shiftSwitches.get(`${extra.file}:${extra.at}`);
|
|
342
|
+
const plan = active === undefined ? null : baselineCoverage(active);
|
|
343
|
+
if (!plan) record({ extra: index, status: 'unsupported' });
|
|
344
|
+
else if (!plan.hits) record({ extra: index, status: 'unreached' });
|
|
345
|
+
else extras.push({ mutant: { id: `extra:${index}`, index, active, shift: extra.shift }, plan });
|
|
346
|
+
}
|
|
347
|
+
await decide(extras, (mutant, result) => record({ extra: mutant.index, ...result }));
|
|
348
|
+
}
|
|
349
|
+
record({ trials: { workers: totals.inWorkerUsed ? lanes.filter(lane => !lane.serial).length : 1, inWorker: totals.inWorker,
|
|
350
|
+
isolated: totals.isolated,
|
|
351
|
+
...(verifyTrials ? { verified: { sampled: totals.sampled, mismatches: totals.mismatches } } : {}) } });
|
|
352
|
+
record({ complete: true });
|
|
353
|
+
}
|
|
354
|
+
exitStatus = 0;
|
|
355
|
+
} catch (error) {
|
|
356
|
+
record({ error: error.message });
|
|
357
|
+
} finally {
|
|
358
|
+
await Promise.race([Promise.all(lanes.map(lane => lane.context.close())), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
359
|
+
// Vitest sets the exit code of a run with failures, and a worker caught in an endless loop outlives its
|
|
360
|
+
// Vitest instance, so the session ends itself with its own status.
|
|
361
|
+
process.exit(exitStatus);
|
|
362
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { afterEach, beforeAll, beforeEach, inject } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const session = inject('tmtSession');
|
|
4
|
+
// The in-thread engine replaces the injected state for each control and trial it starts.
|
|
5
|
+
const state = globalThis[Symbol.for('targeted-mutation-ts/trial')] ?? session;
|
|
6
|
+
globalThis[Symbol.for('targeted-mutation-ts/session')] = session;
|
|
7
|
+
const { active, hitLimit, phase, staticActivation, shift } = state;
|
|
8
|
+
const namespace = globalThis.__stryker__ ??= {};
|
|
9
|
+
namespace.activeMutant = staticActivation ? active : undefined;
|
|
10
|
+
namespace.hitCount = 0;
|
|
11
|
+
namespace.hitLimit = hitLimit;
|
|
12
|
+
namespace.shift = shift ?? 0;
|
|
13
|
+
|
|
14
|
+
// The baseline needs to know which test reaches which switch. A trial notes the same, so that what a surviving
|
|
15
|
+
// edit changes in the code a test runs can be told per test. A control run counts all its hits together.
|
|
16
|
+
if (phase === 'baseline' || phase === 'trial') {
|
|
17
|
+
beforeEach(({ task }) => { namespace.currentTestId = task.id; });
|
|
18
|
+
afterEach(() => { namespace.currentTestId = undefined; });
|
|
19
|
+
}
|
|
20
|
+
if (phase === 'trial' && !staticActivation) beforeAll(() => { namespace.activeMutant = active; });
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// What a surviving edit of the targeted rules says about the tests. The recording run noted, per test, whether
|
|
2
|
+
// the edit would have given the same value as the original after evaluating the same operands.
|
|
3
|
+
// No test in which it would not: the input that tells the two apart is missing. Otherwise the tests that had
|
|
4
|
+
// such an input passed all the same, so an assertion is missing.
|
|
5
|
+
const clip = text => {
|
|
6
|
+
const line = String(text).replace(/\s+/g, ' ').trim();
|
|
7
|
+
return line.length > 60 ? line.slice(0, 57) + '...' : line;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const rules = { arithmetic: 'arithmetic-swap/v1', extreme: 'extreme-swap/v1', rounding: 'rounding-swap/v1', ends: 'sequence-end/v1',
|
|
11
|
+
order: 'sort-order/v1', awaited: 'await-dropped/v1', copy: 'copy-dropped/v1',
|
|
12
|
+
spreadDrop: 'spread-property-drop/v1', prefixSubstring: 'prefix-to-substring/v1', replaceMultiplicity: 'replace-multiplicity/v1',
|
|
13
|
+
clampBound: 'clamp-bound/v1', literalSetPrune: 'literal-set-prune/v1', mergePrecedence: 'merge-precedence/v1',
|
|
14
|
+
quantifierSwap: 'quantifier-swap/v1', regexAnchor: 'regex-anchor-slack/v1', cleanupDropped: 'cleanup-dropped/v1' };
|
|
15
|
+
// What to assert where no recording can say which input is missing.
|
|
16
|
+
const advice = {
|
|
17
|
+
[rules.awaited]: 'the tests pass when this call is not waited for: assert on what it has done before what follows it goes on',
|
|
18
|
+
[rules.cleanupDropped]: 'the tests pass when this finally cleanup call is skipped: assert that the resource or state is cleaned up after the try block finishes or throws',
|
|
19
|
+
[rules.copy]: 'the tests pass when this copy is the original itself: assert that the original is unchanged after the copy is changed, or that the two are not the same object',
|
|
20
|
+
iterableCopy: 'the tests pass when this iterable is not converted to an array: assert that the result is an array (Array.isArray(...)) or use array operations on it',
|
|
21
|
+
spreadCoercion: 'the tests pass when this object spread is replaced by its source directly: assert on the resulting plain object properties, prototype, or nullish handling',
|
|
22
|
+
};
|
|
23
|
+
// For which numbers two ways of rounding differ.
|
|
24
|
+
const roundingDiffers = { 'floor trunc': 'negative and not a whole number (-0.5)', 'ceil trunc': 'positive and not a whole number (0.5)',
|
|
25
|
+
'floor round': 'a number that rounds up (1.5, -1.5)', 'ceil round': 'a number that rounds down (1.4, -1.6)',
|
|
26
|
+
'round trunc': 'a number that rounds away from zero (1.5, -1.6)', 'ceil floor': 'not a whole number (0.5)' };
|
|
27
|
+
|
|
28
|
+
function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, key, boundKind, pruned, argName }, expression, rule, replacement) {
|
|
29
|
+
const side = '`' + clip(left) + '`';
|
|
30
|
+
if (rule === rules.spreadDrop) return `a test in which \`${clip(left)}.${key}\` is missing or differs from its updated value`;
|
|
31
|
+
if (rule === rules.prefixSubstring) {
|
|
32
|
+
return `a test in which ${side} contains the ${operator === 'startsWith' ? 'prefix somewhere other than the start' : 'suffix somewhere other than the end'}`;
|
|
33
|
+
}
|
|
34
|
+
if (rule === rules.replaceMultiplicity) return `a test in which ${side} contains the searched text more than once`;
|
|
35
|
+
if (rule === rules.clampBound) return `a test in which the value exceeds the ${boundKind === 'upper' ? 'upper' : 'lower'} clamp bound of \`${clip(expression)}\``;
|
|
36
|
+
if (rule === rules.literalSetPrune) return `a test in which \`${clip(argName)}\` is ${pruned}`;
|
|
37
|
+
if (rule === rules.mergePrecedence) return `a test in which ${side} and \`${clip(rightExpr)}\` share a key with different values`;
|
|
38
|
+
if (rule === rules.quantifierSwap) return `a test in which ${side} is empty or has elements where the predicate gives both true and false`;
|
|
39
|
+
if (rule === rules.regexAnchor) return `a test in which \`${clip(argName)}\` matches without the ${form === 'dropStart' ? 'leading `^`' : 'trailing `$`'} anchor`;
|
|
40
|
+
if (rule === rules.arithmetic) return `a test in which \`${clip(expression)}\` is not \`${clip(replacement)}\``;
|
|
41
|
+
if (rule === rules.order) return `a test in which ${side} holds numbers whose order as text is not their order as numbers (9 and 10)`;
|
|
42
|
+
if (rule === rules.extreme) return `a test in which the two arguments of \`${clip(expression)}\` differ`;
|
|
43
|
+
if (rule === rules.rounding) return `a test in which ${side} is ${roundingDiffers[[operator, form].sort().join(' ')]}`;
|
|
44
|
+
if (rule === rules.ends) {
|
|
45
|
+
return operator.startsWith('find') ? `a test in which ${side} has two or more elements`
|
|
46
|
+
: operator.endsWith('ndexOf') ? `a test in which ${side} holds the searched value more than once`
|
|
47
|
+
: `a test in which ${side} has two or more elements and the first is not the last`;
|
|
48
|
+
}
|
|
49
|
+
if (form === 'true' || form === 'false') return `a test in which \`${clip(expression)}\` is ${form === 'true' ? 'false' : 'true'}`;
|
|
50
|
+
if (form === 'loose' || form === 'strict' || form === 'other') return `a test in which \`${clip(subject)}\` is ${differsFor}`;
|
|
51
|
+
if (form === 'or' || form === 'nullish') return `a test in which ${side} is 0, 0n, '', false or NaN${pureRight ? ' and not the right side\'s value' : ''}`;
|
|
52
|
+
const takesRight = { '&&': 'truthy', '||': 'falsy', '??': 'null or undefined' }[operator];
|
|
53
|
+
if (form === 'left') return `a test in which ${side} is ${{ '&&': 'falsy', '||': 'truthy', '??': 'neither null nor undefined' }[operator]}`;
|
|
54
|
+
const kept = { '&&': 'true', '||': 'false', '??': 'undefined' }[operator];
|
|
55
|
+
const right = boolean ? (operator === '&&' ? 'falsy' : 'truthy') : `not ${kept}`;
|
|
56
|
+
return `a test in which ${side} is ${takesRight} and the right side is ${right}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function targetedGap(mutant, seen) {
|
|
60
|
+
if (!mutant.targeted || mutant.status !== 'survived' || (!seen && !advice[mutant.mutatorName])) return null;
|
|
61
|
+
const common = {
|
|
62
|
+
site: mutant.id, location: mutant.location, rule: mutant.mutatorName, expression: mutant.original,
|
|
63
|
+
mutations: [{ rule: mutant.mutatorName, edit: mutant.edit, replacement: mutant.replacement, evidence: mutant.evidence,
|
|
64
|
+
...(mutant.source ? { source: mutant.source } : {}) }],
|
|
65
|
+
};
|
|
66
|
+
if (mutant.mutatorName === rules.copy) {
|
|
67
|
+
const note = seen && !seen.realCopy && seen.nonArray ? advice.iterableCopy
|
|
68
|
+
: seen && !seen.realCopy && seen.nonPlain ? advice.spreadCoercion
|
|
69
|
+
: advice[rules.copy];
|
|
70
|
+
return { kind: 'ASSERTION GAP', ...common, advice: note };
|
|
71
|
+
}
|
|
72
|
+
if (!seen) return { kind: 'ASSERTION GAP', ...common, advice: advice[mutant.mutatorName] };
|
|
73
|
+
if (seen.differing.length || seen.outside) {
|
|
74
|
+
return { kind: 'ASSERTION GAP', ...common, tests: seen.differing, ...(seen.outside ? { outsideTests: true } : {}),
|
|
75
|
+
...(seen.differ ? { example: { operands: seen.differ } } : {}) };
|
|
76
|
+
}
|
|
77
|
+
const missing = missingInput(mutant.targeted, mutant.original, mutant.mutatorName, mutant.replacement);
|
|
78
|
+
// Where the recording could not work the edit out (a search callback, an object among the operands), the
|
|
79
|
+
// tests may have the input already and only lack the assertion.
|
|
80
|
+
if (seen.unsure?.length || seen.outsideUnsure) {
|
|
81
|
+
return { kind: 'INPUT GAP', ...common, missing, uncertain: true, tests: seen.unsure ?? [], ...(seen.outsideUnsure ? { outsideTests: true } : {}),
|
|
82
|
+
...(seen.unknown ? { example: { operands: seen.unknown } } : {}) };
|
|
83
|
+
}
|
|
84
|
+
return { kind: 'INPUT GAP', ...common, reachedBy: seen.agreeing, missing, ...(seen.agree ? { observed: { operands: seen.agree } } : {}) };
|
|
85
|
+
}
|