supercov 4.28.0 → 4.29.1

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.
Files changed (33) hide show
  1. package/README.md +43 -16
  2. package/docs/cli.md +338 -2
  3. package/docs/getting-started.md +18 -0
  4. package/docs/mutation.md +588 -0
  5. package/docs/supported-suites.md +109 -60
  6. package/package.json +11 -10
  7. package/runtime/javascript/atomic.mjs +6 -2
  8. package/runtime/javascript/ava.mjs +12 -0
  9. package/runtime/javascript/bunTest.mjs +17 -0
  10. package/runtime/javascript/jest.cjs +67 -0
  11. package/runtime/javascript/jest.config.mjs +46 -6
  12. package/runtime/javascript/jestReporter.mjs +5 -2
  13. package/runtime/javascript/mocha.mjs +79 -5
  14. package/runtime/javascript/nodeTest.mjs +28 -0
  15. package/runtime/javascript/playwright.mjs +33 -0
  16. package/runtime/javascript/playwrightStrong.mjs +477 -0
  17. package/runtime/javascript/playwrightStrongReporter.mjs +377 -0
  18. package/runtime/javascript/resolve-loader.mjs +4 -1
  19. package/runtime/javascript/runnerEntry.mjs +62 -0
  20. package/runtime/javascript/runtime.mjs +752 -13
  21. package/runtime/javascript/snapshots.mjs +16 -1
  22. package/runtime/javascript/strongJestHost.mjs +103 -0
  23. package/runtime/javascript/strongJob.mjs +78 -0
  24. package/runtime/javascript/strongJobs.mjs +809 -0
  25. package/runtime/javascript/strongMochaHost.mjs +166 -0
  26. package/runtime/javascript/strongWasmOut.cjs +96 -0
  27. package/runtime/javascript/tap.mjs +43 -1
  28. package/runtime/javascript/transport.mjs +5 -0
  29. package/runtime/javascript/vitest.mjs +74 -2
  30. package/runtime/javascript/vitestBrowser.mjs +34 -2
  31. package/runtime/javascript/vitestStrong.mjs +234 -0
  32. package/runtime/javascript/vitestStrongReporter.mjs +2268 -0
  33. package/runtime/javascript/vitestStrongSpawner.mjs +248 -0
@@ -0,0 +1,234 @@
1
+ // Strong mutation's setup file for Vitest (docs/design/strong-mutation.md).
2
+ //
3
+ // The strong reporter (vitestStrongReporter.mjs) runs the suite in stages. A
4
+ // stage can run one test file many times, each copy with its own mutant; the
5
+ // copies cannot be told apart by Vitest's own results (they share the file's
6
+ // path), so each copy claims its assignment from the stage's directory as it
7
+ // starts, and reports its tests' outcomes there itself.
8
+ //
9
+ // This file runs in the test file's isolated module graph before the test
10
+ // file's imports: it switches the copy's mutant on, so a mutant evaluated
11
+ // while a module loads is in place too, and skips every test the assignment
12
+ // did not choose. After the copy's first chosen test fails, the rest are
13
+ // skipped: the mutant is killed.
14
+ import { appendFileSync, readFileSync, existsSync } from "node:fs";
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { isMainThread } from "node:worker_threads";
17
+ import { afterAll, afterEach, beforeAll, beforeEach, inject, vi } from "vitest";
18
+
19
+ /** The test file's path from the project root, as the plan names it. */
20
+ function thisFile(root) {
21
+ const state = globalThis.__vitest_worker__;
22
+ const filepath = state?.filepath ?? state?.current?.file?.filepath;
23
+ if (!filepath)
24
+ return undefined;
25
+ return filepath.startsWith(root)
26
+ ? filepath.slice(root.length).replace(/^[\\/]+/, "").split("\\").join("/")
27
+ : filepath;
28
+ }
29
+
30
+ /**
31
+ * This copy's assignment: the next of its file's. Each copy appends a token
32
+ * of its own to the file's claims (an append is one atomic write), and the
33
+ * line it landed on is the assignment it takes.
34
+ */
35
+ function claim() {
36
+ let provided;
37
+ try {
38
+ provided = inject("supercovStrong");
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ if (!provided?.stage)
44
+ return undefined;
45
+ const file = thisFile(provided.root);
46
+ if (!file)
47
+ return undefined;
48
+ const key = createHash("sha256").update(file).digest("hex").slice(0, 24);
49
+ const directory = `${provided.stage}/${key}`;
50
+ // Where Supercov's spawner starts the workers, the strong reporter told
51
+ // this copy its assignment already.
52
+ let index = provided.claim;
53
+ if (index === undefined) {
54
+ const token = randomBytes(12).toString("hex");
55
+ try {
56
+ appendFileSync(`${directory}/claims`, `${token}\n`);
57
+ index = readFileSync(`${directory}/claims`, "utf8").split("\n").indexOf(token);
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ // A copy beyond its file's assignments has nothing to run.
64
+ if (index < 0 || !existsSync(`${directory}/${index}.json`))
65
+ return { surplus: true };
66
+ return {
67
+ ...JSON.parse(readFileSync(`${directory}/${index}.json`, "utf8")),
68
+ // The mutant got its verdict from another copy meanwhile.
69
+ skip: existsSync(`${directory}/${index}.skip`),
70
+ out: `${directory}/${index}.out`,
71
+ claimed: { log: `${provided.stage}/claimed`, line: `${key}/${index}` },
72
+ };
73
+ }
74
+
75
+ const claimed = claim();
76
+ // A copy with nothing to run -- beyond its file's assignments, or one whose
77
+ // mutant another copy has decided -- ends here, before its test file loads.
78
+ if (claimed?.surplus || claimed?.skip) {
79
+ if (claimed.skip) {
80
+ const at = Date.now();
81
+ appendFileSync(claimed.out, `${JSON.stringify({ claimed: true, at, up: Math.round(performance.now()), pid: isMainThread ? process.pid : undefined, skipped: true })}\n${JSON.stringify({ done: true, at })}\n`);
82
+ try {
83
+ appendFileSync(claimed.claimed.log, `${claimed.claimed.line}\n`);
84
+ }
85
+ catch {
86
+ // The stage is over.
87
+ }
88
+ }
89
+ throw new Error("supercov: this copy has nothing to run");
90
+ }
91
+ // Loaded only by a copy that runs.
92
+ const runtime = globalThis.__SUPERCOV_DIRECT_RUNTIME__ ?? (await import("./runtime.mjs"));
93
+ const assignment = claimed;
94
+ const chosen = new Set(assignment?.tests ?? []);
95
+ let killed = false;
96
+ // Set once the active mutant was evaluated past the hit limit.
97
+ let limitReached = false;
98
+ let limitReported = false;
99
+ // The clock as it was when this file loaded: a test file may fake Date.
100
+ const realNow = Date.now.bind(Date);
101
+ // How often the copy's mutant has been evaluated so far: a failure before its
102
+ // first evaluation is the program's without the mutant, not the mutant's.
103
+ const hitsNow = () => assignment?.mutant ? runtime.mutantHitCount?.() : undefined;
104
+ const report = (record) => {
105
+ if (assignment)
106
+ appendFileSync(assignment.out, `${JSON.stringify(record)}\n`);
107
+ };
108
+
109
+ // An error no test catches -- work a test left running, a rejected promise
110
+ // nobody awaited -- fails the run as Vitest reports it, and is the mutant's
111
+ // doing where the same file without a mutant raised none. A mutant that
112
+ // made a loop endless outside any test throws its timeout error there.
113
+ function outsideTests(error) {
114
+ if (!assignment)
115
+ return;
116
+ const timeout = runtime.isMutantTimeout?.(error) ||
117
+ /SUPERCOV_MUTANT_TIMEOUT|MutantTimeout/.test(`${error?.name} ${error?.code} ${error?.message}`);
118
+ report({ outside: true, timeout, message: `${error?.message ?? error}`.slice(0, 300), hits: hitsNow() });
119
+ }
120
+ if (assignment) {
121
+ process.on("uncaughtException", outsideTests);
122
+ process.on("unhandledRejection", outsideTests);
123
+ // A worker process of its own (not a thread of Vitest's) can be
124
+ // stopped alone, should it stop reporting.
125
+ // `up`: how long the worker had been starting (its process, Vitest, the
126
+ // environment) before this copy claimed.
127
+ report({ claimed: true, at: realNow(), up: Math.round(performance.now()), pid: isMainThread ? process.pid : undefined });
128
+ try {
129
+ appendFileSync(assignment.claimed.log, `${assignment.claimed.line}\n`);
130
+ }
131
+ catch {
132
+ // The stage is over.
133
+ }
134
+ // The copy's own test limit, read as the test file's tests are collected.
135
+ if (assignment.testTimeout)
136
+ vi.setConfig({ testTimeout: assignment.testTimeout });
137
+ if (assignment.mutant) {
138
+ runtime.setMutantHitLimit?.(assignment.hitLimit ?? 1_000_000);
139
+ runtime.setActiveMutant(assignment.mutant.file, assignment.mutant.index);
140
+ // Code under test may catch the hit limit's error and carry on (a
141
+ // stream that turns an error into a frame): the limit having been
142
+ // reached is the mutant's timeout all the same.
143
+ const strong = globalThis[Symbol.for("supercov.strongMutation")];
144
+ if (strong)
145
+ strong.onTimeout = () => {
146
+ limitReached = true;
147
+ };
148
+ }
149
+ }
150
+
151
+ // When the file's tests start: what came before was loading it.
152
+ beforeAll(() => {
153
+ if (assignment)
154
+ report({ started: true, at: realNow() });
155
+ });
156
+
157
+ beforeEach((context) => {
158
+ if (!assignment) {
159
+ // Outside a strong pass's stage.
160
+ context.skip();
161
+ return;
162
+ }
163
+ const id = `vitest:${context.task.id}`;
164
+ if (killed || (!assignment.wholeFile && !chosen.has(id)))
165
+ context.skip();
166
+ });
167
+
168
+ afterEach((context) => {
169
+ if (!assignment)
170
+ return;
171
+ const result = context.task.result;
172
+ if (result?.state === "skip")
173
+ return;
174
+ // `state` is not final before the hooks after a test are done; an error
175
+ // already recorded is what failed it.
176
+ const errors = result?.errors ?? [];
177
+ const failed = result?.state === "fail" || errors.length > 0;
178
+ const limitNow = limitReached && !limitReported;
179
+ if (limitNow)
180
+ limitReported = true;
181
+ const timeout = limitNow || errors.some((error) => runtime.isMutantTimeout?.(error) ||
182
+ /SUPERCOV_MUTANT_TIMEOUT|MutantTimeout/.test(`${error?.name} ${error?.code} ${error?.message}`) ||
183
+ /Test timed out in \d+ms/.test(`${error?.message}`));
184
+ report({ test: `vitest:${context.task.id}`, failed: failed || limitNow, timeout, ms: result?.duration, hits: hitsNow() });
185
+ // A test that fails without the mutant too (its file's baseline says)
186
+ // decides nothing: the copy goes on past it.
187
+ const failsWithout = !limitNow && assignment.continueAfter?.includes(`vitest:${context.task.id}`);
188
+ if ((failed || limitNow) && assignment.mutant && !failsWithout)
189
+ killed = true;
190
+ });
191
+
192
+ // Work a mutant left going after the tests (a loop that never ends between
193
+ // awaits, timers that re-arm) keeps evaluating the mutant: Vitest would have
194
+ // to stop the worker by force, and a run waiting on it never ends. A short
195
+ // look after the tests tells that from code that runs now and then. Most
196
+ // copies leave nothing evaluating the mutant: a brief probe that sees no
197
+ // steady evaluation ends the look there, so only a copy whose mutant is
198
+ // still being evaluated over and over waits the whole window.
199
+ const LEFT_RUNNING_PROBE_MS = 25;
200
+ const LEFT_RUNNING_WINDOW_MS = 300;
201
+ const LEFT_RUNNING_EVALUATIONS = 100;
202
+ // Half the rate the window looks for: a few late evaluations (a promise the
203
+ // tests left settling) end the look; work that keeps going does not.
204
+ const LEFT_RUNNING_PROBE_EVALUATIONS = Math.ceil(LEFT_RUNNING_EVALUATIONS * LEFT_RUNNING_PROBE_MS / LEFT_RUNNING_WINDOW_MS / 2);
205
+ // Timers as they were when this file loaded: a test file that fakes the
206
+ // clock (vi.useFakeTimers) and leaves it faked must not hold the look up.
207
+ const realSetTimeout = globalThis.setTimeout;
208
+ const pause = (ms) => new Promise((resolve) => realSetTimeout(resolve, ms));
209
+ afterAll(async () => {
210
+ if (!assignment)
211
+ return;
212
+ if (assignment.mutant && runtime.mutantHitCount) {
213
+ const before = runtime.mutantHitCount();
214
+ await pause(LEFT_RUNNING_PROBE_MS);
215
+ if (runtime.mutantHitCount() - before >= LEFT_RUNNING_PROBE_EVALUATIONS)
216
+ await pause(LEFT_RUNNING_WINDOW_MS - LEFT_RUNNING_PROBE_MS);
217
+ const evaluations = runtime.mutantHitCount() - before;
218
+ if (limitReached && !limitReported) {
219
+ limitReported = true;
220
+ report({ outside: true, timeout: true, message: "the mutant was evaluated past the hit limit outside any test" });
221
+ }
222
+ if (evaluations > LEFT_RUNNING_EVALUATIONS)
223
+ report({
224
+ outside: true,
225
+ timeout: true,
226
+ message: `the mutant was evaluated ${evaluations} times in ${LEFT_RUNNING_WINDOW_MS} ms after the tests ended`,
227
+ });
228
+ }
229
+ // A worker process whose channel to Vitest closed (the mutant
230
+ // disconnected it) cannot tell Vitest its file ended: it did not.
231
+ report({ done: true, at: realNow(), channelLost: Boolean(process.send) && !process.connected && isMainThread });
232
+ if (assignment.mutant)
233
+ runtime.clearActiveMutant();
234
+ });