supercov 4.28.0 → 4.29.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.
Files changed (32) hide show
  1. package/README.md +43 -16
  2. package/docs/cli.md +322 -2
  3. package/docs/getting-started.md +18 -0
  4. package/docs/mutation.md +539 -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/runnerEntry.mjs +62 -0
  19. package/runtime/javascript/runtime.mjs +752 -13
  20. package/runtime/javascript/snapshots.mjs +16 -1
  21. package/runtime/javascript/strongJestHost.mjs +103 -0
  22. package/runtime/javascript/strongJob.mjs +78 -0
  23. package/runtime/javascript/strongJobs.mjs +809 -0
  24. package/runtime/javascript/strongMochaHost.mjs +166 -0
  25. package/runtime/javascript/strongWasmOut.cjs +96 -0
  26. package/runtime/javascript/tap.mjs +43 -1
  27. package/runtime/javascript/transport.mjs +5 -0
  28. package/runtime/javascript/vitest.mjs +74 -2
  29. package/runtime/javascript/vitestBrowser.mjs +34 -2
  30. package/runtime/javascript/vitestStrong.mjs +234 -0
  31. package/runtime/javascript/vitestStrongReporter.mjs +2268 -0
  32. package/runtime/javascript/vitestStrongSpawner.mjs +248 -0
@@ -0,0 +1,477 @@
1
+ // Strong mutation for Playwright (docs/design/strong-mutation.md, browser
2
+ // tests against a server).
3
+ //
4
+ // One Playwright invocation runs the plan. The generated config repeats every
5
+ // test (`repeatEach`) as often as the busiest test file has rows: a file's row
6
+ // k is what every test of the file does in its k-th repetition -- run with
7
+ // one mutant, run with none (the baseline, row 0, and canaries), or skip. A
8
+ // test's repetition finds its row from its file and `repeatEachIndex`, so
9
+ // nothing is claimed at run time and no two repetitions can take the same
10
+ // work. The attempt's mutant goes into its scope, which reaches the app's
11
+ // server with every request (header, cookies, child processes) and the page
12
+ // through an init script, so the workers of one run each test their own
13
+ // mutant against one server.
14
+ //
15
+ // A mutant the server must start with (its code ran in work no request named,
16
+ // or is a server module's top level, or ran for a request that named no test)
17
+ // gets no row: it is run alone afterwards, in an invocation of its own with
18
+ // SUPERCOV_ACTIVE_MUTANT set, which the engine starts for each `restart`
19
+ // record the reporter writes (javascript_run.rs). So do a test that ran out
20
+ // of time (again, with twice the time) and every verdict a failing canary
21
+ // puts in doubt.
22
+ //
23
+ // This module holds what the config, the fixture (playwright.mjs) and the
24
+ // reporter (playwrightStrongReporter.mjs) share.
25
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
26
+ import { createHash } from "node:crypto";
27
+ import { basename, dirname, resolve } from "node:path";
28
+
29
+ const TIMEOUT_FACTOR = 1.5;
30
+ const TIMEOUT_CONSTANT_MS = 5_000;
31
+ const DEFAULT_DURATION_MS = 1_000;
32
+ const CANARY_FILES = 3;
33
+ const POLL_MS = 50;
34
+
35
+ /** What a page writes to its console when its mutant passed the hit limit. */
36
+ export const PAGE_TIMEOUT_MARKER = "SUPERCOV_MUTANT_TIMEOUT";
37
+
38
+ /** The pass this process belongs to, or `undefined` outside strong mode. */
39
+ export function strongPass() {
40
+ const planPath = process.env["SUPERCOV_STRONG_PLAN"];
41
+ const resultsPath = process.env["SUPERCOV_STRONG_RESULTS"];
42
+ if (!planPath || !resultsPath)
43
+ return undefined;
44
+ const restart = process.env["SUPERCOV_STRONG_RESTART"] || undefined;
45
+ const name = restart ? basename(restart).replace(/\.json$/, "") : "main";
46
+ return {
47
+ planPath,
48
+ resultsPath,
49
+ restart,
50
+ name,
51
+ round: resolve(dirname(resultsPath), "playwright", name),
52
+ };
53
+ }
54
+
55
+ export function key(text) {
56
+ return createHash("sha256").update(String(text)).digest("hex").slice(0, 24);
57
+ }
58
+
59
+ export function writeJson(path, value) {
60
+ mkdirSync(dirname(path), { recursive: true });
61
+ const draft = `${path}.${process.pid}.draft`;
62
+ writeFileSync(draft, JSON.stringify(value));
63
+ renameSync(draft, path);
64
+ }
65
+
66
+ function readJson(path) {
67
+ return JSON.parse(readFileSync(path, "utf8"));
68
+ }
69
+
70
+ function budgetOf(durations, factor = 1) {
71
+ const longest = Math.max(DEFAULT_DURATION_MS, ...durations.map((ms) => ms ?? DEFAULT_DURATION_MS));
72
+ return Math.ceil((longest * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * factor);
73
+ }
74
+
75
+ /**
76
+ * The files whose tests must not run side by side: those whose tests the
77
+ * measured run ran, two or more of them, and never at once (by their
78
+ * spans), and, where the spans tell nothing (a file with one test, or none
79
+ * spanned), those the project runs one test at a time (not
80
+ * `fullyParallel`). A file whose tests overlapped runs side by side. The
81
+ * strong pass runs the others one test at a time; its workers are the
82
+ * project's own.
83
+ */
84
+ function serialFilesOf(plan, tests, fullyParallel) {
85
+ const byFile = new Map();
86
+ for (const { file } of Object.values(tests)) {
87
+ if (!byFile.has(file))
88
+ byFile.set(file, []);
89
+ }
90
+ for (const test of plan.tests) {
91
+ if (tests[playwrightId(test)] && Array.isArray(test.span))
92
+ byFile.get(tests[playwrightId(test)].file).push(test.span);
93
+ }
94
+ const serialFiles = [];
95
+ for (const [file, spans] of byFile) {
96
+ if (spans.length < 2) {
97
+ if (!fullyParallel)
98
+ serialFiles.push(file);
99
+ continue;
100
+ }
101
+ spans.sort((a, b) => a[0] - b[0]);
102
+ if (spans.every((span, at) => at === 0 || spans[at - 1][1] <= span[0]))
103
+ serialFiles.push(file);
104
+ }
105
+ return serialFiles.sort();
106
+ }
107
+
108
+ /** Whether the project runs a file's tests side by side: every project, or the config, says `fullyParallel`. */
109
+ function fullyParallelOf(config) {
110
+ const projects = Array.isArray(config?.projects) && config.projects.length ? config.projects : [{}];
111
+ return projects.every((project) => project.fullyParallel ?? config?.fullyParallel ?? false);
112
+ }
113
+
114
+ /** A mutant's rows: one per file its tests are in, each with its tests there. */
115
+ function mutantRows(tests, entry) {
116
+ const grouped = new Map();
117
+ for (const id of entry.tests) {
118
+ const file = tests[id].file;
119
+ if (!grouped.has(file))
120
+ grouped.set(file, []);
121
+ grouped.get(file).push(id);
122
+ }
123
+ return [...grouped].map(([file, ids]) => [file, {
124
+ kind: "mutant",
125
+ id: entry.id,
126
+ mutant: entry.mutant,
127
+ tests: ids,
128
+ budgetMs: budgetOf(ids.map((id) => tests[id].durationMs), entry.budgetFactor ?? 1),
129
+ }]);
130
+ }
131
+
132
+ /**
133
+ * The pass's rows: for each test file, what each repetition of its tests
134
+ * does. Worked out once, in the runner, from the plan (or the job the pass
135
+ * runs). The main pass runs each mutant against its likeliest killer alone
136
+ * (a test that infected it, cheapest first): its other candidates run in a
137
+ * later pass only if that one survives.
138
+ */
139
+ // A plan test's id as Playwright knows it: a Rust wasm run names a test by
140
+ // its file too (`<file>::<id>`).
141
+ function playwrightId(test) {
142
+ return test.file && test.id.startsWith(`${test.file}::`) ? test.id.slice(test.file.length + 2) : test.id;
143
+ }
144
+
145
+ function buildRows(pass, root, config) {
146
+ const plan = readJson(pass.planPath);
147
+ const tests = {};
148
+ plan.tests.forEach((test) => {
149
+ if (test.runner === "playwright" && test.file)
150
+ tests[playwrightId(test)] = { file: test.file, durationMs: test.durationMs ?? null };
151
+ });
152
+ // `workers` set only where the pass runs one test at a time.
153
+ const concurrency = { workers: undefined, serialFiles: serialFilesOf(plan, tests, fullyParallelOf(config)) };
154
+ if (pass.restart) {
155
+ const job = readJson(pass.restart);
156
+ const files = {};
157
+ const entries = {};
158
+ for (const entry of job.mutants) {
159
+ const known = { ...entry, tests: entry.tests.filter((id) => tests[id]) };
160
+ entries[entry.id] = known;
161
+ for (const [file, row] of mutantRows(tests, known))
162
+ (files[file] ??= []).push(row);
163
+ }
164
+ // A serial pass runs one test at a time: what it kills, nothing
165
+ // beside it did.
166
+ if (job.kind === "serial")
167
+ concurrency.workers = 1;
168
+ return { pass: pass.name, kind: job.kind, job, tests, files, entries, concurrency, immediate: [], restarts: [], otherRunners: job.otherRunners ?? {} };
169
+ }
170
+
171
+ // The copy's own list: the mutant at each index must be the run's, and
172
+ // one the instrumenter could not place has no switch to turn on.
173
+ let listed = {};
174
+ try {
175
+ listed = readJson(`${root}/.supercov/frontend-evidence/mutants.json`).files ?? {};
176
+ }
177
+ catch {
178
+ listed = {};
179
+ }
180
+ const idOf = (file, entry) => entry.id ||
181
+ `${file}:${entry.start?.[0]}:${entry.start?.[1]}-${entry.end?.[0]}:${entry.end?.[1]}:${entry.mutator}:${entry.replacement}`;
182
+ const indexes = new Map();
183
+ for (const [file, entries] of Object.entries(listed))
184
+ entries.forEach((entry, index) => indexes.set(idOf(file, entry), { index, entry }));
185
+
186
+ const immediate = [];
187
+ const restarts = [];
188
+ const otherRunners = {};
189
+ const entries = {};
190
+ const byFile = new Map();
191
+ const baseline = new Map();
192
+ const needBaseline = (file, id) => {
193
+ if (!baseline.has(file))
194
+ baseline.set(file, new Set());
195
+ baseline.get(file).add(id);
196
+ };
197
+ for (const mutant of plan.mutants) {
198
+ if (mutant.decided)
199
+ continue;
200
+ // A Rust mutant (Rust compiled to wasm) is switched by its index in
201
+ // its file's list, as the pass's build placed it.
202
+ const found = mutant.language === "rust" ? { index: mutant.index, entry: {} } : indexes.get(mutant.id);
203
+ if (!found || found.entry.unplaceable) {
204
+ immediate.push({
205
+ id: mutant.id,
206
+ status: "error",
207
+ reason: found ? `no switch could be placed (${found.entry.unplaceable})` : "the copy lists no such mutant: the source changed since the run",
208
+ tests: 0,
209
+ durationMs: 0,
210
+ });
211
+ continue;
212
+ }
213
+ // Its candidates, cheapest first (the plan's order), those whose own
214
+ // evidence shows it infected first of all.
215
+ const own = [];
216
+ const others = new Set();
217
+ for (const candidate of mutant.candidates) {
218
+ const test = plan.tests[candidate.test];
219
+ if (test && tests[playwrightId(test)])
220
+ own.push({ id: playwrightId(test), infected: candidate.reason === "infected" });
221
+ else if (test)
222
+ others.add(test.runner);
223
+ }
224
+ if (others.size)
225
+ otherRunners[mutant.id] = [...others].sort();
226
+ if (!own.length) {
227
+ immediate.push(others.size
228
+ ? { id: mutant.id, status: "error", reason: `its candidates ran under ${[...others].sort().join(", ")}, which this pass does not run`, tests: 0, durationMs: 0 }
229
+ : { id: mutant.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
230
+ continue;
231
+ }
232
+ const ordered = [...own.filter((test) => test.infected), ...own.filter((test) => !test.infected)].map((test) => test.id);
233
+ const switched = `${mutant.file}#${found.index}`;
234
+ for (const id of ordered)
235
+ needBaseline(tests[id].file, id);
236
+ if (mutant.serverWide) {
237
+ restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: mutant.serverWide, budgetFactor: 1 });
238
+ continue;
239
+ }
240
+ const entry = { id: mutant.id, mutant: switched, tests: [ordered[0]], rest: ordered.slice(1), budgetFactor: 1 };
241
+ entries[mutant.id] = entry;
242
+ for (const [file, row] of mutantRows(tests, entry)) {
243
+ if (!byFile.has(file))
244
+ byFile.set(file, []);
245
+ byFile.get(file).push(row);
246
+ }
247
+ }
248
+ const files = {};
249
+ for (const [file, ids] of baseline) {
250
+ files[file] = [{ kind: "baseline", id: null, mutant: null, tests: [...ids], budgetMs: null }, ...(byFile.get(file) ?? [])];
251
+ }
252
+ // Canaries: rows with no mutant among the mutated ones, in the files
253
+ // with the most mutants. One that fails means what one attempt did to
254
+ // the shared server reached another's (or the test is flaky).
255
+ const busiest = [...byFile.entries()]
256
+ .sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1))
257
+ .slice(0, CANARY_FILES);
258
+ for (const [file, mutated] of busiest) {
259
+ const canary = () => ({ kind: "canary", id: null, mutant: null, tests: files[file][0].tests, budgetMs: null });
260
+ const rows = files[file];
261
+ if (mutated.length >= 2)
262
+ rows.splice(1 + Math.floor(mutated.length / 2), 0, canary());
263
+ rows.push(canary());
264
+ }
265
+ return { pass: pass.name, kind: "main", job: null, tests, files, entries, concurrency, immediate, restarts, otherRunners };
266
+ }
267
+
268
+ /** The rows of this pass: built and written by the runner, read elsewhere. */
269
+ let rowsCache;
270
+ export function loadRows(pass) {
271
+ rowsCache ??= readJson(`${pass.round}/rows.json`);
272
+ return rowsCache;
273
+ }
274
+
275
+ /**
276
+ * The generated config in strong mode: every test repeated once per row,
277
+ * no retries (a retry would be a repetition of its own), no failure limit
278
+ * (a killed mutant fails a test), the project's own workers (one in a
279
+ * serial pass), and the strong reporter alone.
280
+ */
281
+ export function strongConfig(normalized, root, reporterPath) {
282
+ const pass = strongPass();
283
+ let rows;
284
+ if (process.env.TEST_WORKER_INDEX === undefined) {
285
+ rows = buildRows(pass, root, normalized);
286
+ rmSync(pass.round, { recursive: true, force: true });
287
+ writeJson(`${pass.round}/rows.json`, rows);
288
+ rowsCache = rows;
289
+ }
290
+ else {
291
+ rows = loadRows(pass);
292
+ }
293
+ const repeatEach = Math.max(1, ...Object.values(rows.files).map((fileRows) => fileRows.length));
294
+ const strongProject = (project) => ({ ...project, repeatEach, retries: 0 });
295
+ return {
296
+ ...normalized,
297
+ ...(Array.isArray(normalized.projects) ? { projects: normalized.projects.map(strongProject) } : {}),
298
+ repeatEach,
299
+ retries: 0,
300
+ maxFailures: 0,
301
+ ...(rows.concurrency.workers ? { workers: rows.concurrency.workers } : {}),
302
+ // The strong reporter alone: `mutants test --json` owns stdout.
303
+ reporter: [[reporterPath]],
304
+ };
305
+ }
306
+
307
+ /** How a test did with no mutant: `passed`, `failed`, or `undefined` before it ended. */
308
+ export function baselineOf(pass, original) {
309
+ const marker = `${pass.round}/baseline/${key(original)}`;
310
+ try {
311
+ return readJson(marker);
312
+ }
313
+ catch {
314
+ return undefined;
315
+ }
316
+ }
317
+
318
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
319
+
320
+ let repetitionsCache;
321
+ async function originalTestId(pass, testInfo) {
322
+ if (!testInfo.repeatEachIndex)
323
+ return testInfo.testId;
324
+ for (let waited = 0; waited < 10_000; waited += POLL_MS) {
325
+ if (!repetitionsCache?.[testInfo.testId] && existsSync(`${pass.round}/repetitions.json`))
326
+ repetitionsCache = readJson(`${pass.round}/repetitions.json`);
327
+ if (repetitionsCache?.[testInfo.testId])
328
+ return repetitionsCache[testInfo.testId];
329
+ await sleep(POLL_MS);
330
+ }
331
+ return undefined;
332
+ }
333
+
334
+ function alive(pid) {
335
+ try {
336
+ process.kill(pid, 0);
337
+ return true;
338
+ }
339
+ catch (error) {
340
+ return error?.code === "EPERM";
341
+ }
342
+ }
343
+
344
+ /**
345
+ * One test of `file` at a time, across the pass's workers: the file's lock,
346
+ * a directory, held by this worker's process until the test ends. A lock
347
+ * whose holder died is taken over.
348
+ */
349
+ async function lockFile(pass, file) {
350
+ const lock = `${pass.round}/locks/${key(file)}`;
351
+ mkdirSync(`${pass.round}/locks`, { recursive: true });
352
+ for (;;) {
353
+ try {
354
+ mkdirSync(lock);
355
+ writeFileSync(`${lock}/owner`, String(process.pid));
356
+ return lock;
357
+ }
358
+ catch (error) {
359
+ if (error?.code !== "EEXIST")
360
+ throw error;
361
+ }
362
+ let owner;
363
+ try {
364
+ owner = Number(readFileSync(`${lock}/owner`, "utf8"));
365
+ }
366
+ catch {
367
+ owner = undefined;
368
+ }
369
+ if (owner && owner !== process.pid && !alive(owner))
370
+ rmSync(lock, { recursive: true, force: true });
371
+ await sleep(POLL_MS);
372
+ }
373
+ }
374
+
375
+ /**
376
+ * What this repetition of a test does: `undefined` outside strong mode,
377
+ * `null` to skip, else the mutant (`file#index`, `-` for none) and its time
378
+ * budget. A row after the baseline waits for the test's own baseline: a test
379
+ * that fails with no mutant cannot tell one. A file whose tests the measured
380
+ * run never ran side by side runs one at a time here too.
381
+ */
382
+ export async function strongClaim(testInfo) {
383
+ const pass = strongPass();
384
+ if (!pass)
385
+ return undefined;
386
+ const started = Date.now();
387
+ const rows = loadRows(pass);
388
+ const original = await originalTestId(pass, testInfo);
389
+ const test = original && rows.tests[original];
390
+ const row = test && rows.files[test.file]?.[testInfo.repeatEachIndex];
391
+ if (!row || !row.tests.includes(original))
392
+ return null;
393
+ const configured = testInfo.timeout;
394
+ // Waiting is not the test's time.
395
+ testInfo.setTimeout(0);
396
+ if (row.kind !== "baseline" && !rows.job) {
397
+ const deadline = Date.now() + Math.max(120_000, budgetOf([test.durationMs]) * 4);
398
+ while (baselineOf(pass, original) === undefined && Date.now() < deadline)
399
+ await sleep(POLL_MS);
400
+ if (baselineOf(pass, original) !== "passed")
401
+ return null;
402
+ }
403
+ const killed = () => row.kind === "mutant" && existsSync(`${pass.round}/killed/${key(row.id)}`);
404
+ if (killed())
405
+ return null;
406
+ const lock = rows.concurrency.workers !== 1 && rows.concurrency.serialFiles.includes(test.file)
407
+ ? await lockFile(pass, test.file)
408
+ : undefined;
409
+ if (killed()) {
410
+ if (lock)
411
+ rmSync(lock, { recursive: true, force: true });
412
+ return null;
413
+ }
414
+ // The test's time from here: a mutant's from the test's measured
415
+ // duration and the time Playwright gives an assertion and an action to
416
+ // fail in (a failing `expect` waits for its own timeout), a canary's as
417
+ // configured.
418
+ if (row.kind === "mutant") {
419
+ const expectTimeout = testInfo.project?.expect?.timeout ?? 5_000;
420
+ const actionTimeout = testInfo.project?.use?.actionTimeout ?? 0;
421
+ // Playwright itself ends the test at its configured timeout (the
422
+ // project's, or its own `test.slow()` / `describe.configure`), and an
423
+ // assertion may wait up to there with a timeout of its own: that is
424
+ // the floor.
425
+ const budget = Math.max(row.budgetMs + expectTimeout + actionTimeout, configured > 0 ? configured : 0);
426
+ testInfo.setTimeout(Date.now() - started + budget);
427
+ }
428
+ else if (configured > 0)
429
+ testInfo.setTimeout(Date.now() - started + configured);
430
+ const claimed = { original, kind: row.kind, id: row.id, mutant: row.mutant ?? "-", startedAt: Date.now(), lock };
431
+ writeJson(`${pass.round}/attempts/${key(testInfo.testId)}.json`, claimed);
432
+ return claimed;
433
+ }
434
+
435
+ /** The attempt's end, and whether its page said the mutant ran away. */
436
+ export function strongFinish(testInfo, claimed, details) {
437
+ const pass = strongPass();
438
+ if (!pass || !claimed)
439
+ return;
440
+ // A kill is marked here, before the worker starts its next test: the
441
+ // reporter hears of it later, and the next test of the row would run.
442
+ if (claimed.kind === "mutant" && testInfo.status !== undefined && testInfo.status !== "passed" && testInfo.status !== "skipped")
443
+ writeJson(`${pass.round}/killed/${key(claimed.id)}`, claimed.original);
444
+ writeJson(`${pass.round}/attempts/${key(testInfo.testId)}.json`, { ...claimed, ...details, endedAt: Date.now() });
445
+ if (claimed.lock)
446
+ rmSync(claimed.lock, { recursive: true, force: true });
447
+ }
448
+
449
+ /**
450
+ * Switches a document's mutant on before its scripts run: an init script.
451
+ * Every copy of the runtime in the page reads the state from here.
452
+ */
453
+ export function activatePageMutant({ file, index, marker }) {
454
+ const stateKey = Symbol.for("supercov.strongMutation");
455
+ let strong = globalThis[stateKey];
456
+ if (strong === undefined) {
457
+ strong = { slots: new Map(), file: undefined, index: -1, hits: 0, limit: 1e6 };
458
+ Object.defineProperty(globalThis, stateKey, { value: strong, configurable: true });
459
+ }
460
+ const previous = strong.slots.get(strong.file);
461
+ if (previous !== undefined)
462
+ previous.a = -1;
463
+ strong.file = file;
464
+ strong.index = index;
465
+ strong.hits = 0;
466
+ const slot = strong.slots.get(file);
467
+ if (slot !== undefined)
468
+ slot.a = index;
469
+ strong.onTimeout = () => {
470
+ try {
471
+ console.error(marker);
472
+ }
473
+ catch {
474
+ // A page that replaced its console.
475
+ }
476
+ };
477
+ }