//! The public commands, end to end: a node:test project in a git repository,
//! measured by the binary Cargo built, and read back the way a user reads it.
//! Each scenario asserts what the user sees -- numbers, file names, exit
//! codes -- rather than how the binary arrives at it.
mod common;
use common::{Project, contains_all};
#[test]
fn a_measured_suite_reads_back_through_every_query() {
let project = Project::cart("queries");
let measured = project.supercov(&["--", "node", "--test"]);
let output = measured.succeeds();
contains_all(
&output,
&["total adds prices", "pass 3", "[coverage] evidence:"],
);
let run = project.latest();
let listed = project.supercov(&["runs"]).succeeds();
contains_all(
&listed,
&[&run, "76.92%", "50.00%", "20.00%", "showing 1-1 of 1"],
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
&format!("run {run}"),
"command: node --test",
"Lines 76.92% (10/13)",
"Branches 50.00% (4/8)",
"MC/DC 20.00% (1/5)",
"not assessed",
"Exact for 3 test(s)",
"Passed 3",
],
);
let by_id = project.supercov(&["runs", &run]).succeeds();
assert!(by_id.contains("Lines 76.92% (10/13)"), "{by_id}");
let gaps = project.supercov(&["runs", "latest", "gaps"]).succeeds();
contains_all(
&gaps,
&[
"src/cart.js",
"lines 3 statements 2 functions 2 branch outcomes 4 MC/DC conditions 4",
],
);
let files = project.supercov(&["runs", "latest", "files"]).succeeds();
assert!(files.contains("src/cart.js"), "{files}");
let file = project
.supercov(&["runs", "latest", "file", "src/cart.js"])
.succeeds();
contains_all(
&file,
&[
"Lines not executed 3",
"Functions not called 2",
"Tests touching this file: 3",
"zero-iteration outcome not observed",
"`express` was never true; needs `express` true, decision true",
"`express` was never evaluated\n",
],
);
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:14"])
.succeeds();
contains_all(&line, &["NOT COVERED", "return express ? 15 : 5;", "None"]);
let decision = project
.supercov(&["runs", "latest", "decision", "src/cart.js:13"])
.succeeds();
contains_all(
&decision,
&[
"express || sum < 50",
"C1 MISSING: express",
"C2 MISSING: sum < 50",
"FF -> F",
],
);
let test = project
.supercov(&["runs", "latest", "test", "shipping"])
.succeeds();
contains_all(
&test,
&[
"shipping is free over fifty",
"line: src/cart.js:12",
"line: src/cart.js:16",
"node:assert/strict.equal at test/cart.test.js:14:3",
],
);
let kinds = project.supercov(&["runs", "latest", "kinds"]).succeeds();
assert!(kinds.contains("unit 3 test(s) lines 76.92%"), "{kinds}");
let runners = project.supercov(&["runs", "latest", "runners"]).succeeds();
assert!(runners.contains("node:test 3 test(s)"), "{runners}");
// Coverage by directory, split by the kinds of test that ran, and the
// counts a percentage is worked out from on every file.
let areas = project
.supercov(&["runs", "latest", "files", "--group", "dir"])
.succeeds();
contains_all(
&areas,
&[
"Coverage by directory, 1 deep",
"Directory Files Lines unit All",
"src 1 13 76.92% 76.92%",
],
);
let areas = project
.supercov(&["runs", "latest", "files", "--group", "dir", "--json"])
.json();
let area = &areas["data"]["areas"][0];
assert_eq!(area["directory"], "src");
assert_eq!(area["totals"]["lines"], 13);
assert_eq!(area["covered"]["lines"], 10);
assert_eq!(area["byKind"][0]["kind"], "unit");
assert_eq!(area["byKind"][0]["covered"]["lines"], 10);
assert_eq!(area["coveredByTests"]["lines"], 10);
let files = project
.supercov(&["runs", "latest", "files", "--json"])
.json();
let file = &files["data"]["files"][0];
assert_eq!(file["totals"]["lines"], 13);
assert_eq!(file["covered"]["lines"], 10);
assert_eq!(
file["covered"]["branches"].as_u64().unwrap() + file["missingBranches"].as_u64().unwrap(),
file["totals"]["branches"].as_u64().unwrap()
);
let wrong = project.supercov(&["runs", "latest", "files", "--depth", "2"]);
assert_eq!(wrong.code(), 2);
// The scope is read as a table of places first, and file by file on
// request.
let scope = project.supercov(&["runs", "latest", "scope"]).succeeds();
contains_all(
&scope,
&[
"Files Status Directory Reason",
" 1 INCLUDED src discovered package source root",
" 1 EXCLUDED test test or fixture source",
"File by file: supercov runs",
"scope --files",
],
);
let scope = project
.supercov(&["runs", "latest", "scope", "--files"])
.succeeds();
contains_all(
&scope,
&["INCLUDED src/cart.js", "EXCLUDED test/cart.test.js"],
);
let source = project
.supercov(&["runs", "latest", "source", "src/cart.js", "--limit", "3"])
.succeeds();
contains_all(
&source,
&[
"1 │ export function total(items, coupon) {",
"Showing 1-3 of 21",
"--offset 3",
],
);
let next = project
.supercov(&[
"runs",
"latest",
"source",
"src/cart.js",
"--offset",
"11",
"--limit",
"1",
])
.succeeds();
assert!(
next.contains("12 │ export function shipping(sum, express) {"),
"{next}"
);
for (arguments, said) in [
(
&["src/cart.js", "--offset"][..],
"--offset requires a value",
),
(
&["src/missing.js"],
"File absent from the run's source manifest: src/missing.js",
),
] {
let mut command = vec!["runs", "latest", "source"];
command.extend(arguments);
let refused = project.supercov(&command).exits(2);
assert!(refused.contains(said), "{refused}");
}
let assertions = project
.supercov(&["runs", "latest", "assertions"])
.succeeds();
assert!(
assertions.contains("assertions not assessed"),
"{assertions}"
);
let impossible = project
.supercov(&["runs", "latest", "minimize", "--target", "100"])
.exits(2);
assert!(
impossible.contains("target 100% is impossible"),
"{impossible}"
);
let minimized = project
.supercov(&[
"runs", "latest", "minimize", "--target", "70", "--metric", "lines",
])
.exits(0);
assert!(minimized.contains("test"), "{minimized}");
// Minimizing reads the run's evidence itself; evidence it cannot read
// refuses the question.
let unread = project
.supercov_with(
&[
"runs", "latest", "minimize", "--target", "70", "--metric", "lines",
],
&[(
"SUPERCOV_TEST_FAULT",
"fs.read_from#evidence_archive.rs:677",
)],
)
.exits(2);
assert!(unread.contains("invalid coverage archive"), "{unread}");
}
#[test]
fn every_query_answers_in_json_too() {
let project = Project::cart("json");
let run = project.measure(&[]);
let summary = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(summary["ok"], true);
assert_eq!(summary["data"]["run"], run.as_str());
for query in [
vec!["gaps"],
vec!["files"],
vec!["file", "src/cart.js", "--limit", "5"],
vec!["line", "src/cart.js:14"],
vec!["decision", "src/cart.js:13"],
vec!["test", "shipping"],
vec!["kinds"],
vec!["runners"],
vec!["scope"],
vec!["source", "src/cart.js", "--limit", "2"],
vec!["assertions"],
vec!["minimize", "--target", "50", "--metric", "lines"],
vec!["tests", "affected"],
] {
let mut args = vec!["runs", run.as_str()];
args.extend(query.iter().copied());
args.push("--json");
let report = project.supercov(&args).json();
assert_eq!(report["ok"], true, "{query:?}: {report}");
}
let listed = project.supercov(&["runs", "--json", "--limit", "1"]).json();
assert_eq!(listed["data"]["runs"][0]["id"], run.as_str());
}
#[test]
fn check_gates_on_counts_and_refuses_what_it_cannot_judge() {
let project = Project::cart("check");
project.measure(&[]);
let passed = project
.supercov(&["runs", "check", "--min-lines", "50"])
.succeeds();
contains_all(
&passed,
&["lines 76.92% 10/13 (floor 50%)", "PASS"],
);
let failed = project
.supercov(&[
"runs",
"check",
"--min-lines",
"100",
"--min-branches",
"100",
])
.exits(1);
contains_all(
&failed,
&[
"FAIL: 2 floor(s) not met.",
"(whole run): lines 76.92% 10/13 below 100%",
"(whole run): branches 50.00% 4/8 below 100%",
],
);
// 10 of 13 lines is 76.923...%: a floor at the rounded figure fails.
project
.supercov(&["runs", "check", "--min-lines", "76.93"])
.exits(1);
project
.supercov(&["runs", "check", "--min-lines", "76.92"])
.succeeds();
let per_file = project
.supercov(&[
"runs",
"check",
"--min-functions",
"60",
"--per-file",
"--json",
])
.json();
assert_eq!(per_file["data"]["outcome"]["result"], "fail", "{per_file}");
let file = &per_file["data"]["view"]["files"][0];
assert_eq!(file["file"], "src/cart.js");
assert_eq!(file["uncoveredLines"], serde_json::json!([14, 19, 20]));
for (args, message) in [
(vec!["--min-mcdc", "101"], "is above 100"),
(vec!["--min-lines", "abc"], "is not a percentage"),
] {
let mut full = vec!["runs", "check"];
full.extend(args);
let refused = project.supercov(&full).exits(2);
assert!(refused.contains(message), "{refused}");
}
// A run that no longer matches the checkout cannot answer.
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let stale = project
.supercov(&["runs", "check", "--min-lines", "10"])
.exits(2);
contains_all(&stale, &["cannot answer", "instrumented source changed"]);
}
#[test]
fn a_failing_suite_keeps_its_exit_status_and_cannot_pass_a_gate() {
let project = Project::cart("failing");
project.edit(
"test/cart.test.js",
"shipping(60, false), 0",
"shipping(60, false), 1",
);
let measured = project.supercov(&["--", "node", "--test"]);
let output = measured.exits(1);
assert!(output.contains("fail 1"), "{output}");
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Passed 2", "Failed 1"]);
let gate = project
.supercov(&["runs", "check", "--min-lines", "10"])
.exits(2);
assert!(gate.contains("cannot answer"), "{gate}");
let failed = project
.supercov(&["runs", "latest", "--filter", "failed", "--json"])
.json();
assert_eq!(failed["ok"], true, "{failed}");
}
#[test]
fn patch_judges_only_the_lines_a_change_touches() {
let project = Project::cart("patch");
// An untested change: describe() gains a line no test runs.
project.edit(
"src/cart.js",
" return items.map((item) => item.name).join(\", \");",
" const names = items.map((item) => item.name);\n return names.join(\", \");",
);
project.measure(&[]);
let uncovered = project
.supercov(&["runs", "patch", "--base", "HEAD", "--min-lines", "100"])
.exits(1);
contains_all(
&uncovered,
&["0 of 2 changed executable line(s) covered", "src/cart.js"],
);
let annotated = project
.supercov(&["runs", "patch", "--base", "HEAD", "--annotate", "github"])
.succeeds();
assert!(
annotated.contains("::warning file=src/cart.js,line=20"),
"{annotated}"
);
// Annotations name files from the top of the repository: git asked
// where that is, after the four asks of the patch itself, and failing.
let unplaced = project
.supercov_with(
&["runs", "patch", "--base", "HEAD", "--annotate", "github"],
&[("SUPERCOV_TEST_FAULT", "git@5")],
)
.exits(2);
assert!(unplaced.contains("could not run git"), "{unplaced}");
assert!(!unplaced.contains("::warning"), "{unplaced}");
// Tested now: the same change passes.
project.edit(
"test/cart.test.js",
"import { total, shipping } from \"../src/cart.js\";",
"import { total, shipping, describe } from \"../src/cart.js\";\n\ntest(\"describe lists names\", () => {\n assert.equal(describe([{ name: \"a\" }, { name: \"b\" }]), \"a, b\");\n});",
);
project.measure(&[]);
let covered = project
.supercov(&[
"runs",
"patch",
"--base",
"HEAD",
"--min-lines",
"100",
"--json",
])
.json();
assert_eq!(covered["ok"], true, "{covered}");
let text = covered.to_string();
assert!(text.contains("\"pass\""), "{text}");
// Only a comment changed.
project.commit("describe");
project.edit(
"src/cart.js",
"export function describe",
"// Names, in order.\nexport function describe",
);
project.measure(&[]);
let comment = project
.supercov(&["runs", "patch", "--base", "HEAD"])
.succeeds();
assert!(comment.contains("No executable changes"), "{comment}");
// Untracked new source counts as entirely added.
project.write(
"src/tax.js",
"export function rate(country) {\n return country === \"LT\" ? 0.21 : 0;\n}\n",
);
project.measure(&[]);
let added = project
.supercov(&["runs", "patch", "--base", "HEAD", "--min-lines", "100"])
.exits(1);
contains_all(
&added,
&["0 of 2 changed executable line(s) covered", "src/tax.js"],
);
// A source change the run has not seen cannot be mapped.
project.edit("src/tax.js", "0.21", "0.2");
let stale = project
.supercov(&["runs", "patch", "--base", "HEAD"])
.exits(2);
assert!(stale.contains("cannot map a patch"), "{stale}");
}
/// A patch is read from git: where the branch left its base, the
/// repository's top, the changed lines, the files not yet tracked. Git that
/// cannot run for any of them refuses the patch, saying so.
#[test]
fn a_patch_whose_git_cannot_run_is_refused() {
let project = Project::cart("patch-git");
project.edit(
"src/cart.js",
" return items.map((item) => item.name).join(\", \");",
" const names = items.map((item) => item.name);\n return names.join(\", \");",
);
project.measure(&[]);
for fault in ["git@2", "git@3", "git@4"] {
let refused = project
.supercov_with(
&["runs", "patch", "--base", "HEAD"],
&[("SUPERCOV_TEST_FAULT", fault)],
)
.exits(2);
assert!(
refused.contains("could not run git: injected fault at git"),
"{fault}: {refused}"
);
}
project
.supercov(&["runs", "patch", "--base", "HEAD"])
.succeeds();
}
/// After a run, nothing of the rest of the repository stays in the
/// project's `.supercov`. The copy is laid out within its repository, with
/// the other packages linked around it; left there, a test runner started in
/// the project followed the links and ran another package's tests too, as
/// Vitest's includes did in a monorepo. The next run links them again.
#[test]
fn a_package_run_leaves_no_way_to_its_repositorys_other_packages() {
let (repository, project) = Project::cart_below("around-copy", "web");
repository.write(
"admin/test/admin.test.js",
"import test from 'node:test';\ntest('admin', () => {});\n",
);
repository.write("tsconfig.base.json", "{}\n");
repository.commit("admin");
// A test that writes beside its package makes a directory there.
project.write(
"test/beside.test.js",
"import test from 'node:test';\nimport { mkdirSync } from 'node:fs';\ntest('beside', () => { mkdirSync('../made-by-a-test/inner', { recursive: true }); });\n",
);
project.commit("beside");
let name = repository.root.file_name().unwrap();
let around = project
.root
.join(".supercov/workspaces/workspace")
.join(name);
for _ in 0..2 {
project.supercov(&["--", "node", "--test"]).succeeds();
assert!(around.join("web").is_dir(), "the package's copy is kept");
for left in ["admin", "tsconfig.base.json", "made-by-a-test"] {
assert!(
std::fs::symlink_metadata(around.join(left)).is_err(),
"{left} stayed beside the copy"
);
}
}
// Clearing is best effort: a level or an entry that cannot be read
// leaves it, and the run goes on.
for fault in [
"fs.read_dir#workspace.rs:2269",
"fs.read_dir entry#workspace.rs:2269",
"fs.symlink_metadata#workspace.rs:2274",
] {
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
assert_eq!(ran.code(), 0, "{fault}: {}", ran.stderr());
assert!(
fired_at(&ran.stderr(), &fault[fault.find('#').unwrap() + 1..]),
"{fault}: {}",
ran.stderr()
);
}
}
#[test]
fn patch_reads_a_project_kept_below_the_top_of_its_repository() {
// Git names a file from the top (`web/src/cart.js`), the run from where
// it stood (`src/cart.js`), and a workflow marks a line by the first.
let (_repository, project) = Project::cart_below("patch-below", "web");
project.edit(
"src/cart.js",
" return items.map((item) => item.name).join(\", \");",
" const names = items.map((item) => item.name);\n return names.join(\", \");",
);
project.write(
"src/tax.js",
"export function rate(country) {\n return country === \"LT\" ? 0.21 : 0;\n}\n",
);
project.measure(&[]);
let patch = project
.supercov(&["runs", "patch", "--base", "HEAD", "--annotate", "github"])
.succeeds();
contains_all(
&patch,
&[
"0 of 4 changed executable line(s) covered",
" src/cart.js: ",
" src/tax.js: ",
"::warning file=web/src/cart.js,line=",
"::warning file=web/src/tax.js,line=",
],
);
}
/// A script that answers each line typed to it and ends on the second.
#[cfg(unix)]
const ASKS: &str = "\
import { shipping } from './src/cart.js';
let lines = 0;
process.stdin.on('data', (typed) => {
lines += 1;
console.log(`line ${lines}: ${String(typed).trim()} (${shipping(60, false)})`);
if (lines === 2) process.exit(0);
});
console.log('asking');
";
#[cfg(unix)]
#[test]
fn a_command_on_a_terminal_reads_what_is_typed() {
// A debugger at a breakpoint, a watch mode, a question before an
// install: the command never got the keys, and stood stopped.
let project = Project::cart("keyboard");
project.write("ask.mjs", ASKS);
project.commit("asks");
let mut terminal = common::OnTerminal::start(&project, &["--", "node", "ask.mjs"]);
terminal.wait_for("asking");
terminal.press("first\n");
terminal.wait_for("line 1: first (0)");
terminal.press("second\n");
terminal.wait_for("line 2: second (0)");
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{seen}");
assert!(seen.contains("[coverage] evidence:"), "{seen}");
// The run is recorded as any other.
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("command: node ask.mjs"), "{summary}");
}
#[cfg(unix)]
#[test]
fn bytes_a_command_writes_to_a_terminal_that_are_not_text_pass_on_unchanged() {
// A binary dump, or a terminal in another encoding: nothing in it is a
// name to put right, and it reaches the terminal as it was written.
let project = Project::cart("terminal-bytes");
project.write(
"bytes.mjs",
"process.stdout.write(Buffer.from([0x62, 0xff, 0xfe, 0x0a]));\nconsole.log('after the bytes');\n",
);
project.commit("bytes");
let mut terminal = common::OnTerminal::start(&project, &["--", "node", "bytes.mjs"]);
terminal.wait_for("after the bytes");
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{seen}");
assert!(seen.contains("b\u{fffd}\u{fffd}"), "{seen:?}");
}
#[cfg(unix)]
#[test]
fn ctrl_c_at_a_command_that_reads_the_keyboard_interrupts_the_run() {
// With the terminal lent, Ctrl-C reaches the command and not Supercov.
// The run is still one that was interrupted: its status, and no record.
let project = Project::cart("keyboard-interrupt");
project.write("ask.mjs", ASKS);
project.commit("asks");
let mut terminal = common::OnTerminal::start(&project, &["--", "node", "ask.mjs"]);
terminal.wait_for("asking");
terminal.press("first\n");
terminal.wait_for("line 1: first (0)");
terminal.press("\u{3}");
let (code, seen) = terminal.finish();
assert_eq!(code, 130, "{seen}");
assert!(!seen.contains("[coverage] evidence:"), "{seen}");
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(
runs["data"]["runs"].as_array().map(Vec::len),
Some(0),
"{runs}"
);
// The interrupted run's state that cannot be read to be marked so ends
// the run, saying where.
let mut terminal = common::OnTerminal::start_with(
&project,
&["--", "node", "ask.mjs"],
&[("SUPERCOV_TEST_FAULT", "fs.read#javascript_run.rs:1260")],
);
terminal.wait_for("asking");
terminal.press("\u{3}");
let (code, seen) = terminal.finish();
assert_ne!(code, 0, "{seen}");
assert!(
seen.contains("test fault at fs (javascript_run.rs:1260"),
"{seen}"
);
}
/// A terminal Supercov cannot open to lend is not lent: the command that
/// asks for the keyboard waits for it, as it would have behind Supercov,
/// and Ctrl-C still ends the run.
#[cfg(unix)]
#[test]
fn a_terminal_supercov_cannot_open_is_not_lent() {
let project = Project::cart("terminal-unopened");
project.write("ask.mjs", ASKS);
project.commit("asks");
let mut terminal = common::OnTerminal::start_with(
&project,
&["--", "node", "ask.mjs"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.open_with#process_supervision.rs:1708",
)],
);
terminal.wait_for("asking");
terminal.press("first\n");
terminal.wait_for("test fault at fs (process_supervision.rs:1708");
terminal.press("\u{3}");
let (code, seen) = terminal.finish();
assert_eq!(code, 130, "{seen}");
assert!(!seen.contains("line 1: first"), "{seen}");
}
#[cfg(unix)]
#[test]
fn ctrl_z_at_a_command_that_reads_the_keyboard_stops_supercov_too() {
// The shell waits on Supercov. Were the command alone stopped, the
// terminal would belong to nothing that reads it.
let project = Project::cart("keyboard-stop");
project.write("ask.mjs", ASKS);
project.commit("asks");
let mut terminal = common::OnTerminal::start(&project, &["--", "node", "ask.mjs"]);
terminal.wait_for("asking");
terminal.press("first\n");
terminal.wait_for("line 1: first (0)");
terminal.press("\u{1a}");
terminal.wait_until_stopped();
terminal.resume();
terminal.press("second\n");
terminal.wait_for("line 2: second (0)");
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{seen}");
}
#[cfg(unix)]
#[test]
fn suites_started_together_from_one_command_are_one_run_with_their_kinds() {
// What to do where two suites run side by side: one command starts
// both, each says its own kind, and the run holds every test.
let project = Project::cart("together");
project.write(
"test/slow.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\n\ntest(\"describe lists names\", async () => {\n await new Promise((done) => setTimeout(done, 200));\n assert.equal(describe([{ name: \"a\" }]), \"a\");\n});\n",
);
project.commit("a slow suite");
let together = "SUPERCOV_TEST_KIND=unit node --test test/cart.test.js & unit=$!; SUPERCOV_TEST_KIND=integration node --test test/slow.test.js & integration=$!; wait $unit; first=$?; wait $integration && exit $first";
project.supercov(&["--", "sh", "-c", together]).succeeds();
let kinds = project.supercov(&["runs", "latest", "kinds"]).succeeds();
contains_all(&kinds, &["unit", "integration"]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Total 4", "Passed 4"]);
// A filter narrows the grouping to the tests it picks.
let counted = |args: &[&str], field: &str| -> Vec<(String, u64)> {
let mut all = vec!["runs", "latest"];
all.extend_from_slice(args);
all.push("--json");
project.supercov(&all).json()["data"][field]
.as_array()
.unwrap()
.iter()
.map(|entry| {
let name = entry["kind"].as_str().or(entry["runner"].as_str()).unwrap();
(name.to_owned(), entry["tests"].as_u64().unwrap())
})
.collect()
};
assert_eq!(
counted(&["runners", "--kind", "integration"], "runners"),
[("node:test".to_owned(), 1)]
);
assert_eq!(
counted(&["runners", "--kind", "unit"], "runners"),
[("node:test".to_owned(), 3)]
);
assert_eq!(
counted(&["kinds", "--kind", "unit"], "kinds"),
[("unit".to_owned(), 3)]
);
let mut by_runner = counted(&["kinds", "--runner", "node:test"], "kinds");
by_runner.sort();
assert_eq!(
by_runner,
[("integration".to_owned(), 1), ("unit".to_owned(), 3)]
);
}
#[test]
fn reports_carry_the_same_view_in_every_format() {
let project = Project::cart("reports");
project.measure(&[]);
let lcov = project
.supercov(&["runs", "report", "--format", "lcov"])
.succeeds();
contains_all(
&lcov,
&[
"SF:src/cart.js",
"FNDA:0,describe",
"FNH:2",
"BRH:4",
"DA:14,0",
"LH:10",
"LF:13",
],
);
let cobertura = project
.supercov(&["runs", "report", "--format", "cobertura"])
.succeeds();
contains_all(
&cobertura,
&[
"lines-covered=\"10\" lines-valid=\"13\"",
"branches-covered=\"4\" branches-valid=\"8\"",
"filename=\"src/cart.js\"",
],
);
// Istanbul places what it reports by range, found in the checkout: the
// cart's `shipping` returns 15 or 5 on line 14, which no test reached.
let istanbul: serde_json::Value = serde_json::from_str(
&project
.supercov(&["runs", "report", "--format", "istanbul"])
.succeeds(),
)
.unwrap();
// Keyed as Node writes a path: on Windows without the verbatim prefix
// the test's own root carries.
let cart = project.root.join("src").join("cart.js");
let cart = cart.to_string_lossy();
let cart = cart.strip_prefix(r"\\?\").unwrap_or(&cart);
let file = &istanbul[cart];
assert_eq!(file["path"], cart);
let statements = file["statementMap"].as_object().unwrap();
let missed = statements
.iter()
.filter(|(key, _)| file["s"][key.as_str()] == 0)
.map(|(_, range)| range.clone())
.collect::<Vec<_>>();
assert_eq!(
missed,
[
serde_json::json!({ "start": { "line": 14, "column": 4 }, "end": { "line": 14, "column": 28 } }),
serde_json::json!({ "start": { "line": 20, "column": 2 }, "end": { "line": 20, "column": 51 } }),
]
);
assert_eq!(
file["fnMap"]["1"]["loc"],
serde_json::json!({ "start": { "line": 12, "column": 7 }, "end": { "line": 17, "column": 1 } })
);
assert_eq!(
file["f"],
serde_json::json!({ "0": 1, "1": 1, "2": 0, "3": 0 })
);
// `describe`'s arrow has no name, and is named as Istanbul names one.
assert_eq!(file["fnMap"]["3"]["name"], "(anonymous_3)");
let summary = project
.supercov(&["runs", "report", "--format", "istanbul-summary"])
.succeeds();
contains_all(
&summary,
&[
"\"total\":{\"lines\":{\"total\":13,\"covered\":10,\"skipped\":0,\"pct\":76.92}",
"\"statements\":{\"total\":10,\"covered\":8,\"skipped\":0,\"pct\":80.0}",
"\"functions\":{\"total\":4,\"covered\":2,\"skipped\":0,\"pct\":50.0}",
"\"branches\":{\"total\":8,\"covered\":4,\"skipped\":0,\"pct\":50.0}",
],
);
let clover = project
.supercov(&["runs", "report", "--format", "clover"])
.succeeds();
contains_all(
&clover,
&[
"statements=\"10\" coveredstatements=\"8\" conditionals=\"8\" coveredconditionals=\"4\" methods=\"4\" coveredmethods=\"2\"",
"<file name=\"cart.js\" path=\"src/cart.js\">",
"<line num=\"14\" count=\"0\" type=\"cond\" truecount=\"0\" falsecount=\"2\"/>",
],
);
let jacoco = project
.supercov(&["runs", "report", "--format", "jacoco"])
.succeeds();
contains_all(
&jacoco,
&[
"<package name=\"src\">",
"<sourcefile name=\"cart.js\">",
"<line nr=\"14\" mi=\"1\" ci=\"0\" mb=\"2\" cb=\"0\"/>",
"<counter type=\"LINE\" missed=\"3\" covered=\"10\"/>",
"<counter type=\"BRANCH\" missed=\"4\" covered=\"4\"/>",
],
);
let sonar = project
.supercov(&["runs", "report", "--format", "sonar"])
.succeeds();
contains_all(
&sonar,
&[
"<file path=\"src/cart.js\">",
"<lineToCover lineNumber=\"14\" covered=\"false\" branchesToCover=\"2\" coveredBranches=\"0\"/>",
],
);
// A file that no longer holds what the run recorded is not placed by a
// guess: Istanbul refuses it, and the formats that state lines still
// write.
project.edit(
"src/cart.js",
" return express ? 15 : 5;",
" return 9;",
);
let refused = project
.supercov(&["runs", "report", "--format", "istanbul"])
.exits(2);
// `shipping` spans the changed line, and comes first.
assert!(
refused.contains("src/cart.js:12 no longer holds"),
"{refused}"
);
project
.supercov(&["runs", "report", "--format", "sonar"])
.succeeds();
project.edit(
"src/cart.js",
" return 9;",
" return express ? 15 : 5;",
);
let written = project.root.join("coverage/lcov.info");
project
.supercov(&[
"runs",
"report",
"--format",
"lcov",
"--output",
"coverage/lcov.info",
])
.succeeds();
assert_eq!(std::fs::read_to_string(&written).unwrap(), lcov);
let kept = project
.supercov(&[
"runs",
"report",
"--format",
"lcov",
"--output",
"coverage/lcov.info",
])
.exits(2);
assert!(kept.contains("--force"), "{kept}");
project
.supercov(&[
"runs",
"report",
"--format",
"lcov",
"--output",
"coverage/lcov.info",
"--force",
])
.succeeds();
project
.supercov(&[
"runs",
"report",
"--format",
"html",
"--output",
"coverage/report",
])
.succeeds();
let html = std::fs::read_to_string(project.root.join("coverage/report/index.html")).unwrap();
assert!(html.contains("src/cart.js"));
let interactive = project
.supercov(&["report", "--output", "coverage/portable", "--no-open"])
.exits(0);
assert!(interactive.contains("self-contained"), "{interactive}");
}
/// A diff says the code did not change only when neither the source nor
/// what it runs on did: a new dependency is a change in the code too.
#[test]
fn a_diff_counts_a_dependency_change_as_a_change_in_the_code() {
let added_test = "test(\"express shipping costs fifteen\", () => {\n assert.equal(shipping(10, true), 15);\n});\n\ntest(\"shipping is free over fifty\"";
let same_source = "Both runs measured the same source";
let project = Project::cart("diff-tests-only");
let before = project.measure(&[]);
project.edit(
"test/cart.test.js",
"test(\"shipping is free over fifty\"",
added_test,
);
let after = project.measure(&[]);
let diff = project.supercov(&["diff", &before, &after]).succeeds();
assert!(diff.contains(same_source), "{diff}");
let project = Project::cart("diff-dependency");
let before = project.measure(&[]);
project.edit(
"test/cart.test.js",
"test(\"shipping is free over fifty\"",
added_test,
);
project.edit(
"package.json",
"\"type\": \"module\"",
"\"type\": \"module\", \"dependencies\": { \"left-pad\": \"1.3.0\" }",
);
let after = project.measure(&[]);
let diff = project.supercov(&["diff", &before, &after]).succeeds();
assert!(!diff.contains(same_source), "{diff}");
}
/// A run whose recorded source cannot be read from its evidence, with no
/// cached copy to read instead, cannot say which tests a change affects.
#[test]
fn tests_affected_by_a_run_whose_recorded_source_cannot_be_read_are_refused() {
let project = Project::cart("affected-unreadable");
let run = project.measure(&[]);
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&run)
.join("source-manifest.cache.json"),
)
.unwrap();
let refused = project.supercov_with(
&["runs", "latest", "tests", "affected"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.read_from#evidence_archive.rs:677",
)],
);
let said = refused.stderr();
assert_eq!(refused.code(), 2, "{said}");
assert!(fired_at(&said, "evidence_archive.rs:677"), "{said}");
}
/// Quality snapshots are read as far as they hold: a catalog entry or finding
/// that names no check, a file with no path, health or size, a finding one
/// snapshot has that the other does not answer, a file not in the snapshot,
/// a snapshot with no files, and a file record that is no list.
#[test]
fn quality_snapshots_are_read_as_far_as_they_hold() {
let project = Project::empty("quality-snapshots");
project.git(&["init", "-q"]);
let gaps = project.supercov(&["quality", "gaps"]).exits(2);
assert!(gaps.contains("no quality snapshot here yet"), "{gaps}");
let snapshot = |id: &str, files: serde_json::Value| {
let directory = format!(".supercov/quality/snapshots/{id}");
project.write(
&format!("{directory}/manifest.json"),
&serde_json::json!({
"created_at": format!("2026-01-01T00-00-0{}-000000Z", &id[id.len() - 1..]),
"instrument": "catalog",
"catalog_version": "v1",
"model": "m",
"catalog": [{"name": "unnamed"}, {"check": "c1", "name": "one"}],
})
.to_string(),
);
project.write(
&format!("{directory}/files.json"),
&serde_json::json!({ "files": files }).to_string(),
);
};
snapshot(
"q_0000000000000001",
serde_json::json!([
{"path": "a.js", "status": "completed", "health": 5.0, "bytes": 10,
"present": [{"value": 0.9}, {"check": "c1", "value": 0.9}],
"checks": {"c1": 0.9}},
{"path": 7, "status": "completed"},
{"path": "b.js", "status": "completed", "health": 4.0},
]),
);
snapshot(
"q_0000000000000002",
serde_json::json!([
{"path": "a.js", "status": "completed", "health": 6.0, "bytes": 10},
{"path": "c.js", "status": "completed", "health": 7.0, "bytes": 5},
]),
);
snapshot("q_0000000000000003", serde_json::json!([]));
let file = project
.supercov(&["quality", "file", "a.js", "q_0000000000000001"])
.succeeds();
assert!(file.contains("a.js"), "{file}");
let missing = project
.supercov(&["quality", "file", "z.js", "q_0000000000000001"])
.exits(2);
assert!(missing.contains("z.js is not in snapshot"), "{missing}");
let diff = project
.supercov(&[
"quality",
"diff",
"q_0000000000000001",
"q_0000000000000002",
])
.succeeds();
assert!(diff.contains("c.js"), "{diff}");
project
.supercov(&[
"quality",
"diff",
"q_0000000000000001",
"q_0000000000000003",
])
.succeeds();
project.write(
".supercov/quality/snapshots/q_0000000000000003/files.json",
r#"{"files": "none"}"#,
);
let invalid = project
.supercov(&["quality", "gaps", "q_0000000000000003"])
.exits(2);
assert!(
invalid.contains("invalid snapshot file record"),
"{invalid}"
);
}
/// A query names its run by position or `--run`; an option missing its value,
/// a diff missing a run, a run that is not there, and a store of runs that
/// cannot be listed are refused, each saying why.
#[test]
fn query_options_and_runs_are_read_or_refused_by_name() {
let project = Project::cart("query-options");
project.measure(&[]);
let named = project
.supercov(&["runs", "latest", "files", "--run", "latest"])
.succeeds();
assert!(named.contains("src/cart.js"), "{named}");
for (args, said) in [
(
&["runs", "latest", "files", "--run"][..],
"--run requires a run ID",
),
(
&["runs", "latest", "files", "--limit"][..],
"--limit must be a number",
),
(
&["diff"][..],
"Usage: supercov diff <older-run> <newer-run>",
),
(
&["diff", "latest"][..],
"Usage: supercov diff <older-run> <newer-run>",
),
(
&["runs", "nosuch", "tests", "affected"][..],
"coverage run not found: nosuch",
),
] {
let refused = project.supercov(args).exits(2);
assert!(refused.contains(said), "{args:?}: {refused}");
}
let unlisted = project
.supercov_with(
&["runs", "latest", "tests", "affected"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695")],
)
.exits(2);
assert!(unlisted.contains("run_store.rs:695"), "{unlisted}");
// So is a file's source asked of a store that cannot be listed.
let unlisted = project
.supercov_with(
&["runs", "latest", "source", "src/cart.js"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695")],
)
.exits(2);
assert!(unlisted.contains("run_store.rs:695"), "{unlisted}");
// A run whose entry in the store cannot be read is left out of the list.
let rejected = project
.supercov_with(
&["runs"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir entry#run_store.rs:695")],
)
.succeeds();
assert!(rejected.contains("showing 0-0 of 0"), "{rejected}");
}
/// A test whose file is gone since the run is affected, and says why.
#[test]
fn a_test_whose_file_was_removed_is_affected() {
let project = Project::cart("test-removed");
project.write(
"test/more.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\ntest(\"total of nothing\", () => assert.equal(total([]), 0));\n",
);
project.commit("more");
project.measure(&[]);
std::fs::remove_file(project.root.join("test/more.test.js")).unwrap();
let affected = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&affected,
&["test/more.test.js › total of nothing", "test file removed"],
);
}
/// `tests affected` reads only the tests a filter picks, as every query does:
/// a merged run's names for one runner, or only some of the affected tests.
#[test]
fn tests_affected_narrows_to_the_tests_a_filter_picks() {
let project = Project::cart("affected-filter");
project.measure(&[]);
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let picked = project
.supercov(&["runs", "latest", "tests", "affected", "--title", "shipping"])
.succeeds();
contains_all(
&picked,
&[
"1 of 1 test affected",
"(--title shipping)",
"shipping is free over fifty",
],
);
let others = project
.supercov(&[
"runs",
"latest",
"tests",
"affected",
"--names",
"--title",
"!shipping",
])
.succeeds();
assert_eq!(others.trim(), "", "only the shipping test was affected");
let json = project
.supercov(&[
"runs",
"latest",
"tests",
"affected",
"--json",
"--runner",
"node:test",
])
.json();
assert_eq!(json["data"]["summary"]["tests"], 3, "{json}");
assert_eq!(json["data"]["filter"], "--runner node:test");
let none = project
.supercov(&["runs", "latest", "tests", "affected", "--runner", "jest"])
.exits(2);
assert!(none.contains("No tests match --runner jest"), "{none}");
let missing = project
.supercov(&["runs", "latest", "tests", "affected", "--tag"])
.exits(2);
assert!(missing.contains("--tag needs a value"), "{missing}");
// A merged run answers from its parts: each kind's affected tests alone.
let project = Project::cart("affected-filter-merged");
project
.supercov_with(
&["--", "node", "--test", "--test-name-pattern=total"],
&[("SUPERCOV_TEST_KIND", "unit")],
)
.succeeds();
let unit = project.latest();
project
.supercov_with(
&["--", "node", "--test", "--test-name-pattern=shipping"],
&[("SUPERCOV_TEST_KIND", "e2e")],
)
.succeeds();
let e2e = project.latest();
project.supercov(&["merge", &unit, &e2e]).succeeds();
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let e2e_names = project
.supercov(&[
"runs", "latest", "tests", "affected", "--names", "--kind", "e2e",
])
.succeeds();
assert_eq!(e2e_names.trim(), "shipping is free over fifty");
let unit_names = project
.supercov(&[
"runs", "latest", "tests", "affected", "--names", "--kind", "unit",
])
.succeeds();
assert_eq!(unit_names.trim(), "", "no unit test ran the changed line");
}
/// Node's module mocks keep the CJS resolver they find when node:test first
/// loads. A preload the command gives (`--import tsx`, which maps tsconfig
/// paths by patching it) comes after Supercov's own, so the adapter must not
/// load node:test before the command's preloads have run.
#[test]
fn a_mocking_test_resolves_paths_a_later_preload_maps() {
let project = Project::empty("mock-paths");
project.write(
"package.json",
r#"{ "name": "mock-paths", "private": true }"#,
);
project.write(
"alias.mjs",
"import Module from 'node:module';\nimport path from 'node:path';\nconst resolve = Module._resolveFilename;\nModule._resolveFilename = function (request, ...rest) {\n if (request.startsWith('@/')) request = path.resolve('src', request.slice(2));\n return resolve.call(this, request, ...rest);\n};\n",
);
project.write(
"src/lib/log.js",
"exports.log = (line) => (line ? `log: ${line}` : 'empty');\n",
);
project.write("src/clock.js", "exports.now = () => Date.now();\n");
project.write(
"src/app.js",
"const { log } = require('@/lib/log');\nconst { now } = require('./clock');\nexports.stamp = (line) => `${log(line)} at ${now()}`;\n",
);
project.write(
"test/app.test.js",
"const { mock, test } = require('node:test');\nconst assert = require('node:assert/strict');\nmock.module('../src/clock.js', { namedExports: { now: () => 7 } });\ntest('stamps a line', () => {\n const { stamp } = require('../src/app.js');\n assert.equal(stamp('a'), 'log: a at 7');\n});\n",
);
let command = [
"node",
"--import",
"./alias.mjs",
"--experimental-test-module-mocks",
"--test",
"test/app.test.js",
];
let plain = std::process::Command::new(command[0])
.args(&command[1..])
.current_dir(&project.root)
.output()
.unwrap();
assert!(
plain.status.success(),
"{}",
String::from_utf8_lossy(&plain.stdout)
);
let measured = project
.supercov(&[&["--"][..], &command].concat())
.succeeds();
assert!(measured.contains("pass 1"), "{measured}");
assert!(!measured.contains("Cannot find module"), "{measured}");
}
#[test]
fn diff_and_tests_affected_follow_a_change() {
let project = Project::cart("change");
let before = project.measure(&[]);
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let affected = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&affected,
&[
"1 of 3 tests affected",
"shipping is free over fifty",
"shipping (line 12) changed (this test ran it)",
],
);
let names = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert_eq!(names.trim(), "shipping is free over fifty");
project.edit(
"test/cart.test.js",
"test(\"shipping is free over fifty\"",
"test(\"express shipping costs twenty\", () => {\n assert.equal(shipping(10, true), 20);\n});\n\ntest(\"shipping is free over fifty\"",
);
let after = project.measure(&[]);
let diff = project.supercov(&["diff", &before, &after]).succeeds();
contains_all(
&diff,
&[
"lines +7.7pp, branches +25pp, MC/DC +20pp",
"+ line src/cart.js:14",
"+ MC/DC src/cart.js:13 C1 express",
],
);
let listed = project.supercov(&["runs"]).succeeds();
assert!(listed.contains("STALE"), "{listed}");
}
/// A merge whose store of runs or a shard's evidence cannot be read is
/// refused, naming it; one that cannot release its lock after merging says
/// so.
#[test]
fn a_merge_of_two_shards_whose_read_or_release_fails_says_so() {
let project = Project::cart("merge-steps");
let first = project.measure(&["--test-name-pattern=total"]);
let second = project.measure(&["--test-name-pattern=shipping"]);
for (fault, said) in [
(
"fs.read_dir#run_store.rs:695",
"Cannot read local coverage runs",
),
(
"fs.read_from#evidence_archive.rs:677",
"Cannot merge coverage run",
),
("copy-release", "Could not release merge lock"),
] {
let refused = project.supercov_with(
&["merge", &first, &second],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let output = format!("{}{}", refused.stdout(), refused.stderr());
assert_ne!(refused.code(), 0, "{fault}: {output}");
assert!(output.contains(said), "{fault}: {output}");
}
}
/// Whether an import only types use is a line to run is the project's
/// tsconfig's to say, not the command's: on 2026-11-06 a unit run and an
/// end-to-end run (`node --import tsx …`) of one commit counted
/// `import { type Funnel }` differently and could not be merged. Here one
/// run's command is a `tsx` the old check took for the compiler.
#[cfg(unix)]
#[test]
fn runs_of_two_commands_count_a_type_only_import_alike_and_merge() {
let project = Project::empty("type-import-merge");
project.write(
"package.json",
r#"{ "name": "rates", "private": true, "type": "module" }"#,
);
// Read as JSON with comments: a quote in a comment, an escape in a string.
project.write(
"tsconfig.json",
r#"{
// keeps "strict" on
"compilerOptions": { "strict": true, "rootDir": ".\\" }
}
"#,
);
project.write(
"src/rate.ts",
"export type Rate = { cents: number };\nexport const zero = 0;\n",
);
project.write(
"src/price.ts",
r#"import { type Rate } from "./rate.ts";
export function price(rate: Rate, discount: boolean): number {
return discount ? rate.cents - 1 : rate.cents;
}
"#,
);
project.write(
"test/price.test.ts",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { price } from "../src/price.ts";
test("full price", () => assert.equal(price({ cents: 5 }, false), 5));
test("discount", () => assert.equal(price({ cents: 5 }, true), 4));
"#,
);
project.write_script("tsx", "#!/bin/sh\nexec node --test \"$@\"\n");
project.git(&["init", "-q"]);
project.commit("rates");
project
.supercov(&["--", "node", "--test", "--test-name-pattern=full"])
.succeeds();
let unit = project.latest();
project
.supercov(&["--", "./tsx", "--test-name-pattern=discount"])
.succeeds();
let e2e = project.latest();
let lines = |run: &str| {
project.supercov(&["runs", run, "--json"]).json()["data"]["coverage"]["lines"]["total"]
.clone()
};
// The import is no line to run under either command.
assert_eq!(lines(&unit), 3);
assert_eq!(lines(&e2e), 3);
let merged = project.supercov(&["merge", &unit, &e2e]).exits(0);
assert!(merged.contains("merged run"), "{merged}");
}
#[test]
fn shards_merge_into_one_run_and_mismatched_ones_do_not() {
let project = Project::cart("merge");
let first = project.measure(&["--test-name-pattern=total"]);
let second = project.measure(&["--test-name-pattern=shipping"]);
let merged = project.supercov(&["merge", &first, &second]).exits(0);
assert!(merged.contains("merged run"), "{merged}");
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"command: supercov merge",
"Lines 76.92% (10/13)",
"Passed 3",
],
);
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let third = project.measure(&["--test-name-pattern=shipping"]);
let refused = project.supercov(&["merge", &first, &third]);
assert_ne!(
refused.code(),
0,
"a merge across source changes is refused"
);
// The merged run outlives the runs it was made of, and is still listed
// and read by its own command.
project
.supercov(&["runs", "clean", "--keep", "2"])
.succeeds();
let listed = project.supercov(&["runs", "--json"]).json();
let commands = listed["data"]["runs"]
.as_array()
.unwrap()
.iter()
.map(|run| run["command"][1].as_str().unwrap_or_default().to_owned())
.collect::<Vec<_>>();
assert!(commands.contains(&"merge".to_owned()), "{listed}");
}
#[test]
fn clean_removes_runs_and_keeps_what_it_is_told_to() {
let project = Project::cart("clean");
let oldest = project.measure(&["--test-name-pattern=total"]);
let newest = project.measure(&["--test-name-pattern=shipping"]);
let dry = project.supercov(&["runs", "clean", "--dry-run"]).exits(0);
contains_all(&dry, &["would remove 2 stored run(s)", &oldest, &newest]);
assert!(project.supercov(&["runs"]).succeeds().contains(&oldest));
let kept = project.supercov(&["runs", "clean", "--keep", "1"]).exits(0);
assert!(kept.contains("removed 1 stored run(s)"), "{kept}");
let listed = project.supercov(&["runs"]).succeeds();
assert!(
listed.contains(&newest) && !listed.contains(&oldest),
"{listed}"
);
project.supercov(&["runs", "clean"]).exits(0);
let empty = project.supercov(&["runs", "latest"]).exits(2);
assert!(empty.contains("No local coverage runs"), "{empty}");
}
/// The `--` in front of a test command does not always reach the binary:
/// Bun drops a leading one (#209), Yarn 1 the one in `yarn supercov --`, and
/// PowerShell the first on its way into a package manager's `.ps1` shim, so
/// `supercov -- bun test` arrived as `supercov bun test`. A first word that is
/// no command of Supercov's but a program is measured as the test command,
/// also right after `--exact-attribution`; Supercov's own commands keep their
/// meaning, and a word that starts nothing is still a mistake that records
/// nothing.
#[test]
fn a_test_command_whose_separator_was_lost_is_measured() {
let project = Project::cart("separator lost");
let runs = || {
let listed = project.supercov(&["runs", "--json"]);
if listed.code() != 0 {
return 0;
}
listed.json()["data"]["runs"].as_array().map_or(0, Vec::len)
};
assert_eq!(runs(), 0);
project.supercov(&["node", "--test"]).succeeds();
assert_eq!(runs(), 1);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Passed 3", "Lines"]);
project
.supercov(&["--exact-attribution", "node", "--test"])
.succeeds();
assert_eq!(runs(), 2);
let exact = project.supercov(&["runs", "latest"]).succeeds();
assert!(exact.contains("Exact for 3 test(s)"), "{exact}");
// The separator, when it does arrive, is read as always.
project.supercov(&["--", "node", "--test"]).succeeds();
project
.supercov(&["--exact-attribution", "--", "node", "--test"])
.succeeds();
assert_eq!(runs(), 4);
// A path to a program is one too.
let node = std::process::Command::new("node")
.args(["-p", "process.execPath"])
.output()
.unwrap();
let node = String::from_utf8(node.stdout).unwrap().trim().to_owned();
project.supercov(&[&node, "--test"]).succeeds();
assert_eq!(runs(), 5);
// Supercov's own commands win; a word that is no program, or is not a
// file that can be run, is refused and measures nothing.
let listed = project.supercov(&["runs"]).succeeds();
assert!(listed.contains("run_"), "{listed}");
for args in [
vec!["frobnicate"],
vec!["frobnicate", "--test"],
vec!["package.json"],
vec!["src"],
] {
let refused = project.supercov(&args).exits(2);
assert!(
refused.contains(&format!("Unknown command: {}", args[0])),
"{args:?}: {refused}"
);
}
let flagged = project
.supercov(&["--exact-attribution", "frobnicate"])
.exits(2);
assert!(
flagged.contains("--exact-attribution goes before"),
"{flagged}"
);
assert_eq!(runs(), 5);
}
#[test]
fn mistakes_are_named_and_end_with_two() {
let project = Project::cart("mistakes");
for (args, message) in [
(vec!["runs", "latest"], "No local coverage runs"),
(
vec!["runs", "check", "--min-lines", "10"],
"no local coverage runs",
),
(vec!["frobnicate"], "Unknown command: frobnicate"),
(vec!["--"], "Usage: supercov -- <test command>"),
] {
let output = project.supercov(&args).exits(2);
assert!(output.contains(message), "{args:?}: {output}");
}
project.measure(&[]);
for (args, message) in [
(vec!["runs", "latest", "bogus"], "Unknown run query: bogus"),
(vec!["runs", "run_0000000000000000"], "run_0000000000000000"),
(
vec!["runs", "latest", "minimize", "--target-lines", "70"],
"Unknown option: --target-lines",
),
(
vec!["runs", "latest", "file", "src/missing.js"],
"src/missing.js",
),
(
vec!["runs", "latest", "line", "src/cart.js"],
"Expected <source-file>:<line>",
),
(vec!["runs", "--nonsense"], "Unknown option: --nonsense"),
] {
let output = project.supercov(&args);
assert_ne!(output.code(), 0, "{args:?}");
let text = format!("{}{}", output.stdout(), output.stderr());
assert!(text.contains(message), "{args:?}: {text}");
}
let json = project.supercov(&["runs", "latest", "bogus", "--json"]);
assert_ne!(json.code(), 0);
}
/// A command started in a directory deleted under the shell has no project
/// to work in, and each says so instead of acting somewhere else. Linux's
/// `getcwd` refuses a removed directory; macOS may still name it.
#[cfg(target_os = "linux")]
#[test]
fn a_command_whose_directory_is_gone_says_so() {
let parent = std::env::temp_dir().join(format!("supercov-gone-{}", std::process::id()));
std::fs::create_dir_all(&parent).unwrap();
for arguments in [
&["merge"][..],
&["import", "evidence.lcov", "--background"],
&["--", "true"],
&["runs", "clean"],
&["__supervise", "--", "true"],
] {
let gone = parent.join("gone");
std::fs::create_dir_all(&gone).unwrap();
// `cd` into it, remove it, then become Supercov there.
let output = std::process::Command::new("sh")
.arg("-c")
.arg(r#"cd "$1" && rmdir "$1" && shift && exec "$@""#)
.arg("sh")
.arg(&gone)
.arg(env!("CARGO_BIN_EXE_supercov"))
.args(arguments)
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}");
assert!(
stderr.contains("could not resolve the current directory"),
"{arguments:?}: {stderr}"
);
}
std::fs::remove_dir_all(parent).unwrap();
}
#[test]
fn help_and_bundled_guides_need_no_project() {
let project = Project::empty("help");
for args in [
vec!["help"],
vec!["--help"],
vec!["runs", "--help"],
vec!["report", "--help"],
vec!["runs", "latest", "--help"],
] {
let help = project.supercov(&args).succeeds();
assert!(help.contains("supercov"), "{args:?}: {help}");
}
// `help <command>` is `<command> --help`, for every command.
for command in [
"quality", "security", "docs", "runs", "diff", "report", "merge", "import",
] {
let help = project.supercov(&["help", command]).succeeds();
assert_eq!(
help,
project.supercov(&[command, "--help"]).succeeds(),
"{command}"
);
}
let unknown = project.supercov(&["help", "fly"]).exits(2);
assert!(unknown.contains("No help for fly"), "{unknown}");
let guides = project.supercov(&["docs"]).succeeds();
contains_all(
&guides,
&["Bundled guides", "getting-started", "assertions", "cli"],
);
let guide = project.supercov(&["docs", "assertions"]).succeeds();
assert!(guide.starts_with("# Assertion coverage"), "{guide}");
// Every guide listed is in the binary: an installed one has no
// repository to read a missing one from.
for topic in guides.lines().skip(1).map(str::trim) {
let guide = project.supercov(&["docs", topic]).succeeds();
assert!(guide.starts_with("# "), "{topic}: {guide}");
}
let missing = project.supercov(&["docs", "no-such-guide"]);
assert_ne!(missing.code(), 0);
let version = project.supercov(&["--version"]).succeeds();
assert!(version.contains(env!("CARGO_PKG_VERSION")), "{version}");
// Every setting the CLI guide's table lists is named where people and
// agents look first.
let help = project.supercov(&["--help"]).succeeds();
let cli = project.supercov(&["docs", "cli"]).succeeds();
let table = cli
.split("## Environment variables")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.expect("the CLI guide lists its environment variables");
let settings = table
.lines()
.filter_map(|line| line.strip_prefix("| `"))
.filter_map(|line| line.split('`').next())
.collect::<Vec<_>>();
assert!(settings.len() >= 5, "{table}");
for setting in settings {
assert!(
help.contains(setting),
"{setting} is not in --help:\n{help}"
);
}
}
#[test]
fn every_way_of_importing_node_assert_is_credited_to_its_test() {
let project = Project::empty("assert-styles");
project.write(
"package.json",
r#"{ "name": "styles", "private": true, "type": "module" }"#,
);
project.write(
"src/lib.js",
"export function* evens(limit) {\n for (let n = 0; n < limit; n += 2) {\n yield n;\n }\n}\n\nexport const label = (value) => (value ? `on:${value}` : \"off\");\n",
);
project.write(
"test/default.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { evens } from \"../src/lib.js\";\ntest(\"default import\", () => {\n assert.deepStrictEqual([...evens(5)], [0, 2, 4]);\n assert.ok(true);\n});\n",
);
project.write(
"test/namespace.test.js",
"import test from \"node:test\";\nimport * as assert from \"node:assert/strict\";\nimport { label } from \"../src/lib.js\";\ntest(\"namespace import\", () => {\n assert.equal(label(\"x\"), \"on:x\");\n});\n",
);
project.write(
"test/named.test.js",
"import test from \"node:test\";\nimport { strict as assert, notEqual } from \"node:assert\";\nimport { equal, ok } from \"node:assert/strict\";\nimport { label } from \"../src/lib.js\";\ntest(\"named imports\", () => {\n equal(label(\"x\"), \"on:x\");\n ok(label(0) === \"off\");\n assert.match(label(\"y\"), /on/);\n notEqual(label(1), \"off\");\n});\n",
);
project.write(
"test/require.test.cjs",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert/strict\");\ntest(\"require\", async () => {\n const { label } = await import(\"../src/lib.js\");\n assert.strictEqual(label(\"\"), \"off\");\n});\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 4"), "{measured}");
for (test, assertions) in [
(
"default import",
&[
"node:assert.deepStrictEqual at test/default.test.js:5:3",
"node:assert.ok at test/default.test.js:6:3",
][..],
),
(
"namespace import",
&["node:assert/strict.equal at test/namespace.test.js:5:3"][..],
),
(
"named imports",
&[
"node:assert/strict.equal at test/named.test.js:6:3",
"node:assert/strict.ok at test/named.test.js:7:3",
"node:assert/strict.match at test/named.test.js:8:3",
"node:assert.notEqual at test/named.test.js:9:3",
][..],
),
(
"require",
&["node:assert/strict.strictEqual at test/require.test.cjs:5:3"][..],
),
] {
let read = project
.supercov(&["runs", "latest", "test", test])
.succeeds();
contains_all(&read, assertions);
}
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 100.00% (4/4)"), "{summary}");
}
#[test]
fn a_function_shipped_as_text_runs_where_no_probe_exists() {
// A function sent to a worker, a `vm` context or a browser page goes as
// its source text; a probe inside it names a global that is not there.
let project = Project::empty("shipped");
project.write(
"package.json",
r#"{ "name": "shipped", "private": true, "type": "module" }"#,
);
project.write(
"src/task.js",
"export function square(n) {\n if (n < 0) {\n throw new Error(\"negative\");\n }\n return n * n;\n}\nexport const cube = (n) => n * n * n;\nexport const shipped = [square.toString(), `${cube}`, String(square)];\nexport function local(flag) {\n return flag ? \"a\" : \"b\";\n}\n",
);
project.write(
"test/task.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport vm from \"node:vm\";\nimport { shipped, local } from \"../src/task.js\";\ntest(\"shipped functions run\", () => {\n assert.equal(vm.runInNewContext(`(${shipped[0]})(4)`), 16);\n assert.equal(vm.runInNewContext(`(${shipped[1]})(2)`), 8);\n assert.equal(vm.runInNewContext(`(${shipped[2]})(3)`), 9);\n assert.equal(local(true), \"a\");\n});\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 1"), "{measured}");
// What is left as source is declared, never silently uncovered.
let file = project
.supercov(&["runs", "latest", "file", "src/task.js"])
.succeeds();
assert!(file.contains("Measurement limitations 2"), "{file}");
let local = project
.supercov(&["runs", "latest", "line", "src/task.js:10"])
.succeeds();
assert!(!local.contains("NOT COVERED"), "{local}");
// A function reached by name through `+`, `||`, `?:` or an assignment
// is shipped as text too. A local of the same name read elsewhere is a
// different binding and leaves the function measured.
project.write(
"src/named.js",
"const worker = (n) => { if (n) { return 1; } return 0; };\nexport const joined = \"(\" + worker + \")\";\nconst fallback = (n) => { if (n) { return 2; } return 0; };\nexport const chosen = \"\" + (null || fallback);\nconst branch = (n) => { if (n) { return 3; } return 0; };\nexport const picked = String(Math.random() >= 0 ? branch : null);\nlet later;\nlater = (n) => { if (n) { return 4; } return 0; };\nexport const assigned = `${later}`;\nexport function total(n) {\n if (n > 1) {\n return n;\n }\n return 0;\n}\nexport function counter() {\n let total = 0;\n if (total < 5) total += 1;\n return total;\n}\n",
);
project.write(
"test/named.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport vm from \"node:vm\";\nimport { joined, chosen, picked, assigned, total, counter } from \"../src/named.js\";\ntest(\"named functions run as text\", () => {\n assert.equal(vm.runInNewContext(`${joined}(1)`), 1);\n assert.equal(vm.runInNewContext(`(${chosen})(1)`), 2);\n assert.equal(vm.runInNewContext(`(${picked})(1)`), 3);\n assert.equal(vm.runInNewContext(`(${assigned})(1)`), 4);\n assert.equal(total(2), 2);\n assert.equal(counter(), 1);\n});\n",
);
let measured = project
.supercov(&["--", "node", "--test", "test/named.test.js"])
.succeeds();
assert!(measured.contains("pass 1"), "{measured}");
let named = project
.supercov(&["runs", "latest", "file", "src/named.js"])
.succeeds();
assert!(
named.contains("Measurement limitations 4"),
"{named}"
);
assert!(named.contains(" 14 NOT COVERED return 0;"), "{named}");
}
#[test]
fn every_subcommand_explains_itself_and_names_a_mistake() {
let project = Project::cart("usage");
project.measure(&[]);
for (args, help) in [
(vec!["runs", "check", "--help"], "check [--min-lines <pct>]"),
(vec!["runs", "patch", "--help"], "patch --base <ref>"),
(
vec!["runs", "report", "--help"],
"--format lcov|cobertura|istanbul|istanbul-summary|clover|jacoco|sonar|html",
),
(
vec!["merge", "--help"],
"With no run named, merges the runs recorded on the source as it is now",
),
(
vec!["runs", "clean", "--help"],
"Saved quality assessments are never removed here",
),
] {
let output = project.supercov(&args).succeeds();
assert!(output.contains(help), "{args:?}: {output}");
}
for (args, message) in [
(
vec!["runs", "check", "--min-foo", "3"],
"unknown metric in --min-foo",
),
(
vec!["runs", "check", "--min-lines"],
"--min-lines needs a percentage",
),
(vec!["runs", "check", "--bogus"], "unknown option --bogus"),
(vec!["runs", "patch"], "patch needs --base <ref>"),
(vec!["runs", "patch", "--base"], "--base needs a value"),
(
vec!["runs", "patch", "--base", "HEAD", "--min-lines", "x"],
"is not a percentage",
),
(
vec!["runs", "patch", "--base", "HEAD", "--annotate", "gitlab"],
"--annotate only supports github",
),
(
vec!["runs", "patch", "--base", "HEAD", "--max-annotations", "x"],
"--max-annotations needs a whole number",
),
(
vec!["runs", "patch", "--base", "HEAD", "--bogus"],
"unknown option --bogus",
),
(vec!["runs", "report"], "report needs --format"),
(vec!["runs", "report", "--format"], "--format needs a value"),
(
vec!["runs", "report", "--format", "pdf"],
"unknown format pdf",
),
(vec!["runs", "report", "--bogus"], "unknown option --bogus"),
(
vec!["merge", "run_0000000000000001"],
"Usage: supercov merge",
),
(
vec!["merge", "run_0000000000000001", "run_0000000000000002"],
"run_0000000000000001: no such local run",
),
(
vec!["runs", "clean", "--keep", "x"],
"--keep must be a non-negative integer",
),
(
vec!["runs", "clean", "--bogus"],
"Unknown clean option: --bogus",
),
(
vec!["docs", "cli", "assertions"],
"docs accepts at most one topic",
),
(vec!["docs", "nosuch"], "unknown guide \"nosuch\""),
] {
let output = project.supercov(&args).exits(2);
assert!(output.contains(message), "{args:?}: {output}");
}
}
#[test]
fn a_command_supercov_cannot_measure_is_refused_with_the_reason() {
let empty = Project::empty("unknown");
let unknown = empty.supercov(&["--", "make", "test"]).exits(2);
assert!(
unknown.contains("could not recognize this project's language or test framework"),
"{unknown}"
);
let runner = empty.supercov(&["--", "phpunit"]).exits(2);
assert!(
runner.contains("This looks like a PHP test run (the test command runs `phpunit`)"),
"{runner}"
);
empty.write("composer.json", "{}");
let project = empty.supercov(&["--", "make", "test"]).exits(2);
assert!(
project.contains("This looks like a PHP project (composer.json is present)"),
"{project}"
);
let polyglot = empty
.supercov(&["--", "sh", "-c", "node --test && cargo test"])
.exits(2);
assert!(
polyglot.contains("launches multiple language frontends (javascript, rust)"),
"{polyglot}"
);
}
#[test]
fn a_per_file_floor_names_where_a_file_falls_short() {
let project = Project::cart("per-file");
let mut untested = String::from("export function untested(kind) {\n");
for n in 0..14 {
untested.push_str(&format!(" if (kind === {n}) {{ return {n}; }}\n"));
}
untested.push_str(" return -1;\n}\n");
project.write("src/untested.js", &untested);
project.measure(&[]);
let failed = project
.supercov(&["runs", "check", "--min-lines", "50", "--per-file"])
.exits(1);
contains_all(
&failed,
&[
"src/untested.js: lines 0.00% 0/16 below 50%",
"uncovered lines: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 6 more",
],
);
assert!(!failed.contains("src/cart.js: lines"), "{failed}");
}
#[test]
fn a_platform_gated_item_counts_only_where_it_compiles() {
let project = Project::empty("cfg");
project.write(
"Cargo.toml",
"[package]\nname = \"platform\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[features]\nextra = []\n",
);
project.write(
"src/lib.rs",
"pub fn platform() -> &'static str {\n native()\n}\n\n#[cfg(unix)]\nfn native() -> &'static str {\n \"unix\"\n}\n\n#[cfg(windows)]\nfn native() -> &'static str {\n \"windows\"\n}\n\n#[cfg(feature = \"extra\")]\npub fn extra() -> u32 {\n 1\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn names_the_platform() {\n assert!(!super::platform().is_empty());\n }\n}\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "cargo", "test"]);
measured.succeeds();
// The variant this host compiles is measured and covered; the other one
// no test here could ever reach, and it is not counted.
let (built, absent) = if cfg!(windows) { (11, 6) } else { (6, 11) };
let covered = project
.supercov(&["runs", "latest", "line", &format!("src/lib.rs:{built}")])
.succeeds();
assert!(
covered.contains("COVERED") && !covered.contains("NOT COVERED"),
"{covered}"
);
let gaps = project
.supercov(&["runs", "latest", "file", "src/lib.rs", "--json"])
.json();
let lines = gaps["data"]["gapLines"]
.as_array()
.unwrap()
.iter()
.map(|line| line["line"].as_u64().unwrap())
.collect::<Vec<_>>();
// A feature is not the target's to settle; the build settles it. This
// one was off, so `extra` was never compiled and is not counted either.
assert!(lines.is_empty(), "{gaps}");
assert!(
measured.stderr().contains(
"1 item(s) behind a #[cfg] no build compiled are outside the denominator: src/lib.rs:15 cfg(feature = \"extra\")"
),
"{}",
measured.stderr()
);
// Built with the feature, it is code no test runs.
project
.supercov(&["--", "cargo", "test", "--features", "extra"])
.succeeds();
let gaps = project
.supercov(&["runs", "latest", "file", "src/lib.rs", "--json"])
.json();
let lines = gaps["data"]["gapLines"]
.as_array()
.unwrap()
.iter()
.map(|line| line["line"].as_u64().unwrap())
.collect::<Vec<_>>();
assert_eq!(lines, [16, 17], "{gaps}");
assert!(!lines.contains(&absent));
}
#[test]
fn a_closure_in_a_static_is_measured_and_a_const_block_is_declined_in_a_counted_file() {
let project = Project::empty("const-contexts");
project.write(
"Cargo.toml",
"[package]\nname = \"contexts\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"use std::sync::LazyLock;\n\npub static WORD: LazyLock<String> = LazyLock::new(|| {\n let word = \"hi\";\n word.to_uppercase()\n});\n\npub const LIMIT: u32 = { 2 + 1 };\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn reads_both() {\n assert_eq!(*super::WORD, \"HI\");\n assert_eq!(super::LIMIT, 3);\n }\n}\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "cargo", "test"]).succeeds();
// The closure runs at run time, and its test ran it.
let line = project
.supercov(&["runs", "latest", "line", "src/lib.rs:4"])
.succeeds();
assert!(
line.contains("COVERED") && !line.contains("NOT COVERED"),
"{line}"
);
// The const block is the compiler's: declined, so a floor cannot be
// judged, and the file holding it is counted, not outside the roots.
let check = project.supercov(&["runs", "latest", "check", "--min-lines", "100"]);
let out = check.exits(2);
assert!(
out.contains("lines left 1 obligation(s) unmeasured"),
"{out}{}",
check.stderr()
);
assert!(!out.contains("outside the source roots"), "{out}");
}
#[test]
fn a_crate_with_no_library_runs_its_tests_and_no_doctests() {
// A Worker or a plugin: `cargo test` runs its unit tests and, since a
// cdylib cannot have doctests, none of those. `--doc` alone is Cargo's
// own error.
let project = Project::empty("cdylib");
project.write(
"Cargo.toml",
"[package]\nname = \"plugin\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n",
);
project.write(
"src/lib.rs",
"pub fn double(value: u32) -> u32 {\n value * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.git(&["init", "-q"]);
let output = project.supercov(&["--", "cargo", "test"]).succeeds();
assert!(output.contains("1 passed"), "{output}");
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Lines 100.00% (2/2)", "Passed 1"]);
let doc = project.supercov(&["--", "cargo", "test", "--doc"]).exits(1);
assert!(doc.contains("no library targets found"), "{doc}");
// A crate that is only a binary has no library to doctest either.
let binary = Project::empty("bin-only");
binary.write(
"Cargo.toml",
"[package]\nname = \"tool\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
binary.write(
"src/main.rs",
"fn double(value: u32) -> u32 {\n value * 2\n}\n\nfn main() {\n println!(\"{}\", double(2));\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
binary.git(&["init", "-q"]);
let output = binary.supercov(&["--", "cargo", "test"]).succeeds();
assert!(output.contains("1 passed"), "{output}");
}
#[test]
fn a_run_of_two_test_kinds_narrows_pages_and_groups() {
let project = Project::cart("views");
project.write(
"src/tax.js",
"export function tax(c) {\n return c === \"LT\" || c === \"LV\" ? 0.21 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { tax } from \"../src/tax.js\";\ntest(\"tax in LT\", () => { assert.equal(tax(\"LT\"), 0.21); });\n",
);
project.commit("tax");
project
.supercov_with(
&["--", "node", "--test", "test/cart.test.js"],
&[("SUPERCOV_TEST_KIND", "unit")],
)
.succeeds();
let unit = project.latest();
project
.supercov_with(
&["--", "node", "--test", "test/tax.test.js"],
&[("SUPERCOV_TEST_KIND", "e2e")],
)
.succeeds();
let e2e = project.latest();
project.supercov(&["merge", &unit, &e2e]).exits(0);
let kinds = project.supercov(&["runs", "latest", "kinds"]).succeeds();
contains_all(&kinds, &["e2e 1 test(s)", "unit 3 test(s)"]);
let narrowed = project
.supercov(&["runs", "latest", "gaps", "--kind", "e2e"])
.succeeds();
contains_all(
&narrowed,
&[
"Projection: kind e2e",
"[covered elsewhere: 25; nowhere: 15]",
"file --kind 'e2e'",
],
);
let runner = project
.supercov(&[
"runs",
"latest",
"files",
"--runner",
"node:test",
"--limit",
"1",
])
.succeeds();
contains_all(
&runner,
&["showing 1-1 of 2", "next page:", "--offset 1 --limit 1"],
);
let second = project
.supercov(&["runs", "latest", "files", "--offset", "1", "--limit", "1"])
.succeeds();
assert!(second.contains("showing 2-2 of 2"), "{second}");
let grouped = project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--sort",
"missing",
])
.succeeds();
contains_all(
&grouped,
&[
"MC/DC by decision",
"decisions 3, with missing conditions 3",
"missing 2/2 express || sum < 50",
],
);
let refused = project
.supercov(&["runs", "latest", "file", "src/cart.js", "--sort", "missing"])
.exits(2);
assert!(
refused.contains("--sort requires --group decision"),
"{refused}"
);
let decision = project
.supercov(&[
"runs",
"latest",
"decision",
"src/tax.js:2",
"--kind",
"e2e",
])
.succeeds();
contains_all(&decision, &["C2 MISSING: c === \"LV\"", "T- -> T tests=1"]);
let line = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:13",
"--kind",
"unit",
"--limit",
"1",
])
.succeeds();
assert!(line.contains("PARTIAL"), "{line}");
// Directories, the summary and a file's decisions narrow to one kind or
// runner, and a filter no test matches is refused.
for (args, expected) in [
(
&["runs", "latest", "files", "--group", "dir", "--kind", "e2e"][..],
&[
"Coverage by directory, 1 deep — kind e2e",
"src 2 15 13.33%",
][..],
),
(
&[
"runs",
"latest",
"files",
"--group",
"dir",
"--runner",
"node:test",
],
&["— runner node:test", "src 2 15 80.00%"],
),
(
&["runs", "latest", "files", "--group", "dir"],
&[
"Lines e2e unit All",
"src 2 15 13.33% 66.67% 80.00%",
],
),
(
&["runs", "latest", "--kind", "e2e"],
&["(kind e2e)", "Lines 13.33% (2/15)", "Total 1"],
),
(
&["runs", "latest", "--runner", "node:test"],
&[
"(runner node:test)",
"Lines 80.00% (12/15)",
"Total 4",
],
),
(
&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--kind",
"e2e",
],
&["decisions 3, with missing conditions 3; conditions missing 5/5"],
),
] {
contains_all(&project.supercov(args).succeeds(), expected);
}
for args in [
&[
"runs",
"latest",
"files",
"--group",
"dir",
"--kind",
"integration",
][..],
&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--kind",
"integration",
],
] {
let refused = project.supercov(args).exits(2);
assert!(
refused.contains("No tests match kind=integration"),
"{refused}"
);
}
// After an edit, the summary says the run is stale.
project.edit("src/tax.js", "0.21", "0.2");
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(
summary.contains("[STALE: instrumented source changed"),
"{summary}"
);
}
#[test]
fn the_report_compares_two_runs_and_names_a_mistake() {
let project = Project::cart("report-compare");
let older = project.measure(&["--test-name-pattern=total"]);
let newer = project.measure(&[]);
let help = project.supercov(&["report", "--help"]).succeeds();
contains_all(&help, &["--compare <run-id>", "--no-open"]);
assert_eq!(project.supercov(&["report", "-h"]).succeeds(), help);
for (args, message) in [
(vec!["report", "--compare"], "--compare requires a run ID"),
(vec!["report", "--output"], "--output requires a path"),
(
vec!["report", "--output", ""],
"--output requires a non-empty path",
),
] {
let output = project.supercov(&args).exits(2);
assert!(output.contains(message), "{args:?}: {output}");
}
project
.supercov(&[
"report",
&newer,
"--compare",
&older,
"--runs",
"2",
"--output",
"compare.html",
"--no-open",
])
.exits(0);
// The page carries its data gzipped and base64-encoded, so it needs no
// server; both runs are in it.
let html = project.read("compare.html");
let encoded = html
.split(|character: char| !(character.is_ascii_alphanumeric() || "+/=".contains(character)))
.max_by_key(|run| run.len())
.unwrap();
use base64::Engine as _;
use std::io::Read as _;
let compressed = base64::engine::general_purpose::STANDARD
.decode(encoded)
.unwrap();
let mut payload = String::new();
flate2::read::GzDecoder::new(compressed.as_slice())
.read_to_string(&mut payload)
.unwrap();
assert!(
payload.contains(&older) && payload.contains(&newer),
"both runs are in the report"
);
let missing = project
.supercov(&[
"report",
&newer,
"--compare",
"run_0000000000000009",
"--no-open",
"--output",
"x.html",
])
.exits(2);
assert!(missing.contains("run_0000000000000009"), "{missing}");
}
/// A bug in Supercov's instrumenter, made to happen on a file
/// (`SUPERCOV_TEST_FAULT`), costs that file its measurement and nothing more:
/// it runs as written, the suite passes, and the run names the file and the
/// error to report.
#[test]
fn an_internal_error_instrumenting_a_file_leaves_it_unmeasured_and_said() {
let project = Project::cart("instrumenter-bug");
let fault = [("SUPERCOV_TEST_FAULT", "instrument-panic")];
let measured = project.supercov_with(&["--", "node", "--test"], &fault);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured.stdout().contains("pass 3"),
"{}",
measured.stdout()
);
assert!(
measured.stderr().contains("test fault at instrument-panic"),
"{}",
measured.stderr()
);
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:1"])
.succeeds();
contains_all(
&line,
&[
"NOT MEASURED",
"Supercov hit an internal error: injected fault at instrument-panic instrumenting this file, a bug to report",
],
);
// The same in Rust: the file compiles as written.
let project = Project::empty("instrumenter-bug-rust");
project.write(
"Cargo.toml",
"[package]\nname = \"p\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn half(x: i32) -> i32 { x / 2 }\n#[cfg(test)]\nmod tests { #[test] fn h() { assert_eq!(super::half(4), 2); } }\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov_with(&["--", "cargo", "test"], &fault);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured.stderr().contains("test fault at instrument-panic"),
"{}",
measured.stderr()
);
let line = project
.supercov(&["runs", "latest", "line", "src/lib.rs:1"])
.succeeds();
contains_all(
&line,
&[
"NOT MEASURED",
"Supercov hit an internal error: injected fault at instrument-panic instrumenting this file, a bug to report",
],
);
// A transform that no longer parses is refused by file, not compiled.
let refused = project.supercov_with(
&["--", "cargo", "test"],
&[("SUPERCOV_TEST_FAULT", "rust-unparsable-transform")],
);
assert_ne!(refused.code(), 0);
assert!(
refused.stderr().contains("src/lib.rs"),
"{}",
refused.stderr()
);
}
#[test]
fn a_source_file_that_does_not_parse_runs_as_written_and_is_declared() {
let project = Project::cart("unparsable");
project.write(
"src/broken.js",
"export function broken( {\n return 1;\n}\n",
);
// The suite never loads it, and passes with or without Supercov.
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 3"), "{measured}");
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Lines 76.92% (10/13)",
"Incomplete — 1 blocking limitation(s) in 1 file(s)",
],
);
let line = project
.supercov(&["runs", "latest", "line", "src/broken.js:1"])
.succeeds();
contains_all(
&line,
&[
"NOT MEASURED",
"Supercov could not parse this file (Expected `:` but found `decimal` at line 2, column 10)",
"(read from the current working tree)",
],
);
// A test file that does not parse fails in its runner, exactly as it
// does without Supercov.
project.write(
"test/broken.test.js",
"import test from \"node:test\";\ntest(\"broken\", () => {\n",
);
let plain = std::process::Command::new("node")
.args(["--test"])
.current_dir(&project.root)
.output()
.unwrap();
let under = project.supercov(&["--", "node", "--test"]);
assert_eq!(under.code(), plain.status.code().unwrap());
assert!(under.stdout().contains("fail 1"), "{}", under.stdout());
}
#[cfg(unix)]
#[test]
fn links_inside_the_project_are_carried_and_ones_leaving_it_are_not() {
use std::os::unix::fs::symlink;
let project = Project::cart("links");
let outside = Project::empty("links-outside");
outside.write("shared.js", "export const shared = 1;\n");
symlink(
outside.root.join("shared.js"),
project.root.join("src/escaping.js"),
)
.unwrap();
symlink("cart.js", project.root.join("src/alias.js")).unwrap();
symlink("nowhere.js", project.root.join("src/dangling.js")).unwrap();
std::fs::create_dir(project.root.join("data")).unwrap();
symlink("../src", project.root.join("data/sources")).unwrap();
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 3"), "{measured}");
let said = project.supercov(&["--", "node", "--test"]).stderr();
assert!(
said.contains("omitting symlink outside the isolated project"),
"{said}"
);
assert!(said.contains("src/escaping.js"), "{said}");
// The author's links are left as they were.
assert!(
std::fs::symlink_metadata(project.root.join("src/escaping.js"))
.unwrap()
.file_type()
.is_symlink()
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 76.92% (10/13)"), "{summary}");
}
#[cfg(unix)]
#[test]
fn a_store_that_is_a_link_elsewhere_is_refused() {
let project = Project::cart("store-link");
let elsewhere = Project::empty("store-elsewhere");
std::os::unix::fs::symlink(&elsewhere.root, project.root.join(".supercov")).unwrap();
let refused = project.supercov(&["--", "node", "--test"]);
assert_ne!(refused.code(), 0);
assert!(
refused.stderr().contains("unsafe Supercov storage path"),
"{}",
refused.stderr()
);
assert!(
std::fs::read_dir(&elsewhere.root).unwrap().next().is_none(),
"nothing written through the link"
);
}
#[test]
fn cargo_flags_the_build_owns_are_left_to_it_and_runs_with_no_test_are_refused() {
let project = Project::empty("cargo-flags");
project.write(
"Cargo.toml",
"[package]\nname = \"flags\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn double(x: u32) -> u32 {\n x * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.git(&["init", "-q"]);
// The build reads Cargo's JSON into its own target directory; a command
// asking for another format or directory still measures.
for flags in [
vec!["--message-format", "json"],
vec!["--message-format=short"],
vec!["--target-dir", "elsewhere"],
vec!["--target-dir=elsewhere"],
] {
let mut args = vec!["--", "cargo", "test"];
args.extend(flags.iter().copied());
let measured = project.supercov(&args).succeeds();
let said = format!(
"{measured}{}",
project.supercov(&["runs", "latest"]).succeeds()
);
assert!(
said.contains("Lines 100.00% (2/2)"),
"{flags:?}: {said}"
);
}
for (args, message) in [
(
vec!["--", "cargo", "test", "--no-run"],
"`--no-run` builds the tests without running any",
),
(
vec!["--", "cargo", "test", "--", "--list"],
"libtest --list does not execute a test suite",
),
(
vec!["--", "cargo", "bench"],
"requires `cargo test` or `cargo nextest run`",
),
] {
// Cargo quotes a refused argument in color when CI asks for it.
let refused = project.supercov_with(&args, &[("CARGO_TERM_COLOR", "never")]);
assert_ne!(refused.code(), 0, "{args:?}");
assert!(
refused.stderr().contains(message),
"{args:?}: {}",
refused.stderr()
);
}
}
#[test]
fn a_rust_command_supercov_cannot_select_tests_from_is_refused_with_why() {
let project = Project::empty("cargo-refusals");
project.write(
"Cargo.toml",
"[package]\nname = \"refusals\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn double(x: u32) -> u32 {\n x * 2\n}\n\npub fn half(x: u32) -> u32 {\n x / 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n\n #[test]\n fn halves() {\n assert_eq!(super::half(4), 2);\n }\n}\n",
);
project.write(
"package.json",
"{\"scripts\":{\"test\":\"cargo test 'unclosed\",\"chained\":\"cargo test && echo done\"}}\n",
);
project.git(&["init", "-q"]);
// A package script is expanded and split the way a shell would.
for (args, message) in [
(
vec!["--", "npm", "test"],
"contains an incomplete quote or escape",
),
(
vec!["--", "npm", "run", "chained"],
"the Cargo test command contains an unsupported shell boundary",
),
] {
// Cargo quotes a refused argument in color when CI asks for it.
let refused = project.supercov_with(&args, &[("CARGO_TERM_COLOR", "never")]);
assert_ne!(refused.code(), 0, "{args:?}");
assert!(
refused.stderr().contains(message),
"{args:?}: {}",
refused.stderr()
);
}
std::fs::remove_file(project.root.join("package.json")).unwrap();
for (args, message) in [
(
vec!["--", "sh", "-c", "cargo build && cargo test"],
"contains a shell boundary before `test`",
),
(
vec!["--", "make", "test"],
"does not expose a stable Cargo invocation",
),
(
vec!["--", "cargo", "test", "nextest", "run"],
"ambiguously contains both test and nextest run",
),
(
vec!["--", "cargo", "test", "--frobnicate"],
"does not recognize option --frobnicate",
),
(
vec!["--", "cargo", "test", "--package"],
"Cargo option --package has no value",
),
(
vec!["--", "cargo", "test", "--doc", "--lib"],
"--doc cannot be combined with another explicit target selection",
),
(
vec!["--", "cargo", "test", "doubles", "halves"],
"unexpected argument 'halves' found",
),
(
vec!["--", "cargo", "test", "--", "--skip"],
"libtest --skip has no filter value",
),
(
vec!["--", "cargo", "test", "--", "--test-threads"],
"libtest --test-threads has no value",
),
(
vec!["--", "cargo", "test", "--", "--test-threads", "0"],
"must not be 0",
),
(
vec!["--", "cargo", "test", "--", "--test-threads=many"],
"must be a number > 0",
),
(
vec![
"--",
"cargo",
"test",
"--",
"--test-threads",
"2",
"--test-threads=3",
],
"was provided more than once",
),
(
vec![
"--",
"cargo",
"test",
"--",
"--test-threads=2",
"--test-threads",
"3",
],
"was provided more than once",
),
(
vec!["--", "cargo", "test", "--", "-Z"],
"libtest -Z has no feature value",
),
(
vec!["--", "cargo", "test", "--", "--format"],
"libtest --format has no value",
),
(
vec!["--", "cargo", "test", "--", "-h"],
"libtest -h does not execute a test suite",
),
(
vec!["--", "cargo", "test", "--", "--frobnicate"],
"libtest discovery contract does not recognize option --frobnicate",
),
] {
// Cargo quotes a refused argument in color when CI asks for it.
let refused = project.supercov_with(&args, &[("CARGO_TERM_COLOR", "never")]);
assert_ne!(refused.code(), 0, "{args:?}");
assert!(
refused.stderr().contains(message),
"{args:?}: {}",
refused.stderr()
);
}
// Selections libtest understands narrow the run to the tests they name.
for (args, tests) in [
(
vec!["--", "cargo", "test", "--", "--exact", "tests::doubles"],
1,
),
(vec!["--", "cargo", "test", "--", "--skip", "halves"], 1),
(
vec![
"--",
"cargo",
"test",
"--",
"--skip=doubles",
"--format",
"terse",
],
1,
),
(
vec![
"--",
"cargo",
"test",
"-j",
"2",
"--",
"--test-threads",
"1",
],
2,
),
] {
project.supercov(&args).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(
summary.contains(&format!("Passed {tests}")),
"{args:?}: {summary}"
);
}
}
#[test]
fn the_harness_commands_refuse_input_they_cannot_read() {
let project = Project::cart("harness-commands");
let run = project.measure(&[]);
let input = project.root.join("input.json");
let input_path = input.to_str().unwrap();
let feed = |command: &str, bytes: &[u8]| {
std::fs::write(&input, bytes).unwrap();
project.supercov_with(&[command], &[("SUPERCOV_INTERNAL_INPUT_FILE", input_path)])
};
for (command, invalid) in [
("__run-js-direct", "invalid direct JavaScript run input"),
("__benchmark-js-transform", "invalid Rust benchmark input"),
("__instrument-js", "invalid Rust instrumenter input"),
("__query-stored-run", "invalid stored query input"),
] {
let missing = project.supercov_with(
&[command],
&[("SUPERCOV_INTERNAL_INPUT_FILE", "no-such-input.json")],
);
assert!(
missing
.exits(2)
.contains("failed to read Rust engine input"),
"{command}"
);
assert!(
feed(command, b"\xff\xfe").exits(2).contains("is not UTF-8"),
"{command}"
);
assert!(feed(command, b"{").exits(2).contains(invalid), "{command}");
}
// Input on stdin that cannot be read: a directory in its place.
#[cfg(unix)]
{
let read = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.arg("__instrument-js")
.stdin(std::fs::File::open(&project.root).unwrap())
.output()
.unwrap();
assert_eq!(read.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&read.stderr);
assert!(
stderr.contains("failed to read Rust engine input:"),
"{stderr}"
);
}
// A launcher that names no tool is refused.
assert_eq!(project.supercov(&["__source-tool"]).code(), 2);
let source = r#"[{"file":"a.js","source":"export const f = (x) => x ? 1 : 2;\n"}]"#;
let timed = feed("__benchmark-js-transform", source.as_bytes()).json();
assert_eq!(timed["files"], 1);
let instrumented = feed("__instrument-js", source.as_bytes()).json();
assert_eq!(instrumented.as_array().unwrap().len(), 1);
// No case is a batch of nothing.
assert_eq!(feed("__benchmark-js-transform", b"[]").json()["files"], 0);
assert_eq!(feed("__instrument-js", b"[]").json(), serde_json::json!([]));
let broken = r#"[{"file":"broken.js","source":"let = ;"}]"#;
for command in ["__benchmark-js-transform", "__instrument-js"] {
assert!(
feed(command, broken.as_bytes())
.exits(2)
.contains("broken.js"),
"{command}"
);
}
let root = project.root.to_str().unwrap();
let query = |run_id: &str, command: &str, newer: Option<&str>| {
serde_json::json!({
"root": root,
"query": {"runId": run_id, "filter": "passed", "command": command, "target": 20.0},
"newerRunId": newer,
})
.to_string()
};
let minimized = feed(
"__query-stored-run",
query(&run, "minimize", None).as_bytes(),
)
.json();
assert_eq!(minimized["ok"], true, "{minimized}");
let diffed = feed(
"__query-stored-run",
query(&run, "diff", Some(&run)).as_bytes(),
)
.json();
assert_eq!(diffed["ok"], true, "{diffed}");
for (request, message) in [
(
query(&run, "diff", None),
"stored diff requires a newer run ID",
),
(query("no-such-run", "summary", None), "stored query failed"),
// Several lines with no first, or a first with no line.
(
serde_json::json!({
"root": root,
"query": {"runId": run, "filter": "passed", "command": "line", "moreLines": [["src/cart.js", 2]]},
})
.to_string(),
"stored query failed",
),
(
serde_json::json!({
"root": root,
"query": {"runId": run, "filter": "passed", "command": "line", "file": "src/cart.js", "moreLines": [["src/cart.js", 2]]},
})
.to_string(),
"stored query failed",
),
(
query(&run, "diff", Some("no-such-run")),
"stored query failed",
),
] {
assert!(
feed("__query-stored-run", request.as_bytes())
.exits(2)
.contains(message),
"{request}"
);
}
// Each of the two indexes a stored diff opens, refused: the older run's,
// then the newer's. Before each, the inventory opens one and reads past
// it, so they are the second and fourth opens.
std::fs::write(&input, query(&run, "diff", Some(&run))).unwrap();
for open in ["coverage-index@2", "coverage-index@4"] {
let ran = project.supercov_with(
&["__query-stored-run"],
&[
("SUPERCOV_INTERNAL_INPUT_FILE", input_path),
("SUPERCOV_TEST_FAULT", open),
],
);
assert_eq!(ran.code(), 2, "{open}: {}", ran.stderr());
}
// The supervisor runs a command and passes its exit code on.
assert!(
project
.supercov(&["__supervise"])
.exits(2)
.contains("test command must not be empty")
);
project
.supercov(&["__supervise", "--", "sh", "-c", "exit 3"])
.exits(3);
// A command that cannot start is said to, and fails.
assert!(
!project
.supercov(&["__supervise", "--", "/nonexistent/supercov-command"])
.exits(1)
.is_empty()
);
// So does a supervisor that cannot find itself to supervise from.
let lost = project.supercov_with(
&["__supervise", "--", "true"],
&[("SUPERCOV_TEST_FAULT", "supervisor-exe")],
);
assert_eq!(lost.code(), 1, "{}", lost.stderr());
assert!(
lost.stderr().contains("injected fault at supervisor-exe"),
"{}",
lost.stderr()
);
// Output passed on after nobody reads it any more, text or not, is
// dropped without a panic.
for script in ["printf 'a\\n'", "printf '\\377\\n'"] {
let mut child = project
.supercov_command(&[
"__supervise",
"--",
"sh",
"-c",
&format!("sleep 0.2; {script}"),
])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
let output = child.wait_with_output().unwrap();
let said = String::from_utf8_lossy(&output.stderr);
assert!(!said.contains("panicked at"), "{script}: {said}");
}
// A command that cannot be started fails the supervisor, and so does a
// watchdog program it cannot find (Unix only: Windows needs none).
let unstarted = project.supercov_with(
&["__supervise", "--", "true"],
&[("SUPERCOV_TEST_FAULT", "spawn")],
);
assert_ne!(unstarted.code(), 0, "{}", unstarted.stderr());
if cfg!(unix) {
let unfound = project.supercov_with(
&["__supervise", "--", "true"],
&[("SUPERCOV_TEST_FAULT", "fs@1")],
);
assert_ne!(unfound.code(), 0, "{}", unfound.stderr());
}
for name in [
"SUPERCOV_DIAGNOSTIC_INTERVAL_MS",
"SUPERCOV_COMMAND_TIMEOUT_MS",
] {
assert!(
project
.supercov_with(&["__supervise", "--", "true"], &[(name, "soon")])
.exits(2)
.contains(name),
"{name}"
);
}
// A command still running is reported at each interval, in ms then s.
// The interval is short enough that a busy machine still reports once
// before the first second.
let slow = project
.supercov_with(
&["__supervise", "--", "sleep", "2.5"],
&[("SUPERCOV_DIAGNOSTIC_INTERVAL_MS", "100")],
)
.exits(0);
let reports = slow
.lines()
.filter(|line| line.starts_with("[supercov] command still running after "))
.collect::<Vec<_>>();
assert!(reports.iter().any(|line| line.ends_with("ms")), "{slow}");
assert!(
reports
.iter()
.any(|line| line.ends_with('s') && !line.ends_with("ms")),
"{slow}"
);
project.supercov(&["__sweep-trash"]).exits(2);
project.supercov(&["__sweep-trash", root]).succeeds();
}
/// A sandbox SDK as a package would ship it: it mounts a host directory into
/// a "guest" (a symlink here) and runs a command there with exactly the
/// environment the call passes.
const SANDBOX: &str = r#"import { spawn } from "node:child_process";
import { mkdirSync, symlinkSync } from "node:fs";
import { dirname } from "node:path";
export const sandbox = {
async boot(options) {
const mount = options.mounts?.[0] ?? { source: options.hostPath, target: options.guestPath };
mkdirSync(dirname(mount.target), { recursive: true });
symlinkSync(mount.source, mount.target, "dir");
return {
run(argv, options) {
// A remote guest sees only what the call hands it: Supercov has to
// have translated the project root into the guest's path already.
if (options.env.SUPERCOV_PROJECT_ROOT !== mount.target) return 97;
return new Promise((resolve, reject) => {
const child = spawn(argv[0], argv.slice(1), {
cwd: mount.target,
env: options.env,
stdio: "inherit",
});
child.once("error", reject);
child.once("close", (code) => resolve(code));
});
},
};
},
};
export default sandbox;
"#;
#[test]
fn code_a_test_runs_inside_a_sandbox_it_mounts_is_credited_to_that_test() {
let project = Project::empty("sandbox-launch");
project.write(
"package.json",
r#"{ "name": "remote", "private": true, "type": "module" }"#,
);
project.write("src/cart.js", common::CART);
project.write(
"node_modules/opaque-sandbox/package.json",
r#"{ "name": "opaque-sandbox", "type": "module", "exports": "./index.mjs" }"#,
);
project.write("node_modules/opaque-sandbox/index.mjs", SANDBOX);
project.write(
"guest/describe.mjs",
"import { describe } from \"../src/cart.js\";\nif (describe([{ name: \"pen\" }]) !== \"pen\") process.exit(1);\n",
);
project.write(
"test/remote.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { sandbox } from "opaque-sandbox";
test("the guest describes the cart", async () => {
const target = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
const machine = await sandbox.boot({ mounts: [{ source: process.cwd(), target }] });
const code = await machine.run([process.execPath, "guest/describe.mjs"], { env: process.env });
assert.equal(code, 0);
});
"#,
);
// The same launch through a namespace import and a parenthesized callee,
// and through a default import with the mapping spelled out.
project.write(
"test/namespace.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as sdk from "opaque-sandbox";
test("a namespace import launches too", async () => {
const target = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
const machine = await (sdk.sandbox).boot({ mounts: [{ source: process.cwd(), target }] });
assert.equal(await machine.run([process.execPath, "guest/describe.mjs"], { env: process.env }), 0);
});
"#,
);
project.write(
"test/default.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import box from "opaque-sandbox";
test("a default import launches too", async () => {
const guestPath = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
const machine = await box.boot({ hostPath: process.cwd(), guestPath });
assert.equal(await machine.run([process.execPath, "guest/describe.mjs"], { env: process.env }), 0);
});
"#,
);
// Product code that launches the sandbox is rewritten the same way.
project.write(
"src/remote.js",
r#"import { sandbox } from "opaque-sandbox";
import * as sdk from "opaque-sandbox";
import box from "opaque-sandbox";
export async function runInGuest(how, script, target) {
const options = { mounts: [{ source: process.cwd(), target }] };
const machine =
how === "named"
? await sandbox.boot(options)
: how === "namespace"
? await (sdk.sandbox).boot(options)
: await box.boot(options);
return machine.run([process.execPath, script], { env: process.env });
}
"#,
);
project.write(
"test/source.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runInGuest } from "../src/remote.js";
test("product code launches the guest", async () => {
for (const how of ["named", "namespace", "default"]) {
const guest = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
assert.equal(await runInGuest(how, "guest/describe.mjs", guest), 0);
}
});
"#,
);
project.git(&["init", "-q"]);
project.supercov(&["--", "node", "--test"]).succeeds();
let summary = project.supercov(&["runs", "latest", "--json"]).json();
let transport = &summary["data"]["transport"];
assert_eq!(transport["workspaceCapabilities"], 6, "{transport}");
assert_eq!(transport["remoteLaunches"], 6, "{transport}");
// `describe` runs only in the guest, and its line is the launching tests'.
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:20"])
.succeeds();
contains_all(
&line,
&[
"the guest describes the cart",
"a namespace import launches too",
"a default import launches too",
"product code launches the guest",
],
);
}
#[test]
fn optional_calls_through_typescript_wrappers_are_measured_alternative_by_alternative() {
let project = Project::empty("optional-calls");
project.write(
"package.json",
r#"{ "name": "calls", "private": true, "type": "module" }"#,
);
project.write(
"src/calls.ts",
r#"type Fn = (() => string) | undefined;
export class Box {
#hook: Fn;
constructor(hook: Fn) {
this.#hook = hook;
}
hook(): string | undefined {
return this.#hook?.();
}
}
export function call(f: Fn, table?: Record<string, Fn>, key = "k", box?: { run?: Fn; make?: () => Fn }) {
return [
(f as Fn)?.(),
(f satisfies Fn)?.(),
f!?.(),
(f)?.(),
table?.[key]?.(),
box?.run?.(),
box?.run!?.(),
box?.make?.()?.(),
(box?.make?.())?.(),
];
}
export function never(f: Fn) {
return [
f?.(),
];
}
"#,
);
project.write(
"test/calls.test.ts",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { Box, call } from "../src/calls.ts";
test("calls each shape when present", () => {
const f = () => "y";
assert.deepEqual(call(f, { k: f }, "k", { run: f, make: () => f }), Array(9).fill("y"));
assert.equal(new Box(f).hook(), "y");
});
test("skips each shape when absent", () => {
assert.deepEqual(call(undefined, undefined, "k", undefined), Array(9).fill(undefined));
assert.equal(new Box(undefined).hook(), undefined);
});
"#,
);
project.git(&["init", "-q"]);
project.supercov(&["--", "node", "--test"]).succeeds();
let file = project
.supercov(&["runs", "latest", "file", "src/calls.ts"])
.succeeds();
contains_all(
&file,
&[
"Branch outcomes not taken 9",
"key = \"k\"",
"table?.[key]?.()",
"box?.run?.()",
"box?.run!?.()",
],
);
// A line inside an expression that never ran is not covered, though it
// has no line obligation of its own.
assert!(file.contains(" 29 NOT COVERED f?.()"), "{file}");
let never = project
.supercov(&["runs", "latest", "line", "src/calls.ts:29"])
.succeeds();
assert!(never.contains("Status\n NOT COVERED"), "{never}");
// A chain that stops at `box?.` never asked whether `make()` returned
// nothing; parentheses end the chain, so there the call did see nothing.
let chained = project
.supercov(&["runs", "latest", "line", "src/calls.ts:22"])
.succeeds();
assert_eq!(
chained
.matches("Unobserved: nullish / short-circuited")
.count(),
2,
"{chained}"
);
let parenthesized = project
.supercov(&["runs", "latest", "line", "src/calls.ts:23"])
.succeeds();
assert_eq!(
parenthesized
.matches("Unobserved: nullish / short-circuited")
.count(),
1,
"{parenthesized}"
);
project.edit(
"test/calls.test.ts",
"test(\"skips each shape when absent\"",
"test(\"skips each shape whose own step is absent\", () => {\n const f = () => \"y\";\n assert.deepEqual(call(f, {}, undefined, {}), [\"y\", \"y\", \"y\", \"y\", undefined, undefined, undefined, undefined, undefined]);\n assert.deepEqual(call(f, {}, undefined, { make: () => undefined }).slice(7), [undefined, undefined]);\n});\n\ntest(\"skips each shape when absent\"",
);
project.supercov(&["--", "node", "--test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Lines 77.78% (7/9)", "Branches 94.74% (36/38)"],
);
}
#[cfg(unix)]
#[test]
fn a_switch_case_reached_by_falling_through_is_not_credited_and_nested_switches_count() {
// `level(20)` falls from `case n > 10` into `case n > 5`, and `kind(0)`
// from `case 0` into `case 1`: neither later test matched. A switch inside
// a switch with no default used to be neither measured nor declared.
let project = Project::empty("switches");
project.write(
"package.json",
r#"{ "name": "switches", "type": "module" }"#,
);
project.write("src/s.js", "export function level(n) {\n let out = \"\";\n switch (true) {\n case n > 10:\n out += \"high \";\n case n > 5:\n out += \"mid\";\n break;\n default:\n out = \"low\";\n }\n return out;\n}\nexport function kind(x) {\n switch (x) {\n case 0:\n case 1:\n return \"small\";\n }\n return \"other\";\n}\nexport function nested(a, b) {\n switch (a) {\n case 1:\n switch (b) {\n case \"x\":\n return \"1x\";\n case \"y\":\n return \"1y\";\n }\n }\n return \"?\";\n}\nexport function looped(xs) {\n let total = 0;\n outer: for (const x of xs) {\n switch (x) {\n case -1:\n break outer;\n case 0:\n continue;\n default:\n total += x;\n }\n }\n return total;\n}\n");
project.write("test/s.test.js", "import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { level, kind, nested, looped } from \"../src/s.js\";\ntest(\"switches\", () => {\n assert.equal(level(20), \"high mid\");\n assert.equal(kind(0), \"small\");\n assert.equal(nested(1, \"x\"), \"1x\");\n assert.equal(looped([1, 0, 2, -1, 5]), 3);\n});\n");
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 1"), "{measured}");
let file = project
.supercov(&["runs", "latest", "file", "src/s.js"])
.succeeds();
contains_all(
&file,
&[
" 3 PARTIAL true\n Unobserved: branch outcome not observed: case n > 5\n Unobserved: branch outcome not observed: default\n",
" 15 PARTIAL x\n Unobserved: branch outcome not observed: case 1\n",
" 25 PARTIAL b\n Unobserved: branch outcome not observed: case \"y\"\n Unobserved: switch no-match outcome not observed\n",
],
);
// Labels still reach the loop around the switch, and each of its cases
// was selected.
assert!(!file.contains(" 37 PARTIAL"), "{file}");
assert!(!file.contains(" 38 PARTIAL"), "{file}");
}
#[test]
fn an_optional_link_a_chain_cut_short_before_it_is_not_credited() {
// In `a?.b?.c` the object of `?.c` is undefined when `a` is, though
// `?.c` never ran, and so is the object of `?.b` in `f?.()?.b` when `f`
// is. Each link is credited only with what it saw itself,
// and a getter or call between two links that evaluates chains of its
// own does not disturb them.
let project = Project::empty("optional-links");
project.write(
"package.json",
r#"{ "name": "chain", "private": true, "type": "module" }"#,
);
project.write(
"src/c.js",
"export const realNullish = (o) => o?.inner?.value;\nexport const three = (a) => a?.b?.c?.d;\nexport const viaCall = (o) => o?.get().x?.y;\nconst noisy = { get a() { const cut = null; cut?.z?.w; return { b: 1 }; } };\nexport const viaGetter = (o) => o?.a?.b;\nexport { noisy };\nexport class Holder {\n #inner;\n constructor(inner) { this.#inner = inner; }\n read(self) { return self?.#inner?.value; }\n}\nexport const callThenMember = (f) => f?.()?.b;\nexport const callReturnsNothing = (f) => f?.()?.b;\n",
);
project.write(
"test/c.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport * as c from \"../src/c.js\";\ntest(\"chains\", () => {\n // both links of realNullish: first nullish, then second nullish\n assert.equal(c.realNullish(null), undefined);\n assert.equal(c.realNullish({ inner: null }), undefined);\n assert.equal(c.realNullish({ inner: { value: 1 } }), 1);\n // three: a null, then b null; c never null\n assert.equal(c.three(null), undefined);\n assert.equal(c.three({ b: null }), undefined);\n assert.equal(c.three({ b: { c: { d: 4 } } }), 4);\n // viaCall: o null only; x never null\n assert.equal(c.viaCall(null), undefined);\n assert.equal(c.viaCall({ get: () => ({ x: { y: 2 } }) }), 2);\n // viaGetter: o present, getter cuts its own chain short; a never null\n assert.equal(c.viaGetter(c.noisy), 1);\n assert.equal(c.viaGetter(null), undefined);\n const h = new c.Holder({ value: 3 });\n assert.equal(h.read(h), 3);\n assert.equal(h.read(null), undefined);\n // callThenMember: f null only; f() never returns nullish\n assert.equal(c.callThenMember(null), undefined);\n assert.equal(c.callThenMember(() => ({ b: 1 })), 1);\n // callReturnsNothing: f null, f() null, and f() an object\n assert.equal(c.callReturnsNothing(null), undefined);\n assert.equal(c.callReturnsNothing(() => null), undefined);\n assert.equal(c.callReturnsNothing(() => ({ b: 1 })), 1);\n});\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]).succeeds();
assert!(measured.contains("pass 1"), "{measured}");
let file = project
.supercov(&["runs", "latest", "file", "src/c.js"])
.succeeds();
let gaps = file
.lines()
.skip_while(|line| !line.starts_with(" LINE"))
.filter(|line| !line.contains("Inspect:"))
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
gaps,
" LINE STATUS SOURCE\n 2 PARTIAL a?.b?.c?.d\n Unobserved: nullish short-circuit outcome not observed\n 3 PARTIAL o?.get().x?.y\n Unobserved: nullish short-circuit outcome not observed\n 4 PARTIAL cut?.z\n Unobserved: non-nullish continuation outcome not observed\n Unobserved: nullish short-circuit outcome not observed\n Unobserved: non-nullish continuation outcome not observed\n 5 PARTIAL o?.a?.b\n Unobserved: nullish short-circuit outcome not observed\n 10 PARTIAL self?.#inner?.value\n Unobserved: nullish short-circuit outcome not observed\n 12 PARTIAL f?.()?.b\n Unobserved: nullish short-circuit outcome not observed\nshowing 1-6 of 6 gap lines",
);
}
#[cfg(unix)]
#[test]
fn a_project_with_links_sockets_and_pipes_is_measured_through_them() {
let outside = Project::empty("links-outside");
outside.write("secret.js", "export const secret = 1;\n");
outside.write(
"store/fake-pkg/package.json",
r#"{ "name": "fake-pkg", "type": "module", "exports": "./index.js" }"#,
);
outside.write(
"store/fake-pkg/index.js",
"export const triple = (x) => x * 3;\n",
);
let project = Project::empty("links");
project.write(
"package.json",
r#"{ "name": "links", "private": true, "type": "module" }"#,
);
project.write(
"src/math.js",
"export function double(x) {\n return x * 2;\n}\n",
);
let link = |target: &std::path::Path, name: &str| {
std::os::unix::fs::symlink(target, project.root.join(name)).unwrap();
};
// `lib` is a conventional source directory name; here it is a link.
link(std::path::Path::new("src"), "lib");
link(&project.root.join("src"), "abs-lib");
link(std::path::Path::new("nowhere.js"), "dangling");
link(&project.root.join("nowhere.js"), "abs-dangling");
link(&outside.root, "escape");
// pnpm keeps the root node_modules in a store elsewhere.
link(&outside.root.join("store"), "node_modules");
// A running dev server's socket and a pipe hold no source.
std::fs::create_dir(project.root.join("tmp")).unwrap();
// A socket path is limited to about a hundred bytes, so it is bound
// short and moved in.
let short = std::env::temp_dir().join(format!("supercov-{}.sock", std::process::id()));
let _listener = std::os::unix::net::UnixListener::bind(&short).unwrap();
std::fs::rename(&short, project.root.join("tmp/dev.sock")).unwrap();
assert!(
std::process::Command::new("mkfifo")
.arg(project.root.join("tmp/pipe"))
.status()
.unwrap()
.success()
);
project.write(
"test/links.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync } from "node:fs";
import { double } from "../lib/math.js";
import { double as absDouble } from "../abs-lib/math.js";
import { triple } from "fake-pkg";
test("links inside the project resolve in the copy", () => {
assert.equal(double(2), 4);
assert.equal(absDouble(3), 6);
assert.equal(triple(2), 6);
});
test("dangling links stay, a link out of the project does not", () => {
assert.ok(lstatSync("dangling").isSymbolicLink());
assert.ok(lstatSync("abs-dangling").isSymbolicLink());
assert.equal(existsSync("escape"), false);
});
"#,
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]);
assert!(
measured
.exits(0)
.contains("omitting symlink outside the isolated project"),
"the link out of the project is named"
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Lines 100.00% (2/2)", "Passed 2"]);
}
#[test]
fn the_gate_and_the_export_count_what_ran_outside_a_test_as_the_summary_does() {
// A script no runner attributes test by test: everything it runs is
// background coverage.
let script = Project::empty("aggregate-gate");
script.write("package.json", r#"{ "name": "agg", "type": "module" }"#);
script.write(
"src/math.js",
"export function double(x) {\n return x * 2;\n}\n",
);
script.write(
"run.mjs",
"import { double } from \"./src/math.js\";\nif (double(2) !== 4) process.exit(1);\n",
);
script.git(&["init", "-q"]);
script.supercov(&["--", "node", "run.mjs"]).succeeds();
let summary = script.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 100.00% (2/2)"), "{summary}");
let gate = script
.supercov(&["runs", "latest", "check", "--min-lines", "100"])
.succeeds();
assert!(gate.contains("lines 100.00% 2/2"), "{gate}");
script
.supercov(&["runs", "report", "--format", "lcov", "--output", "out.lcov"])
.succeeds();
let lcov = script.read("out.lcov");
contains_all(&lcov, &["LF:2", "LH:2"]);
// A module's top level runs as it is imported, before any test starts.
let tests = Project::empty("import-gate");
tests.write("package.json", r#"{ "name": "imp", "type": "module" }"#);
tests.write(
"src/pages.js",
"const prefix = \"/pages/\";\n\nexport function page(name) {\n return prefix + name;\n}\n",
);
tests.write(
"test/pages.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { page } from \"../src/pages.js\";\n\ntest(\"names a page\", () => assert.equal(page(\"a\"), \"/pages/a\"));\n",
);
tests.git(&["init", "-q"]);
tests.supercov(&["--", "node", "--test"]).succeeds();
let summary = tests.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 100.00% (3/3)"), "{summary}");
let gate = tests
.supercov(&["runs", "latest", "check", "--min-lines", "100"])
.succeeds();
assert!(gate.contains("lines 100.00% 3/3"), "{gate}");
}
#[test]
fn the_file_view_counts_and_labels_lines_as_the_summary_and_line_view_do() {
let project = Project::empty("line-states");
project.write("package.json", r#"{ "name": "states" }"#);
project.write(
"src/states.js",
"const scope = { value: 7 };\nfunction sloppy() {\n with (scope) {\n return value;\n }\n}\nfunction both(a, b) {\n if (a && b) {\n return 1;\n }\n return 0;\n}\nfunction never() {\n return 2;\n}\nfunction half(flag) {\n return flag ? 1 : 0;\n}\nmodule.exports = { sloppy, both, never, half };\n",
);
project.write(
"test/states.test.js",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert/strict\");\nconst { sloppy, both, half } = require(\"../src/states.js\");\ntest(\"sloppy reads the scope\", () => assert.equal(sloppy(), 7));\ntest(\"both, true and true\", () => assert.equal(both(true, true), 1));\ntest(\"both, false\", () => assert.equal(both(false, true), 0));\ntest(\"half, true\", () => assert.equal(half(true), 1));\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "node", "--test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Branches 75.00% (3/4)"), "{summary}");
// `half` only ever returned 1: the decision's false outcome is the one
// branch the summary counts as missing, and the file view says so too.
let file = project
.supercov(&["runs", "latest", "file", "src/states.js"])
.succeeds();
contains_all(
&file,
&[
"Branch outcomes not taken 1",
" 17 PARTIAL flag",
"Unobserved: decision never false",
],
);
let counts = project
.supercov(&["runs", "latest", "file", "src/states.js", "--json"])
.succeeds();
let counts: serde_json::Value = serde_json::from_str(&counts).unwrap();
assert_eq!(counts["data"]["counts"]["missingBranches"], 1, "{counts}");
project
.supercov(&["runs", "report", "--format", "lcov", "--output", "out.lcov"])
.succeeds();
let lcov = project.read("out.lcov");
contains_all(&lcov, &["BRF:4", "BRH:3", "BRDA:17,1,0,1", "BRDA:17,1,1,-"]);
assert_eq!(
lcov.lines()
.filter(|line| line.starts_with("BRDA:"))
.count(),
4,
"{lcov}"
);
// The `with` line ran; only its body is outside measurement. Both views
// call it partial, and the body, which nothing recorded, not measured.
assert!(
file.contains(" 3 PARTIAL with (scope) {"),
"{file}"
);
assert!(!file.contains("NOT MEASURED"), "{file}");
let with_line = project
.supercov(&["runs", "latest", "line", "src/states.js:3"])
.succeeds();
assert!(with_line.contains("Status\n PARTIAL"), "{with_line}");
let body = project
.supercov(&["runs", "latest", "line", "src/states.js:4"])
.succeeds();
assert!(body.contains("Status\n NOT MEASURED"), "{body}");
}
#[test]
fn a_line_query_answers_every_line_it_can_and_warns_only_about_files_that_changed() {
let project = Project::cart("line-answers");
project.write(
"src/tax.js",
"export function rate(country) {\n return country === \"LT\" ? 0.21 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { rate } from \"../src/tax.js\";\n\ntest(\"rate in LT\", () => {\n assert.equal(rate(\"LT\"), 0.21);\n});\n",
);
project.measure(&[]);
// One mistyped path among several: the others are still answered, the
// mistake is named beside them, and the call succeeds.
let mixed = project.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:14",
"src/crat.js:3",
"src/tax.js:2",
]);
let answered = mixed.succeeds();
contains_all(
&answered,
&[
"return express ? 15 : 5;",
"return country === \"LT\" ? 0.21 : 0;",
"Not answered\n src/crat.js:3: ",
],
);
let json = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:14",
"src/crat.js:3",
"--json",
])
.json();
assert_eq!(json["ok"], true, "{json}");
assert_eq!(
json["data"]["failed"][0]["location"], "src/crat.js:3",
"{json}"
);
assert_eq!(
json["data"]["failed"].as_array().unwrap().len(),
1,
"{json}"
);
// Every path wrong is still a mistake.
let wrong = project
.supercov(&["runs", "latest", "line", "src/crat.js:3"])
.exits(2);
assert!(wrong.contains("src/crat.js"), "{wrong}");
// A blank line is no code at all, and the answer says why.
let blank = project
.supercov(&["runs", "latest", "line", "src/cart.js:11"])
.succeeds();
contains_all(
&blank,
&[
"Status\n NOT MEASURED",
"Nothing on this line is code the run measures",
],
);
// Only a test changed: the source lines asked about are as the run saw
// them, so nothing is stale about the answer.
project.edit("test/tax.test.js", "rate in LT", "rate in Lithuania");
let after_test_edit = project.supercov(&["runs", "latest", "line", "src/tax.js:2"]);
after_test_edit.succeeds();
assert!(
!after_test_edit.stderr().contains("stale run"),
"{}",
after_test_edit.stderr()
);
// cart.js changed: a question about tax.js is still answered from the
// run with no warning, one about cart.js names the file that changed.
project.edit("src/cart.js", "return 0;", "return 0; // free");
let unchanged = project.supercov(&["runs", "latest", "line", "src/tax.js:2"]);
let unchanged_output = unchanged.succeeds();
assert!(
!unchanged.stderr().contains("stale run"),
"{}",
unchanged.stderr()
);
assert!(
!unchanged_output.contains("working tree"),
"{unchanged_output}"
);
let changed = project.supercov(&["runs", "latest", "line", "src/cart.js:16"]);
changed.succeeds();
assert!(
changed.stderr().contains("stale run") && changed.stderr().contains("src/cart.js"),
"{}",
changed.stderr()
);
}
#[test]
fn a_patch_on_a_failing_run_shows_its_coverage_and_still_cannot_pass() {
let project = Project::cart("patch-failing");
project.edit(
"src/cart.js",
" return items.map((item) => item.name).join(\", \");",
" const names = items.map((item) => item.name);\n return names.join(\", \");",
);
project.edit(
"test/cart.test.js",
"shipping(60, false), 0",
"shipping(60, false), 1",
);
project.supercov(&["--", "node", "--test"]).exits(1);
let human = project
.supercov(&["runs", "patch", "--base", "HEAD"])
.exits(2);
contains_all(
&human,
&[
"this run cannot pass a patch gate",
"0 of 2 changed executable line(s) covered",
"src/cart.js",
],
);
let ran = project.supercov(&["runs", "patch", "--base", "HEAD", "--json"]);
ran.exits(2);
let json = ran.json();
assert_eq!(json["data"]["result"], "error", "{json}");
assert_eq!(json["data"]["patch"]["eligible"], 2, "{json}");
assert_eq!(json["data"]["patch"]["covered"], 0, "{json}");
assert!(
json["data"]["reasons"]
.as_array()
.is_some_and(|reasons| !reasons.is_empty()),
"{json}"
);
}
#[test]
fn a_page_too_large_for_one_reply_says_where_the_rest_starts() {
let project = Project::empty("page-cut");
project.write(
"package.json",
r#"{ "name": "wide", "private": true, "type": "module" }"#,
);
let mut source = String::new();
for index in 0..400 {
source.push_str(&format!(
"export function step{index}(flag) {{\n return flag ? \"a long enough value for line {index} to take some room in a reply\" : {index};\n}}\n"
));
}
project.write("src/wide.js", &source);
project.write(
"test/wide.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { step0 } from \"../src/wide.js\";\n\ntest(\"step0\", () => {\n assert.equal(step0(false), 0);\n});\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
let page = project.supercov(&[
"runs",
"latest",
"file",
"src/wide.js",
"--limit",
"1000",
"--json",
]);
let json = page.json();
let cut = &json["data"]["pageCut"];
assert_eq!(cut["asked"], 1000, "{json}");
let returned = cut["returned"].as_u64().unwrap();
assert!(returned > 0 && returned < 1000, "{json}");
assert_eq!(cut["nextOffset"], returned, "{json}");
assert!(
page.stderr().contains(&format!(
"this page holds {returned} of the 1000 entries asked for"
)),
"{}",
page.stderr()
);
// A page that fits is not marked.
let small = project
.supercov(&[
"runs",
"latest",
"file",
"src/wide.js",
"--limit",
"5",
"--json",
])
.json();
assert!(small["data"]["pageCut"].is_null(), "{small}");
}
/// A page cut to fit carries a note of the cut, and the note is part of
/// the reply: fitted without it, a page that had just fit went over by the
/// note and was refused. These lines, sixty long ones then short ones, give
/// a page that fits within the note's size of the limit.
#[test]
fn a_cut_page_fits_with_its_note_of_the_cut() {
let project = Project::empty("page-cut-note");
project.write(
"package.json",
r#"{ "name": "wide", "private": true, "type": "module" }"#,
);
let mut source = String::new();
for index in 0..400 {
let filler = "y".repeat(if index < 60 { 177 } else { 0 });
source.push_str(&format!(
"export function step{index}(flag) {{\n return flag === \"v{index}{filler}\" ? 1 : {index};\n}}\n"
));
}
project.write("src/wide.js", &source);
project.write(
"test/wide.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { step0 } from \"../src/wide.js\";\ntest(\"step0\", () => { assert.equal(step0(false), 0); });\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
let page = project
.supercov(&[
"runs",
"latest",
"file",
"src/wide.js",
"--metric",
"branches",
"--limit",
"1000",
"--json",
])
.json();
assert_eq!(page["ok"], true, "{}", page["error"]);
assert_eq!(page["data"]["pageCut"]["asked"], 1000, "{page}");
}
#[test]
fn todo_tests_are_counted_as_node_test_counts_them() {
// supergateway's suite: node said 1,076 tests, 1,057 passed, 6 todo;
// Supercov said 1,071 total and 1,058 passed. A body-less todo was never
// recorded, a todo whose body failed was a failure, and tests in a
// describe.todo were passes.
let project = Project::cart("todo");
project.write(
"test/todo.test.js",
r#"import test, { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { total } from '../src/cart.js';
test.todo('todo without a body');
test.todo('todo with a passing body', () => assert.equal(total([]), 0));
test.todo('todo with a failing body', () => assert.equal(1, 2));
test('option todo, passing', { todo: true }, () => assert.equal(1, 1));
test('option todo with a reason, failing', { todo: 'later' }, () => assert.equal(1, 2));
test('context todo', (t) => { t.todo('not yet'); assert.equal(1, 1); });
test.skip('skipped', () => assert.equal(1, 2));
describe('suite', () => { it.todo('it todo'); });
describe.todo('todo suite', () => { it('inside a todo suite', () => assert.equal(1, 1)); });
"#,
);
project.commit("todo");
let native = std::process::Command::new("node")
.args(["--test", "--test-reporter", "spec"])
.current_dir(&project.root)
.output()
.unwrap();
let native = String::from_utf8_lossy(&native.stdout).into_owned();
let count = |label: &str| -> String {
native
.lines()
.find_map(|line| line.trim().strip_prefix(&format!("\u{2139} {label} ")))
.unwrap_or_else(|| panic!("no {label} in\n{native}"))
.trim()
.to_owned()
};
project.measure(&[]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
for (label, ours) in [
("tests", "Total"),
("pass", "Passed"),
("skipped", "Skipped"),
("todo", "Todo"),
] {
let expected = count(label);
assert!(
summary.contains(&format!(" {ours:<11} {expected}\n")),
"{ours} should be node's {label} {expected}:\n{summary}"
);
}
assert!(!summary.contains(" Failed"), "{summary}");
}
#[test]
fn printed_commands_name_the_way_supercov_was_started() {
let project = Project::cart("launchers");
let run = project.measure(&[]);
let root = project.root.to_string_lossy().into_owned();
// The PyPI, Ruby and Rust packages run the binary itself; npm sets the
// package root; the Go launcher says so.
for (env, command) in [
(vec![], "supercov"),
(
vec![("SUPERCOV_PACKAGE_ROOT", root.as_str())],
"npx supercov",
),
(
vec![("SUPERCOV_LAUNCHER", "go")],
"go run github.com/supercorp-ai/supercov/cmd/supercov@latest",
),
] {
let summary = project.supercov_with(&["runs", "latest"], &env).succeeds();
assert!(
summary.contains(&format!(
"not assessed — {command} runs {run} assertions assess"
)),
"{env:?}: {summary}"
);
assert!(
summary.contains(&format!(" {command} runs '{run}' files\n")),
"{env:?}: {summary}"
);
if command == "supercov" {
assert!(!summary.contains("npx supercov"), "{summary}");
}
}
}
#[test]
fn every_listing_pages_and_names_its_next_page() {
let project = Project::cart("pages");
project.write(
"src/tax.js",
"export function tax(sum, rate) {\n return rate > 0 ? sum * rate : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { tax } from \"../src/tax.js\";\n\ntest(\"taxes a sum\", () => assert.equal(tax(10, 0.5), 5));\n",
);
project.commit("tax");
let first = project.measure(&["--test-name-pattern", "total"]);
let second = project.measure(&[]);
let run = format!("'{second}'");
for (args, next) in [
(
vec!["runs", "--limit", "1"],
"supercov runs --offset 1 --limit 1".to_owned(),
),
(
vec!["runs", "latest", "files", "--limit", "1"],
format!("runs {run} files --offset 1 --limit 1"),
),
(
vec!["runs", "latest", "gaps", "--limit", "1"],
format!("runs {run} gaps --offset 1 --limit 1"),
),
// A filtered listing's next page keeps the filter.
(
vec![
"runs", "latest", "gaps", "--filter", "passed", "--limit", "1",
],
format!("runs {run} gaps --filter passed --offset 1 --limit 1"),
),
(
vec![
"runs", "latest", "files", "--filter", "passed", "--limit", "1",
],
format!("runs {run} files --filter passed --offset 1 --limit 1"),
),
(
vec!["runs", "latest", "file", "src/cart.js", "--limit", "1"],
format!("runs {run} file 'src/cart.js' --offset 1 --limit 1"),
),
(
vec!["runs", "latest", "line", "src/cart.js:13", "--limit", "1"],
format!("runs {run} line 'src/cart.js:13' --offset 1 --limit 1"),
),
(
vec![
"runs",
"latest",
"decision",
"src/cart.js:13",
"--limit",
"1",
],
format!("runs {run} decision 'src/cart.js:13' --offset 1 --limit 1"),
),
(
vec!["runs", "latest", "scope", "--files", "--limit", "1"],
format!("runs {run} scope --files --offset 1 --limit 1"),
),
(
vec!["runs", "latest", "source", "src/cart.js", "--limit", "2"],
format!("runs {run} source 'src/cart.js' --offset 2 --limit 2"),
),
(
vec![
"runs",
"latest",
"test",
"total adds prices",
"--limit",
"1",
],
format!("runs {run} test 'total adds prices' --offset 1 --limit 1"),
),
(
vec!["diff", &first, &second, "--limit", "1"],
format!("diff '{first}' {run} --offset 1 --limit 1"),
),
] {
let listed = project.supercov(&args).succeeds();
assert!(listed.contains(&next), "{args:?}: no {next:?} in\n{listed}");
// The command it names reads the next page.
let mut words = vec![String::new()];
let mut quoted = false;
for character in next.trim_start_matches("supercov ").chars() {
match character {
'\'' => quoted = !quoted,
' ' if !quoted => words.push(String::new()),
_ => words.last_mut().unwrap().push(character),
}
}
let words = words.iter().map(String::as_str).collect::<Vec<_>>();
let following = project.supercov(&words).succeeds();
assert_ne!(following, listed, "{words:?} repeated the first page");
}
// A run whose suite failed says so where runs are listed.
project.write(
"test/broken.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\n\ntest(\"breaks\", () => assert.equal(1, 2));\n",
);
project.supercov(&["--", "node", "--test"]).exits(1);
let listed = project.supercov(&["runs", "--limit", "1"]).succeeds();
assert!(listed.contains("FAILED (exit 1)"), "{listed}");
}
#[test]
fn the_html_report_says_what_it_could_not_embed() {
let project = Project::cart("html-edges");
let mut big = String::from("export function big(x) {\n return x + 1;\n}\n");
big.push_str(&format!("// {}\n", "x".repeat(1024 * 1024)));
project.write("src/big.js", &big);
project.write(
"test/big.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { big } from \"../src/big.js\";\n\ntest(\"big adds one\", () => assert.equal(big(1), 2));\n",
);
project.commit("big");
// Measured with the mutants' probes, so the report has their verdicts.
project
.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
project
.supercov(&["report", "--no-open", "--output", "fresh.html"])
.succeeds();
let fresh = report_data(&project.read("fresh.html"));
let run = &fresh["runs"][0];
assert_eq!(
run["fileTotals"]["src/cart.js"],
serde_json::json!({"branches": 8, "functions": 4, "statements": 10})
);
assert_eq!(
run["omittedSources"],
serde_json::json!(["src/big.js"]),
"{run}"
);
assert_eq!(run["stale"], false);
// The run's mutants: its counts, each file's, and every mutant with its
// change, status and reason; those no test infects or reaches are the
// ones left alive.
let mutants = &run["mutants"];
assert_eq!(mutants["mutantSet"], "stryker-js@10.1.1", "{mutants}");
assert!(
mutants["summary"]["mutants"].as_u64() > Some(0),
"{mutants}"
);
assert!(mutants["files"]["src/cart.js"].is_object(), "{mutants}");
for mutant in mutants["mutants"].as_array().unwrap() {
assert_eq!(
mutant["alive"],
["not-infected", "not-reached"].contains(&mutant["status"].as_str().unwrap()),
"{mutant}"
);
assert!(
mutant["change"].as_str().unwrap().contains(" → "),
"{mutant}"
);
assert!(!mutant["reason"].as_str().unwrap().is_empty(), "{mutant}");
}
assert!(
run["sources"]["src/cart.js"].is_object(),
"{}",
run["sources"]
);
// Source that changed since the run is not shown beside its lines.
project.edit("src/cart.js", "return 0;", "return 1;");
project
.supercov(&["report", "--no-open", "--output", "stale.html"])
.succeeds();
let stale = report_data(&project.read("stale.html"));
let run = &stale["runs"][0];
assert_eq!(run["stale"], true);
assert_eq!(
run["staleReasons"],
serde_json::json!(["instrumented source changed"])
);
assert_eq!(run["sources"], serde_json::json!({}), "{run}");
// A directory gets the report under its default name.
std::fs::create_dir(project.root.join("reports")).unwrap();
project
.supercov(&["report", "--no-open", "--output", "reports"])
.succeeds();
report_data(&project.read("reports/supercov-report.html"));
// A run to compare with that is not stored is named.
let missing = project
.supercov(&["report", "--no-open", "--compare", "run_0000000000000009"])
.exits(2);
assert!(missing.contains("run_0000000000000009"), "{missing}");
// A run that left nothing uncovered has no file to detail.
let whole = Project::empty("html-whole");
whole.git(&["init", "-q"]);
whole.write("package.json", r#"{"type":"module"}"#);
whole.write("src/one.js", "export function one() {\n return 1;\n}\n");
whole.write(
"test/one.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { one } from \"../src/one.js\";\n\ntest(\"one\", () => assert.equal(one(), 1));\n",
);
whole.supercov(&["--", "node", "--test"]).succeeds();
whole
.supercov(&["report", "--no-open", "--output", "whole.html"])
.succeeds();
let data = report_data(&whole.read("whole.html"));
// And no gap to export, in every line format.
let exported = whole
.supercov(&["runs", "latest", "gaps", "--format", "jsonl"])
.succeeds();
assert!(!exported.contains("\"file\""), "{exported}");
assert_eq!(
data["runs"][0]["fileDetails"],
serde_json::json!({}),
"{data}"
);
// An assessment that judged no statement is shown as one, with none.
let runs = whole.supercov(&["runs", "--json"]).json();
let id = runs["data"]["runs"][0]["id"].as_str().unwrap();
whole.write(
&format!(".supercov/runs/{id}/assertion-coverage.json"),
"{}",
);
whole
.supercov(&["report", "--no-open", "--output", "assessed.html"])
.succeeds();
let assessed = report_data(&whole.read("assessed.html"));
let assertions = &assessed["runs"][0]["assertions"];
assert_eq!(assertions["available"], true, "{assertions}");
assert_eq!(
assertions["statements"],
serde_json::json!([]),
"{assertions}"
);
let summary = whole.supercov(&["runs", "latest"]).succeeds();
assert!(
summary.contains("Assertions no executed statements to assess"),
"{summary}"
);
let empty = Project::empty("html-nothing");
empty.git(&["init", "-q"]);
// The report opens in the browser the system names, and says when none
// could be started; `-h` among its options is its help.
#[cfg(unix)]
{
let tools = project.root.with_extension("open-tools");
std::fs::create_dir_all(&tools).unwrap();
let git = String::from_utf8(
std::process::Command::new("sh")
.args(["-c", "command -v git"])
.output()
.unwrap()
.stdout,
)
.unwrap();
std::os::unix::fs::symlink(git.trim(), tools.join("git")).unwrap();
let path = tools.to_str().unwrap();
let unopened = project
.supercov_with(&["report", "--output", "unopened.html"], &[("PATH", path)])
.succeeds();
let said = format!("{unopened}{}", project.read("unopened.html").len());
assert!(said.contains("wrote"), "{said}");
for opener in ["open", "xdg-open"] {
use std::os::unix::fs::PermissionsExt;
let script = tools.join(opener);
std::fs::write(&script, "#!/bin/sh\nexit 0\n").unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let opened = project
.supercov_with(&["report", "--output", "opened.html"], &[("PATH", path)])
.succeeds();
assert!(
opened.contains("opened the report in your browser"),
"{opened}"
);
let help = project.supercov(&["report", "--no-open", "-h"]).succeeds();
assert!(help.contains("Usage: supercov report"), "{help}");
std::fs::remove_dir_all(tools).unwrap();
}
let nothing = empty.supercov(&["report", "--no-open"]).exits(2);
assert!(
nothing.contains("no local coverage runs and no saved assessments to report"),
"{nothing}"
);
}
/// The data a report page renders from: gzip-compressed JSON, base64-encoded
/// into its `report-data` script.
/// Whether a fault announced firing at `place` (`file.rs:line`); any place
/// when `place` is empty.
fn fired_at(stderr: &str, place: &str) -> bool {
stderr
.lines()
.any(|line| line.contains("test fault at") && line.contains(place))
}
fn report_data(html: &str) -> serde_json::Value {
use base64::Engine;
use std::io::Read;
let start = html
.find(r#"<script id="report-data" type="application/octet-stream">"#)
.expect("report data")
+ r#"<script id="report-data" type="application/octet-stream">"#.len();
let end = start + html[start..].find("</script>").expect("report data end");
let compressed = base64::engine::general_purpose::STANDARD
.decode(&html[start..end])
.unwrap();
let mut json = String::new();
flate2::read::GzDecoder::new(compressed.as_slice())
.read_to_string(&mut json)
.unwrap();
serde_json::from_str(&json).unwrap()
}
#[test]
fn a_lock_an_older_release_holds_is_left_alone_and_one_left_behind_is_taken_over() {
let project = Project::cart("locks");
let lock = project.root.join(".supercov/locks/active.json");
std::fs::create_dir_all(lock.parent().unwrap()).unwrap();
let owner = |pid: u32| {
format!(r#"{{"runId":"run_other","pid":{pid},"startedAt":"2026-10-02T00:00:00Z"}}"#)
};
// A run of a release that locked nothing wrote this file and is alive
// while its process is; this test's process stands in for it. The run
// started beside it takes a copy of its own.
std::fs::write(&lock, owner(std::process::id())).unwrap();
let beside = project.supercov(&["--", "node", "--test"]);
assert_eq!(beside.code(), 0, "{}", beside.stderr());
assert!(
beside.stderr().contains("workspace-2"),
"{}",
beside.stderr()
);
// One whose owner has gone, or that was never finished, holds nothing.
for left in [owner(u32::MAX - 1), "{".to_owned()] {
std::fs::write(&lock, left).unwrap();
let alone = project.supercov(&["--", "node", "--test"]);
assert_eq!(alone.code(), 0, "{}", alone.stderr());
assert!(
!alone.stderr().contains("workspace-2"),
"{}",
alone.stderr()
);
}
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
// The trash sweeper keeps the same rules for its own lock. The runs above
// each started one in the background; it is let finish first.
let trash = project.root.join(".supercov/.trash");
let started = std::time::Instant::now();
while trash.join(".deleter.lock").exists() && started.elapsed().as_secs() < 30 {
std::thread::sleep(std::time::Duration::from_millis(50));
}
let root = project.root.to_str().unwrap();
let sweep = |deleter: &str, modified: Option<std::time::SystemTime>| {
std::fs::create_dir_all(trash.join("left")).unwrap();
let path = trash.join(".deleter.lock");
std::fs::write(&path, deleter).unwrap();
if let Some(modified) = modified {
std::fs::File::options()
.write(true)
.open(&path)
.unwrap()
.set_modified(modified)
.unwrap();
}
project.supercov(&["__sweep-trash", root]).succeeds();
let swept = !trash.join("left").exists();
let _ = std::fs::remove_file(&path);
swept
};
assert!(
!sweep(&std::process::id().to_string(), None),
"a live sweeper is left to it"
);
assert!(!sweep("", None), "a sweeper starting up is left to it");
assert!(
sweep(&(u32::MAX - 1).to_string(), None),
"a dead sweeper's lock is taken over"
);
assert!(sweep("", Some(old)), "an old unowned lock is taken over");
}
#[test]
fn a_selector_that_matches_nothing_or_several_says_so() {
let project = Project::cart("selectors");
project.write(
"src/pick.js",
"export const pick = (a, b) => (a ? 1 : 2) + (b ? 3 : 4);\n",
);
project.write(
"test/pick.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { pick } from \"../src/pick.js\";\n\ntest(\"picks\", () => assert.equal(pick(true, false), 5));\n",
);
project.commit("pick");
project.measure(&[]);
for (args, message) in [
(
vec!["runs", "latest", "gaps", "--kind", "e2e"],
"No tests match kind=e2e",
),
(
vec!["runs", "latest", "gaps", "--runner", "jest"],
"No tests match runner=jest",
),
(
vec!["runs", "latest", "file", "src/cart.js", "--kind", "e2e"],
"No tests match kind=e2e",
),
(
vec!["runs", "latest", "minimize", "--target", "150"],
"--target must be between 0 and 100",
),
(
vec!["runs", "latest", "test", "nosuch"],
"Test not found: nosuch",
),
(
vec!["runs", "latest", "decision", "src/cart.js:99"],
"Decision not found: src/cart.js:99",
),
(
vec!["runs", "latest", "test", "total", "--limit", "-1"],
"--limit must be a number of entries, or 0 for all of them",
),
] {
let refused = project.supercov(&args).exits(2);
assert!(refused.contains(message), "{args:?}: {refused}");
}
// A selector two tests or two decisions answer to lists them to choose from.
let tests = project
.supercov(&["runs", "latest", "test", "total"])
.succeeds();
contains_all(
&tests,
&[
"total adds prices [",
"total applies a coupon [",
"showing 1-2 of 2 matching tests",
],
);
let decisions = project
.supercov(&["runs", "latest", "decision", "src/pick.js:1"])
.succeeds();
contains_all(
&decisions,
&[
"src/pick.js:1:32 a",
"src/pick.js:1:46 b",
"showing 1-2 of 2 matching decisions",
],
);
// Minimizing over one runner's tests.
let minimized = project
.supercov(&[
"runs",
"latest",
"minimize",
"--runner",
"node:test",
"--target",
"50",
"--metric",
"lines",
])
.succeeds();
assert!(
minimized.contains("exact minimum 1/4 test(s) for 50% lines"),
"{minimized}"
);
}
#[test]
fn phase_timing_says_where_setup_went_when_asked() {
let project = Project::cart("phase-timing");
let timed = project
.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_PHASE_TIMING", "1")])
.exits(0);
contains_all(
&timed,
&[
"[supercov] setup detail runtime=",
"| files=",
"[supercov] timings initialization=",
],
);
let quiet = project.supercov(&["--", "node", "--test"]).exits(0);
assert!(!quiet.contains("setup detail"), "{quiet}");
}
#[test]
fn a_pnpm_workspace_finds_the_source_of_each_package_it_lists() {
let project = Project::empty("pnpm-workspace");
project.write(
"package.json",
r#"{ "name": "mono", "private": true, "type": "module" }"#,
);
project.write(
"pnpm-workspace.yaml",
"packages:\n - \"packages/*\"\n - 'tools/cli'\n - \"!packages/ignored\"\n - \"apps/**\"\n# the rest is not packages\ncatalog:\n left-pad: 1.0.0\n",
);
project.write(
"packages/a/package.json",
r#"{ "name": "a", "type": "module", "exports": { ".": ["./entry/index.js"] } }"#,
);
project.write(
"packages/a/entry/index.js",
"export const a = (x) => x + 1;\n",
);
project.write(
"packages/a/entry/types.d.ts",
"export declare const a: (x: number) => number;\n",
);
project.write(
"tools/cli/package.json",
r#"{ "name": "cli", "type": "module" }"#,
);
project.write("tools/cli/main.js", "export const run = () => \"ran\";\n");
project.write(
"apps/web/package.json",
r#"{ "name": "web", "type": "module" }"#,
);
project.write("apps/web/page.js", "export const page = () => 1;\n");
project.write(
"test/all.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { a } from \"../packages/a/entry/index.js\";\nimport { run } from \"../tools/cli/main.js\";\n\ntest(\"both packages\", () => {\n assert.equal(a(1), 2);\n assert.equal(run(), \"ran\");\n});\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "node", "--test"]).succeeds();
let scope = project
.supercov(&["runs", "latest", "scope", "--files", "--limit", "50"])
.succeeds();
contains_all(
&scope,
&[
// An array of export targets names the entry file; a package
// with no conventional source directory is its own root.
"INCLUDED packages/a/entry/index.js discovered package source root [package packages/a]",
"INCLUDED tools/cli/main.js discovered package source root [package tools/cli]",
"INCLUDED apps/web/page.js discovered package source root [package apps/web]",
"EXCLUDED packages/a/entry/types.d.ts TypeScript declaration",
],
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 66.67% (2/3)"), "{summary}");
}
#[test]
fn absolute_source_roots_name_the_same_rust_code_in_the_workspace() {
let project = Project::empty("rust-roots");
project.write(
"Cargo.toml",
"[package]\nname = \"roots\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub mod extra;\n\npub fn double(x: u32) -> u32 {\n x * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.write(
"src/extra.rs",
"pub fn half(x: u32) -> u32 {\n x / 2\n}\n",
);
project.git(&["init", "-q"]);
let measured = |roots: &str| {
project
.supercov_with(
&["--", "cargo", "test"],
&[("SUPERCOV_SOURCE_ROOTS", roots)],
)
.succeeds();
project.supercov(&["runs", "latest"]).succeeds()
};
// The run measures a copy; a root written as the project's absolute path
// names the same file there.
let file = project.root.join("src/lib.rs");
let one = measured(file.to_str().unwrap());
assert!(one.contains("Lines 100.00% (2/2)"), "{one}");
let whole = measured(project.root.to_str().unwrap());
assert!(whole.contains("Lines 50.00% (2/4)"), "{whole}");
}
/// Tests that load files an earlier build made, which the isolated copy
/// leaves out and nothing built there: the run names the files the project
/// has and the copy lacks, by `import` and by `require`, and says why. With
/// the build in the measured command, it says nothing.
#[cfg(unix)]
#[test]
fn tests_that_load_build_output_the_copy_left_out_are_told_why() {
let project = Project::empty("left-out-build");
project.write(
"package.json",
r#"{ "name": "built", "private": true, "type": "module" }"#,
);
project.write(
"src/x.js",
"export const double = (n) => (n > 0 ? n * 2 : 0);\n",
);
project.write(
"build.mjs",
"import { mkdirSync, copyFileSync, writeFileSync } from \"node:fs\";\nmkdirSync(\"dist\", { recursive: true });\ncopyFileSync(\"src/x.js\", \"dist/x.js\");\nwriteFileSync(\"dist/y.cjs\", \"module.exports = { triple: (n) => n * 3 };\\n\");\n",
);
project.write(
"test/x.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { double } from \"../dist/x.js\";\ntest(\"doubles\", () => assert.equal(double(2), 4));\n",
);
project.write(
"test/y.test.cjs",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert/strict\");\nconst { triple } = require(\"../dist/y.cjs\");\ntest(\"triples\", () => assert.equal(triple(2), 6));\n",
);
project.write(".gitignore", "dist/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let built = std::process::Command::new("node")
.arg("build.mjs")
.current_dir(&project.root)
.status()
.unwrap();
assert!(built.success());
let ran = project.supercov(&["--", "node", "--test"]);
let stderr = ran.stderr();
assert_ne!(ran.code(), 0, "{stderr}");
assert!(
stderr.contains("warning: the tests could not load dist/x.js, dist/y.cjs, which the project has and its isolated copy does not"),
"{stderr}"
);
let rebuilt = project.supercov(&["--", "sh", "-c", "node build.mjs && node --test"]);
assert_eq!(rebuilt.code(), 0, "{}", rebuilt.stderr());
assert!(
!rebuilt.stderr().contains("could not load"),
"{}",
rebuilt.stderr()
);
// A command that builds, and whose build failed, is not told to add a
// build: what to look at is its build's own output.
let unbuilt = project.supercov(&["--", "sh", "-c", "npm run build; node --test"]);
let stderr = unbuilt.stderr();
assert_ne!(unbuilt.code(), 0, "{stderr}");
assert!(
stderr.contains("could not load dist/x.js, dist/y.cjs, which the project has and its isolated copy does not. The command builds, and its build did not make them in the copy: if the build failed, its output above says why"),
"{stderr}"
);
// More than four left out are named by count; a file the copy has by
// the time the run looks, as a test wrote it there after failing to
// load it, is not left out.
let many = Project::empty("left-out-many");
many.write(
"package.json",
r#"{ "name": "many", "private": true, "type": "module" }"#,
);
many.write("src/x.js", "export const x = 1;\n");
many.write(
"test/many.test.js",
"import test from \"node:test\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\ntest(\"loads what was built\", async () => {\n for (const name of [\"m0\", \"m1\", \"m2\", \"m3\", \"m4\", \"m5\", \"late\"]) {\n await import(`../dist/${name}.js`).catch(() => {});\n }\n mkdirSync(\"dist\", { recursive: true });\n writeFileSync(\"dist/late.js\", \"export const late = 1;\\n\");\n throw new Error(\"nothing was built\");\n});\n",
);
many.write(".gitignore", "dist/\n");
many.git(&["init", "-q"]);
many.commit("fixture");
for name in ["m0", "m1", "m2", "m3", "m4", "m5", "late"] {
many.write(&format!("dist/{name}.js"), "export const built = 1;\n");
}
let ran = many.supercov(&["--", "node", "--test"]);
let stderr = ran.stderr();
assert_ne!(ran.code(), 0, "{stderr}");
assert!(
stderr.contains(
"could not load dist/m0.js, dist/m1.js, dist/m2.js, dist/m3.js and 2 more, which the project has"
),
"{stderr}"
);
assert!(!stderr.contains("late.js"), "{stderr}");
}
/// A target runner configuration Supercov cannot read -- here a runner that
/// leads to the crate itself -- refuses the run, saying why, as plain
/// `cargo test` fails on it. Run without the runner, the tests would pass.
#[test]
fn a_target_runner_supercov_cannot_read_refuses_the_run() {
let project = Project::empty("unreadable-runner");
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"pub fn double(n: u32) -> u32 {\n n * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.write(".gitignore", "target/\n");
let host = String::from_utf8(
std::process::Command::new("rustc")
.arg("-vV")
.output()
.unwrap()
.stdout,
)
.unwrap()
.lines()
.find_map(|line| line.strip_prefix("host: ").map(str::to_owned))
.unwrap();
project.write(
".cargo/config.toml",
&format!("[target.{host}]\nrunner = \"bin/..\"\n"),
);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", "cargo", "test", "-q"]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{stderr}");
assert!(
stderr.contains("invalid Cargo configuration: runner path"),
"{stderr}"
);
assert!(project.supercov(&["runs", "--json"]).json()["data"]["runs"][0].is_null());
}
#[test]
fn cargo_configuration_and_target_flags_reach_the_measured_build() {
let project = Project::empty("cargo-config");
project.write(
"Cargo.toml",
"[package]\nname = \"config\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn double(x: u32) -> u32 {\n x * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.git(&["init", "-q"]);
let rustc = std::process::Command::new("rustc")
.arg("-vV")
.output()
.unwrap();
let host = String::from_utf8(rustc.stdout)
.unwrap()
.lines()
.find_map(|line| line.strip_prefix("host: ").map(str::to_owned))
.unwrap();
let target_eq = format!("--target={host}");
let mut measured = vec![
vec!["--", "cargo", "test", "--config", "build.incremental=false"],
vec!["--", "cargo", "test", "--config=build.incremental=false"],
vec!["--", "cargo", "test", "--target", &host],
vec!["--", "cargo", "test", &target_eq],
];
// A toolchain selector goes through rustup, where there is one.
let rustup = std::process::Command::new("rustup")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success());
if rustup {
measured.push(vec!["--", "cargo", "+stable", "test"]);
}
for args in measured {
project.supercov(&args).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(
summary.contains("Lines 100.00% (2/2)"),
"{args:?}: {summary}"
);
}
for (args, message) in [
(
vec!["--", "cargo", "test", "--config"],
"Cargo option --config has no value",
),
(
vec!["--", "cargo", "test", "--target"],
"Cargo option --target has no value",
),
// What Cargo refuses itself, it says.
(
vec!["--", "cargo", "test", "--config="],
"was not a TOML dotted key expression",
),
(vec!["--", "cargo", "test", "--target="], "target was empty"),
] {
// Cargo quotes a refused argument in color when CI asks for it.
let refused = project.supercov_with(&args, &[("CARGO_TERM_COLOR", "never")]);
assert_ne!(refused.code(), 0, "{args:?}");
assert!(
refused.stderr().contains(message),
"{args:?}: {}",
refused.stderr()
);
}
}
#[cfg(unix)]
#[test]
fn a_workspace_directory_the_project_does_not_own_is_never_written_through() {
let project = Project::cart("planted-workspace");
let elsewhere = Project::empty("planted-target");
std::fs::create_dir_all(project.root.join(".supercov")).unwrap();
// A link where Supercov keeps its isolated copy, pointing out of the
// project, as a hostile checkout or a confused script could leave it.
std::os::unix::fs::symlink(&elsewhere.root, project.root.join(".supercov/workspaces")).unwrap();
let measured = project.supercov(&["--", "node", "--test"]).exits(0);
assert!(measured.contains(".supercov/workspaces-"), "{measured}");
assert!(
std::fs::read_dir(&elsewhere.root).unwrap().next().is_none(),
"nothing was written through the link"
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Lines 76.92% (10/13)"), "{summary}");
}
#[test]
fn cargo_configuration_planted_in_the_rust_workspace_is_refused() {
let project = Project::empty("planted-cargo");
project.write(
"Cargo.toml",
"[package]\nname = \"planted\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn double(x: u32) -> u32 {\n x * 2\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.git(&["init", "-q"]);
let first = project.supercov(&["--", "cargo", "test"]).exits(0);
let workspace = first
.lines()
.find_map(|line| {
line.strip_prefix("[supercov] detected Rust; instrumenting isolated Cargo workspace ")
})
.expect("the run names its workspace");
let container = std::path::Path::new(workspace)
.parent()
.unwrap()
.parent()
.unwrap();
// A Cargo configuration there would change how the copy builds.
std::fs::create_dir(container.join(".cargo")).unwrap();
let refused = project.supercov(&["--", "cargo", "test"]);
assert_ne!(refused.code(), 0);
assert!(
refused
.stderr()
.contains("would change how Supercov builds the project but not how `cargo test` does"),
"{}",
refused.stderr()
);
std::fs::remove_dir(container.join(".cargo")).unwrap();
project.supercov(&["--", "cargo", "test"]).succeeds();
}
#[test]
fn affected_test_names_select_exactly_those_tests_in_their_runner() {
let project = Project::empty("runner-names");
project.write("package.json", r#"{ "name": "names", "type": "module" }"#);
project.write(
"src/fee.js",
"export function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\n\nexport function tax(sum) {\n return sum * 2;\n}\n",
);
// One name in two describe blocks; only one of them runs fee.
project.write(
"test/fee.test.js",
"import { describe, test } from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { fee, tax } from \"../src/fee.js\";\n\ndescribe(\"small\", () => {\n test(\"charges\", () => assert.equal(fee(10), 5));\n});\ndescribe(\"large\", () => {\n test(\"charges\", () => assert.equal(tax(10), 20));\n});\n",
);
project.git(&["init", "-q"]);
project.commit("names");
project.supercov(&["--", "node", "--test"]).succeeds();
let tests = project
.supercov(&["runs", "latest", "test", "charges"])
.succeeds();
contains_all(&tests, &["small > charges [", "large > charges ["]);
project.edit("src/fee.js", "? 0 : 5", "? 0 : 6");
let names = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert_eq!(names.trim(), "small charges");
// node:test matches a test by its suites and its name joined by spaces.
let selected = std::process::Command::new("node")
// Node 22 reports in TAP when its output is not a terminal.
.args([
"--test",
"--test-reporter",
"spec",
"--test-name-pattern",
names.trim(),
])
.current_dir(&project.root)
.output()
.unwrap();
let output = String::from_utf8_lossy(&selected.stdout);
assert!(output.contains("ℹ tests 1\n"), "{output}");
}
/// Sandbox SDKs pass a command's environment in different places: an `env`
/// option, an `envs` option (E2B), or a plain map after the command
/// (Daytona) or a builder method (Testcontainers). Each refuses unless
/// Supercov already moved the project root to the guest's path.
const SANDBOX_SHAPES: &str = r#"import { spawnSync } from "node:child_process";
import { mkdirSync, symlinkSync } from "node:fs";
import { dirname } from "node:path";
function go(target, argv, environment) {
if (environment?.SUPERCOV_PROJECT_ROOT !== target) return 97;
return spawnSync(argv[0], argv.slice(1), { cwd: target, env: environment, stdio: "inherit" }).status;
}
export const sandbox = {
boot(options) {
const { source, target } = options.mounts[0];
mkdirSync(dirname(target), { recursive: true });
symlinkSync(source, target, "dir");
return {
exec: (argv, options) => go(target, argv, options.env),
run: (argv, options) => go(target, argv, options.envs),
execute: (argv, environment) => go(target, argv, environment),
};
},
};
// A builder, as Testcontainers is: mounts, environment and command set one
// call at a time, then started.
export class Container {
withBindMounts(mounts) { this.mount = mounts[0]; return this; }
withEnvironment(environment) { this.environment = environment; return this; }
withCommand(argv) { this.argv = argv; return this; }
start() {
mkdirSync(dirname(this.mount.target), { recursive: true });
symlinkSync(this.mount.source, this.mount.target, "dir");
return go(this.mount.target, this.argv, this.environment);
}
}
"#;
#[test]
fn each_way_a_sandbox_sdk_takes_an_environment_reaches_the_guest() {
let project = Project::empty("sandbox-shapes");
project.write("package.json", r#"{ "name": "shapes", "type": "module" }"#);
project.write("src/cart.js", common::CART);
project.write(
"node_modules/sandbox-shapes/package.json",
r#"{ "name": "sandbox-shapes", "type": "module", "exports": "./index.mjs" }"#,
);
project.write("node_modules/sandbox-shapes/index.mjs", SANDBOX_SHAPES);
project.write(
"guest/describe.mjs",
"import { describe } from \"../src/cart.js\";\nif (describe([{ name: \"pen\" }]) !== \"pen\") process.exit(1);\n",
);
project.write(
"test/shapes.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { sandbox, Container } from "sandbox-shapes";
const machine = () =>
sandbox.boot({ mounts: [{ source: process.cwd(), target: join(mkdtempSync(join(tmpdir(), "guest-")), "workspace") }] });
const argv = [process.execPath, "guest/describe.mjs"];
// Windows' own environment has names like this one in it.
const windowsLike = { ...process.env, "ProgramFiles(x86)": "C:\\Program Files (x86)" };
test("an env option", () => assert.equal(machine().exec(argv, { env: { ...process.env } }), 0));
test("an envs option", () => assert.equal(machine().run(argv, { envs: { ...process.env } }), 0));
test("an environment map", () => assert.equal(machine().execute(argv, windowsLike), 0));
test("a builder", () => {
const target = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
const started = new Container()
.withBindMounts([{ source: process.cwd(), target }])
.withEnvironment(windowsLike)
.withCommand(argv)
.start();
assert.equal(started, 0);
});
"#,
);
project.git(&["init", "-q"]);
project.supercov(&["--", "node", "--test"]).succeeds();
let summary = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(
summary["data"]["transport"]["remoteLaunches"], 4,
"{summary}"
);
// Every guest had the settings, so none set itself up.
assert_eq!(
summary["data"]["transport"]["guestProcesses"], 0,
"{summary}"
);
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:20"])
.succeeds();
contains_all(
&line,
&[
"an env option",
"an envs option",
"an environment map",
"a builder",
],
);
}
/// The shape of #176 without Bun: a guest process starts from a project that
/// also has a Playwright config, with none of the run's environment. Its
/// source has to bootstrap the runtime itself or the first probe throws.
/// The host loader must read the run's settings before the browser fallback
/// initializes a runtime, so the guest's coverage reaches the run too.
#[cfg(unix)]
#[test]
fn a_guest_in_a_project_with_a_browser_config_bootstraps_its_source() {
let project = Project::empty("guest-browser-config");
project.write(
"package.json",
r#"{ "name": "guest-browser", "type": "module" }"#,
);
project.write("src/cart.js", common::CART);
project.write("test/playwright.config.js", "export default {};\n");
project.write(
"guest/describe.mjs",
"import { describe } from \"../src/cart.js\";\nif (describe([{ name: \"pen\" }]) !== \"pen\") process.exit(1);\n",
);
project.write(
"test/guest.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
test("the guest describes the cart", () => {
const result = spawnSync(process.execPath, ["guest/describe.mjs"], {
cwd: process.cwd(),
env: { PATH: process.env.PATH },
encoding: "utf8",
});
assert.equal(result.status, 0, result.stderr);
});
"#,
);
project.git(&["init", "-q"]);
project.commit("guest beside a browser config");
project.supercov(&["--", "node", "--test"]).succeeds();
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:20"])
.succeeds();
contains_all(
&line,
&[
"Status\n COVERED",
"the guest describes the cart [",
"unit/node:test",
],
);
}
#[cfg(unix)]
#[test]
fn a_guest_started_with_none_of_supercovs_settings_runs_and_is_counted() {
let project = Project::empty("clean-guest");
project.write("package.json", r#"{ "name": "clean", "type": "module" }"#);
project.write("src/cart.js", common::CART);
// A VM: the project mounted at `target`, a command run there with only
// what the VM provides.
project.write(
"node_modules/fake-vm/package.json",
r#"{ "name": "fake-vm", "type": "module", "exports": "./index.mjs" }"#,
);
project.write(
"node_modules/fake-vm/index.mjs",
r#"import { spawnSync } from "node:child_process";
import { mkdirSync, symlinkSync } from "node:fs";
import { dirname } from "node:path";
export function boot({ source, target }) {
mkdirSync(dirname(target), { recursive: true });
symlinkSync(source, target, "dir");
return {
run(argv) {
const result = spawnSync("/usr/bin/env", ["-i", `PATH=${process.env.PATH}`, ...argv], { cwd: target, encoding: "utf8" });
return { code: result.status, stderr: result.stderr };
},
};
}
"#,
);
project.write(
"guest/describe.mjs",
"import { describe } from \"../src/cart.js\";\nif (describe([{ name: \"pen\" }]) !== \"pen\") process.exit(1);\n",
);
project.write(
"test/vm.test.js",
r#"import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { boot } from "fake-vm";
test("the guest describes the cart", () => {
const target = join(mkdtempSync(join(tmpdir(), "guest-")), "workspace");
const result = boot({ source: process.cwd(), target }).run(["node", "guest/describe.mjs"]);
assert.equal(result.code, 0, result.stderr);
});
"#,
);
project.git(&["init", "-q"]);
// The instrumented source used to throw at its first probe in the guest.
project.supercov(&["--", "node", "--test"]).succeeds();
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:20"])
.succeeds();
contains_all(&line, &["Status\n COVERED", "Background / unattributed"]);
// The run says so, and how many.
let summary = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(
summary["data"]["transport"]["guestProcesses"], 1,
"{summary}"
);
let text = project.supercov(&["runs", "latest"]).succeeds();
assert!(
text.contains(" Unattributed 1 process(es) initialized coverage without the preload"),
"{text}"
);
}
/// Executes instrumented TypeScript in a page and a worker, including when
/// Playwright is launched by an opaque child of node:test. Set the dependency
/// directory to use dependencies outside the repository's node_modules.
#[cfg(unix)]
#[test]
fn a_browser_worker_bootstraps_when_playwright_is_launched_by_a_unit_test() {
let modules = std::env::var_os("SUPERCOV_BROWSER_NODE_MODULES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules")
});
let available = std::process::Command::new("node")
.args(["--input-type=module", "-e", "import { chromium } from '@playwright/test'; import { existsSync } from 'node:fs'; process.exit(existsSync(chromium.executablePath()) ? 0 : 1)"])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright and Chromium are required"
);
eprintln!("skipping: Playwright or Chromium is unavailable");
return;
}
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("browser-worker-bootstrap");
std::os::unix::fs::symlink(modules, project.root.join("node_modules")).unwrap();
project.write(
"package.json",
r#"{"type":"module","scripts":{"test":"playwright test"}}"#,
);
project.write(
"index.html",
"<script type=\"module\" src=\"/src/main.ts\"></script>",
);
project.write("src/main.ts", "export function choose(v: boolean): number { return v ? 3 : 4; }\n(globalThis as any).ready = choose(true);\n");
project.write("src/worker.ts", "export function choose(v: boolean): number { return v ? 7 : 8; }\npostMessage(choose(true));\n");
project.write(
"src/classic.js",
"function choose(v) { return v ? 9 : 10; }\npostMessage(choose(true));\n",
);
project.write("playwright.config.mjs", &format!(r#"import {{ defineConfig }} from '@playwright/test';
export default defineConfig({{ testDir: './tests', testMatch: '*.spec.js', workers: 1,
use: {{ baseURL: 'http://127.0.0.1:{port}' }},
webServer: {{ command: './node_modules/.bin/vite --host 127.0.0.1 --strictPort --port {port}', url: 'http://127.0.0.1:{port}', timeout: 30000 }} }});
"#));
project.write(
"tests/browser.spec.js",
r#"import { test, expect } from '@playwright/test';
test('page and worker', async ({ page }) => {
await page.goto('/');
await expect.poll(() => page.evaluate(() => globalThis.ready)).toBe(3);
const value = await page.evaluate(() => new Promise((resolve, reject) => {
const worker = new Worker('/src/worker.ts', { type: 'module' });
worker.onmessage = event => resolve(event.data);
worker.onerror = event => reject(event.message);
}));
expect(value).toBe(7);
const classic = await page.evaluate(() => new Promise((resolve, reject) => {
const worker = new Worker('/src/classic.js');
worker.onmessage = event => resolve(event.data);
worker.onerror = event => reject(event.message);
}));
expect(classic).toBe(9);
});
"#,
);
project.write(
"tests/wrapper.cjs",
r#"const test = require('node:test');
const { spawnSync } = require('node:child_process');
const assert = require('node:assert/strict');
test('run browser', () => {
const result = spawnSync('./node_modules/.bin/playwright', ['test'], { stdio: 'inherit' });
assert.equal(result.status, 0);
});
"#,
);
project.git(&["init", "-q"]);
project.commit("browser worker");
for command in [
vec!["--", "npm", "test"],
vec!["--", "node", "--test", "tests/wrapper.cjs"],
] {
project.supercov(&command).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Lines 100.00% (6/6)", "Exact for"]);
}
}
fn bun_is_available() -> bool {
let available = std::process::Command::new("bun")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success());
assert!(
available || std::env::var_os("SUPERCOV_REQUIRE_BUN").is_none(),
"Bun is required"
);
available
}
/// A runner Bun starts by its entry point is adapted as Node's preload adapts
/// it, though Bun loads no Node preload: Vitest takes the run's generated
/// config, keeping the project's own for it to merge, and Mocha's Runner is
/// patched before the CLI loads it. Bun-launched Vitest passed and recorded
/// no test, every probe counted as background (#205). Stand-ins at each
/// runner's entry point print what they were given.
#[cfg(unix)]
#[test]
fn bun_launched_runners_are_adapted_as_node_ones_are() {
if !bun_is_available() {
return;
}
let project = Project::empty("bun launched runners");
project.write("package.json", r#"{ "private": true, "type": "module" }"#);
project.write(
"src/pick.js",
"export function pick(flag) {\n if (flag) return 'yes';\n return 'no';\n}\n",
);
project.write("vitest.config.ts", "export default {};\n");
project.write(
"node_modules/vitest/vitest.mjs",
"console.log('VITEST ' + JSON.stringify({ argv: process.argv.slice(2), original: process.env.SUPERCOV_ORIGINAL_VITEST_CONFIG }));\n",
);
project.write("node_modules/mocha/package.json", r#"{ "name": "mocha" }"#);
project.write(
"node_modules/mocha/lib/runner.js",
"class Runner { run() { return this; } }\nmodule.exports = Runner;\n",
);
project.write(
"node_modules/mocha/bin/mocha.js",
"const Runner = require('../lib/runner.js');\nconsole.log('MOCHA patched=' + Boolean(Runner.prototype.run.supercovMocha));\n",
);
project.write(".gitignore", "node_modules\n");
project.git(&["init", "-q"]);
project.commit("runners");
let vitest = project
.supercov(&[
"--",
"bun",
"node_modules/vitest/vitest.mjs",
"run",
"--config",
"vitest.config.ts",
])
.succeeds();
let line = vitest
.lines()
.find_map(|line| line.strip_prefix("VITEST "))
.unwrap_or_else(|| panic!("{vitest}"));
let seen: serde_json::Value = serde_json::from_str(line).unwrap();
let argv = seen["argv"].as_array().unwrap();
assert_eq!(argv[0], "run", "{seen}");
assert_eq!(argv[1], "--config", "{seen}");
assert!(
argv[2]
.as_str()
.unwrap()
.ends_with(".supercov/vitest.config.mjs"),
"{seen}"
);
assert_eq!(argv.len(), 3, "{seen}");
assert!(
seen["original"]
.as_str()
.unwrap()
.ends_with("/vitest.config.ts"),
"{seen}"
);
let mocha = project
.supercov(&["--", "bun", "node_modules/mocha/bin/mocha.js"])
.succeeds();
assert!(mocha.contains("MOCHA patched=true"), "{mocha}");
}
/// A Bun test project: one source module, one `bun:test` file, and, where a
/// browser suite is asked for, a Playwright config in the shape discovery
/// finds. Bun ignores `NODE_OPTIONS`, so Supercov's preload never reaches it.
fn bun_project(label: &str, beside_a_browser_config: bool) -> Project {
let project = Project::empty(label);
project.write(
"package.json",
r#"{ "name": "bun-clamp", "private": true, "type": "module", "scripts": { "test": "bun test" } }"#,
);
project.write(
"src/clamp.ts",
"export function clamp(n: number, lo: number, hi: number): number {\n if (n < lo || Number.isNaN(n)) return lo\n return n > hi ? hi : n\n}\n",
);
project.write(
"src/clamp.test.ts",
"import { expect, test } from \"bun:test\"\nimport { clamp } from \"./clamp\"\ntest(\"clamps below\", () => expect(clamp(-1, 0, 10)).toBe(0))\n",
);
if beside_a_browser_config {
project.write("tests/e2e/playwright.config.ts", "export default {};\n");
}
project.git(&["init", "-q"]);
project.commit("bun");
project
}
/// The instrumented copy of a project file, while the workspace is kept.
fn kept_workspace_source(project: &Project, relative: &str) -> String {
let name = project.root.file_name().unwrap();
let path = project
.root
.join(".supercov/workspaces/workspace")
.join(name)
.join(relative);
std::fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()))
}
/// A Playwright config is a file in the project, not a statement that the
/// measured command runs in a browser. A unit-test command beside one still
/// needs the source loader: under Bun the preload never arrives, and this is
/// the failure class in #176, where sources threw at their first probe.
#[test]
fn a_unit_suite_beside_a_playwright_config_keeps_the_source_loader() {
let project = Project::cart("loader-beside-browser-config");
project.write("test/playwright.config.js", "export default {};\n");
project.commit("playwright");
project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_KEEP_WORKSPACE", "1")],
)
.succeeds();
let source = kept_workspace_source(&project, "src/cart.js");
assert!(
source.contains("if (!globalThis.__SUPERCOV_DIRECT_RUNTIME__) try {"),
"a unit suite beside a Playwright config lost its source loader"
);
}
/// Reproduce the reported crash through a discovered browser config. The
/// reporter's precise project configuration is not available in #176.
#[cfg(unix)]
#[test]
fn a_bun_unit_suite_beside_a_playwright_config_runs_and_measures() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = bun_project("bun-beside-playwright", true);
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Lines 66.67% (2/3)", "Branches 25.00% (1/4)"],
);
}
/// `bun test` runs Bun's test runner, not package.json's "test" script.
/// In 4.20.3, a browser runner in that unused script suppressed source
/// bootstrapping even in a project with no browser configuration.
#[cfg(unix)]
#[test]
fn bun_sources_bootstrap_when_an_unused_package_script_names_a_browser_runner() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
// The Bun-only script is the control: changing only an unused script to
// name a browser runner must not change how the measured sources start.
for runner in ["bun test", "karma", "testem", "airtap", "zuul", "mochify"] {
let project = bun_project("bun-unused-browser-script", false);
project.write(
"src/core/runtime/clock.ts",
"export function clock(v: boolean): number {\n if (v) return 1;\n return 0;\n}\n",
);
project.write("src/core/runtime/slug.test.ts", "import { test, expect } from 'bun:test';\nimport { clock } from './clock';\ntest('clock', () => expect(clock(true)).toBe(1));\n");
project.write(
"package.json",
&format!(
r#"{{"type":"module","scripts":{{"test":"npm run browser","browser":"{runner}"}}}}"#
),
);
project.commit("an unrelated package test script");
project
.supercov_with(
&["--", "bun", "test", "src/core/runtime/slug.test.ts"],
&[
("SUPERCOV_KEEP_WORKSPACE", "1"),
("SUPERCOV_SOURCE_ROOTS", "src"),
],
)
.succeeds();
let source = kept_workspace_source(&project, "src/core/runtime/clock.ts");
assert!(
source.contains("var __supercovMcdcBegin"),
"the fixture should reproduce the source path and helper shown in #176"
);
assert!(
source.contains("if (!globalThis.__SUPERCOV_DIRECT_RUNTIME__) try {"),
"{runner}: the unused package script suppressed the source loader"
);
assert!(
!source.contains("(() => { if (!globalThis.__SUPERCOV_DIRECT_RUNTIME__) {")
&& !source.contains("browser-runtime.mjs"),
"{runner}: an unused browser runner added its fallback to a Bun-only source"
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Lines 33.33% (2/6)", "Branches 16.67% (1/6)"],
);
}
}
/// Reproduce the source/test split in #176 at the reported project size.
/// A config in a test fixture must not disable host source initialization;
/// assertion-bearing tests have a separate bootstrap insertion path.
#[cfg(unix)]
#[test]
fn bun_bootstraps_a_large_project_even_with_a_browser_config_in_a_test_fixture() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = Project::empty("bun-large-project-bootstrap");
project.write(".gitignore", ".supercov/\n");
project.write(
"package.json",
r#"{"type":"module","scripts":{"test":"bun test"}}"#,
);
project.write(
"front/package.json",
r#"{"type":"module","devDependencies":{"vite":"*","vitest":"*"}}"#,
);
project.write("front/vite.config.ts", "export default {};\n");
project.write("front/vitest.config.ts", "export default {};\n");
project.write(
"src/core/runtime/clock.ts",
"export function clock(v: boolean): number {\n if (v) return 1;\n return 0;\n}\n",
);
project.write("src/core/runtime/slug.test.ts", "import { test } from 'bun:test';\nimport assert from 'node:assert/strict';\nimport { clock } from './clock';\ntest('clock', () => assert.equal(clock(true), 1));\n");
let sources = std::iter::once("src/core/runtime/clock.ts".to_owned())
.chain((0..2599).map(|index| format!("src/modules/module{index}.ts")))
.collect::<Vec<_>>();
for source in &sources[1..] {
project.write(
source,
"export function value(v: boolean): number { return v ? 1 : 0; }\n",
);
}
let assertion_tests = std::iter::once("src/core/runtime/slug.test.ts".to_owned())
.chain((0..1093).map(|index| format!("tests/cases/check{index}.test.ts")))
.collect::<Vec<_>>();
for test in &assertion_tests[1..] {
project.write(
test,
"import { test, expect } from 'vitest';\ntest('fixture', () => expect(1).toBe(1));\n",
);
}
let other_tests = (0..706)
.map(|index| format!("tests/cases/fixture{index}.test.ts"))
.collect::<Vec<_>>();
for test in &other_tests {
project.write(test, "export const fixture = true;\n");
}
project.git(&["init", "-q"]);
project.commit("reported project size without browser configuration");
for fixture_config in [false, true] {
if fixture_config {
project.write(
"tests/fixtures/browser/playwright.config.ts",
"export default {};\n",
);
project.commit("an unused browser fixture config");
}
let run = project.supercov_with(
&["--", "bun", "test", "src/core/runtime/slug.test.ts"],
&[
("SUPERCOV_KEEP_WORKSPACE", "1"),
("SUPERCOV_SOURCE_ROOTS", "src"),
],
);
let has_loader = |file: &&String| {
kept_workspace_source(&project, file)
.contains("if (!globalThis.__SUPERCOV_DIRECT_RUNTIME__) try {")
};
let source_loaders = sources.iter().filter(has_loader).count();
let assertion_loaders = assertion_tests.iter().filter(has_loader).count();
let other_loaders = other_tests.iter().filter(has_loader).count();
eprintln!(
"browser fixture={fixture_config}: source loaders {source_loaders}/2600, assertion-test loaders {assertion_loaders}/1094, other-test loaders {other_loaders}/706"
);
assert_eq!(
assertion_loaders, 1094,
"assertion instrumentation has its own bootstrap path"
);
assert_eq!(
other_loaders, 0,
"tests with no assertions need no assertion bootstrap"
);
assert_eq!(
source_loaders,
2600,
"the unused browser fixture suppressed source bootstrapping; {}",
run.stderr()
);
run.succeeds();
}
}
/// Source modules evaluate before the importing test's bootstrap. Local
/// bindings must not shadow the loader's host check, including in a mixed
/// browser/unit project. Check every module in the graph, not just the entry.
#[cfg(unix)]
#[test]
fn bun_source_imports_bootstrap_before_probes_even_with_shadowed_host_names() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = bun_project("bun-source-import-graph", true);
project.write(
"src/leaf.mjs",
"const process = { versions: {} };\nexport function leaf(v) { return v ? 3 : 4; }\n",
);
project.write("src/common.cjs", "const process = { versions: {} };\nmodule.exports = function common(v) { return v ? 5 : 6; };\n");
project.write("src/middle.ts", "import { leaf } from './leaf.mjs';\nimport common from './common.cjs';\nconst process = { versions: {} };\nexport function middle(v: boolean): number { return leaf(v) + common(v); }\n");
project.write("src/clamp.test.ts", "import { test, expect } from 'bun:test';\nimport { middle } from './middle';\ntest('imports initialize before the test body', () => { expect(middle(true)).toBe(8); expect(middle(false)).toBe(10); });\n");
project.commit("shadowed globals in imported sources");
project
.supercov_with(
&["--", "bun", "test", "src/clamp.test.ts"],
&[
("SUPERCOV_KEEP_WORKSPACE", "1"),
("SUPERCOV_SOURCE_ROOTS", "src"),
],
)
.succeeds();
for file in ["src/leaf.mjs", "src/common.cjs", "src/middle.ts"] {
let source = kept_workspace_source(&project, file);
let loader = source
.find("new Function(\"stack\", \"specifier\"")
.unwrap();
let fallback = source
.find("(() => { if (!globalThis.__SUPERCOV_DIRECT_RUNTIME__)")
.unwrap();
assert!(
loader < fallback,
"{file}: the host must load run settings before the browser fallback initializes"
);
let line = project
.supercov(&[
"runs",
"latest",
"line",
&format!("{file}:{}", if file.ends_with(".ts") { 4 } else { 2 }),
])
.succeeds();
contains_all(&line, &["Status\n COVERED"]);
}
}
/// Exercise the project features listed in #176 both with and without a
/// browser config. None may leave an instrumented source dependent on the
/// bootstrap in the test that imports it.
#[cfg(unix)]
#[test]
fn bun_bootstraps_sources_with_nested_frontend_aliases_and_preloads() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
for browser_config in [false, true] {
let project = bun_project("bun-project-shape", browser_config);
project.write(
"front/package.json",
r#"{"type":"module","devDependencies":{"vite":"*","vitest":"*"}}"#,
);
project.write("front/vite.config.ts", "export default {};\n");
project.write("front/vitest.config.ts", "export default {};\n");
project.write(
"tsconfig.json",
r#"{"compilerOptions":{"baseUrl":".","paths":{"@/*":["./src/*","./*"]}}}"#,
);
project.write("bunfig.toml", "[test]\npreload = [\"./tests/preload0.ts\", \"./tests/preload1.ts\", \"./tests/preload2.ts\", \"./tests/preload3.ts\", \"./tests/compat.ts\"]\n");
for index in 0..4 {
project.write(&format!("tests/preload{index}.ts"), "import { clamp } from '@/clamp';\nif (clamp(-1, 0, 10) !== 0) throw new Error('preload source did not execute');\n");
}
project.write("tests/compat.ts", "import { mock } from 'bun:test';\nimport * as native from 'bun:test';\nmock.module('vitest', () => native);\n");
project.write("src/clamp.test.ts", "import { test, expect } from 'vitest';\nimport { clamp } from '@/clamp';\ntest('alias import after preloads', () => expect(clamp(11, 0, 10)).toBe(10));\n");
for index in 0..64 {
project.write(
&format!("src/core/runtime/clock{index}.ts"),
"export function clock(v: boolean): number { return v ? 1 : 0; }\n",
);
}
project.commit("nested frontend and five preloads");
for explicit_roots in [false, true] {
let mut environment = vec![("SUPERCOV_KEEP_WORKSPACE", "1")];
if explicit_roots {
environment.push(("SUPERCOV_SOURCE_ROOTS", "src"));
}
project
.supercov_with(&["--", "bun", "test", "src/clamp.test.ts"], &environment)
.succeeds();
for file in std::iter::once("src/clamp.ts".to_owned())
.chain((0..64).map(|index| format!("src/core/runtime/clock{index}.ts")))
{
let code = kept_workspace_source(&project, &file);
let loader = code.find("new Function(\"stack\", \"specifier\"").unwrap_or_else(|| panic!("{file} has no source bootstrap (browser={browser_config}, explicit roots={explicit_roots})"));
let helper = code
.find(" = globalThis.__SUPERCOV_DIRECT_RUNTIME__.mcdcBegin")
.unwrap();
assert!(
loader < helper,
"{file}: runtime initialization follows the first read"
);
}
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(!summary.contains("diagnostic"), "{summary}");
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
assert!(!line.contains("UNCOVERED"), "{line}");
// This fixture deliberately mocks Vitest with a copied bun:test
// namespace. Some Bun versions copy the native exports before the
// adapter; either identity is valid for this bootstrap regression.
assert!(
line.contains("alias import after preloads")
|| line.contains("Background / unattributed"),
"{line}"
);
}
}
}
/// Distinct Bun tests must be identified independently, rather than
/// crediting the combined coverage to an unnamed process.
#[cfg(unix)]
#[test]
fn bun_tests_have_separate_test_attribution() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = bun_project("bun-test-attribution", false);
project.write(
"src/clamp.test.ts",
r#"import { expect, test } from "bun:test";
import { clamp } from "./clamp";
test("below", () => expect(clamp(-1, 0, 10)).toBe(0));
test("above", () => expect(clamp(11, 0, 10)).toBe(10));
"#,
);
project.commit("two tests");
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 2 test(s)", "Total 2", "Passed 2"],
);
}
#[cfg(unix)]
#[test]
fn bun_concurrent_async_tests_keep_exact_coverage_and_complete_all_metrics() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-concurrent-attribution", false);
project.write(
"src/clamp.test.ts",
r#"import { describe, test, expect } from 'bun:test';
import { clamp } from './clamp';
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
describe('bounds', () => {
const run = test.concurrent ?? test;
run('below', async () => { await pause(30); expect(clamp(-1,0,10)).toBe(0); await pause(5); });
run('nan', async () => { await pause(5); expect(clamp(NaN,0,10)).toBe(0); await pause(20); });
run('above', async () => { await pause(20); expect(clamp(11,0,10)).toBe(10); });
run('inside', async () => { await pause(10); expect(clamp(5,0,10)).toBe(5); });
});
"#,
);
project.commit("overlapping async tests");
let native = std::process::Command::new("bun")
.args(["test"])
.current_dir(&project.root)
.output()
.unwrap();
assert!(
native.status.success(),
"native Bun: {}",
String::from_utf8_lossy(&native.stderr)
);
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Exact for 4 test(s)",
"Total 4",
"Passed 4",
"Lines 100.00%",
"Branches 100.00%",
"MC/DC 100.00%",
],
);
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
contains_all(
&line,
&["bounds > above [", "bounds > inside [", "unit/bun:test"],
);
assert!(!line.contains("bounds > below ["), "{line}");
assert!(!line.contains("bounds > nan ["), "{line}");
}
#[cfg(unix)]
#[test]
fn bun_configured_preloads_importing_test_keep_exact_test_and_hook_scopes() {
if !bun_is_available() {
return;
}
let project = bun_project("bun configured preload attribution", false);
let config = "# Keep the project's settings and preload order.\n[test]\ntimeout = 5000\npreload = [\"./first.ts\", \"./second.ts\"]\n";
project.write("bunfig.toml", config);
project.write(
"src/setup-only.ts",
"export function setupOnly() {\n return 7;\n}\n",
);
project.write("first.ts", "import { test, beforeEach } from 'bun:test';\nglobalThis.preloadOrder = ['first'];\nbeforeEach(async () => { const { setupOnly } = await import('./src/setup-only'); setupOnly(); });\n");
project.write("second.ts", "import { mock } from 'bun:test';\nimport * as native from 'bun:test';\nglobalThis.preloadOrder.push('second');\nmock.module('vitest', () => ({ ...native }));\n");
project.write("src/clamp.test.ts", "import { test, expect } from 'bun:test';\nimport { clamp } from './clamp';\ntest('ready slot', async () => { await Promise.resolve(); expect(globalThis.preloadOrder).toEqual(['first', 'second']); expect(clamp(11, 0, 10)).toBe(10); });\n");
project.write("src/compat.test.ts", "import { test, expect } from 'vitest';\nimport { clamp } from './clamp';\ntest('compatible slot', () => { expect(clamp(5, 0, 10)).toBe(5); });\n");
project.commit("configured preloads import the test module");
for _ in 0..2 {
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 2 test(s)", "Total 2", "Passed 2"],
);
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
contains_all(&line, &["ready slot", "compatible slot"]);
let setup = project
.supercov(&["runs", "latest", "line", "src/setup-only.ts:2"])
.succeeds();
contains_all(&setup, &["COVERED"]);
assert!(
!setup.contains("ready slot"),
"hook work was credited to a test body: {setup}"
);
assert!(
!setup.contains("compatible slot"),
"hook work was credited to a test body: {setup}"
);
assert_eq!(
std::fs::read_to_string(project.root.join("bunfig.toml")).unwrap(),
config
);
assert!(project.git(&["status", "--porcelain"]).trim().is_empty());
}
}
#[cfg(unix)]
#[test]
fn bun_string_preload_keeps_named_tests_and_original_configuration() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-string-preload", false);
let config = "[test]\npreload = './preload.ts'\n";
project.write("bunfig.toml", config);
project.write("preload.ts", "import { test } from 'bun:test';\nif (typeof test !== 'function') throw new Error('test API missing');\n");
project.commit("string preload imports the test module");
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 1 test(s)", "Total 1", "Passed 1"],
);
let named = project
.supercov(&["runs", "latest", "test", "clamps below"])
.succeeds();
contains_all(&named, &["clamps below", "bun:test"]);
assert_eq!(project.read("bunfig.toml"), config);
}
#[cfg(unix)]
#[test]
fn bun_preloads_namespace_and_commonjs_imports_keep_named_test_scopes() {
if !bun_is_available() {
return;
}
let project = bun_project("bun preload paths with spaces", false);
project.write("user-options.mjs", "import { beforeEach } from 'bun:test';\nglobalThis.optionsLoaded = true;\nbeforeEach(() => { globalThis.optionsHook = true; });\n");
project.write("user-config.mjs", "globalThis.configLoaded = true;\n");
project.write("bunfig.toml", "[test]\npreload = [\"./user-config.mjs\"]\n");
project.write("src/clamp.test.ts", "import * as suite from 'bun:test';\nimport { clamp } from './clamp';\nsuite.describe('namespace', () => suite.test('below', () => { suite.expect(globalThis.optionsLoaded && globalThis.configLoaded && globalThis.optionsHook).toBe(true); suite.expect(clamp(-1,0,10)).toBe(0); }));\n");
project.write("src/other.test.cjs", "const { describe, it, expect } = require('bun:test');\nconst { clamp } = require('./clamp.ts');\ndescribe('commonjs', () => it('above', () => { expect(globalThis.optionsLoaded && globalThis.configLoaded && globalThis.optionsHook).toBe(true); expect(clamp(11,0,10)).toBe(10); }));\n");
project.commit("preloads and both import styles");
project
.supercov_with(
&["--", "bun", "test"],
&[("BUN_OPTIONS", "--preload=./user-options.mjs --smol")],
)
.succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 2 test(s)", "Total 2", "Passed 2"],
);
let tests = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:2"])
.succeeds();
contains_all(
&tests,
&["namespace > below", "commonjs > above", "bun:test"],
);
}
#[cfg(unix)]
#[test]
fn bun_parameterized_rows_callbacks_and_bound_registrations_keep_separate_scopes() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-parameterized", false);
project.write("src/clamp.test.ts", r#"import { test, describe, expect } from 'bun:test';
import { clamp } from './clamp';
describe('rows', () => {
test.each([[-1,0],[11,10],[5,5]])('clamp %# %d', (value, expected) => expect(clamp(value,0,10)).toBe(expected));
test.each([[() => -1]])('function data', fn => expect(clamp(fn(),0,10)).toBe(0));
test.each([[11]])('done row', (value, done) => { setTimeout(() => { expect(clamp(value,0,10)).toBe(10); done(); }, 1); });
test('done', done => { setTimeout(() => { expect(clamp(5,0,10)).toBe(5); done(); }, 1); });
test.bind(null)('bound', () => expect(clamp(-1,0,10)).toBe(0));
test.call(null, 'called', () => expect(clamp(11,0,10)).toBe(10));
test.apply(null, ['applied', () => expect(clamp(5,0,10)).toBe(5)]);
});
"#);
project.commit("parameterized and callback registrations");
let native = std::process::Command::new("bun")
.args(["test"])
.current_dir(&project.root)
.output()
.unwrap();
assert!(
native.status.success(),
"native Bun: {}",
String::from_utf8_lossy(&native.stderr)
);
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 9 test(s)", "Total 9", "Passed 9"],
);
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
contains_all(
&line,
&[
"clamp %# %d [row 2]",
"clamp %# %d [row 3]",
"done row [row 1]",
"rows > done",
"rows > called",
"rows > applied",
],
);
assert!(!line.contains("clamp %# %d [row 1]"), "{line}");
assert!(!line.contains("rows > bound ["), "{line}");
}
#[cfg(unix)]
#[test]
fn bun_failure_and_skip_outcomes_do_not_become_passes() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-outcomes", false);
project.write(
"src/clamp.test.ts",
r#"import { test, describe, expect } from 'bun:test';
import { clamp } from './clamp';
test('throws false', () => { clamp(-1,0,10); throw false; });
test('rejects zero', async () => { clamp(11,0,10); return Promise.reject(0); });
test('done fails', done => { clamp(5,0,10); done(new Error('expected')); });
test.skip('skipped', () => { throw new Error('skip executed'); });
test.todo('todo');
describe.skip('outer skip', () => test('nested', () => { throw new Error('nested executed'); }));
test.if(false)('conditional', () => { throw new Error('conditional executed'); });
test('passes', () => expect(clamp(5,0,10)).toBe(5));
"#,
);
project.commit("failure and selection outcomes");
project.supercov(&["--", "bun", "test"]).exits(1);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Passed 1", "Failed 3", "Skipped 3"],
);
for name in ["throws false", "rejects zero", "done fails"] {
let test = project
.supercov(&["runs", "latest", "test", name])
.succeeds();
contains_all(&test, &["failed", name]);
}
}
#[cfg(unix)]
#[test]
fn bun_run_sources_do_not_require_a_native_test_api() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-run", false);
project.write("main.ts", "import { clamp } from './src/clamp';\nif (clamp(11,0,10) !== 10) throw new Error('wrong result');\n");
project.commit("ordinary bun program");
project
.supercov(&["--", "bun", "run", "main.ts"])
.succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Lines 100.00%"]);
}
#[cfg(unix)]
#[test]
fn bun_hooks_keep_setup_coverage_separate_from_test_bodies() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-hook-scopes", false);
project.write("src/clamp.test.ts", r#"import { test, describe, beforeAll, beforeEach, afterEach, afterAll, expect } from 'bun:test';
import { clamp } from './clamp';
describe('hooks', () => {
beforeAll(function initialize() { expect(clamp(-1,0,10)).toBe(0); });
beforeEach(async function arrange() { await Promise.resolve(); expect(clamp(NaN,0,10)).toBe(0); });
afterEach(function cleanup() { expect(clamp(11,0,10)).toBe(10); });
afterAll(function dispose() { expect(clamp(-1,0,10)).toBe(0); });
test('inside', () => expect(clamp(5,0,10)).toBe(5));
});
"#);
project.commit("native lifecycle hooks");
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Total 1",
"Passed 1",
"Lines 100.00%",
"Branches 100.00%",
"MC/DC 100.00%",
],
);
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
contains_all(&line, &["hooks > inside", "[afterEach] cleanup"]);
assert!(!line.contains("[beforeEach] arrange"), "{line}");
}
#[cfg(unix)]
#[test]
fn bun_timed_out_callbacks_keep_their_named_coverage_without_claiming_a_pass() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-timeout-evidence", false);
project.write("src/clamp.test.ts", r#"import { test, expect } from 'bun:test';
import { clamp } from './clamp';
test('times out', async () => { expect(clamp(11,0,10)).toBe(10); await new Promise(() => {}); }, 30);
"#);
project.commit("timeout after source execution");
project.supercov(&["--", "bun", "test"]).exits(1);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Exact for 1 test(s)", "Total 1", "Unknown 1"],
);
assert!(!summary.contains("Passed"), "{summary}");
let line = project
.supercov(&["runs", "latest", "line", "src/clamp.ts:3"])
.succeeds();
contains_all(&line, &["times out", "unit/bun:test"]);
}
/// Host tests still record coverage when a command selects browser initialization.
/// The echo makes discovery select that path without requiring a browser installation.
#[cfg(unix)]
#[test]
fn a_bun_test_with_browser_initialization_runs_and_measures() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = bun_project("bun-mixed-browser", true);
project.write(
"package.json",
r#"{ "name": "bun-clamp", "private": true, "type": "module", "scripts": { "test": "bun test && echo playwright" } }"#,
);
project.commit("mixed script");
project.supercov(&["--", "npm", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Lines 66.67% (2/3)"]);
}
/// A Bun process can initialize coverage without the Node preload. The report
/// must describe the missing attribution without inferring that the process
/// ran in a container or VM.
#[cfg(unix)]
#[test]
fn a_bun_unit_suite_is_not_reported_as_a_container_guest() {
if !bun_is_available() {
eprintln!("skipping: no Bun found");
return;
}
let project = bun_project("bun-not-a-guest", false);
project.supercov(&["--", "bun", "test"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(
!summary.contains("Guests"),
"the host Bun process was reported as a container or VM guest: {summary}"
);
assert!(
!summary.contains("container or VM"),
"the report assumes where the process ran: {summary}"
);
assert!(
summary.contains("Exact for 1 test(s)"),
"the report must describe the available attribution: {summary}"
);
}
#[cfg(unix)]
#[test]
fn jest_tests_are_named_by_their_describe_blocks_and_selected_by_jest() {
let project = Project::empty("jest-names");
project.write(
"package.json",
r#"{ "name": "jest-names", "scripts": { "test": "jest" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nfunction tax(sum) {\n return sum * 2;\n}\nmodule.exports = { fee, tax };\n",
);
project.write(
"test/fee.test.js",
"const { fee, tax } = require(\"../src/fee\");\ndescribe(\"small\", () => {\n test(\"charges\", () => expect(fee(10)).toBe(5));\n});\ndescribe(\"large\", () => {\n describe(\"orders\", () => {\n test(\"charges\", () => expect(tax(10)).toBe(20));\n });\n});\n",
);
project.git(&["init", "-q"]);
project.commit("jest");
project.supercov(&["--", "npx", "jest"]).succeeds();
let tests = project
.supercov(&["runs", "latest", "test", "charges"])
.succeeds();
contains_all(&tests, &["small > charges [", "large > orders > charges ["]);
project.edit("src/fee.js", "? 0 : 5", "? 0 : 6");
let names = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert_eq!(names.trim(), "small charges");
let selected = std::process::Command::new(project.root.join("node_modules/.bin/jest"))
.args(["-t", names.trim()])
.current_dir(&project.root)
.output()
.unwrap();
let output = String::from_utf8_lossy(&selected.stderr);
assert!(output.contains("1 failed, 1 skipped, 2 total"), "{output}");
}
/// A project with the repository's `node_modules` linked in, committed.
#[cfg(unix)]
fn linked_project(label: &str, files: &[(&str, &str)]) -> Project {
let project = Project::empty(label);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
for (path, text) in files {
project.write(path, text);
}
project.git(&["init", "-q"]);
project.commit(label);
project
}
/// The rewritten copy of `file` a kept workspace holds.
#[cfg(unix)]
fn rewritten_test_file(project: &Project, file: &str) -> String {
let workspaces = project.root.join(".supercov/workspaces");
let mut found = Vec::new();
let mut stack = vec![workspaces];
while let Some(directory) = stack.pop() {
for entry in std::fs::read_dir(&directory)
.into_iter()
.flatten()
.flatten()
{
let path = entry.path();
if path.file_name().is_some_and(|name| name == "node_modules") {
continue;
}
if path.is_dir() {
stack.push(path);
} else if path.to_string_lossy().ends_with(file) {
found.push(path);
}
}
}
assert_eq!(found.len(), 1, "{file}: {found:?}");
std::fs::read_to_string(&found[0]).unwrap()
}
/// The command's own run, without Supercov: the fixture is right before
/// Supercov is asked to keep it so.
#[cfg(unix)]
fn passes_plainly(project: &Project, command: &[&str]) {
let ran = std::process::Command::new(command[0])
.args(&command[1..])
.current_dir(&project.root)
.output()
.unwrap();
assert!(
ran.status.success(),
"{}\n{}",
String::from_utf8_lossy(&ran.stdout),
String::from_utf8_lossy(&ran.stderr)
);
}
/// What the test files below share: where it runs.
#[cfg(unix)]
const RUNTIME_PROBE: &str =
"exports.runtime = () => (typeof window === 'undefined' ? 'node' : 'browser');\n";
/// Jest reads a test's pragmas from the comment the file opens with, and
/// Supercov keeps that comment first in the files it rewrites (#235: since
/// 4.25.0 a lint banner went in front of it, and a test marked
/// `@jest-environment node` ran in the project's default environment). The
/// project's default is a browser-like environment; each file below picks
/// `node` its own way, or does not and stays in the default, and asserts
/// where it runs. Jest reads no docblock behind a shebang or a line comment,
/// with or without Supercov.
#[cfg(unix)]
#[test]
fn jest_reads_each_rewritten_test_s_docblock_as_it_reads_the_original() {
let tests: &[(&str, &str, &str)] = &[
(
"multi-line",
"/**\n * @jest-environment node\n */\n",
"node",
),
("one-line", "/** @jest-environment node */\n", "node"),
("same-line", "/** @jest-environment node */ ", "node"),
("single-star", "/* @jest-environment node */\n", "node"),
(
"options",
"/**\n * @jest-environment node\n * @jest-environment-options {\"customExportConditions\": [\"node\"]}\n */\n",
"node",
),
(
"strict",
"/** @jest-environment node */\n'use strict';\n",
"node",
),
("blank-lines", "\n\n/** @jest-environment node */\n", "node"),
(
"crlf",
"/**\r\n * @jest-environment node\r\n */\r\n",
"node",
),
("default", "", "browser"),
("plain-comment", "/* nothing to read here */\n", "browser"),
(
"line-comment-first",
"// a note\n/** @jest-environment node */\n",
"browser",
),
];
let mut files = vec![
(
"package.json".to_owned(),
r#"{ "name": "jest-docblocks", "scripts": { "test": "jest" }, "jest": { "testEnvironment": "<rootDir>/browser-env.js" } }"#.to_owned(),
),
(
"browser-env.js".to_owned(),
"const { TestEnvironment } = require('jest-environment-node');\nmodule.exports = class BrowserLike extends TestEnvironment {\n constructor(config, context) {\n super(config, context);\n this.global.window = this.global;\n }\n};\n".to_owned(),
),
("src/runtime.js".to_owned(), RUNTIME_PROBE.to_owned()),
];
for (name, opening, expected) in tests {
files.push((
format!("test/{name}.test.js"),
format!(
"{opening}const {{ runtime }} = require('../src/runtime');\ntest('runs in {expected}', () => {{\n expect(runtime()).toBe('{expected}');\n}});\n"
),
));
}
let files = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect::<Vec<_>>();
let project = linked_project("jest-docblocks", &files);
passes_plainly(&project, &["node_modules/.bin/jest"]);
let ran = project.supercov_with(&["--", "npx", "jest"], &[("SUPERCOV_KEEP_WORKSPACE", "1")]);
let said = ran.stderr();
ran.succeeds();
assert!(said.contains(&format!("{} passed", tests.len())), "{said}");
for (name, opening, _) in tests {
let rewritten = rewritten_test_file(&project, &format!("test/{name}.test.js"));
// What comes before the file's code (a directive is code).
let comments = opening.split("'use strict'").next().unwrap();
assert!(
rewritten.starts_with(comments),
"{name}: the file opens as it did\n{rewritten}"
);
assert!(
rewritten.contains("/* eslint-disable */"),
"{name}: still exempt from lint\n{rewritten}"
);
}
}
/// `'use strict'` is a directive only at the start of a file's code: a
/// statement Supercov put in front of it (the runtime's loader) made the
/// test file sloppy, and `this` in a plain function call the global object.
/// node:test and Jest, CommonJS files with and without the semicolon, behind
/// a shebang and a docblock.
#[cfg(unix)]
#[test]
fn a_strict_test_file_stays_strict_under_supercov() {
let strict = |opening: &str, runner: &str| {
let (import, check) = if runner == "node" {
(
"const test = require('node:test');\nconst assert = require('node:assert');\n",
"assert.equal(sloppy(), undefined);\n assert.equal(one(), 1);",
)
} else {
(
"",
"expect(sloppy()).toBeUndefined();\n expect(one()).toBe(1);",
)
};
format!(
"{opening}{import}const {{ one }} = require('../src/one');\nfunction sloppy() {{\n return this;\n}}\ntest('is strict', () => {{\n {check}\n}});\n"
)
};
let openings = [
("semicolon", "'use strict';\n"),
("no-semicolon", "\"use strict\"\n"),
("with-comment", "'use strict' // the whole file\n"),
("docblock", "/** strict below */\n'use strict';\n"),
];
let mut files = vec![
(
"package.json".to_owned(),
r#"{ "name": "strict-tests", "scripts": { "test": "node --test" } }"#.to_owned(),
),
(
"src/one.js".to_owned(),
"exports.one = () => 1;\n".to_owned(),
),
];
for (name, opening) in openings {
files.push((format!("test/{name}.test.cjs"), strict(opening, "node")));
}
files.push((
"test/shebang.test.cjs".to_owned(),
strict("#!/usr/bin/env node\n'use strict';\n", "node"),
));
let files = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect::<Vec<_>>();
let project = linked_project("strict-node-tests", &files);
passes_plainly(&project, &["node", "--test"]);
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_KEEP_WORKSPACE", "1")],
);
let said = ran.stdout() + &ran.stderr();
ran.succeeds();
assert!(said.contains("pass 5"), "{said}");
for (name, _) in openings {
let rewritten = rewritten_test_file(&project, &format!("test/{name}.test.cjs"));
assert!(
rewritten.contains("__SUPERCOV_DIRECT_RUNTIME__"),
"{name}: rewritten\n{rewritten}"
);
}
let mut files = vec![
(
"package.json".to_owned(),
r#"{ "name": "strict-jest", "scripts": { "test": "jest" } }"#.to_owned(),
),
(
"src/one.js".to_owned(),
"exports.one = () => 1;\n".to_owned(),
),
];
for (name, opening) in openings {
files.push((format!("test/{name}.test.js"), strict(opening, "jest")));
}
let files = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect::<Vec<_>>();
let project = linked_project("strict-jest-tests", &files);
passes_plainly(&project, &["node_modules/.bin/jest"]);
let ran = project.supercov(&["--", "npx", "jest"]);
let said = ran.stderr();
ran.succeeds();
assert!(said.contains("4 passed"), "{said}");
}
/// The sources Supercov measures keep their directives too: a strict
/// CommonJS module (with or without the semicolon, behind a license comment
/// or a shebang) and a TypeScript one, which also gets Supercov's lint and
/// type banner, stay strict once instrumented, and their code is measured.
#[cfg(unix)]
#[test]
fn strict_sources_stay_strict_once_instrumented() {
let body = "exports.sloppy = function () {\n return this;\n};\nexports.one = (n) => (n > 0 ? 1 : 0);\n";
let sources = [
("src/semicolon.cjs", format!("'use strict';\n{body}")),
("src/no-semicolon.cjs", format!("\"use strict\"\n{body}")),
("src/licensed.cjs", format!("/*! @license MIT */\n'use strict';\n{body}")),
("src/script.cjs", format!("#!/usr/bin/env node\n'use strict';\n{body}")),
(
"src/typed.cts",
"'use strict';\nexports.sloppy = function (this: unknown): unknown {\n return this;\n};\nexports.one = (n: number): number => (n > 0 ? 1 : 0);\n".to_owned(),
),
];
let mut checks = String::from(
"const test = require('node:test');\nconst assert = require('node:assert');\n",
);
for (path, _) in &sources {
checks.push_str(&format!(
"test('{path} is strict', () => {{\n const {{ sloppy, one }} = require('../{path}');\n assert.equal(sloppy(), undefined);\n assert.equal(one(1), 1);\n}});\n"
));
}
let mut files = vec![
(
"package.json".to_owned(),
r#"{ "name": "strict-sources", "scripts": { "test": "node --test" } }"#.to_owned(),
),
("test/sources.test.cjs".to_owned(), checks),
];
files.extend(
sources
.iter()
.map(|(path, text)| ((*path).to_owned(), text.clone())),
);
let files = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect::<Vec<_>>();
let project = linked_project("strict-sources", &files);
passes_plainly(&project, &["node", "--test"]);
let ran = project.supercov(&["--", "node", "--test"]);
let said = ran.stdout() + &ran.stderr();
ran.succeeds();
assert!(said.contains(&format!("pass {}", sources.len())), "{said}");
for (path, _) in &sources {
let file = project
.supercov(&["runs", "latest", "file", path])
.succeeds();
assert!(
file.contains("Tests touching this file: 1"),
"{path} is measured\n{file}"
);
}
}
/// A second run of the same suite restores the instrumented copy from the
/// cache, and with it the one browser runtime the modules Next.js bundles
/// import: 4.28.0 left it out of the cache, and every test importing such a
/// module failed on the second run ("Cannot find module
/// .../browser-runtime.mjs").
#[cfg(unix)]
#[test]
fn a_second_run_restores_the_browser_runtime_the_bundled_modules_import() {
let project = linked_project(
"next-runtime-cache",
&[
(
"package.json",
r#"{ "name": "next-runtime-cache", "type": "module", "dependencies": { "next": "*" }, "scripts": { "test": "vitest run" } }"#,
),
("playwright.config.js", "export default {};\n"),
(
"app/price.mjs",
"export function price(n) {\n return n > 10 ? n - 1 : n;\n}\n",
),
(
"test/price.test.js",
"import { expect, it } from 'vitest';\nimport { price } from '../app/price.mjs';\nit('discounts', () => expect(price(20)).toBe(19));\n",
),
],
);
for run in 1..=2 {
let ran = project.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_SOURCE_ROOTS", "app")],
);
let said = ran.stdout() + &ran.stderr();
assert_eq!(ran.code(), 0, "run {run}\n{said}");
assert!(!said.contains("browser-runtime.mjs"), "run {run}\n{said}");
}
let file = project
.supercov(&["runs", "latest", "file", "app/price.mjs"])
.succeeds();
assert!(file.contains("Tests touching this file: 1"), "{file}");
}
/// Vitest reads `@vitest-environment` (and `@jest-environment`) anywhere in
/// a test file; a rewritten file keeps each where the file had it, and each
/// test runs where it asks to, the project's default a browser-like
/// environment of its own.
#[cfg(unix)]
#[test]
fn vitest_reads_each_rewritten_test_s_environment_as_it_reads_the_original() {
let tests: &[(&str, &str, &str)] = &[
("line", "// @vitest-environment node\n", "node"),
(
"docblock",
"/**\n * @vitest-environment node\n */\n",
"node",
),
("jest-docblock", "/** @jest-environment node */\n", "node"),
(
"after-comment",
"// a note\n// @vitest-environment node\n",
"node",
),
("default", "", "browser"),
];
let mut files = vec![
(
"package.json".to_owned(),
r#"{ "name": "vitest-environments", "type": "module", "scripts": { "test": "vitest run" } }"#.to_owned(),
),
(
"vitest.config.js".to_owned(),
"export default { test: { environment: './browser-env.js' } };\n".to_owned(),
),
(
"browser-env.js".to_owned(),
"export default {\n name: 'browser-like',\n viteEnvironment: 'ssr',\n setup() {\n globalThis.window = globalThis;\n return { teardown() { delete globalThis.window; } };\n },\n};\n".to_owned(),
),
(
"src/runtime.js".to_owned(),
"export const runtime = () => (typeof window === 'undefined' ? 'node' : 'browser');\n".to_owned(),
),
];
for (name, opening, expected) in tests {
files.push((
format!("test/{name}.test.js"),
format!(
"{opening}import {{ expect, test }} from 'vitest';\nimport {{ runtime }} from '../src/runtime.js';\ntest('runs in {expected}', () => {{\n expect(runtime()).toBe('{expected}');\n}});\n"
),
));
}
let files = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect::<Vec<_>>();
let project = linked_project("vitest-environments", &files);
passes_plainly(&project, &["node_modules/.bin/vitest", "run"]);
let ran = project.supercov(&["--", "npx", "vitest", "run"]);
let said = ran.stdout() + &ran.stderr();
ran.succeeds();
assert!(said.contains(&format!("{} passed", tests.len())), "{said}");
}
#[cfg(unix)]
#[test]
fn mocha_tests_are_attributed_one_by_one_and_selected_by_grep() {
let project = Project::empty("mocha-tests");
project.write(
"package.json",
r#"{ "name": "mocha-tests", "type": "module", "scripts": { "test": "mocha" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/cart.js",
"export function total(items) {\n return items.reduce((sum, item) => sum + item.price, 0);\n}\nexport function discount(sum, code) {\n if (code === \"HALF\") {\n return sum / 2;\n }\n return sum;\n}\nexport function prepare() {\n return 1;\n}\nlet calls = 0;\nexport function flaky() {\n calls += 1;\n return calls > 1;\n}\n",
);
project.write(
"test/cart.test.js",
"import assert from \"node:assert/strict\";\nimport { total, discount, prepare, flaky } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n before(() => prepare());\n describe(\"total\", () => {\n it(\"adds prices\", () => assert.equal(total([{ price: 2 }, { price: 3 }]), 5));\n });\n describe(\"discount\", () => {\n it(\"halves with HALF\", () => assert.equal(discount(10, \"HALF\"), 5));\n it.skip(\"keeps the sum otherwise\", () => assert.equal(discount(10, \"X\"), 10));\n });\n it(\"passes on its second try\", function () {\n this.retries(1);\n assert.ok(flaky());\n });\n});\n",
);
project.git(&["init", "-q"]);
project.commit("mocha");
// Serially, with --parallel, where each worker runs its own files, and
// with --check-leaks, which must not see Supercov's own globals.
for command in [
&["--", "npx", "mocha"][..],
&["--", "npx", "mocha", "--parallel"],
&["--", "npx", "mocha", "--check-leaks"],
] {
project.supercov(command).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Attribution Exact for 4 test(s)",
"Passed 2",
"Flaky 1",
"Skipped 1",
],
);
}
// The before hook ran as setup, not inside the first test.
let hook = project
.supercov(&["runs", "latest", "line", "src/cart.js:11"])
.succeeds();
assert!(!hook.contains("adds prices ["), "{hook}");
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:6"])
.succeeds();
contains_all(
&line,
&[
"cart > discount > halves with HALF [",
"unit/mocha",
"node:assert/strict.equal (passed)",
],
);
assert!(!line.contains("adds prices ["), "{line}");
project.edit("src/cart.js", "return sum / 2;", "return sum * 0.5;");
let names = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert!(
names
.lines()
.any(|name| name == "cart discount halves with HALF"),
"{names}"
);
let selected = std::process::Command::new(project.root.join("node_modules/.bin/mocha"))
.args(["--grep", "cart discount halves with HALF"])
.current_dir(&project.root)
.output()
.unwrap();
let output = String::from_utf8_lossy(&selected.stdout);
assert!(output.contains("1 passing"), "{output}");
assert!(!output.contains("pending"), "{output}");
}
#[cfg(unix)]
#[test]
fn a_one_line_helper_that_returns_a_check_is_still_awaited() {
let project = Project::empty("returned-check");
project.write(
"package.json",
r#"{ "name": "returned-check", "private": true, "type": "module" }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write("src/one.ts", "export const one = () => 1;\n");
project.write(
"playwright.config.ts",
"export default { testDir: \"tests\", reporter: \"line\" };\n",
);
// `settles` returns the check; `await settles(...)` waits for it only if
// the helper still does once its `expect` is measured.
project.write(
"tests/helper.spec.ts",
"import { expect, test } from \"@playwright/test\";\nimport { one } from \"../src/one\";\nlet done = false;\nconst slow = () => new Promise<number>((resolve) => setTimeout(() => { done = true; resolve(one()); }, 300));\nconst settles = (value: Promise<number>) => expect(value).resolves.toBe(1);\ntest(\"waits for its check\", async () => {\n await settles(slow());\n expect(done).toBe(true);\n});\n",
);
project.git(&["init", "-q"]);
project.commit("returned check");
let run = project
.supercov(&["--", "npx", "playwright", "test"])
.succeeds();
assert!(run.contains("1 passed"), "{run}");
}
/// A Playwright config that names no `testDir` finds its tests beside
/// itself, as plain Playwright does, though Supercov's config wraps it from
/// `.supercov/` (playwright-test-coverage: tests in `e2e/`, none named).
#[cfg(unix)]
#[test]
fn a_playwright_config_without_a_test_dir_finds_the_tests_beside_it() {
let project = Project::empty("no-test-dir");
project.write(
"package.json",
r#"{ "name": "no-test-dir", "private": true, "type": "module" }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write("src/one.ts", "export const one = () => 1;\n");
project.write(
"playwright.config.ts",
"export default { reporter: \"line\" };\n",
);
project.write(
"e2e/one.test.ts",
"import { expect, test } from \"@playwright/test\";\nimport { one } from \"../src/one\";\ntest(\"one\", () => expect(one()).toBe(1));\n",
);
project.git(&["init", "-q"]);
project.commit("no test dir");
let run = project
.supercov(&["--", "npx", "playwright", "test"])
.succeeds();
assert!(run.contains("1 passed"), "{run}");
}
#[cfg(unix)]
#[test]
fn ava_tests_running_at_once_are_attributed_each_to_its_own() {
let project = Project::empty("ava-tests");
project.write(
"package.json",
r#"{ "name": "ava-tests", "type": "module", "scripts": { "test": "ava" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/cart.js",
"export function discount(sum, code) {\n if (code === \"HALF\") {\n return sum / 2;\n }\n return sum;\n}\n",
);
// `halves` is still waiting when `keeps` runs: AVA runs a file's tests
// at once, so only the carrier, not the clock, can tell them apart.
project.write(
"test/cart.test.js",
"import test from \"ava\";\nimport { discount } from \"../src/cart.js\";\ntest(\"halves\", async (t) => {\n await new Promise((resolve) => setTimeout(resolve, 50));\n t.is(discount(10, \"HALF\"), 5);\n});\ntest(\"keeps\", async (t) => {\n t.is(discount(10, \"X\"), 10);\n await new Promise((resolve) => setTimeout(resolve, 50));\n});\ntest.skip(\"skipped\", (t) => t.pass());\ntest.todo(\"later\");\n",
);
project.git(&["init", "-q"]);
project.commit("ava");
for command in [
&["--", "npx", "ava"][..],
&["--", "npx", "ava", "--no-worker-threads"],
] {
project.supercov(command).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Attribution Exact for 4 test(s)",
"Passed 2",
"Skipped 2",
],
);
let halved = project
.supercov(&["runs", "latest", "line", "src/cart.js:3"])
.succeeds();
assert!(halved.contains("halves [ava:"), "{halved}");
assert!(!halved.contains("keeps [ava:"), "{halved}");
let kept = project
.supercov(&["runs", "latest", "line", "src/cart.js:5"])
.succeeds();
assert!(kept.contains("keeps [ava:"), "{kept}");
assert!(!kept.contains("halves [ava:"), "{kept}");
}
project.edit("src/cart.js", "return sum / 2;", "return sum * 0.5;");
// Both ran discount; the skipped and todo tests have no pass to keep.
let names = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert_eq!(names.trim(), "halves\nkeeps\nlater\nskipped");
let selected = std::process::Command::new(project.root.join("node_modules/.bin/ava"))
.args(["--match", "halves"])
.current_dir(&project.root)
.output()
.unwrap();
// AVA on its own, with nothing of Supercov's. When it fails it says why
// on the other stream, and this printed an empty string.
let output = String::from_utf8_lossy(&selected.stdout);
assert!(
output.contains("1 test passed"),
"{:?}\n{output}\n{}",
selected.status,
String::from_utf8_lossy(&selected.stderr)
);
}
#[cfg(unix)]
#[test]
fn tap_subtests_running_at_once_are_attributed_each_to_its_own() {
let project = Project::empty("tap-tests");
project.write("package.json", r#"{ "name": "tap-tests" }"#);
// tap 15 and 16 are libtap with a CLI that runs each test file as a
// process of its own, marked with TAP_CHILD_ID; this is one such process.
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../node_modules")
.canonicalize()
.unwrap();
project.write(
"node_modules/tap/package.json",
r#"{ "name": "tap", "version": "16.0.0", "main": "index.js" }"#,
);
project.write(
"node_modules/tap/index.js",
"module.exports = require(\"libtap\");\n",
);
std::os::unix::fs::symlink(
modules.join("libtap"),
project.root.join("node_modules/libtap"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/cart.js",
"exports.discount = function discount(sum, code) {\n if (code === \"HALF\") {\n return sum / 2;\n }\n return sum;\n};\n",
);
// With two jobs `halves` is still waiting when `group > keeps` runs.
project.write(
"test/cart.test.js",
"const t = require(\"tap\");\nconst { discount } = require(\"../src/cart\");\nt.jobs = 2;\nt.test(\"halves\", async (t) => {\n await new Promise((resolve) => setTimeout(resolve, 50));\n t.equal(discount(10, \"HALF\"), 5);\n});\nt.test(\"group\", async (t) => {\n t.test(\"keeps\", async (t) => {\n t.equal(discount(10, \"X\"), 10);\n await new Promise((resolve) => setTimeout(resolve, 50));\n });\n});\nt.test(\"skipped\", { skip: true }, async (t) => t.pass());\n",
);
project.git(&["init", "-q"]);
project
.supercov_with(
&["--", "node", "test/cart.test.js"],
&[("TAP_CHILD_ID", "1")],
)
.succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Attribution Exact for 4 test(s)",
"Passed 3",
"Skipped 1",
],
);
let halved = project
.supercov(&["runs", "latest", "line", "src/cart.js:3"])
.succeeds();
assert!(halved.contains("halves [tap:"), "{halved}");
assert!(!halved.contains("keeps [tap:"), "{halved}");
let kept = project
.supercov(&["runs", "latest", "line", "src/cart.js:5"])
.succeeds();
assert!(kept.contains("group > keeps [tap:"), "{kept}");
assert!(!kept.contains("halves [tap:"), "{kept}");
assert!(!kept.contains(" group [tap:"), "{kept}");
}
#[cfg(unix)]
#[test]
fn typescript_tests_compiled_into_another_directory_run_and_are_measured() {
let project = Project::empty("tsc-outdir");
project.write(
"package.json",
r#"{ "name": "tsc-outdir", "scripts": { "test": "tsc -p . && node --test dist/test/fee.test.js" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\ndist\n");
// A strict check of the test file too, and CommonJS output in `dist/`.
project.write(
"tsconfig.json",
r#"{ "compilerOptions": { "module": "commonjs", "target": "es2022", "outDir": "dist", "rootDir": ".", "strict": true, "types": ["node"] }, "include": ["src", "test"] }"#,
);
project.write(
"src/fee.ts",
"export function fee(sum: number): number {\n return sum > 100 ? 0 : 5;\n}\n",
);
project.write(
"test/fee.test.ts",
"import { test } from \"node:test\";\nimport { equal } from \"node:assert/strict\";\nimport { fee } from \"../src/fee\";\n\ntest(\"small orders pay\", () => equal(fee(10), 5));\n",
);
project.git(&["init", "-q"]);
// The test file used to import the runtime by a path that pointed nowhere
// once compiled into dist/.
project.supercov(&["--", "npm", "test"]).succeeds();
let line = project
.supercov(&["runs", "latest", "line", "src/fee.ts:2"])
.succeeds();
assert!(line.contains("small orders pay ["), "{line}");
}
#[test]
fn the_command_runs_as_given_and_a_build_is_the_commands_to_run() {
let project = Project::empty("built");
project.write(
"package.json",
r#"{ "name": "built", "scripts": { "build": "node build.js", "test": "node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\ndist\n.supercov\n");
project.write(
"build.js",
"const fs = require('node:fs');\nfs.mkdirSync('dist', { recursive: true });\nfs.copyFileSync('src/fee.js', 'dist/fee.js');\n",
);
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../dist/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
project.git(&["init", "-q"]);
// Supercov used to run `npm run build` first here, unasked. The command
// runs as given now, in a copy that starts without build output, and a
// run that fails says what that means.
let unbuilt = project.supercov(&["--", "npm", "test"]);
assert_ne!(unbuilt.code(), 0, "{}", unbuilt.stdout());
let said = format!("{}{}", unbuilt.stdout(), unbuilt.stderr());
assert!(
said.contains("starts without build output") && said.contains("npm run build && npm test"),
"{said}"
);
// Nothing built here: the copy lacks nothing this checkout has, and
// nothing is said before the suite runs.
assert!(!said.contains("starts without `dist/`"), "{said}");
// Built here, as a CI job builds before it measures: the copy starts
// without `dist/`, and that is said before the suite runs, ahead of what
// its failure says at the end.
let built_here = std::process::Command::new("node")
.arg("build.js")
.current_dir(&project.root)
.status()
.unwrap();
assert!(built_here.success());
let early = project.supercov(&["--", "npm", "test"]);
assert_ne!(early.code(), 0, "{}", early.stdout());
let said = early.stderr();
let note = said
.find("the copy the command runs in starts without `dist/`, which this checkout has, and the command does not run `npm run build`")
.unwrap_or_else(|| panic!("{said}"));
let end = said
.find("starts without build output")
.unwrap_or_else(|| panic!("{said}"));
assert!(note < end, "{said}");
// The folder is made first, as this checkout has it: a build that
// starts by removing it (`rm -r dist`) fails in a copy without it.
assert!(
said.contains("supercov -- sh -c \"mkdir -p dist && npm run build && npm test\""),
"{said}"
);
// A command that fails after its tests passed: no test failed, and the
// build the copy starts without is named as what may be missing.
project.write(
"test/plain.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('plain orders pay', () => equal(fee(1), 5));\n",
);
let after = project.supercov(&["--", "sh", "-c", "node --test test/plain.test.js && exit 3"]);
assert_eq!(after.code(), 3, "{}", after.stdout());
assert!(
after
.stderr()
.contains("exited 3 and no test it reported failed. It ran in a copy of the project that starts without build output"),
"{}",
after.stderr()
);
// A command that builds by another name, and whose build failed, is not
// told to add one: its own build is what to look at.
let elsewhere = project.supercov(&["--", "sh", "-c", "npm run build:ci; npm test"]);
assert_ne!(elsewhere.code(), 0, "{}", elsewhere.stdout());
let said = format!("{}{}", elsewhere.stdout(), elsewhere.stderr());
assert!(!said.contains("starts without build output"), "{said}");
// With the build in the command, it compiles the instrumented copy, and
// what the tests run is measured.
let built = project.supercov(&["--", "sh", "-c", "npm run build && npm test"]);
let said = format!("{}{}", built.stdout(), built.stderr());
built.succeeds();
assert!(!said.contains("starts without build output"), "{said}");
assert!(!said.contains("starts without `dist/`"), "{said}");
let line = project
.supercov(&["runs", "latest", "line", "src/fee.js:2"])
.succeeds();
assert!(line.contains("small orders pay"), "{line}");
// A command that builds and then runs no test: said, though no build
// is missing.
let none = project.supercov(&["--", "sh", "-c", "npm run build && exit 4"]);
assert_eq!(none.code(), 4, "{}", none.stdout());
assert!(
none.stderr().contains(
"the command exited 4 and the run recorded no test: its own output above says why"
),
"{}",
none.stderr()
);
// A test that fails on its own is named, and the build is not blamed.
project.write(
"test/wrong.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('large orders are free', () => equal(fee(200), 5));\n",
);
let failed = project.supercov(&[
"--",
"sh",
"-c",
"npm run build && node --test test/fee.test.js test/wrong.test.js",
]);
assert_ne!(failed.code(), 0, "{}", failed.stdout());
let said = failed.stderr();
assert!(
said.contains("1 test(s) failed: large orders are free"),
"{said}"
);
assert!(!said.contains("starts without build output"), "{said}");
// A build the command starts from its own code, as a test harness
// may, failed: the build is named, not taken for one the
// command never ran.
project.write(
"package.json",
r#"{ "name": "built", "scripts": { "build": "node build.js && exit 2", "test": "node harness.mjs" } }"#,
);
project.write(
"harness.mjs",
"import { execSync } from 'node:child_process';\nexecSync('npm run build', { stdio: 'inherit' });\n",
);
let harness = project.supercov(&["--", "npm", "test"]);
assert_ne!(harness.code(), 0, "{}", harness.stdout());
let said = format!("{}{}", harness.stdout(), harness.stderr());
assert!(
said.contains("the build the command started, `npm run build`, exited 2"),
"{said}"
);
assert!(!said.contains("starts without build output"), "{said}");
// The failed build's record reads back as one, not as a malformed line.
let report = project.supercov(&["runs", "latest"]).exits(0);
assert!(!report.contains("malformed"), "{report}");
}
#[cfg(unix)]
#[test]
fn a_tool_that_judges_source_reads_it_as_it_was_written() {
let project = Project::empty("judged");
let script = |tool: &str| {
format!(
r#"{{ "name": "judged", "scripts": {{ "test": "{tool} src && node --test test/fee.test.js" }} }}"#
)
};
project.write("package.json", &script("oxlint"));
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
// What a native linter does, as far as it matters here: it reads the
// files itself, fails on a line nobody wrote, and leaves a report.
let linter = "#!/bin/sh\nif grep -rl supercov \"$1\"; then exit 3; fi\ngrep -c '' \"$1\"/fee.js > lint-report.txt\n";
for tool in ["oxlint", "housestyle"] {
project.write_script(&format!("node_modules/.bin/{tool}"), linter);
}
project.git(&["init", "-q"]);
// Biome, oxlint, dprint, cspell and knip read the instrumented files and
// failed a test script that ran them first. The workspace's own `.bin`
// starts such a tool on the source as it was written, and what it writes
// is the command's output like any other.
project.supercov(&["--", "npm", "test"]).succeeds();
assert_eq!(project.read("lint-report.txt"), "4\n");
let line = project
.supercov(&["runs", "latest", "line", "src/fee.js:2"])
.succeeds();
assert!(line.contains("small orders pay"), "{line}");
// The same tool installed for the whole machine, and started without a
// package manager, is found through PATH.
let machine = project.root.join("machine-tools");
std::fs::create_dir(&machine).unwrap();
std::fs::rename(
project.root.join("node_modules/.bin/oxlint"),
machine.join("oxlint"),
)
.unwrap();
let path = format!(
"{}:{}",
machine.display(),
std::env::var("PATH").unwrap_or_default()
);
project
.supercov_with(&["--", "sh", "-c", "oxlint src"], &[("PATH", &path)])
.succeeds();
// A tool Supercov does not know reads what is there, until it is named.
project.write("package.json", &script("housestyle"));
let unnamed = project.supercov(&["--", "npm", "test"]);
assert_ne!(unnamed.code(), 0, "{}", unnamed.stdout());
project
.supercov_with(
&["--", "npm", "test"],
&[("SUPERCOV_SOURCE_TOOLS", "housestyle")],
)
.succeeds();
}
#[test]
fn nothing_is_still_being_deleted_when_the_command_has_ended() {
let project = Project::empty("swept");
project.write(
"package.json",
r#"{ "name": "swept", "scripts": { "test": "node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", ".supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
// A project of some size: the copy a run replaces takes a while to unlink.
for directory in 0..60 {
let assets = project.root.join(format!("assets/d{directory}"));
std::fs::create_dir_all(&assets).unwrap();
for file in 0..100 {
std::fs::write(assets.join(format!("f{file}.txt")), "x").unwrap();
}
}
project.git(&["init", "-q"]);
// The copy went to `.supercov/.trash` before the command started and was
// unlinked only after it ended, by a process Supercov waited a tenth of a
// second for. It was still going when the next command began, and one
// that walks the project met a directory on its way out: AVA, which looks
// for test files in every directory, failed on `EINVAL: invalid argument,
// scandir '.supercov/.trash/...'`.
for _ in 0..3 {
project.supercov(&["--", "npm", "test"]).succeeds();
let left = match std::fs::read_dir(project.root.join(".supercov/.trash")) {
Ok(entries) => entries
.map(|entry| entry.unwrap().file_name())
.filter(|name| name != ".deleter.lock")
.collect::<Vec<_>>(),
Err(_) => Vec::new(),
};
assert!(left.is_empty(), "{left:?}");
}
}
#[test]
fn a_report_the_command_writes_names_the_project_and_not_the_copy() {
// Under Vitest `coverage-final.json` keyed every file by its path in
// Supercov's copy, and `clover.xml` and Cobertura's `<source>` named the
// copy too: the command runs there, so anything that writes where it is
// writes that. A reporter that writes where it ran stands in for them.
let project = Project::empty("named");
project.write(
"package.json",
r#"{ "name": "named", "scripts": { "test": "node --test test/fee.test.js && node report.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\ncoverage\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('pays', () => equal(fee(1), 5));\n",
);
project.write(
"report.js",
"const fs = require('node:fs');\nconst path = require('node:path');\nconst file = path.resolve('src/fee.js');\nfs.mkdirSync('coverage', { recursive: true });\nfs.writeFileSync('coverage/coverage-final.json', JSON.stringify({ [file]: { path: file } }));\nfs.writeFileSync('coverage/cobertura.xml', `<source>${process.cwd()}</source>`);\n",
);
project.git(&["init", "-q"]);
let run = project.supercov(&["--", "npm", "test"]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
// Windows spells the test's own directory `\\?\C:\…`; a tool spells it
// without the prefix.
let plain = |path: &std::path::Path| {
let text = path.display().to_string();
text.strip_prefix(r"\\?\").unwrap_or(&text).to_owned()
};
let root = plain(&project.root);
let report: serde_json::Value =
serde_json::from_str(&project.read("coverage/coverage-final.json")).unwrap();
let file = plain(&project.root.join("src").join("fee.js"));
assert_eq!(report[&file]["path"], file, "{report}");
assert_eq!(
project.read("coverage/cobertura.xml"),
format!("<source>{root}</source>")
);
}
#[cfg(unix)]
#[test]
fn a_comparison_says_which_files_the_difference_is_in() {
// Two end-to-end runs of one commit differed by 79 rows, and 45 of the 63
// lost lines were one component that rendered in one run and not in the
// other. The rows said so only once they were counted by hand.
let project = Project::empty("where");
project.write(
"package.json",
r#"{ "name": "where", "scripts": { "test": "node --test test/*.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/panel.js",
"function panel(rows) {\n const out = [];\n for (const row of rows) {\n out.push(row.name);\n }\n out.sort();\n return out.join(',');\n}\nmodule.exports = { panel };\n",
);
project.write(
"src/fee.js",
"function fee(sum) {\n if (sum > 100) {\n return 0;\n }\n return 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/app.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\nconst { panel } = require('../src/panel.js');\nconst state = process.env.STATE;\ntest('renders', () => {\n if (state === 'full') equal(panel([{ name: 'a' }]), 'a');\n equal(fee(state === 'full' ? 1 : 500), state === 'full' ? 5 : 0);\n});\n",
);
project.git(&["init", "-q"]);
let run = |state: &str| {
project
.supercov_with(&["--", "npm", "test"], &[("STATE", state)])
.succeeds();
project.supercov(&["runs", "--limit", "1", "--json"]).json()["data"]["runs"][0]["id"]
.as_str()
.unwrap()
.to_owned()
};
let (full, bare) = (run("full"), run("bare"));
let text = project.supercov(&["diff", &full, &bare]).succeeds();
// The file that lost most comes first, with what each lost and gained.
contains_all(
&text,
&[
"in 2 files, most lost first:\n src/panel.js: lost 6 lines, 1 branch\n src/fee.js: lost 1 line, 1 branch; gained 1 line, 1 branch\n",
"- line src/panel.js:2",
],
);
assert!(
text.find("in 2 files").unwrap() < text.find("- line").unwrap(),
"{text}"
);
let json = project.supercov(&["diff", &full, &bare, "--json"]).json();
assert_eq!(json["data"]["files"], 2, "{json}");
assert_eq!(json["data"]["byFile"][0]["file"], "src/panel.js");
assert_eq!(json["data"]["byFile"][0]["lost"]["lines"], 6);
assert_eq!(json["data"]["byFile"][1]["gained"]["branches"], 1);
// The summary counts the whole difference, not the page shown.
let paged = project
.supercov(&["diff", &full, &bare, "--limit", "1", "--json"])
.json();
assert_eq!(paged["data"]["byFile"][0]["lost"]["lines"], 6);
}
#[cfg(unix)]
#[test]
fn a_comparison_says_when_both_runs_measured_the_same_source() {
let project = Project::empty("steady");
project.write(
"package.json",
r#"{ "name": "steady", "scripts": { "test": "node --test test/*.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n if (sum > 100) {\n return 0;\n }\n return 5;\n}\nmodule.exports = { fee };\n",
);
// What the test reaches depends on something outside the code, as an
// end-to-end suite's does on timing.
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\nconst order = process.env.ORDER;\ntest('pays', () => {\n if (order !== 'small') equal(fee(500), 0);\n if (order !== 'large') equal(fee(1), 5);\n});\n",
);
project.git(&["init", "-q"]);
let run = |order: &str| {
project
.supercov_with(&["--", "npm", "test"], &[("ORDER", order)])
.succeeds();
project.supercov(&["runs", "--limit", "1", "--json"]).json()["data"]["runs"][0]["id"]
.as_str()
.unwrap()
.to_owned()
};
// Two end-to-end runs of one commit read "lost: 11 lines, 31 branches",
// and nothing said that no code had changed between them.
let (small, large) = (run("small"), run("large"));
let same = project.supercov(&["diff", &small, &large]).succeeds();
contains_all(
&same,
&[
"gained: 1 line, 1 branch,",
"lost: 1 line, 1 branch,",
"Both runs measured the same source with the same test files",
"Run again before acting on a loss.",
],
);
// What was lost is listed, before what was gained. The text listed gains
// alone: "lost: 2 lines, 12 branches" stood over 73 gains.
let lost = same.find("- line src/fee.js:5").expect(&same);
assert!(
lost < same.find("+ line src/fee.js:3").expect(&same),
"{same}"
);
contains_all(
&same,
&["- branch src/fee.js:2 false", "+ branch src/fee.js:2 true"],
);
// A difference in one file is its own summary.
assert!(!same.contains("most lost first"), "{same}");
let json = project.supercov(&["diff", &small, &large, "--json"]).json();
assert_eq!(json["data"]["inputs"]["sourceChanged"], false);
assert_eq!(json["data"]["inputs"]["testsChanged"], false);
// A comparison with nothing but losses had an empty body.
let both = run("both");
let only = project.supercov(&["diff", &both, &small]).succeeds();
contains_all(
&only,
&[
"gained: 0 lines, 0 branches,",
"lost: 1 line, 1 branch,",
"- line src/fee.js:3",
"- branch src/fee.js:2 true",
"showing 1-1 of 1 per category",
],
);
assert!(!only.contains("\n+ "), "{only}");
// Nothing differs, nothing to explain.
let again = run("large");
let equal = project.supercov(&["diff", &large, &again]).succeeds();
assert!(!equal.contains("Both runs measured"), "{equal}");
// A test added, as an agent adds one: what differs is still not the code.
project.write(
"test/other.test.js",
"const { test } = require('node:test');\ntest('other', () => {});\n",
);
let added = run("small");
let tests = project.supercov(&["diff", &large, &added]).succeeds();
contains_all(
&tests,
&["Both runs measured the same source, and the test files differ."],
);
// The code changed: a loss may be the change's.
project.write(
"src/fee.js",
"function fee(sum) {\n if (sum > 200) {\n return 0;\n }\n return 5;\n}\nmodule.exports = { fee };\n",
);
let changed = run("large");
let source = project.supercov(&["diff", &added, &changed]).succeeds();
assert!(source.contains("gained: 1 line,"), "{source}");
assert!(!source.contains("Both runs measured"), "{source}");
assert_eq!(
project
.supercov(&["diff", &added, &changed, "--json"])
.json()["data"]["inputs"]["sourceChanged"],
true
);
}
#[test]
fn tests_that_recorded_no_coverage_can_be_listed() {
let project = Project::empty("unevidenced");
project.write(
"package.json",
r#"{ "name": "unevidenced", "scripts": { "test": "node --test test/fee.test.js test/static.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
project.write(
"test/static.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\ntest('two is two', () => equal(1 + 1, 2));\ntest('names are strings', () => equal(typeof 'a', 'string'));\ntest('checks nothing', () => {});\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "npm", "test"]).succeeds();
// The summary named one test for 63 and no query named the rest.
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"2 tests made assertions, but Supercov received no source-coverage evidence:",
" All of them: ",
"tests without-evidence",
],
);
let listed = project
.supercov(&["runs", "latest", "tests", "without-evidence"])
.succeeds();
contains_all(
&listed,
&[
"Tests that made assertions and recorded no coverage: 2",
"test/static.test.js > names are strings [",
"test/static.test.js > two is two [",
"passed, 1 assertion; its file imports no measured source",
"showing 1-2 of 2",
],
);
// A test that asserted nothing made no assertion to list it by.
assert!(
!listed.contains("small orders pay") && !listed.contains("checks nothing"),
"{listed}"
);
let page = project
.supercov(&[
"runs",
"latest",
"tests",
"without-evidence",
"--limit",
"1",
"--json",
])
.json();
assert_eq!(page["command"], "coverage.tests-without-evidence");
assert_eq!(page["pagination"]["total"], 2);
assert_eq!(page["data"]["tests"][0]["name"], "names are strings");
assert_eq!(page["data"]["tests"][0]["file"], "test/static.test.js");
assert_eq!(page["data"]["tests"][0]["assertions"], 1);
// It checks only test code: its file imports nothing measured.
assert_eq!(page["data"]["tests"][0]["importsMeasured"], false);
// A run whose record of what it measured cannot be read says nothing of
// what a test's file imports.
let unread = project
.supercov_with(
&["runs", "latest", "tests", "without-evidence", "--json"],
&[("SUPERCOV_TEST_FAULT", "fs.open#evidence_archive.rs:697=50")],
)
.json();
assert_eq!(unread["data"]["tests"][0]["name"], "names are strings");
assert!(
unread["data"]["tests"][0].get("importsMeasured").is_none(),
"{unread}"
);
// `tests affected` is still the other query under `tests`.
let other = project.supercov(&["runs", "latest", "tests", "nonsense"]);
assert_eq!(other.code(), 2);
}
#[test]
fn a_directory_says_what_ran_while_no_test_was_running() {
let project = Project::empty("rollup");
project.write(
"package.json",
r#"{ "name": "rollup", "scripts": { "test": "node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"boot.js",
"const settings = { rate: 5 };\nconst limit = 100;\nmodule.exports = { settings, limit };\n",
);
project.write(
"src/app/fee.js",
"const { settings, limit } = require('../../boot.js');\nfunction fee(sum) {\n return sum > limit ? 0 : settings.rate;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/app/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
project.git(&["init", "-q"]);
project
.supercov_with(
&["--", "npm", "test"],
&[
("SUPERCOV_SOURCE_ROOTS", "src,boot.js"),
("SUPERCOV_TEST_KIND", "unit"),
],
)
.succeeds();
// `.` read unit 0.00% and All 100.00%, and `src` 50.00% and 100.00%: a
// total above every kind, with nothing to say where the rest came from.
// The files were loaded before the first test started.
let areas = project
.supercov(&["runs", "latest", "files", "--group", "dir"])
.succeeds();
contains_all(
&areas,
&[
"Directory Files Lines unit no test All",
"src 1 4 50.00% 50.00% 100.00%",
". 1 3 0.00% 100.00% 100.00%",
"\"no test\" is code that ran only while no test was running",
],
);
let json = project
.supercov(&["runs", "latest", "files", "--group", "dir", "--json"])
.json();
let root = json["data"]["areas"]
.as_array()
.unwrap()
.iter()
.find(|area| area["directory"] == ".")
.unwrap();
assert_eq!(root["covered"]["lines"], 3);
assert_eq!(root["coveredByTests"]["lines"], 0);
// One kind asked for is that kind's coverage, with nothing to compare.
let unit = project
.supercov(&[
"runs", "latest", "files", "--group", "dir", "--kind", "unit",
])
.succeeds();
assert!(!unit.contains("no test"), "{unit}");
}
#[cfg(unix)]
#[test]
fn a_tools_change_to_source_reaches_the_project_and_the_file_stays_measured() {
let project = Project::empty("fixed");
project.write(
"package.json",
r#"{ "name": "fixed", "scripts": { "test": "prettier --write src/fee.js && oxlint --fix src && node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n var rate=5;\n return sum > 100 ? 0 : rate;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
// A formatter that runs on Node and writes through `fs`, and a native
// linter that fixes what it reads, which has to be the formatted text.
project.write_script(
"node_modules/.bin/prettier",
"#!/usr/bin/env node\nconst fs = require('node:fs');\nconst file = process.argv[3];\nfs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('rate=5', 'rate = 5'));\n",
);
project.write_script(
"node_modules/.bin/oxlint",
"#!/bin/sh\nif grep -rl supercov \"$2\"; then exit 3; fi\ngrep -q 'var rate = 5' \"$2\"/fee.js || exit 4\nsed 's/var rate/const rate/' \"$2\"/fee.js > fixed.tmp && mv fixed.tmp \"$2\"/fee.js\n",
);
project.git(&["init", "-q"]);
// Prettier with `--write` and ESLint with `--fix` wrote the source they
// had read over the instrumented copy, so the file ran unmeasured and
// read 0% covered under passing tests, and a native tool's fix was
// dropped. Each change is kept beside the copy, the next tool reads it,
// and the project has it when the command ends.
let run = project.supercov(&["--", "npm", "test"]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(
run.stderr()
.contains("the command's tools changed 1 source file(s)"),
"{}",
run.stderr()
);
assert_eq!(
project.read("src/fee.js"),
"function fee(sum) {\n const rate = 5;\n return sum > 100 ? 0 : rate;\n}\nmodule.exports = { fee };\n"
);
assert!(!project.root.join("fixed.tmp").exists());
let line = project
.supercov(&["runs", "latest", "line", "src/fee.js:3"])
.succeeds();
assert!(line.contains("small orders pay"), "{line}");
// The next run starts from the fixed source: nothing is left to change,
// and it measures the file as the project now has it.
project.write(
"node_modules/.bin/oxlint",
"#!/bin/sh\ngrep -q 'const rate = 5' \"$2\"/fee.js\n",
);
let again = project.supercov(&["--", "npm", "test"]);
assert_eq!(again.code(), 0, "{}{}", again.stdout(), again.stderr());
assert!(
!again.stderr().contains("source file(s)"),
"{}",
again.stderr()
);
let line = project
.supercov(&["runs", "latest", "line", "src/fee.js:3"])
.succeeds();
assert!(line.contains("small orders pay"), "{line}");
}
#[cfg(unix)]
#[test]
fn a_workspace_packages_own_tool_reads_source_as_it_was_written() {
let project = Project::empty("judged-package");
project.write(
"package.json",
r#"{ "name": "judged-package", "private": true, "workspaces": ["packages/*"], "scripts": { "test": "cd packages/app && npm test" } }"#,
);
project.write(
"packages/app/package.json",
r#"{ "name": "app", "scripts": { "test": "oxlint src && node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"packages/app/src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"packages/app/test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
// pnpm, and npm without hoisting, give a package its tools in a `.bin`
// of its own, which is first on PATH when its scripts run.
project.write_script(
"packages/app/node_modules/.bin/oxlint",
"#!/bin/sh\nif grep -rl supercov \"$1\"; then exit 3; fi\ngrep -c '' \"$1\"/fee.js > lint-report.txt\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "npm", "test"]).succeeds();
assert_eq!(project.read("packages/app/lint-report.txt"), "4\n");
// The project's own tool is what it was.
assert!(
project
.read("packages/app/node_modules/.bin/oxlint")
.starts_with("#!/bin/sh\nif grep"),
);
}
#[cfg(windows)]
#[test]
fn a_tool_that_judges_source_reads_it_as_it_was_written_on_windows() {
let project = Project::empty("judged");
project.write(
"package.json",
r#"{ "name": "judged", "scripts": { "test": "oxlint src && node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n return sum > 100 ? 0 : 5;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
// What a native linter does, as far as it matters here: it reads the
// files itself, fails on a line nobody wrote, and leaves a report. npm
// runs a script with cmd.exe, which starts the `.cmd` shim.
project.write(
"node_modules/.bin/oxlint.cmd",
"@ECHO off\r\nfindstr /S /M /C:\"supercov\" \"%1\\*\" >NUL 2>NUL && exit /b 3\r\necho judged> lint-report.txt\r\nexit /b 0\r\n",
);
project.git(&["init", "-q"]);
let run = project.supercov(&["--", "npm", "test"]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(project.read("lint-report.txt").starts_with("judged"));
let line = project
.supercov(&["runs", "latest", "line", "src/fee.js:2"])
.succeeds();
assert!(line.contains("small orders pay"), "{line}");
}
#[cfg(unix)]
#[test]
fn a_workspace_package_another_package_imports_is_measured_through_that_import() {
let project = Project::empty("monorepo");
project.write(
"package.json",
r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"], "scripts": { "test": "npm test --workspaces --if-present" } }"#,
);
project.write(
"packages/money/package.json",
r#"{ "name": "money", "type": "module", "exports": "./src/money.js", "scripts": { "test": "node --test" } }"#,
);
project.write(
"packages/money/src/money.js",
"export function cents(amount) {\n return Math.round(amount * 100);\n}\n",
);
project.write(
"packages/money/test/money.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { cents } from \"../src/money.js\";\ntest(\"cents\", () => assert.equal(cents(1.5), 150));\n",
);
project.write(
"packages/format/package.json",
r#"{ "name": "@acme/format", "type": "module", "exports": "./src/format.js" }"#,
);
project.write(
"packages/format/src/format.js",
"export function label(cents) {\n return `${cents}c`;\n}\n",
);
project.write(
"packages/cart/package.json",
r#"{ "name": "cart", "type": "module", "scripts": { "test": "node --test" } }"#,
);
project.write(
"packages/cart/src/cart.js",
"import { cents } from \"money\";\nimport { label } from \"@acme/format\";\nexport function total(prices) {\n return label(prices.reduce((sum, price) => sum + cents(price), 0));\n}\n",
);
project.write(
"packages/cart/test/cart.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\ntest(\"total\", () => assert.equal(total([1, 2]), \"300c\"));\n",
);
// What npm install makes of the workspaces: links into the project.
std::fs::create_dir_all(project.root.join("node_modules/@acme")).unwrap();
std::os::unix::fs::symlink("../packages/money", project.root.join("node_modules/money"))
.unwrap();
std::os::unix::fs::symlink("../packages/cart", project.root.join("node_modules/cart")).unwrap();
std::os::unix::fs::symlink(
"../../packages/format",
project.root.join("node_modules/@acme/format"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.git(&["init", "-q"]);
project.commit("mono");
project.supercov(&["--", "npm", "test"]).succeeds();
// cart's test reaches money and format through node_modules.
let money = project
.supercov(&["runs", "latest", "line", "packages/money/src/money.js:2"])
.succeeds();
contains_all(&money, &["cents [", "total ["]);
let format = project
.supercov(&["runs", "latest", "line", "packages/format/src/format.js:2"])
.succeeds();
assert!(format.contains("total ["), "{format}");
project.edit(
"packages/money/src/money.js",
"amount * 100",
"amount * 1000",
);
let affected = project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds();
assert_eq!(affected.trim(), "cents\ntotal");
}
#[test]
fn source_roots_named_after_a_first_run_take_effect() {
// The workspace of a first, automatic run was reused for every later one:
// SUPERCOV_SOURCE_ROOTS changed which files are source but not a byte of
// any of them, so the run still reported automatic scope and the same
// counts, with nothing to say the variable had been ignored.
let project = Project::cart("roots-after-first-run");
project.write(
"extra/tax.js",
"export function tax(total) {\n return total > 100 ? 20 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { tax } from \"../extra/tax.js\";\ntest(\"tax applies over a hundred\", () => {\n assert.equal(tax(200), 20);\n});\n",
);
project.commit("tax");
project.supercov(&["--", "node", "--test"]).succeeds();
let automatic = project.supercov(&["runs", "latest", "scope"]).succeeds();
contains_all(
&automatic,
&[
"mode automatic",
" 1 AMBIGUOUS extra unclassified first-party source",
// What would settle it, ready to copy.
"SUPERCOV_SOURCE_ROOTS=src,extra",
],
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Unclassified source: extra 1",
"SUPERCOV_SOURCE_ROOTS=src,extra",
],
);
project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "src,extra")],
)
.succeeds();
let named = project
.supercov(&["runs", "latest", "scope", "--files"])
.succeeds();
contains_all(
&named,
&[
"mode explicit; roots extra, src; included 2",
"INCLUDED extra/tax.js explicit source root",
],
);
assert!(!named.contains("SUPERCOV_SOURCE_ROOTS="), "{named}");
let line = project
.supercov(&["runs", "latest", "line", "extra/tax.js:2"])
.succeeds();
assert!(line.contains("tax applies over a hundred"), "{line}");
}
#[test]
fn a_run_in_which_no_test_ran_is_marked_in_the_listing() {
// Four runs made only to copy files out of the workspace sat in `runs`
// as 0.00% beside the real ones, with nothing to tell them apart.
let project = Project::cart("no-tests-ran");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["--", "node", "-e", "0"]).succeeds();
let runs = project.supercov(&["runs"]).succeeds();
let rows = runs.lines().collect::<Vec<_>>();
assert!(rows[1].ends_with("NO TESTS RAN"), "{runs}");
assert!(!rows[2].contains("NO TESTS RAN"), "{runs}");
let listed = project.supercov(&["runs", "--json"]).json();
assert_eq!(listed["data"]["runs"][0]["tests"], 0);
assert_eq!(listed["data"]["runs"][1]["tests"], 3);
}
/// A suite of one test that takes a moment, so that runs started together
/// are running together.
fn slow_suite(project: &Project, name: &str, function: &str, call: &str) {
project.write(
&format!("test/{name}.test.js"),
&format!(
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport {{ {function} }} from \"../src/cart.js\";\n\ntest(\"{name}\", async () => {{\n await new Promise((done) => setTimeout(done, 600));\n assert.ok({call} !== undefined);\n}});\n"
),
);
}
#[test]
fn runs_started_at_once_each_have_a_copy_and_all_are_recorded() {
// Suites that share nothing run side by side without Supercov. Under it
// the second was refused, because every run rebuilt the one copy.
let project = Project::cart("side-by-side");
slow_suite(&project, "unit", "total", "total([], null)");
slow_suite(&project, "integration", "shipping", "shipping(10, true)");
slow_suite(&project, "e2e", "describe", "describe([])");
project.commit("three suites");
let ran = std::thread::scope(|scope| {
["unit", "integration", "e2e"]
.map(|kind| {
let project = &project;
scope.spawn(move || {
let file = format!("test/{kind}.test.js");
project.supercov_with(
&["--", "node", "--test", &file],
&[("SUPERCOV_TEST_KIND", kind)],
)
})
})
.map(|thread| thread.join().unwrap())
});
let mut copies = Vec::new();
for run in &ran {
assert_eq!(run.code(), 0, "{}", run.stderr());
let stderr = run.stderr();
let copy = stderr
.lines()
.find_map(|line| line.split("instrumenting isolated workspace ").nth(1))
.unwrap_or_else(|| panic!("{stderr}"))
.to_owned();
// What a test prints names the project, whichever copy it ran in.
assert!(
!run.stdout().contains(".supercov/workspaces"),
"{}",
run.stdout()
);
copies.push(copy);
}
copies.sort();
copies.dedup();
assert_eq!(
copies.len(),
3,
"each run has a copy of its own: {copies:?}"
);
let runs = project.supercov(&["runs", "--json"]).json();
let runs = runs["data"]["runs"].as_array().unwrap();
assert_eq!(runs.len(), 3, "{runs:?}");
for run in runs {
let id = run["id"].as_str().unwrap();
let summary = project.supercov(&["runs", id]).succeeds();
contains_all(&summary, &["Total 1", "Passed 1"]);
}
// Cleaning wants the store to itself, and says who has it.
let cleaned = std::thread::scope(|scope| {
let running =
scope.spawn(|| project.supercov(&["--", "node", "--test", "test/unit.test.js"]));
std::thread::sleep(std::time::Duration::from_millis(350));
let cleaned = project.supercov(&["runs", "clean"]);
assert_eq!(running.join().unwrap().code(), 0);
cleaned
});
assert_eq!(cleaned.code(), 2, "{}", cleaned.stderr());
contains_all(
&cleaned.stderr(),
&[
"is active in this project",
"can be cleaned when no run is active",
],
);
// And then removes every copy.
project.supercov(&["runs", "clean"]).succeeds();
assert!(!project.root.join(".supercov/workspaces").exists());
}
#[test]
fn merge_with_no_run_named_adds_up_the_runs_on_the_source_as_it_is() {
// A script that measured three suites had to find what each run was
// called, and took the newest directory's name, which is a guess.
let project = Project::cart("merge-current");
slow_suite(&project, "unit", "total", "total([], null)");
slow_suite(&project, "integration", "shipping", "shipping(10, true)");
project.commit("two suites");
let nothing = project.supercov(&["merge"]);
assert_eq!(nothing.code(), 2, "{}", nothing.stdout());
assert!(
nothing
.stderr()
.contains("no run was recorded on the source as it is now"),
"{}",
nothing.stderr()
);
let measure = |kind: &str| {
let file = format!("test/{kind}.test.js");
project
.supercov_with(
&["--", "node", "--test", &file],
&[("SUPERCOV_TEST_KIND", kind)],
)
.succeeds();
project.latest()
};
let unit = measure("unit");
let one = project.supercov(&["merge"]).succeeds();
assert!(one.contains("nothing to merge it with"), "{one}");
let integration = measure("integration");
// The same command again: its first run is not what the suite did last.
let again = measure("unit");
let merged = project.supercov(&["merge"]).succeeds();
contains_all(
&merged,
&["merging 2 runs", &again, &integration, "merged run run_"],
);
assert!(!merged.contains(&unit), "{merged}");
let kinds = project.supercov(&["runs", "latest", "kinds"]).succeeds();
contains_all(&kinds, &["unit", "integration"]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Total 2", "Passed 2"]);
// Asked again, it is the merge already made, and no third run of it.
let recorded = |project: &Project| {
project.supercov(&["runs", "--json"]).json()["data"]["runs"]
.as_array()
.unwrap()
.len()
};
let before = recorded(&project);
let same = project.supercov(&["merge"]).succeeds();
assert!(same.contains("already merged as"), "{same}");
assert_eq!(recorded(&project), before);
// Once the source has moved on, none of them is of this source.
project.edit("src/cart.js", "return 0;", "return 1;");
assert_eq!(project.supercov(&["merge"]).code(), 2);
}
#[test]
fn merge_with_no_run_named_takes_each_machine_s_run_of_one_command() {
// Four machines ran one command, each its share of the suite, and a job
// copied their runs into one store. Each was the newest run of the
// command, and the merge took one of the four.
let project = Project::cart("merge-machines");
slow_suite(&project, "unit", "total", "total([], null)");
project.commit("one suite");
let measure = || {
project
.supercov(&["--", "node", "--test", "test/unit.test.js"])
.succeeds();
project.latest()
};
let first = measure();
// Another machine's store, which never held the first run.
let runs = project.root.join(".supercov/runs");
let away = project.root.join(".supercov/elsewhere");
std::fs::rename(runs.join(&first), &away).unwrap();
let second = measure();
std::fs::rename(&away, runs.join(&first)).unwrap();
let merged = project.supercov(&["merge"]).succeeds();
contains_all(&merged, &["merging 2 runs", &first, &second]);
// Measured again here, the command's earlier runs make way for it.
measure();
let alone = project.supercov(&["merge"]).succeeds();
assert!(alone.contains("nothing to merge it with"), "{alone}");
// What a run replaces is read from the store it is published into: one
// that cannot be listed cannot take it.
let unlisted = project.supercov_with(
&["--", "node", "--test", "test/unit.test.js"],
&[("SUPERCOV_TEST_FAULT", "run-store-unlisted")],
);
assert_ne!(unlisted.code(), 0, "{}", unlisted.stderr());
assert!(
unlisted
.stderr()
.contains("run store: injected fault at run-store-unlisted"),
"{}",
unlisted.stderr()
);
}
#[test]
fn a_run_of_another_release_is_named_for_what_it_is() {
// Merging a run recorded before an upgrade answered "differing domains:
// instrumenter, tests, configuration", which names nothing to do.
let project = Project::cart("merge-release");
let older = project.measure(&["test/cart.test.js"]);
project.write(
"test/more.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\n\ntest(\"more\", () => {\n assert.equal(describe([{ name: \"a\" }]), \"a\");\n});\n",
);
let newer = project.measure(&["test/more.test.js"]);
let recorded = serde_json::from_str::<serde_json::Value>(
&project.read(&format!(".supercov/runs/{newer}/run.json")),
)
.unwrap();
assert_eq!(
recorded["recordedBy"],
env!("CARGO_PKG_VERSION"),
"{recorded}"
);
// What a run of 4.5.0 looks like to this release.
let path = format!(".supercov/runs/{older}/run.json");
let mut metadata = serde_json::from_str::<serde_json::Value>(&project.read(&path)).unwrap();
metadata["integrity"]["fingerprint"]["instrumenter"] = serde_json::json!("0".repeat(64));
metadata["recordedBy"] = serde_json::json!("4.5.0");
project.write(&path, &serde_json::to_string_pretty(&metadata).unwrap());
let refused = project.supercov(&["merge", &older, &newer]);
assert_eq!(refused.code(), 2, "{}", refused.stdout());
contains_all(
&refused.stderr(),
&[
&format!(
"Cannot merge run {older}: it was recorded by Supercov 4.5.0, which instruments differently"
),
"Measure it again to merge it.",
],
);
let left = project.supercov(&["merge"]);
assert!(
left.stdout().contains(&format!(
"left out {older} (node --test test/cart.test.js): it was recorded by Supercov 4.5.0"
)),
"{}",
left.stdout()
);
// A run from before runs said which release made them: older than the
// first that did, on the day it ran.
metadata.as_object_mut().unwrap().remove("recordedBy");
let day = metadata["startedAt"].as_str().unwrap()[..10].to_owned();
project.write(&path, &serde_json::to_string_pretty(&metadata).unwrap());
let refused = project.supercov(&["merge", &older, &newer]);
assert!(
refused.stderr().contains(&format!(
"it was recorded on {day} by a Supercov older than 4.7.0"
)),
"{}",
refused.stderr()
);
}
#[test]
fn a_run_of_a_new_test_alone_is_added_to_the_runs_before_it() {
// Raising a suite's coverage one test at a time: measure only what was
// added, and add it to what is known. `merge` refused it ("differing
// domains: tests"), so every new test meant the whole suite again.
let project = Project::cart("merge-grown");
let baseline = project.measure(&[]);
let before = project.supercov(&["runs", &baseline]).succeeds();
contains_all(&before, &["76.92% (10/13)", "Total 3"]);
let add = |name: &str| {
project.write(
&format!("test/{name}.test.js"),
&format!(
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport {{ describe }} from \"../src/cart.js\";\n\ntest(\"{name}\", () => {{\n assert.equal(describe([{{ name: \"a\" }}]), \"a\");\n}});\n"
),
);
project
.supercov(&["--", "node", "--test", &format!("test/{name}.test.js")])
.succeeds();
project.latest()
};
let first = add("names");
project.supercov(&["merge", &baseline, &first]).succeeds();
let merged = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&merged, &["Total 4", "Passed 4"]);
assert!(
!merged.contains("76.92%"),
"the added test's lines count: {merged}"
);
// It is a run of the checkout as it is, so a floor can be asked of it.
project
.supercov(&["runs", "latest", "check", "--min-lines", "80"])
.succeeds();
// With no run named, the same sum, and the next test added to it.
let second = add("more-names");
let summed = project.supercov(&["merge"]).succeeds();
contains_all(&summed, &["merging 3 runs", &baseline, &first, &second]);
contains_all(
&project.supercov(&["runs", "latest"]).succeeds(),
&["Total 5", "Passed 5"],
);
// A test changed since a run makes that run's record one of other tests.
project.edit(
"test/names.test.js",
"test(\"names\"",
"test(\"names, again\"",
);
let third = add("yet-more");
let refused = project.supercov(&["merge", &first, &third]);
assert_eq!(refused.code(), 2, "{}", refused.stdout());
contains_all(
&refused.stderr(),
&[
"test/names.test.js, a file of its own tests, has changed",
"Its own tests changed; measure them again.",
],
);
// Accepting changes does not make a changed test's record its own.
let still = project.supercov(&["merge", "--allow-changed", &first, &third]);
assert_eq!(still.code(), 2, "{}", still.stdout());
assert!(
still.stderr().contains("Its own tests changed"),
"{}",
still.stderr()
);
let left = project.supercov(&["merge"]).succeeds();
contains_all(
&left,
&[
&format!("left out {first}"),
"test/names.test.js, a file of its own tests, has changed. Measure it again to count it.",
"merging 3 runs",
],
);
assert!(!left.contains(&format!(" {first}")), "{left}");
}
#[test]
fn new_tests_are_added_across_the_helpers_and_settings_they_bring() {
// A batch of new end-to-end specs usually brings a helper or two and a
// setting of the runner's. Every spec loads the helpers, so merge refused
// to add a run of the new specs to the baseline, and an edit to one
// runner's settings made every other runner's run out of date too. Each
// file is judged by what the earlier tests did with it.
let project = Project::cart("merge-across");
project.write(
"test/helpers.js",
"export const item = (name) => ({ name });\n",
);
project.write(
"test/helped.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\nimport { item } from \"./helpers.js\";\n\ntest(\"helped\", () => {\n assert.equal(describe([item(\"a\")]), \"a\");\n});\n",
);
project.write("runner.config.js", "export default { timeout: 1000 };\n");
project.write(
"playwright.config.js",
"export default { timeout: 1000 };\n",
);
project.commit("helpers");
let baseline = project.measure(&[]);
// The batch: the helper gains a function, the other runner's settings
// change, and one new test uses the new function.
project.edit(
"test/helpers.js",
"\n",
"\n\nexport const items = (...names) => names.map(item);\n",
);
project.edit("playwright.config.js", "timeout: 1000", "timeout: 2000");
project.write(
"test/batch.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\nimport { items } from \"./helpers.js\";\n\ntest(\"batch\", () => {\n assert.equal(describe(items(\"a\")), \"a\");\n});\n",
);
let batch = project.measure(&["test/batch.test.js"]);
let summed = project.supercov(&["merge"]).succeeds();
contains_all(&summed, &["merging 2 runs", &baseline, &batch]);
let merged = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&merged,
&[
"Passed 5",
"merged across: ",
"test/helpers.js (only added items)",
"playwright.config.js (playwright settings; `node --test` ran under node:test)",
],
);
let json = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(json["data"]["stale"], false, "{json}");
assert!(
json["data"]["mergedAcross"]
.as_array()
.is_some_and(|across| across.iter().any(|item| item
.as_str()
.is_some_and(|item| item.starts_with("test/helpers.js")))),
"{json}"
);
// A function the earlier tests ran changing is a change to what they did.
project.edit("test/helpers.js", "({ name })", "({ name: name.trim() })");
let again = project.measure(&["test/batch.test.js"]);
let refused = project.supercov(&["merge", &baseline, &again]);
assert_eq!(refused.code(), 2, "{}", refused.stdout());
contains_all(
&refused.stderr(),
&[
"test/helpers.js changed: ",
"item (line 1)",
"pass --allow-changed if the change alters nothing its tests ran",
],
);
let left = project.supercov(&["merge"]);
contains_all(
&left.stdout(),
&[
&format!("left out {baseline}"),
"test/helpers.js changed: ",
"or pass --allow-changed",
],
);
// The user can say it alters nothing they ran; the merged run says so.
project
.supercov(&["merge", "--allow-changed", &baseline, &again])
.succeeds();
contains_all(
&project.supercov(&["runs", "latest"]).succeeds(),
&["test/helpers.js (accepted)", "--allow-changed"],
);
// Settings no runner owns -- a build's, a tool's -- may set how any test
// runs.
project.edit("test/helpers.js", "({ name: name.trim() })", "({ name })");
project.edit("runner.config.js", "timeout: 1000", "timeout: 2000");
let settings = project.measure(&["test/batch.test.js"]);
let refused = project.supercov(&["merge", &baseline, &settings]);
assert_eq!(refused.code(), 2, "{}", refused.stdout());
assert!(
refused.stderr().contains("runner.config.js has changed"),
"{}",
refused.stderr()
);
// The product code changing is never accepted: nothing is of this
// source, and a merge of the runs named is of the source they ran.
project.edit("src/cart.js", "return 0;", "return 1;");
let source = project.supercov(&["merge", "--allow-changed"]);
assert_eq!(source.code(), 2);
assert!(
source
.stdout()
.contains("src/cart.js, which it measured, has changed"),
"{}",
source.stdout()
);
project
.supercov(&["merge", "--allow-changed", &baseline, &batch])
.succeeds();
let old = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(old["data"]["stale"], true, "{old}");
}
#[test]
fn source_left_out_of_what_is_measured_is_judged_like_a_helper() {
// A project keeps simulators outside SUPERCOV_SOURCE_ROOTS on purpose.
// A change to one made every run out of date for merge, the suites
// that never load it included.
let project = Project::cart("merge-unmeasured");
project.write(
"simulators/echo.js",
"export const echo = (value) => value;\n",
);
project.write(
"test/echo.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { echo } from \"../simulators/echo.js\";\nimport { describe } from \"../src/cart.js\";\n\ntest(\"echo\", () => {\n assert.equal(echo(describe([{ name: \"a\" }])), \"a\");\n});\n",
);
project.commit("simulators");
let roots = [("SUPERCOV_SOURCE_ROOTS", "src")];
let measure = |file: &str| {
project
.supercov_with(&["--", "node", "--test", file], &roots)
.succeeds();
project.latest()
};
let cart = measure("test/cart.test.js");
measure("test/echo.test.js");
project.edit("simulators/echo.js", "=> value", "=> String(value)");
let echo = measure("test/echo.test.js");
let summed = project.supercov_with(&["merge"], &roots).succeeds();
contains_all(&summed, &["merging 2 runs", &cart, &echo]);
contains_all(
&project.supercov(&["runs", "latest"]).succeeds(),
&["simulators/echo.js (`node --test test/cart.test.js` does not load it)"],
);
}
#[test]
fn a_test_is_affected_by_a_helper_its_file_loads() {
// A helper sits beside the tests, where nothing is measured, so no test's
// record names it: a change to a helper every test called left every
// test unaffected.
let project = Project::cart("affected-helper");
project.write(
"test/helpers.js",
"export const item = (name) => ({ name });\n",
);
project.write(
"test/helped.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\nimport { item } from \"./helpers.js\";\n\ntest(\"helped\", () => {\n assert.equal(describe([item(\"a\")]), \"a\");\n});\n",
);
project.commit("helpers");
project.measure(&[]);
let affected = |project: &Project| {
let data = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json()["data"]
.clone();
data["affected"]
.as_array()
.unwrap()
.iter()
.map(|test| {
(
test["name"].as_str().unwrap().to_owned(),
test["reasons"].to_string(),
)
})
.collect::<Vec<_>>()
};
// Only added: no test written before can have run it.
project.edit(
"test/helpers.js",
"\n",
"\n\nexport const items = (...names) => names.map(item);\n",
);
assert_eq!(affected(&project), Vec::<(String, String)>::new());
// A function the helped test runs: that test, and no other.
project.edit("test/helpers.js", "({ name })", "({ name: name.trim() })");
let found = affected(&project);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].0.contains("helped"), "{found:?}");
assert!(
found[0].1.contains("test/helpers.js changed: ")
&& found[0].1.contains("item (line 1)")
&& found[0].1.contains("(this test's file loads it)"),
"{found:?}"
);
}
#[test]
fn gaps_export_writes_every_obligation_of_a_run_too_large_for_one_reply() {
// `gaps --format jsonl` exists for the runs whose gaps do not fit in a
// JSON reply. It read its data back through that reply, so it refused
// exactly those, with the reply's 64 KB message.
const FILES: usize = 400;
let project = Project::empty("gaps-export");
project.write(
"package.json",
r#"{ "name": "rules", "private": true, "type": "module" }"#,
);
let mut imports = String::new();
let mut calls = String::new();
// The second half under long paths: a page of them weighs more than a
// page of the first half, as entries do in a real run.
let path = |index: usize| {
if index < FILES / 2 {
format!("src/rules/rule{index}.js")
} else {
format!(
"src/rules/a/directory/named/at/the/length/real/projects/nest/their/rules/rule{index}.js"
)
}
};
for index in 0..FILES {
project.write(
&path(index),
"export function allowed(admin, owner, open) {\n if ((admin && owner) || open) {\n return true;\n }\n return false;\n}\n",
);
imports.push_str(&format!(
"import {{ allowed as rule{index} }} from '../{}';\n",
path(index)
));
calls.push_str(&format!(
" assert.equal(rule{index}(true, true, false), true);\n"
));
}
project.write(
"test/rules.test.js",
&format!(
"import assert from 'node:assert/strict';\nimport test from 'node:test';\n{imports}\ntest('admins who own it are allowed', () => {{\n{calls}}});\n"
),
);
project.git(&["init", "-q"]);
project.commit("rules");
let run = project.measure(&[]);
// Too large for one reply: each page holds what fits and names the next,
// and following them reaches every file. A page that did not fit used to
// be refused, which stopped a pager after its first page.
let mut offset = 0;
let mut paged = std::collections::BTreeSet::new();
let mut pages = 0;
loop {
let page = project
.supercov(&[
"runs",
&run,
"gaps",
"--json",
"--limit",
"1000",
"--offset",
&offset.to_string(),
])
.json();
assert_eq!(page["ok"], true, "{page}");
pages += 1;
for gap in page["data"]["gaps"].as_array().unwrap() {
paged.insert(gap["file"].as_str().unwrap().to_owned());
}
let pagination = &page["pagination"];
if pagination["hasMore"] != true {
break;
}
assert!(
pagination["returned"].as_u64().unwrap() < 1000,
"{pagination}"
);
offset = pagination["nextOffset"].as_u64().unwrap();
}
assert!(pages > 1, "a run this size takes more than one reply");
assert_eq!(paged.len(), FILES);
let written = project
.supercov(&[
"runs",
&run,
"gaps",
"--format",
"jsonl",
"--metric",
"mcdc",
"--output",
"gaps.jsonl",
])
.exits(0);
let exported = project.read("gaps.jsonl");
let rows: Vec<serde_json::Value> = exported
.lines()
.map(|line| serde_json::from_str(line).expect("one JSON object per line"))
.collect();
// Only the all-true call ran, so no condition of `(admin && owner) ||
// open` is shown to matter: three each, on the decision's line.
assert_eq!(rows.len(), FILES * 3, "{written}");
assert!(rows.iter().all(|row| row["line"] == 2), "{exported}");
let files: std::collections::BTreeSet<&str> =
rows.iter().filter_map(|row| row["file"].as_str()).collect();
assert_eq!(files.len(), FILES);
assert!(
written.contains(&format!(
"wrote {} uncovered obligation(s) in {FILES} file(s)",
FILES * 3
)),
"{written}"
);
// And the same on standard output.
let printed = project
.supercov(&[
"runs", &run, "gaps", "--format", "jsonl", "--metric", "mcdc",
])
.succeeds();
assert_eq!(printed, exported);
}
#[cfg(unix)]
#[test]
fn the_copy_carries_what_a_project_holds_and_keeps_its_deletions() {
let project = Project::cart("copy-shapes");
// A package of its own, with its own installed tools.
project.write(
"packages/tool/node_modules/dep/index.js",
"module.exports = 1;\n",
);
project.write_script(
"packages/tool/node_modules/.bin/tool",
"#!/bin/sh\necho tool\n",
);
// A link to a directory of the project, and one to somewhere outside it.
std::os::unix::fs::symlink("src", project.root.join("linked-src")).unwrap();
let outside = Project::empty("copy-shapes-outside");
outside.write("readme.txt", "outside\n");
std::os::unix::fs::symlink(&outside.root, project.root.join("outside")).unwrap();
project.write("notes/old.txt", "keep me\n");
project.write(
"test/shapes.test.js",
"import assert from 'node:assert/strict';\nimport { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport test from 'node:test';\n\ntest('reads through a link, deletes a note, writes a large report', () => {\n assert.match(readFileSync('linked-src/cart.js', 'utf8'), /export function/);\n rmSync('notes/old.txt');\n mkdirSync('out', { recursive: true });\n writeFileSync('out/big.txt', process.cwd() + '\\n' + 'x'.repeat(17 << 20));\n});\n",
);
project.commit("shapes");
let measured = project.supercov(&["--", "node", "--test", "test/shapes.test.js"]);
let said = format!("{}{}", measured.stdout(), measured.stderr());
assert_eq!(measured.code(), 0, "{said}");
contains_all(
&said,
&[
"the command deleted 1 file(s) in the isolated workspace; deletions are not propagated to the project: notes/ 1",
"omitting symlink outside the isolated project",
],
);
assert_eq!(project.read("notes/old.txt"), "keep me\n");
// Too large to rewrite, the report comes back as the command wrote it.
let report = std::fs::read(project.root.join("out/big.txt")).unwrap();
assert!(report.len() > 17 << 20);
let copy = format!("{}/.supercov/workspaces/", project.root.display());
assert!(
report.starts_with(copy.as_bytes()),
"a file this large still names the copy it was written in"
);
}
#[test]
fn every_human_query_pages_and_names_its_filters() {
let project = Project::cart("human-pages");
project.write(
"src/tax.js",
"export function tax(amount, region) {\n if (region === 'EU' || amount > 1000) {\n return amount * 0.2;\n }\n return 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { tax } from '../src/tax.js';\n\ntest('EU pays tax', () => {\n assert.equal(tax(10, 'EU'), 2);\n});\n",
);
project.commit("tax");
let run = project.measure(&[]);
// Every list cut to one row says how to read the next.
for args in [
vec!["files", "--limit", "1"],
vec!["gaps", "--limit", "1"],
vec!["file", "src/cart.js", "--limit", "1"],
vec!["decision", "src/tax.js:2", "--limit", "1"],
vec!["line", "src/tax.js:2", "--limit", "1"],
vec!["test", "EU pays tax", "--limit", "1"],
] {
let mut all = vec!["runs", run.as_str()];
all.extend(args.iter().copied());
let output = project.supercov(&all).succeeds();
assert!(
output.contains("next page: supercov runs"),
"{args:?}\n{output}"
);
assert!(output.contains("--limit 1"), "{args:?}\n{output}");
}
// A narrowed view says what it was narrowed to.
let narrowed = project
.supercov(&[
"runs",
&run,
"files",
"--filter",
"passed",
"--kind",
"unit",
"--runner",
"node:test",
])
.succeeds();
contains_all(&narrowed, &["passed", "unit", "node:test"]);
// A line the run recorded nothing about is read from the working tree,
// and says when that changed since the run.
let current = project
.supercov(&["runs", &run, "line", "src/tax.js:4"])
.succeeds();
assert!(
current.contains("(read from the current working tree)"),
"{current}"
);
project.edit("src/tax.js", "amount * 0.2", "amount * 0.25");
let stale = project
.supercov(&["runs", &run, "line", "src/tax.js:4"])
.succeeds();
assert!(
stale.contains("(read from the working tree, which changed since this run)"),
"{stale}"
);
// Only what a run gained over another.
let gained = project
.supercov(&["diff", &run, &run, "--gained"])
.succeeds();
assert!(!gained.is_empty(), "{gained}");
}
/// A file changed past reading -- its new text no longer parses -- is
/// named changed by its bytes, whether it is the test's own file or code the
/// test ran; a helper the tests load that is gone is named removed.
#[test]
fn a_change_past_reading_and_a_removed_helper_name_the_tests_they_reach() {
let project = Project::empty("changed-past-reading");
project.write(
"package.json",
r#"{ "name": "past-reading", "private": true, "type": "module" }"#,
);
project.write(
"src/a.js",
"export const a = (x) => (x > 1 ? 'big' : 'small');\n",
);
project.write("test/helper.js", "export const helper = () => 1;\n");
project.write(
"test/a.test.js",
"import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { a } from '../src/a.js';\nimport { helper } from './helper.js';\n\ntest('a', () => {\n assert.equal(a(2), 'big');\n assert.equal(helper(), 1);\n});\n",
);
project.git(&["init", "-q"]);
project.commit("past reading");
project.measure(&["test/a.test.js"]);
project.write("src/a.js", "export const a = (x) => (x > 1 ? 'big' : ;\n");
project.write(
"test/a.test.js",
"import assert from 'node:assert/strict';\ntest('a', () => {\n",
);
std::fs::remove_file(project.root.join("test/helper.js")).unwrap();
let affected = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&affected,
&[
"test file changed",
"src/a.js changed (this test ran code in it)",
"test/helper.js removed",
],
);
}
#[test]
fn changes_since_a_run_name_the_tests_they_reach_and_block_a_merge() {
let project = Project::empty("changes-since");
project.write(
"package.json",
r#"{ "name": "changes", "private": true, "type": "module", "dependencies": {} }"#,
);
project.write(
"src/a.js",
"export const a = (x) => (x > 1 ? 'big' : 'small');\n",
);
project.write("src/b.js", "export const b = (x) => (x ? 1 : 0);\n");
project.write("test/helper.js", "export const helper = () => 1;\n");
project.write(
"test/a.test.js",
"import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { a } from '../src/a.js';\nimport { helper } from './helper.js';\n\ntest('a', () => {\n assert.equal(a(2), 'big');\n assert.equal(helper(), 1);\n});\n",
);
project.write(
"__tests__/b.test.js",
"import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { b } from '../src/b.js';\n\ntest('b', () => {\n assert.equal(b(1), 1);\n});\n",
);
project.git(&["init", "-q"]);
project.commit("changes");
let first = project.measure(&["test/a.test.js"]);
// A dependency added between two runs keeps them apart.
project.edit(
"package.json",
r#""dependencies": {}"#,
r#""dependencies": { "left-pad": "1.3.0" }"#,
);
let second = project.measure(&["__tests__/b.test.js"]);
let refused = project.supercov(&["merge", &first, &second]).exits(2);
assert!(
refused.contains("differing domains: dependencies"),
"{refused}"
);
// A removed source, a changed helper and the dependency change, each
// named with the tests it reaches.
project.edit(
"package.json",
r#""dependencies": { "left-pad": "1.3.0" }"#,
r#""dependencies": {}"#,
);
std::fs::remove_file(project.root.join("src/b.js")).unwrap();
project.edit("test/helper.js", "=> 1", "=> 2");
let since_first = project
.supercov(&["runs", &first, "tests", "affected"])
.succeeds();
contains_all(
&since_first,
&[
"test/a.test.js › a",
"test/helper.js changed: helper (line 1) (this test's file loads it)",
"src/b.js removed",
],
);
let since_second = project
.supercov(&["runs", &second, "tests", "affected"])
.succeeds();
contains_all(
&since_second,
&[
"__tests__/b.test.js › b",
"dependencies or lockfile changed (every test)",
"src/b.js removed (this test ran code in it)",
"test/helper.js changed: helper (line 1) (a file tests may load)",
],
);
}
#[test]
fn runs_of_two_languages_are_refused_for_what_they_are() {
// Each language's instrumenter is its own, so the two runs differed
// there first, and the refusal said the Python run was "recorded by
// another build of Supercov" -- the same build, minutes apart.
let project = Project::cart("two-languages");
project.write("pkg/__init__.py", "");
project.write(
"pkg/half.py",
"def half(x):\n return x / 2 if x else 0\n",
);
project.write(
"test_half.py",
"import unittest\n\nfrom pkg.half import half\n\n\nclass Half(unittest.TestCase):\n def test_half(self):\n self.assertEqual(half(2), 1)\n",
);
project.commit("python beside");
let javascript = project.measure(&[]);
project
.supercov(&["--", "python3", "-m", "unittest", "-q", "test_half"])
.succeeds();
let python = project.latest();
let refused = project.supercov(&["merge", &javascript, &python]).exits(2);
assert!(
refused.contains(&format!(
"Cannot merge run {python}: it measured python, and run {javascript} measured javascript; runs of different languages are not merged"
)),
"{refused}"
);
// A run whose archive cannot be read for its language is refused as
// another build's, the most it can be said to be.
let unread = project
.supercov_with(
&["merge", &javascript, &python],
&[("SUPERCOV_TEST_FAULT", "fs.open#evidence_archive.rs:697")],
)
.exits(2);
assert!(unread.contains("recorded by another build"), "{unread}");
}
#[cfg(unix)]
#[test]
fn a_command_is_watched_stopped_and_passed_through_whole() {
let project = Project::cart("supervision");
// A timeout of nothing is refused before anything runs.
let refused = project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "0")],
)
.exits(1);
assert!(
refused.contains(
"SUPERCOV_COMMAND_TIMEOUT_MS must be a positive integer number of milliseconds"
),
"{refused}"
);
// A command that ignores SIGTERM is killed once the grace runs out.
let stubborn = project.supercov_with(
&[
"--",
"node",
"-e",
"process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)",
],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "300")],
);
let said = format!("{}{}", stubborn.stdout(), stubborn.stderr());
assert_eq!(stubborn.code(), 124, "{said}");
assert!(said.contains("command still running after"), "{said}");
// Asked to be verbose, a slow command's diagnostics name its processes.
let verbose = project.supercov_with(
&["--", "node", "-e", "setTimeout(() => {}, 900)"],
&[
("SUPERCOV_DIAGNOSTIC_INTERVAL_MS", "200"),
("SUPERCOV_VERBOSE", "1"),
],
);
let said = format!("{}{}", verbose.stdout(), verbose.stderr());
assert_eq!(verbose.code(), 0, "{said}");
assert!(said.contains("exe=node"), "{said}");
// A line longer than any relay buffer, with no newline, comes through whole.
let long = project
.supercov(&[
"--",
"node",
"-e",
"process.stdout.write('x'.repeat(70000))",
])
.succeeds();
assert!(long.contains(&"x".repeat(70000)), "{} bytes", long.len());
}
#[test]
fn cargo_reached_in_every_form_runs_what_it_was_asked() {
let project = Project::empty("cargo-forms");
project.write(
"Cargo.toml",
"[package]\nname = \"forms\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[features]\nloud = []\nextra = []\n",
);
project.write(
"src/lib.rs",
"/// Doubles.\n///\n/// ```\n/// assert_eq!(forms::double(2), 4);\n/// ```\npub fn double(x: u32) -> u32 {\n if cfg!(feature = \"loud\") { x * 2 } else { x + x }\n}\n",
);
project.write(
"tests/forms.rs",
"#[test]\nfn doubles() {\n assert_eq!(forms::double(3), 6);\n}\n\n#[test]\nfn slow_one() {\n assert_eq!(forms::double(1), 2);\n}\n",
);
// Through a package script, split as a shell splits it: attached short
// flags, a quoted feature list and a quoted skip after `--`.
project.write(
"package.json",
r#"{ "name": "forms", "private": true, "scripts": { "test": "cargo test -pforms -j2 --features \"loud extra\" --test forms -- --skip='slow_one'" } }"#,
);
project.git(&["init", "-q"]);
project.commit("forms");
let scripted = project.supercov(&["--", "npm", "test"]);
let said = format!("{}{}", scripted.stdout(), scripted.stderr());
assert_eq!(scripted.code(), 0, "{said}");
assert!(
said.contains("1 passed") || said.contains("Rust coverage: 1 test"),
"{said}"
);
// Verbose, timed and quiet forms, with colour asked for and refused.
for (args, env) in [
(
vec!["--", "cargo", "test", "-vv", "--timings"],
vec![("CLICOLOR_FORCE", "1")],
),
(
vec!["--", "cargo", "test", "-q"],
vec![("NO_COLOR", "1"), ("CLICOLOR", "0")],
),
] {
let ran = project.supercov_with(&args, &env);
assert_eq!(ran.code(), 0, "{args:?}\n{}{}", ran.stdout(), ran.stderr());
}
// Doctests alone.
let doc = project.supercov(&["--", "cargo", "test", "--doc"]);
let said = format!("{}{}", doc.stdout(), doc.stderr());
assert_eq!(doc.code(), 0, "{said}");
assert!(said.contains("Rust coverage: 1 test"), "{said}");
// Edition 2024 merges doctests into one harness, which `-q` leaves
// printing a mark per case and no name.
project.write(
"merged/Cargo.toml",
"[package]\nname = \"merged\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace]\n",
);
project.write(
"merged/src/lib.rs",
"/// ```\n/// assert_eq!(merged::half(4), 2);\n/// ```\n///\n/// ```ignore\n/// merged::half(0);\n/// ```\n///\n/// ```\n/// assert_eq!(merged::half(2), 5);\n/// ```\npub fn half(x: u32) -> u32 {\n if x > 0 { x / 2 } else { 0 }\n}\n",
);
let quiet = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args(["--", "cargo", "test", "-q", "--doc"])
.current_dir(project.root.join("merged"))
.output()
.unwrap();
let said = format!(
"{}{}",
String::from_utf8_lossy(&quiet.stdout),
String::from_utf8_lossy(&quiet.stderr)
);
assert_eq!(quiet.status.code(), Some(101), "{said}");
// rustdoc names the file as the platform writes paths.
let said = said.replace('\\', "/");
contains_all(
&said,
&[
"running 3 tests",
"failures:\n src/lib.rs - half (line 9)",
"test result: FAILED. 1 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out",
],
);
// A test that does not compile is reported as the build failing.
project.write(
"tests/broken.rs",
"#[test]\nfn broken() {\n let x: u32 = \"text\";\n}\n",
);
let broken = project.supercov(&["--", "cargo", "test"]);
let said = format!("{}{}", broken.stdout(), broken.stderr());
assert_ne!(broken.code(), 0, "{said}");
assert!(said.contains("mismatched types"), "{said}");
}
#[test]
fn a_go_run_names_the_tests_it_could_not_claim_and_the_files_it_could_not_read() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-holes");
project.write("go.mod", "module example.com/holes\n\ngo 1.22\n");
project.write(
"sign.go",
"package holes\n\nimport \"fmt\"\n\nfunc Sign(n int) string {\n\tif n > 0 {\n\t\treturn \"positive\"\n\t}\n\treturn \"not positive\"\n}\n\nfunc Show(n int) { fmt.Println(Sign(n)) }\n",
);
// A generator kept beside the package, as `go generate` keeps them: the
// build never compiles it, so it is no obligation and no package of
// the directory's.
project.write(
"gen.go",
"//go:build ignore\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tif len(\"x\") > 0 {\n\t\tfmt.Println(\"generated\")\n\t}\n}\n",
);
// Behind a tag nothing sets: a tool of another package, and a source and
// a test that would not parse if anything read them. Discovery cannot
// answer a tag, so it reads them.
project.write(
"a_tool.go",
"//go:build tools\n\npackage main\n\nfunc main() {}\n",
);
project.write(
"broken.go",
"//go:build never\n\npackage holes\n\nfunc Broken( {\n",
);
project.write(
"broken_test.go",
"//go:build never\n\npackage holes\n\nfunc Broken( {\n",
);
project.write(
"sign_test.go",
"package holes\n\nimport \"testing\"\n\nfunc TestPositive(t *testing.T) {\n\tif Sign(1) != \"positive\" {\n\t\tt.Fatal(\"positive\")\n\t}\n}\n\nfunc TestParallel(t *testing.T) {\n\tt.Parallel()\n\tif Sign(-1) != \"not positive\" {\n\t\tt.Fatal(\"not positive\")\n\t}\n}\n\nfunc ExampleShow() {\n\tShow(2)\n\t// Output: positive\n}\n",
);
project.git(&["init", "-q"]);
let ran = project.supercov(&["--", go, "test", "./..."]);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 0, "{said}");
contains_all(
&said,
&[
"Go coverage: 3 test(s) across 2 source file(s) in 1 package(s)",
"2 test(s) could not announce themselves (t.Parallel, Example or Fuzz)",
"1 source file(s) did not parse and are absent from the denominator",
"1 test file(s) did not parse; the tests they declare ran unattributed",
],
);
// What the unclaimed tests reached still counts.
let line = project
.supercov(&["runs", "latest", "line", "sign.go:9"])
.succeeds();
assert!(
line.contains("COVERED") && !line.contains("NOT COVERED"),
"{line}"
);
let files = project.supercov(&["runs", "latest", "files"]).succeeds();
assert!(
files.contains("sign.go") && !files.contains("gen.go"),
"{files}"
);
// Asked about, the parallel test says why it holds nothing.
let parallel = project
.supercov(&["runs", "latest", "test", "TestParallel"])
.succeeds();
contains_all(
¶llel,
&[
"outcome passed",
"coverage not attributable to this test; it ran alongside others",
],
);
}
#[test]
fn a_run_of_one_test_script_points_at_the_whole_suite_however_it_was_named() {
let project = Project::cart("scripts");
let scripts = |scripts: &str| {
project.write(
"package.json",
&format!(r#"{{ "name": "cart", "private": true, "type": "module", "scripts": {{ {scripts} }} }}"#),
);
};
let hints = |command: &[&str]| {
let mut args = vec!["--"];
args.extend_from_slice(command);
let ran = project.supercov(&args);
assert_eq!(
ran.code(),
0,
"{command:?}\n{}{}",
ran.stdout(),
ran.stderr()
);
let run = project.latest();
project.supercov(&["runs", &run, "--json"]).json()["data"]["hints"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.map(|hint| hint.as_str().unwrap().to_owned())
.collect::<Vec<_>>()
};
scripts(
r#""test": "node --test", "test:unit": "node --test test/cart.test.js", "test:other": "node --test""#,
);
// The whole suite, by any of its names, needs no pointer to itself.
for command in [
&["npm", "test"][..],
&["npm", "t"],
&["npm", "run", "-s", "test"],
&["npm", "--silent", "run-script", "test"],
] {
assert_eq!(hints(command), Vec::<String>::new(), "{command:?}");
}
// One script of several names the others and the whole command.
// pnpm where it is installed: not every machine has it.
let pnpm = std::process::Command::new("pnpm")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success());
let mut commands = vec![&["npm", "run", "test:unit"][..]];
if pnpm {
commands.push(&["pnpm", "test:unit"]);
}
for command in commands {
let said = hints(command).join("\n");
contains_all(
&said,
&[
&format!("wrapped `{}`", command.join(" ")),
"Other test scripts include test:other.",
"-- npm test`",
],
);
assert!(!said.contains("include test:unit"), "{said}");
}
// With nothing else to name, it still names the whole command.
scripts(r#""test": "node --test", "test:unit": "node --test test/cart.test.js""#);
let said = hints(&["npm", "run", "test:unit"]).join("\n");
assert!(
said.contains("-- npm test`") && !said.contains("Other test scripts"),
"{said}"
);
// A command of its own beside a lone `test` script is not one of several,
// and a project with no `test` script has no whole suite to point at.
scripts(r#""test": "node --test""#);
assert_eq!(hints(&["node", "--test"]), Vec::<String>::new());
scripts(r#""unit": "node --test""#);
assert_eq!(hints(&["npm", "run", "unit"]), Vec::<String>::new());
}
#[test]
fn merge_says_what_moved_under_each_run_it_leaves_out() {
let project = Project::cart("merge-moved");
project.write(
"test/more.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { shipping } from \"../src/cart.js\";\n\ntest(\"more\", () => {\n assert.equal(shipping(10, true), 15);\n});\n",
);
project.write("src/util.js", "export const util = 1;\n");
project.commit("more");
// A script that measures suites one by one is told each run's id.
let id_file = project.root.join("first-run-id");
let first = project.supercov_with(
&["--", "node", "--test", "test/cart.test.js"],
&[("SUPERCOV_RUN_ID_FILE", id_file.to_str().unwrap())],
);
assert_eq!(first.code(), 0, "{}", first.stderr());
assert_eq!(
project.read("first-run-id").trim(),
project.latest(),
"the id written is the run published"
);
// A file it cannot write to costs the id, not the run.
let unwritable = project.root.join("missing/run-id");
let second = project.supercov_with(
&["--", "node", "--test", "test/more.test.js"],
&[("SUPERCOV_RUN_ID_FILE", unwritable.to_str().unwrap())],
);
assert_eq!(second.code(), 0, "{}", second.stderr());
assert!(
second.stderr().contains("could not write the run id to"),
"{}",
second.stderr()
);
let left_out = |because: &str| {
let refused = project.supercov(&["merge"]);
assert_eq!(refused.code(), 2, "{}", refused.stdout());
let said = format!("{}{}", refused.stdout(), refused.stderr());
contains_all(
&said,
&[
&format!("(node --test test/cart.test.js): {because}"),
&format!("(node --test test/more.test.js): {because}"),
],
);
};
// A measured file added is counted, one removed is named, and with
// every one removed there is no source left to compare.
project.write("src/extra.js", "export const extra = 1;\n");
left_out("the source has changed (1 file(s) added)");
std::fs::remove_file(project.root.join("src/extra.js")).unwrap();
std::fs::remove_file(project.root.join("src/util.js")).unwrap();
left_out("the source has changed (src/util.js)");
let cart = project.read("src/cart.js");
std::fs::remove_file(project.root.join("src/cart.js")).unwrap();
left_out("its source cannot be measured as it is now");
project.write("src/cart.js", &cart);
project.write("src/util.js", "export const util = 1;\n");
let manifest = project.read("package.json");
project.write(
"package.json",
&manifest.replacen(
"\"private\": true,",
"\"private\": true, \"dependencies\": { \"left-pad\": \"1.3.0\" },",
1,
),
);
left_out(
"the dependencies have changed (runs merge only when every job installs the same lockfile",
);
project.write("package.json", &manifest);
// A configuration file added may change how the tests run; told it does
// not, merge counts both runs.
project.write("test.config.mjs", "export default {};\n");
left_out("a configuration file was added");
let merged = project.supercov(&["merge", "--allow-changed"]).succeeds();
assert!(merged.contains("merging 2 runs"), "{merged}");
}
#[test]
fn a_floor_on_what_a_run_has_none_of_cannot_pass() {
let project = Project::empty("nothing-eligible");
project.write(
"package.json",
r#"{ "name": "flat", "private": true, "type": "module" }"#,
);
project.write(
"src/add.js",
"export function add(a, b) {\n return a + b;\n}\n",
);
project.write(
"test/add.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { add } from \"../src/add.js\";\ntest(\"add\", () => assert.equal(add(1, 2), 3));\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
// No branch anywhere is not every branch taken.
let refused = project
.supercov(&["runs", "check", "--min-branches", "80"])
.exits(2);
contains_all(
&refused,
&[
"branches n/a 0/0 (floor 80%)",
"branches has nothing eligible in this run, which is not the same as complete",
],
);
// So for functions, in a run of none, and the flag to drop is named.
let flat = Project::empty("no-functions");
flat.write(
"package.json",
r#"{ "name": "flat", "private": true, "type": "module" }"#,
);
flat.write("src/total.js", "export const total = 1 + 2;\n");
flat.write(
"test/total.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { total } from \"../src/total.js\";\ntest(\"total\", () => assert.equal(total, 3));\n",
);
flat.git(&["init", "-q"]);
flat.measure(&[]);
let refused = flat
.supercov(&["runs", "check", "--min-functions", "50"])
.exits(2);
assert!(
refused.contains("functions has nothing eligible in this run")
&& refused.contains("remove --min-functions"),
"{refused}"
);
// And for statements, in a run whose only source holds none.
let bare = Project::empty("no-statements");
bare.write(
"package.json",
r#"{ "name": "bare", "private": true, "type": "module" }"#,
);
bare.write("src/note.js", "// nothing to run\n");
bare.write(
"test/t.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\ntest(\"t\", () => assert.equal(1, 1));\n",
);
bare.git(&["init", "-q"]);
bare.measure(&[]);
let refused = bare
.supercov(&["runs", "check", "--min-statements", "50"])
.exits(2);
assert!(
refused.contains("statements has nothing eligible in this run")
&& refused.contains("remove --min-statements"),
"{refused}"
);
// Per file, a file with none is passed over and the rest are judged.
project.write(
"src/sign.js",
"export function sign(n) {\n if (n > 0) {\n return 1;\n }\n return -1;\n}\n",
);
project.write(
"test/sign.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { sign } from \"../src/sign.js\";\ntest(\"sign\", () => assert.equal(sign(1), 1));\n",
);
project.measure(&[]);
let failed = project
.supercov(&["runs", "check", "--min-branches", "80", "--per-file"])
.exits(1);
contains_all(
&failed,
&[
"src/sign.js: branches 50.00% 1/2 below 80%",
"uncovered lines: 5\n",
],
);
assert!(!failed.contains("src/add.js"), "{failed}");
}
#[test]
fn the_latest_run_answers_patch_and_report_without_its_id() {
let project = Project::empty("latest-patch");
project.write(
"package.json",
r#"{ "name": "latest", "private": true, "type": "module" }"#,
);
let sign = "export function sign(n) {\n if (n > 0) {\n return 1;\n }\n return -1;\n}\n";
project.write("src/sign.js", sign);
project.write(
"test/sign.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { sign } from \"../src/sign.js\";\ntest(\"sign\", () => {\n assert.equal(sign(1), 1);\n assert.equal(sign(-1), -1);\n});\n",
);
project.git(&["init", "-q"]);
project.commit("base");
// A comment changes nothing a floor could judge.
project.write("src/sign.js", &format!("// Which side of zero.\n{sign}"));
project.measure(&[]);
let quiet = project
.supercov(&["runs", "patch", "--base", "HEAD", "--min-lines", "90"])
.succeeds();
contains_all(
&quiet,
&[
"No executable changes.",
"PASS: nothing executable changed, so 90% does not apply.",
],
);
// A block no test enters reads as one range.
project.write(
"src/sign.js",
"export function sign(n) {\n if (n > 0) {\n return 1;\n }\n if (n < -100) {\n const big = n * 2;\n return big;\n }\n return -1;\n}\n",
);
project.measure(&[]);
let patch = project
.supercov(&["runs", "patch", "--base", "HEAD"])
.succeeds();
contains_all(
&patch,
&[
"1 of 3 changed executable line(s) covered (33.33%)",
"src/sign.js: 6-7\n",
],
);
// An HTML report goes to the file named, or into the directory named.
project
.supercov(&[
"runs",
"report",
"--format",
"html",
"--output",
"out/sign.html",
])
.succeeds();
project
.supercov(&["runs", "report", "--format", "html", "--output", "out/site"])
.succeeds();
for file in ["out/sign.html", "out/site/index.html"] {
assert!(project.read(file).contains("src/sign.js"), "{file}");
}
}
#[test]
fn a_decision_is_found_again_by_the_location_its_line_lists() {
let project = Project::empty("decision-location");
project.write(
"package.json",
r#"{ "name": "pick", "private": true, "type": "module" }"#,
);
let long = format!(
" return (a && {name}) || (c && {name}) ? 4 : c || a ? 5 : 6;",
name = "an_argument_named_at_such_length_that_the_line_it_sits_on_runs_on"
);
project.write(
"src/pick.js",
&format!(
"export function pick(a, b, c) {{\n return a && b ? 1 : (c || a) ? 2 : 3;\n}}\n\nexport function long(a, c, an_argument_named_at_such_length_that_the_line_it_sits_on_runs_on) {{\n{long}\n}}\n"
),
);
project.write(
"test/pick.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { pick, long } from \"../src/pick.js\";\ntest(\"pick\", () => {\n assert.equal(pick(1, 1, 0), 1);\n assert.equal(long(0, 0, 1), 6);\n});\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
// A line of two decisions lists both, each at its own column.
let listed = project
.supercov(&["runs", "latest", "decision", "src/pick.js:2"])
.succeeds();
assert!(
listed.contains("showing 1-2 of 2 matching decisions"),
"{listed}"
);
let location = listed
.lines()
.find(|line| line.ends_with("c || a"))
.and_then(|line| line.split_whitespace().nth(1))
.unwrap_or_else(|| panic!("{listed}"))
.to_owned();
// Named by the location listed, it is the one decision.
let one = project
.supercov(&["runs", "latest", "decision", &location])
.succeeds();
contains_all(&one, &[&location, "c || a", "C1 MISSING: c"]);
assert!(!one.contains("matching decisions"), "{one}");
// A gap says what run would close it: the one seen, the condition
// flipped, the outcome the other way; or that nothing evaluated it.
let gaps = project
.supercov(&["runs", "latest", "line", "src/pick.js:2", "--json"])
.json();
let needs = gaps["data"]["remaining"]
.as_array()
.unwrap()
.iter()
.filter(|gap| gap["kind"] == "mcdc")
.map(|gap| {
(
gap["missingCondition"].as_str().unwrap().to_owned(),
gap["neededVector"].as_str().unwrap_or("").to_owned(),
gap["needs"].as_str().unwrap().to_owned(),
)
})
.collect::<Vec<_>>();
assert!(
needs.contains(&(
"a".into(),
"F- -> F".into(),
"`a` false, decision false".into()
)),
"{needs:?}"
);
// No test evaluated `c`: both runs of the pair that would show it.
assert!(
needs.contains(&(
"c".into(),
"FF -> F and T- -> T".into(),
"`c` false, `a` false, decision false; and `c` true, decision true".into()
)),
"{needs:?}"
);
for missing in ["src/pick.js:2:1", "src/pick.js:3"] {
let refused = project
.supercov(&["runs", "latest", "decision", missing])
.exits(2);
assert!(refused.contains("Decision not found"), "{refused}");
}
// The file's gaps quote a decision too long to show whole, cut short.
let file = project
.supercov(&["runs", "latest", "file", "src/pick.js"])
.succeeds();
assert!(
file.lines()
.any(|line| line.contains("(a && an_argument") && line.ends_with('…')),
"{file}"
);
}
#[cfg(unix)]
#[test]
fn a_workspace_package_runs_with_its_own_node_modules_and_tools() {
let project = Project::empty("monorepo");
project.write(
"package.json",
r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"] }"#,
);
project.write(".gitignore", "node_modules\n");
// The root holds one version of a dependency, the package another; a
// pnpm-style package is a link into the root's store; the package's own
// tool is in its own `.bin`.
project.write(
"node_modules/dep/package.json",
r#"{ "name": "dep", "version": "1.0.0", "main": "index.js" }"#,
);
project.write(
"node_modules/dep/index.js",
"module.exports = { version: 1 };\n",
);
project.write(
"packages/app/node_modules/dep/package.json",
r#"{ "name": "dep", "version": "2.0.0", "main": "index.js" }"#,
);
project.write(
"packages/app/node_modules/dep/index.js",
"module.exports = { version: 2 };\n",
);
let store = "node_modules/.pnpm/left@3.0.0/node_modules/left";
project.write(
&format!("{store}/package.json"),
r#"{ "name": "left", "version": "3.0.0", "main": "index.js" }"#,
);
project.write(
&format!("{store}/index.js"),
"module.exports = (s) => \" \" + s;\n",
);
std::os::unix::fs::symlink(
format!("../../../{store}"),
project.root.join("packages/app/node_modules/left"),
)
.unwrap();
project.write_script(
"packages/app/node_modules/.bin/apptool",
"#!/usr/bin/env node\nconsole.log(\"the package's own tool ran\");\n",
);
project.write(
"packages/app/package.json",
r#"{ "name": "app", "private": true, "scripts": { "test": "apptool && node --test" } }"#,
);
project.write(
"packages/app/src/label.js",
"const dep = require(\"dep\");\nconst left = require(\"left\");\nexports.label = (n) => (dep.version === 2 && n > 0 ? left(\"v2\") : \"other\");\n",
);
project.write(
"packages/app/test/label.test.js",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert\");\nconst { label } = require(\"../src/label.js\");\ntest(\"label\", () => {\n assert.equal(label(1), \" v2\");\n assert.equal(label(0), \"other\");\n});\n",
);
project.git(&["init", "-q"]);
let ran = project.supercov(&["--", "npm", "test", "-w", "packages/app"]);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 0, "{said}");
assert!(said.contains("the package's own tool ran"), "{said}");
let line = project
.supercov(&["runs", "latest", "line", "packages/app/src/label.js:3"])
.succeeds();
// Measured and run: the test's " v2" was only reachable through the
// package's own `dep` and the linked `left`.
assert!(
line.contains("dep.version === 2") && !line.contains("NOT COVERED"),
"{line}"
);
// The links in the project are as they were.
assert!(
std::fs::symlink_metadata(project.root.join("packages/app/node_modules/left"))
.unwrap()
.file_type()
.is_symlink()
);
}
/// `from` and everything under it, copied to `to`.
fn copy_tree(from: &std::path::Path, to: &std::path::Path) {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), target).unwrap();
}
}
}
/// Homebrew's Go is not on a non-login shell's PATH on macOS.
fn go() -> Option<&'static str> {
["go", "/opt/homebrew/bin/go", "/usr/local/go/bin/go"]
.into_iter()
.find(|go| {
std::process::Command::new(go)
.arg("version")
.output()
.is_ok_and(|out| out.status.success())
})
}
#[test]
fn a_file_a_test_deletes_in_the_copy_is_named_and_kept() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-deletes");
project.write("go.mod", "module example.com/deletes\n\ngo 1.22\n");
project.write("stale.txt", "left from a run before\n");
project.write(
"clean.go",
"package deletes\n\nimport \"os\"\n\nfunc Clean(path string) bool {\n\tif err := os.Remove(path); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n",
);
project.write(
"clean_test.go",
"package deletes\n\nimport \"testing\"\n\nfunc TestClean(t *testing.T) {\n\tif !Clean(\"stale.txt\") || Clean(\"stale.txt\") {\n\t\tt.Fatal(\"clean\")\n\t}\n}\n",
);
project.git(&["init", "-q"]);
let ran = project.supercov(&["--", go, "test", "./..."]);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 0, "{said}");
assert!(
said.contains("the command deleted 1 file(s) in the isolated workspace; deletions are not propagated to the project: stale.txt"),
"{said}"
);
assert_eq!(project.read("stale.txt"), "left from a run before\n");
}
#[test]
fn assertions_reached_through_require_a_shebang_or_types_are_credited() {
let project = Project::empty("assert-forms");
project.write("package.json", r#"{ "name": "forms", "private": true }"#);
project.write(
"src/lib.js",
"exports.label = (v) => (v ? \"on:\" + v : \"off\");\n",
);
project.write(
"src/item.ts",
"export interface Item { name: string }\nexport const named = (item: Item): string => (item.name ? item.name : \"anonymous\");\n",
);
project.write(
"test/strict.test.js",
"const test = require(\"node:test\");\nconst assert = require(\"assert\").strict;\nconst { label } = require(\"../src/lib.js\");\ntest(\"strict property\", () => {\n assert.equal(label(\"x\"), \"on:x\");\n});\n",
);
project.write(
"test/destructured.test.js",
"const test = require(\"node:test\");\nconst { strictEqual, notEqual: differs } = require(\"node:assert\");\nconst { label } = require(\"../src/lib.js\");\ntest(\"destructured\", () => {\n strictEqual(label(\"\"), \"off\");\n differs(label(1), \"off\");\n});\n",
);
project.write(
"test/shebang.test.js",
"#!/usr/bin/env node\nconst test = require(\"node:test\");\nconst assert = require(\"node:assert\");\nconst { label } = require(\"../src/lib.js\");\ntest(\"shebang\", () => {\n assert.ok(label(2));\n});\n",
);
project.write(
"test/typed.test.ts",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport type { Item } from \"../src/item.ts\";\nimport { named } from \"../src/item.ts\";\ntest(\"typed\", () => {\n const item: Item = { name: \"\" };\n assert.equal(named(item), \"anonymous\");\n assert.equal(named({ name: \"b\" }), \"b\");\n});\n",
);
project.git(&["init", "-q"]);
let measured = project.supercov(&["--", "node", "--test"]);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured
.stderr()
.contains("attributed 6 native node:assert call(s)"),
"{}",
measured.stderr()
);
for (test, assertions) in [
(
"strict property",
&["node:assert/strict.equal at test/strict.test.js:5:3"][..],
),
(
"destructured",
&[
"node:assert.strictEqual at test/destructured.test.js:5:3",
"node:assert.notEqual at test/destructured.test.js:6:3",
],
),
("shebang", &["node:assert.ok at test/shebang.test.js:6:3"]),
(
"typed",
&[
"node:assert.equal at test/typed.test.ts:7:3",
"node:assert.equal at test/typed.test.ts:8:3",
],
),
] {
let read = project
.supercov(&["runs", "latest", "test", test])
.succeeds();
contains_all(&read, assertions);
}
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&["Lines 100.00% (2/2)", "Branches 100.00% (4/4)"],
);
// A test file that does not parse runs as written, fails as Node fails
// it, and the run cannot pass a gate.
project.write(
"test/broken.test.js",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert\");\ntest(\"broken\", () => {\n assert.ok(1;\n});\n",
);
let broken = project.supercov(&["--", "node", "--test"]);
assert_eq!(broken.code(), 1, "{}", broken.stderr());
assert!(
broken.stdout().contains("SyntaxError"),
"{}",
broken.stdout()
);
let refused = project
.supercov(&["runs", "latest", "check", "--min-lines", "50"])
.exits(2);
assert!(
refused.contains("the wrapped test command did not pass"),
"{refused}"
);
}
#[test]
fn many_lines_are_answered_in_one_call_and_every_gap_says_what_is_missing() {
let project = Project::empty("line-batch");
project.write(
"package.json",
r#"{ "name": "ship", "private": true, "type": "module" }"#,
);
project.write(
"src/ship.js",
"export function ship(sum, express, member) {\n if (express || sum < 50) {\n return express ? 15 : 5;\n }\n if (member && sum > 100) {\n return 0;\n }\n return 2;\n}\n",
);
project.write(
"test/ship.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { ship } from \"../src/ship.js\";\ntest(\"express\", () => assert.equal(ship(10, true, false), 15));\ntest(\"member\", () => assert.equal(ship(200, false, true), 0));\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
// Each missing condition names the value it never took, in every view.
let decisions = project
.supercov(&[
"runs",
"latest",
"file",
"src/ship.js",
"--group",
"decision",
])
.succeeds();
contains_all(
&decisions,
&[
"`sum < 50` was never true; needs `express` false, `sum < 50` true, decision true",
"`member` was never false; needs `member` false, decision false",
],
);
let rows = project
.supercov(&[
"runs",
"latest",
"file",
"src/ship.js",
"--group",
"decision",
"--json",
])
.json();
let first = &rows["data"]["decisions"][0];
assert_eq!(first["missing"][0]["condition"], "sum < 50", "{rows}");
assert_eq!(
first["missing"][0]["missingOutcomes"],
serde_json::json!(["true"]),
"{rows}"
);
let decision = project
.supercov(&["runs", "latest", "decision", "src/ship.js:2"])
.succeeds();
assert!(
decision.contains("C2 MISSING: sum < 50 (never true)"),
"{decision}"
);
// Several lines, named or listed in a file, from one opened run.
let both = project
.supercov(&[
"runs",
"latest",
"line",
"src/ship.js:2",
"src/ship.js:5",
"--json",
])
.json();
assert_eq!(both["command"], "coverage.lines", "{both}");
let lines = both["data"]["lines"].as_array().unwrap();
assert_eq!(lines.len(), 2, "{both}");
assert_eq!(lines[1]["location"]["line"], 5);
let gaps = lines[1]["remaining"]
.as_array()
.unwrap()
.iter()
.filter(|gap| gap["kind"] == "mcdc")
.map(|gap| {
(
gap["missingCondition"].as_str().unwrap().to_owned(),
gap["missingOutcomes"].clone(),
)
})
.collect::<Vec<_>>();
assert_eq!(
gaps,
[
("member".to_owned(), serde_json::json!(["false"])),
("sum > 100".to_owned(), serde_json::json!(["false"])),
]
);
// One line answers as it always did.
let one = project
.supercov(&["runs", "latest", "line", "src/ship.js:2", "--json"])
.json();
assert_eq!(one["command"], "coverage.line", "{one}");
project.write("lines.txt", "src/ship.js:2\n# skipped\n\nsrc/ship.js:5\n");
let listed = project
.supercov(&["runs", "latest", "line", "--from-file", "lines.txt"])
.succeeds();
contains_all(
&listed,
&[
"src/ship.js:2",
"src/ship.js:5",
"`sum > 100` was never false",
],
);
// More than one reply holds: a page of the lines that fit, the rest by
// name, and `nextOffset` for a pager. A location asked twice is one.
let mut source = String::new();
for value in 0..200 {
source.push_str(&format!("export const v{value} = {value};\n"));
}
project.write("src/many.js", &source);
project.write(
"test/many.test.js",
"import test from \"node:test\";\nimport \"../src/many.js\";\ntest(\"loads\", () => {});\n",
);
let many_run = project.measure(&["test/many.test.js"]);
let mut locations = (1..=200)
.map(|line| format!("src/many.js:{line}"))
.collect::<Vec<_>>();
locations.push("src/many.js:1".into());
let mut answered = Vec::new();
let mut offset = 0;
loop {
let mut arguments = vec!["runs".to_owned(), many_run.clone(), "line".into()];
arguments.extend(locations.iter().cloned());
arguments.extend(["--json".into(), "--offset".into(), offset.to_string()]);
let arguments = arguments.iter().map(String::as_str).collect::<Vec<_>>();
let page = project.supercov(&arguments).json();
assert_eq!(page["ok"], true, "{page}");
assert_eq!(page["pagination"]["total"], 200, "{page}");
for line in page["data"]["lines"].as_array().unwrap() {
answered.push(line["location"]["line"].as_u64().unwrap());
}
match page["pagination"]["nextOffset"].as_u64() {
Some(next) => {
assert!(
page["data"]["remaining"]
.as_array()
.is_some_and(|rest| !rest.is_empty())
);
offset = next as usize;
}
None => break,
}
}
assert!(offset > 0, "200 lines take more than one reply");
assert_eq!(answered, (1..=200).collect::<Vec<_>>());
// Lines that hold only their statements' anchors are cut the same way.
let mut source = String::new();
for value in 0..200 {
source.push_str(&format!(
"export function f{value}(x) {{\n if (x) {{\n return {value};\n }}\n return 0;\n}}\n"
));
}
project.write("src/blocks.js", &source);
project.write(
"test/blocks.test.js",
"import test from \"node:test\";\nimport { f0 } from \"../src/blocks.js\";\ntest(\"one\", () => f0(true));\n",
);
let blocks_run = project.measure(&["test/blocks.test.js"]);
let mut arguments = vec!["runs".to_owned(), blocks_run, "line".into()];
arguments.extend((0..200).map(|block| format!("src/blocks.js:{}", block * 6 + 4)));
arguments.push("--json".into());
let arguments = arguments.iter().map(String::as_str).collect::<Vec<_>>();
let page = project.supercov(&arguments).json();
assert_eq!(page["ok"], true, "{page}");
assert!(
page["pagination"]["nextOffset"].as_u64().is_some(),
"{page}"
);
}
#[test]
fn a_measured_run_reads_back_for_some_of_its_tests_by_tag_title_or_file() {
let project = Project::empty("test-filters");
project.write(
"package.json",
r#"{ "name": "shop", "private": true, "type": "module" }"#,
);
project.write(
"src/shop.js",
"export function price(sum, member) {\n if (member && sum > 100) {\n return sum * 0.9;\n }\n return sum;\n}\nexport function label(sum) {\n return sum > 50 ? \"big\" : \"small\";\n}\n",
);
project.write(
"test/api/price.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { price } from \"../../src/shop.js\";\ntest(\"member discount @api\", () => assert.equal(price(200, true), 180));\n",
);
project.write(
"test/ui/label.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { label } from \"../../src/shop.js\";\ntest(\"big label @ui @e2e\", () => assert.equal(label(60), \"big\"));\n",
);
project.git(&["init", "-q"]);
let run = project.measure(&["test/api/price.test.js", "test/ui/label.test.js"]);
// A tag naming a test level is the test's kind; the others stay tags.
let kinds = project.supercov(&["runs", &run, "kinds"]).succeeds();
contains_all(&kinds, &["e2e 1 test(s)", "unit 1 test(s)"]);
let detail = project
.supercov(&["runs", &run, "test", "big label"])
.succeeds();
assert!(detail.contains("node:test e2e; tags @ui @e2e"), "{detail}");
let lines = |arguments: &[&str]| {
let mut all = vec!["runs", run.as_str(), "--json"];
all.extend_from_slice(arguments);
let summary = project.supercov(&all).json();
let lines = &summary["data"]["coverage"]["lines"];
(
lines["covered"].as_u64().unwrap(),
lines["total"].as_u64().unwrap(),
)
};
assert_eq!(lines(&[]), (5, 6));
// The price test runs the discount; the label test the ternary.
assert_eq!(lines(&["--tag", "@api"]), (3, 6));
assert_eq!(lines(&["--tag", "API"]), (3, 6));
assert_eq!(lines(&["--title", "big label"]), (2, 6));
assert_eq!(lines(&["--test-file", "test/ui"]), (2, 6));
assert_eq!(lines(&["--test-file", "test/ui/label.test.js"]), (2, 6));
// Any of one criterion; every criterion given.
assert_eq!(lines(&["--tag", "api", "--tag", "ui"]), (5, 6));
assert_eq!(lines(&["--tag", "api", "--test-file", "test/api"]), (3, 6));
// A leading `!` leaves tests out: everything but the API tests.
assert_eq!(lines(&["--tag", "!api"]), (2, 6));
assert_eq!(lines(&["--test-file", "!test/api"]), (2, 6));
let neither = project
.supercov(&["runs", &run, "--tag", "!api", "--tag", "!e2e", "--json"])
.json();
assert_eq!(neither["error"]["code"], "TEST_FILTER_EMPTY", "{neither}");
let none = project
.supercov(&[
"runs",
&run,
"--tag",
"api",
"--test-file",
"test/ui",
"--json",
])
.json();
assert_eq!(none["error"]["code"], "TEST_FILTER_EMPTY", "{none}");
assert_eq!(
none["error"]["message"],
"No tests match --tag api --test-file test/ui"
);
// A query below the summary says the same.
let files = project
.supercov(&["runs", &run, "files", "--tag", "nightly", "--json"])
.json();
assert_eq!(files["error"]["code"], "TEST_FILTER_EMPTY", "{files}");
assert_eq!(files["error"]["message"], "No tests match --tag nightly");
let plain = project
.supercov(&["runs", &run, "gaps", "--title", "never named"])
.exits(2);
assert!(
plain.contains("No tests match --title never named"),
"{plain}"
);
// Every query reads the same tests, and says which.
let summary = project
.supercov(&["runs", &run, "--test-file", "test/api"])
.succeeds();
assert!(summary.contains("(tests in test/api)"), "{summary}");
let file = project
.supercov(&["runs", &run, "file", "src/shop.js", "--tag", "ui"])
.succeeds();
assert!(file.contains("member && sum > 100"), "{file}");
let line = project
.supercov(&[
"runs",
&run,
"line",
"src/shop.js:3",
"--tag",
"ui",
"--json",
])
.json();
assert_eq!(line["data"]["covered"], false, "{line}");
let gaps = project
.supercov(&["runs", &run, "gaps", "--format", "jsonl", "--tag", "api"])
.succeeds();
assert!(gaps.lines().any(|gap| gap.contains("sum > 50")), "{gaps}");
// Reports too, which a CI step uploads.
let lcov = project
.supercov(&["runs", &run, "report", "--format", "lcov", "--tag", "e2e"])
.succeeds();
contains_all(&lcov, &["SF:src/shop.js", "LH:2", "LF:6"]);
let lcov = project
.supercov(&["runs", &run, "report", "--format", "lcov", "--kind", "unit"])
.succeeds();
assert!(lcov.contains("LH:3"), "{lcov}");
// Gates and the interactive report read the same tests.
project
.supercov(&["runs", &run, "check", "--min-lines", "80"])
.succeeds();
let gate = project
.supercov(&["runs", &run, "check", "--min-lines", "80", "--tag", "e2e"])
.exits(1);
contains_all(
&gate,
&[
"reading only the tests --tag e2e picks",
"lines 33.33% 2/6 below 80%",
],
);
let written = project
.supercov(&[
"report",
&run,
"--no-open",
"--tag",
"api",
"--output",
"api.html",
])
.exits(0);
assert!(written.contains("api.html"), "{written}");
let refused = project
.supercov(&["report", &run, "--no-open", "--tag", "nothing"])
.exits(2);
assert!(refused.contains("matches --tag nothing"), "{refused}");
// Worked out once from the stored run, then read back.
let filtered = |root: &std::path::Path| {
std::fs::read_dir(root.join(".supercov/runs").join(&run))
.unwrap()
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("filtered-"))
.count()
};
let before = filtered(&project.root);
lines(&["--tag", "@API"]);
assert_eq!(
filtered(&project.root),
before,
"the same filter reads its index"
);
}
#[cfg(unix)]
#[test]
fn a_playwright_suite_reads_back_by_its_tags() {
let project = Project::empty("playwright-tags");
project.write(
"package.json",
r#"{ "name": "playwright-tags", "private": true, "type": "module" }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/ship.js",
"export const ship = (sum) => (sum > 100 ? 0 : 5);\nexport const label = (sum) => (sum > 50 ? \"big\" : \"small\");\n",
);
project.write(
"playwright.config.js",
"export default { testDir: \"tests\", reporter: \"line\" };\n",
);
// A tag given to the test, and one in the title of its group.
project.write(
"tests/ship.spec.js",
"import { test, expect } from \"@playwright/test\";\nimport { ship, label } from \"../src/ship.js\";\ntest(\"small orders pay\", { tag: \"@api\" }, () => expect(ship(10)).toBe(5));\ntest.describe(\"labels @ui\", () => {\n test(\"big label\", () => expect(label(60)).toBe(\"big\"));\n});\n",
);
project.git(&["init", "-q"]);
project.commit("playwright tags");
project
.supercov(&["--", "npx", "playwright", "test"])
.succeeds();
let detail = project
.supercov(&["runs", "latest", "test", "small orders"])
.succeeds();
assert!(detail.contains("playwright e2e; tags @api"), "{detail}");
// The run declares a background runner, which no picked test ran under.
for tag in ["@api", "ui"] {
let summary = project
.supercov(&["runs", "latest", "--tag", tag, "--json"])
.json();
let lines = &summary["data"]["coverage"]["lines"];
assert_eq!(
(lines["covered"].as_u64(), lines["total"].as_u64()),
(Some(1), Some(2)),
"{tag}: {summary}"
);
}
}
/// Unit tests beside the specs import `test` and `expect` from their own
/// runner more often than the specs import them from their fixture module.
/// On 2026-11-06 a suite's Vitest files outscored its fixture
/// module, Supercov wrapped Vitest as the Playwright fixture, and every
/// Playwright test crashed loading Vitest's `expect`. Another runner's API
/// is never the fixture.
#[cfg(unix)]
#[test]
fn a_playwright_fixture_is_not_taken_from_the_unit_tests_beside_it() {
let project = Project::empty("playwright-beside-vitest");
project.write(
"package.json",
r#"{ "name": "playwright-beside-vitest", "private": true, "type": "module" }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/ship.js",
"export const ship = (sum) => (sum > 100 ? 0 : 5);\n",
);
project.write(
"playwright.config.js",
"export default { testDir: \"tests/e2e\", reporter: \"line\" };\n",
);
project.write(
"tests/e2e/fixtures.js",
"import { test as base, expect } from \"@playwright/test\";\nexport const test = base.extend({ order: async ({}, use) => use(10) });\nexport { expect };\n",
);
project.write(
"tests/e2e/ship.spec.js",
"import { test, expect } from \"./fixtures.js\";\nimport { ship } from \"../../src/ship.js\";\ntest(\"small orders pay\", ({ order }) => expect(ship(order)).toBe(5));\n",
);
for name in ["a", "b", "c", "d", "e", "f"] {
project.write(
&format!("tests/unit/{name}.test.js"),
"import { test, expect } from \"vitest\";\nimport { ship } from \"../../src/ship.js\";\ntest(\"free\", () => expect(ship(200)).toBe(0));\n",
);
}
project.git(&["init", "-q"]);
project.commit("playwright beside vitest");
let output = project
.supercov(&["--", "npx", "playwright", "test"])
.succeeds();
assert!(output.contains("1 passed"), "{output}");
}
#[test]
fn a_stale_run_names_the_files_that_changed_since_it() {
let project = Project::empty("stale-names");
project.write(
"package.json",
r#"{ "name": "stale-names", "private": true, "type": "module" }"#,
);
project.write("src/shop.js", "export const price = (sum) => sum * 2;\n");
project.write(
"test/price.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { price } from \"../src/shop.js\";\ntest(\"doubles\", () => assert.equal(price(2), 4));\n",
);
project.git(&["init", "-q"]);
project.commit("start");
let run = project.measure(&["test/price.test.js"]);
project.write(
"test/price.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { price } from \"../src/shop.js\";\ntest(\"doubles\", () => assert.equal(price(3), 6));\n",
);
project.write(
"test/more.test.js",
"import test from \"node:test\";\ntest(\"more\", () => {});\n",
);
let said = project.supercov(&["runs", &run]).exits(0);
assert!(
said.contains("changed since the run: test/more.test.js, test/price.test.js"),
"{said}"
);
}
/// A page names the command for the next one; that command, run as printed,
/// shows the next page.
#[test]
fn each_page_names_a_next_page_command_that_shows_it() {
let project = Project::cart("next-page");
project.supercov(&["--", "node", "--test"]).succeeds();
for args in [
&["file", "src/cart.js", "--group", "decision"][..],
&["test", "total"],
&["minimize", "--metric", "lines", "--target", "76"],
] {
let first = project
.supercov(&[&["runs", "latest"][..], args, &["--limit", "1"]].concat())
.succeeds();
assert!(first.contains("showing 1-1 of "), "{first}");
let next = first
.lines()
.find_map(|line| line.strip_prefix("next page: supercov "))
.unwrap_or_else(|| panic!("no next page in\n{first}"));
let words = next
.split(' ')
.map(|word| word.trim_matches('\''))
.collect::<Vec<_>>();
assert!(
words.ends_with(&["--offset", "1", "--limit", "1"]),
"{next}"
);
let second = project.supercov(&words).succeeds();
assert!(second.contains("showing 2-2 of "), "{next}\n{second}");
assert!(
first.contains(&format!("all {} at once", total(&first))),
"{first}"
);
}
fn total(page: &str) -> String {
page.split("showing 1-1 of ")
.nth(1)
.and_then(|rest| rest.split_whitespace().next())
.unwrap()
.to_owned()
}
}
#[test]
fn a_limit_of_zero_lists_every_entry_as_the_other_commands_do() {
let project = Project::cart("limit-zero-everywhere");
let run = project.measure(&[]);
let paged = project
.supercov(&["runs", &run, "files", "--limit", "1", "--json"])
.succeeds();
let paged: serde_json::Value = serde_json::from_str(&paged).unwrap();
let total = paged["pagination"]["total"].as_u64().unwrap();
let every = project
.supercov(&["runs", &run, "files", "--limit", "0", "--json"])
.succeeds();
let every: serde_json::Value = serde_json::from_str(&every).unwrap();
let page = &every["pagination"];
assert_eq!(page["returned"].as_u64(), Some(total), "{every}");
assert_eq!(
page["limit"].as_u64(),
Some(total),
"the page says how many all was: {every}"
);
assert_eq!(page["hasMore"], false, "{every}");
let refused = project
.supercov(&["runs", &run, "files", "--limit", "x"])
.exits(2);
assert!(refused.contains("0 for all of them"), "{refused}");
}
#[test]
fn import_says_what_is_wrong_with_its_arguments_and_takes_values_inline() {
let project = Project::cart("import-arguments");
project.measure(&[]);
project.write("lcov.info", "SF:src/cart.js\nDA:1,1\nend_of_record\n");
std::fs::write(project.root.join("binary.info"), [0xff, 0xfe]).unwrap();
project.write("broken.info", "SF:src/cart.js\nDA:one,1\nend_of_record\n");
contains_all(
&project.supercov(&["import", "--help"]).succeeds(),
&["Usage: supercov import <tracefile>"],
);
contains_all(
&project.supercov(&["docs", "-h"]).succeeds(),
&["Usage: supercov docs [topic]"],
);
for (arguments, said) in [
(
&["import", "lcov.info", "--test"][..],
"--test needs a value",
),
(&["import", "--bogus"][..], "unknown option --bogus"),
(
&["import", "lcov.info", "other.info", "--test", "x"][..],
"unexpected argument other.info",
),
(
&["import", "lcov.info"][..],
"--test <name> or --background",
),
(&["import", "--background"][..], "name the evidence file"),
(
&["import", "lcov.info", "--test= "][..],
"the imported test needs a name",
),
(
&["import", "lcov.info", "--test=device", "--status=flaky"][..],
"--status is passed or failed, not flaky",
),
(
&["import", "binary.info", "--background"][..],
"binary.info is not an LCOV tracefile",
),
(
&["import", "broken.info", "--background"][..],
"Cannot read broken.info as LCOV",
),
] {
let stderr = project.supercov(arguments).exits(2);
assert!(stderr.contains(said), "{arguments:?}: {stderr}");
}
// Every value given inline, as `--name=value`.
project
.supercov(&["import", "lcov.info", "--test=device", "--status=passed"])
.succeeds();
}
#[test]
fn a_kind_or_runner_no_test_has_is_said_to_match_nothing_by_every_query() {
let project = Project::cart("filter-matches-nothing");
project.measure(&[]);
for query in ["summary", "scope", "gaps", "files", "kinds", "runners"] {
for (flag, value, said) in [
("--kind", "e2e", "No tests match kind=e2e"),
("--runner", "jest", "No tests match runner=jest"),
] {
let stderr = project
.supercov(&["runs", "latest", query, flag, value])
.exits(2);
assert!(stderr.contains(said), "{query} {flag} {value}: {stderr}");
assert!(
!stderr.contains("invalid coverage index"),
"{query}: {stderr}"
);
}
}
// A line read for such a filter, too.
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:14", "--kind", "e2e"])
.exits(2);
assert!(line.contains("No tests match kind=e2e"), "{line}");
// A file's decisions read for such a filter, too.
let decisions = project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--kind",
"e2e",
])
.exits(2);
assert!(decisions.contains("No tests match kind=e2e"), "{decisions}");
contains_all(
&project
.supercov(&["runs", "latest", "summary", "--runner", "node:test"])
.succeeds(),
&["(runner node:test)"],
);
}
#[test]
fn a_line_that_is_not_in_the_file_is_refused_not_read_as_unmeasured() {
let project = Project::cart("line-bounds");
project.measure(&[]);
let lines = project.read("src/cart.js").lines().count();
let past = project
.supercov(&["runs", "latest", "line", "src/cart.js:9999"])
.exits(2);
assert!(
past.contains(&format!(
"src/cart.js has {lines} lines; there is no line 9999"
)),
"{past}"
);
let zero = project
.supercov(&["runs", "latest", "line", "src/cart.js:0"])
.exits(2);
assert!(zero.contains("with lines counted from 1"), "{zero}");
// The last line is still a line.
project
.supercov(&["runs", "latest", "line", &format!("src/cart.js:{lines}")])
.succeeds();
// Several lines answer what they can, as before.
project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:1",
"src/cart.js:9999",
])
.succeeds();
}
#[test]
fn diff_refuses_a_third_run() {
let project = Project::cart("diff-extra");
project.measure(&[]);
let id = project.latest();
let said = project.supercov(&["diff", &id, &id, "extra"]).exits(2);
assert!(said.contains("unexpected argument extra"), "{said}");
project.supercov(&["diff", &id, &id]).succeeds();
}
#[test]
fn a_command_that_cannot_start_exits_as_a_shell_would() {
let project = Project::cart("cannot-start");
let missing = project.supercov(&["--", "no-such-program-xyz"]).exits(127);
assert!(
missing.contains("could not spawn no-such-program-xyz"),
"{missing}"
);
#[cfg(unix)]
{
project.write("not-executable.sh", "#!/bin/sh\nexit 0\n");
let denied = project.supercov(&["--", "./not-executable.sh"]).exits(126);
assert!(denied.contains("could not spawn"), "{denied}");
}
}
#[test]
fn a_page_past_the_end_says_so() {
let project = Project::cart("page-past-end");
project.measure(&[]);
let gaps = project
.supercov(&["runs", "latest", "gaps", "--offset", "999999"])
.succeeds();
contains_all(
&gaps,
&["showing none of 1: --offset 999999 is past the end"],
);
contains_all(
&project.supercov(&["runs", "latest", "gaps"]).succeeds(),
&["showing 1-1 of 1"],
);
}
#[test]
fn a_file_the_scope_left_out_says_why_rather_than_not_found() {
let project = Project::cart("scope-reason");
project.measure(&[]);
for args in [
&["runs", "latest", "file", "test/cart.test.js"][..],
&["runs", "latest", "line", "test/cart.test.js:3"][..],
] {
let said = project.supercov(args).exits(2);
assert!(
said.contains("test/cart.test.js is outside the run's scope: test or fixture source"),
"{args:?}: {said}"
);
}
// Among several lines, that location says why and the others answer.
let several = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:1",
"test/cart.test.js:3",
])
.succeeds();
assert!(several.contains("outside the run's scope"), "{several}");
let missing = project
.supercov(&["runs", "latest", "file", "src/none.js"])
.exits(2);
assert!(
missing.contains("Source file not found: src/none.js"),
"{missing}"
);
}
#[test]
fn every_query_flag_is_read_and_a_wrong_one_named() {
let project = Project::cart("query-flags");
project.measure(&[]);
for (args, said) in [
(
&["runs", "latest", "gaps", "--offset", "nan"][..],
"--offset must be a non-negative integer",
),
(
&["runs", "latest", "gaps", "--offset", "1.5"][..],
"--offset must be a non-negative integer",
),
(
&["runs", "latest", "gaps", "--offset", "-1"][..],
"--offset must be a non-negative integer",
),
(
&["runs", "latest", "gaps", "--offset", "1e20"][..],
"--offset must be a non-negative integer",
),
(
&["runs", "latest", "gaps", "--filter", "bogus"][..],
"--filter must be all, passed, or failed",
),
(
&["runs", "latest", "minimize", "--target", "inf"][..],
"--target must be between 0 and 100",
),
(
&["runs", "latest", "minimize", "--metric", "nope"][..],
"--metric must be all, lines",
),
(
&["runs", "latest", "files", "--sort", "missing"][..],
"--sort requires --group decision",
),
(
&["runs", "latest", "files", "--sort", "bogus"][..],
"--sort must be location or missing",
),
(
&["runs", "latest", "gaps", "--depth", "2"][..],
"--depth requires --group dir",
),
(
&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--metric",
"lines",
][..],
"--group decision",
),
(
&["runs", "latest", "line"][..],
"Usage: supercov runs <run-id> line",
),
(
&["runs", "latest", "test"][..],
"Usage: supercov runs <run-id> test",
),
] {
let stderr = project.supercov(args).exits(2);
assert!(stderr.contains(said), "{args:?}: {stderr}");
}
contains_all(
&project
.supercov(&["runs", "latest", "gaps", "--filter", "passed"])
.succeeds(),
&["passed attempts only"],
);
for (metric, target, said) in [
("statements", "50", "for 50% statements"),
("functions", "50", "for 50% functions"),
("branches", "50", "for 50% branches"),
("mcdc", "10", "for 10% mcdc"),
] {
contains_all(
&project
.supercov(&[
"runs", "latest", "minimize", "--metric", metric, "--target", target,
])
.succeeds(),
&[said],
);
}
project
.supercov(&["runs", "latest", "files", "--sort", "location"])
.succeeds();
project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--sort",
"missing",
])
.succeeds();
project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--metric",
"mcdc",
])
.succeeds();
}
#[test]
fn a_diff_keeps_only_what_the_tests_a_filter_picks_covered() {
let project = Project::cart("diff-filters");
project.write(
"test/describe.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { describe } from \"../src/cart.js\";\n\ntest(\"describe lists names\", () => {\n assert.equal(describe([{ name: \"a\" }]), \"a\");\n});\n",
);
project.commit("an integration test");
project
.supercov(&[
"--",
"sh",
"-c",
"SUPERCOV_TEST_KIND=unit node --test test/cart.test.js",
])
.succeeds();
let unit_only = project.latest();
project
.supercov(&[
"--",
"sh",
"-c",
"SUPERCOV_TEST_KIND=unit node --test test/cart.test.js && SUPERCOV_TEST_KIND=integration node --test test/describe.test.js",
])
.succeeds();
let both = project.latest();
let gained = |filter: &[&str]| {
let mut args = vec!["diff", unit_only.as_str(), both.as_str(), "--json"];
args.extend_from_slice(filter);
project.supercov(&args).json()["data"]["gained"]["lineCount"]
.as_u64()
.unwrap()
};
let everything = gained(&[]);
assert!(everything > 0, "the new test covered new lines");
// The unit tests are the same in both runs; the integration test is new.
assert_eq!(gained(&["--kind", "unit"]), 0);
// Run A has no integration test: all its lines are gained.
assert!(gained(&["--kind", "integration"]) >= everything);
assert_eq!(gained(&["--runner", "node:test"]), everything);
// The same unit tests in both runs cover the same share of the code.
let unit = project
.supercov(&["diff", &unit_only, &both, "--kind", "unit", "--json"])
.json();
assert_eq!(unit["data"]["delta"]["lines"], 0, "{unit}");
// A filtered comparison says so.
let human = project
.supercov(&["diff", &unit_only, &both, "--kind", "integration"])
.succeeds();
assert!(
human.lines().next().unwrap().contains("integration"),
"{human}"
);
let refused = project
.supercov(&["diff", &unit_only, &both, "--runner", "jest"])
.exits(2);
assert!(refused.contains("No tests match runner=jest"), "{refused}");
}
#[test]
fn tests_affected_lists_files_names_and_why_and_says_when_it_cannot_narrow() {
let project = Project::cart("affected-forms");
project.measure(&[]);
project.edit("src/cart.js", "let sum = 0;", "let sum = 0 + 0;");
project.edit(
"test/cart.test.js",
"total adds prices",
"total adds all prices",
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--files"])
.succeeds()
.trim(),
"test/cart.test.js"
);
for narrowing in ["--ran-changed", "--asserting"] {
let ran = project.supercov(&["runs", "latest", "tests", "affected", narrowing, "--names"]);
assert_eq!(ran.code(), 0);
assert!(
ran.stderr()
.contains("no assertion assessment; listing every affected test"),
"{narrowing}"
);
assert_eq!(ran.stdout().lines().count(), 3, "{narrowing}");
}
let json = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json();
let affected = json["data"]["affected"].as_array().unwrap();
assert_eq!(affected.len(), 3);
let reasons = |name: &str| {
affected.iter().find(|test| test["name"] == name).unwrap()["reasons"]
.as_array()
.unwrap()
.len()
};
// The shipping test never ran the changed `total`; the other two did.
assert_eq!(reasons("shipping is free over fifty"), 1);
assert_eq!(reasons("total applies a coupon"), 2);
contains_all(
&project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds(),
&[
"3 of 3 tests affected",
"test file changed: top level",
"this test ran it",
],
);
}
#[test]
fn minimize_without_a_target_keeps_what_the_tests_cover() {
let project = Project::cart("minimize-default");
project.measure(&[]);
// The cart's tests cover 76.92% of its lines: no target, no 100% to miss.
let said = project.supercov(&["runs", "latest", "minimize"]).succeeds();
contains_all(
&said,
&[
"exact minimum 3/3 test(s) keeping the coverage of all 3 tests in every measured metric",
"lines 76.92%",
],
);
contains_all(
&project
.supercov(&["runs", "latest", "minimize", "--metric", "lines"])
.succeeds(),
&["keeping the lines coverage of all 3 tests", "lines 76.92%"],
);
let json = project
.supercov(&["runs", "latest", "minimize", "--json"])
.json();
assert_eq!(json["data"]["target"], serde_json::Value::Null, "{json}");
// An explicit target is still held to.
assert!(
project
.supercov(&["runs", "latest", "minimize", "--target", "100"])
.exits(2)
.contains("target 100% is impossible")
);
}
#[test]
fn a_branch_lists_its_unrun_outcomes_in_one_order() {
let project = Project::cart("branch-order");
project.measure(&[]);
// Each call is a new process, with its own hash order.
for _ in 0..8 {
contains_all(
&project
.supercov(&["runs", "latest", "line", "src/cart.js:14"])
.succeeds(),
&["Unobserved: true; false"],
);
}
}
#[test]
fn covered_unmeasured_and_empty_views_say_which_they_are() {
let project = Project::cart("empty-views");
let first = project.measure(&[]);
for at in 0..2 {
project.write(
&format!("src/part{at}.js"),
&format!("export function part{at}(a) {{\n return a ? {at} : -{at};\n}}\n"),
);
project.write(
&format!("test/part{at}.test.js"),
&format!(
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport {{ part{at} }} from \"../src/part{at}.js\";\ntest(\"part{at} both\", () => {{\n assert.equal(part{at}(true), {at});\n assert.equal(part{at}(false), -{at});\n}});\n"
),
);
}
project.commit("parts");
let second = project.measure(&[]);
// Every line covered is not "nothing measured".
let covered = project
.supercov(&["runs", "latest", "file", "src/part1.js"])
.succeeds();
contains_all(
&covered,
&["No gap lines: every line is covered and measured."],
);
assert!(!covered.contains("Nothing measured"), "{covered}");
// Everything passed, so no attempt failed.
for query in ["kinds", "runners"] {
contains_all(
&project
.supercov(&["runs", "latest", query, "--filter", "failed"])
.succeeds(),
&[
"No tests in this view (failed attempts only)",
"showing 0-0 of 0",
],
);
}
// Only gains: no "most lost first" over a list with nothing lost.
let gained = project.supercov(&["diff", &first, &second]).succeeds();
contains_all(&gained, &["in 2 files:", "src/part0.js: gained"]);
assert!(!gained.contains("most lost first"), "{gained}");
contains_all(
&project.supercov(&["diff", &second, &first]).succeeds(),
&["in 2 files, most lost first:", "src/part0.js: lost"],
);
}
#[test]
fn every_view_names_its_filters_pages_and_notes() {
let project = Project::cart("view-notes");
let first = project.measure(&[]);
for at in 0..12 {
project.write(
&format!("src/part{at}.js"),
&format!("export function part{at}(a) {{\n return a ? {at} : -{at};\n}}\n"),
);
project.write(
&format!("test/part{at}.test.js"),
&format!("import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport {{ part{at} }} from \"../src/part{at}.js\";\ntest(\"part{at} both\", () => {{\n assert.equal(part{at}(true), {at});\n assert.equal(part{at}(false), -{at});\n}});\n"),
);
}
project.write(
"test/none.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\ntest(\"asserts alone\", () => {\n assert.equal(1 + 1, 2);\n});\n",
);
project.commit("parts");
let second = project.measure(&[]);
let said = |args: &[&str]| project.supercov(args).succeeds();
// Gains over more files than are listed.
contains_all(
&said(&["diff", &first, &second, "--gained"]),
&[
"in 12 files:",
" ... and 2 more files",
"+ line src/part0.js:1",
],
);
// A page of a filtered comparison carries the filters to the next one.
contains_all(
&said(&[
"diff",
&first,
&second,
"--filter",
"passed",
"--runner",
"node:test",
"--limit",
"1",
]),
&[
"(passed attempts only, runner node:test)",
"showing 1-1 of 24 per category",
"--filter passed --runner 'node:test' --offset 1 --limit 1",
],
);
contains_all(
&said(&["diff", &first, &second, "--kind", "unit", "--limit", "2"]),
&["(kind unit)", "--kind 'unit' --offset 2 --limit 2"],
);
contains_all(
&said(&["runs", "latest", "tests", "without-evidence"]),
&[
"Tests that made assertions and recorded no coverage: 1",
"asserts alone",
"1 assertion; its file imports no measured source",
],
);
for (args, next) in [
(
&["runs", "latest", "minimize", "--limit", "2"][..],
"minimize --offset 2 --limit 2",
),
(
&["runs", "latest", "scope", "--files", "--limit", "3"][..],
"scope --files --offset 3 --limit 3",
),
(
&["runs", "latest", "files", "--limit", "3"][..],
"files --offset 3 --limit 3",
),
] {
contains_all(&said(args), &[next]);
}
contains_all(
&said(&["runs", "latest", "--test-file", "test/part3.test.js"]),
&["(tests in test/part3.test.js)", "Lines 5.41% (2/37)"],
);
contains_all(
&said(&["runs", "latest", "gaps", "--title", "part"]),
&[
"Projection: title containing \"part\"",
"file --title 'part' 'src/cart.js'",
],
);
contains_all(
&said(&["runs", "latest", "line", "src/part3.js:2"]),
&[
"COVERED",
"Test phases",
"node:assert/strict.equal (passed)",
],
);
// A run whose command failed says its coverage cannot gate.
project.write(
"src/cart.js",
&common::CART.replace("return 0;", "return 1;"),
);
project.supercov(&["--", "node", "--test"]).exits(1);
contains_all(
&said(&["runs", "latest"]),
&[
"status: wrapped command exited 1 — coverage below is diagnostic and cannot gate",
"Failed 1",
],
);
contains_all(
&said(&["runs", "latest", "decision", "src/cart.js:14"]),
&[
"C1 MISSING: express (never evaluated)",
"confidence unexecuted",
],
);
contains_all(
&said(&[
"runs",
"latest",
"line",
"src/cart.js:14",
"src/cart.js:21",
"src/cart.js:2",
]),
&["showing 1-3 of 5 per category", "every test and phase:"],
);
}
#[test]
fn check_patch_and_affected_tests_answer_or_say_what_is_missing() {
let project = Project::cart("check-patch-affected");
project.measure(&[]);
contains_all(
&project
.supercov(&["runs", "latest", "check", "--min-mcdc", "10"])
.succeeds(),
&[
"mcdc 20.00% 1/5 (floor 10%)",
"PASS: every floor is met.",
],
);
contains_all(
&project
.supercov(&["runs", "latest", "check", "--min-lines", "99"])
.exits(1),
&[
"FAIL: 1 floor(s) not met.",
"(whole run): lines 76.92% 10/13 below 99%",
],
);
for (args, said) in [
(
&["runs", "latest", "check", "--min-branches", "abc"][..],
"\"abc\" is not a percentage",
),
(
&["runs", "latest", "check", "--bogus"][..],
"unknown option --bogus",
),
(
&["runs", "latest", "check"][..],
"no floor requested; give at least one --min-<metric>",
),
(
&["runs", "run_0000000000000000"][..],
"Coverage run not found: run_0000000000000000",
),
(&["runs", "latest", "patch"][..], "patch needs --base <ref>"),
(
&["runs", "latest", "patch", "--json"][..],
"patch needs --base <ref>",
),
(
&["runs", "latest", "patch", "extra"][..],
"unknown option extra",
),
(
&["report", "--runs", "0"][..],
"--runs must be between 1 and 20",
),
(&["report", "--bogus"][..], "Unknown report option: --bogus"),
] {
contains_all(&project.supercov(args).exits(2), &[said]);
}
project.write(
"src/cart.js",
&format!(
"{}\nexport function extra() {{ return 1; }}\n",
common::CART.replace("sum * 100", "sum * 1000")
),
);
contains_all(
&project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds(),
&[
"3 of 3 tests affected by changes since the run",
"src/cart.js: top level, total (line 1); added extra (line 23) changed",
"Changed files:",
],
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds(),
"shipping is free over fifty\ntotal adds prices\ntotal applies a coupon\n"
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--files"])
.succeeds(),
"test/cart.test.js\n"
);
}
#[test]
fn a_changed_helper_reaches_the_tests_that_load_it_and_an_unplaced_one_reaches_all() {
let project = Project::cart("affected-helpers");
project.write(
"test/helpers.js",
"export function sample() {\n return [{ price: 10, quantity: 2 }];\n}\n",
);
project.write("test/unplaced.js", "export const unused = 1;\n");
project.write(
"src/extra.js",
"export function extra() {\n return 1;\n}\n",
);
project.write(
"test/helped.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\nimport { sample } from \"./helpers.js\";\n// mentions extra by name\ntest(\"helped\", () => {\n assert.equal(total(sample()), 20);\n});\n",
);
project.commit("helpers");
project.measure(&[]);
project.write(
"test/helpers.js",
"export function sample() {\n return [{ price: 10, quantity: 3 }];\n}\n",
);
project.write("test/unplaced.js", "export const unused = 2;\n");
project.write(
"src/extra.js",
"export function extra() {\n return 2;\n}\nexport function added() {}\n",
);
let said = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&said,
&[
"4 of 4 tests affected by changes since the run",
"test/helpers.js changed: sample (line 1) (this test's file loads it)",
"test/unplaced.js changed: top level (a file tests may load)",
],
);
// Only the test that imports the helper is reached through it.
assert_eq!(said.matches("test/helpers.js changed").count(), 1, "{said}");
assert_eq!(
said.matches("test/unplaced.js changed").count(),
4,
"{said}"
);
}
#[test]
fn tests_affected_reads_formatting_other_runners_and_dependencies_apart() {
let project = Project::cart("affected-shapes");
project.write("vitest.config.js", "export default {};\n");
project.commit("config");
project.measure(&[]);
let said = |args: &[&str]| project.supercov(args).succeeds();
contains_all(
&said(&["runs", "latest", "tests", "affected"]),
&[
"0 of 3 tests affected",
"No captured file has changed.",
"Working tree: matches the run.",
],
);
// Asked for an action it does not have, flag or word: refused.
for action in ["-x", "nope"] {
contains_all(
&project
.supercov(&["runs", "latest", "tests", action])
.exits(2),
&["unknown tests action"],
);
}
contains_all(
&said(&["runs", "latest", "tests", "--help"]),
&["Usage: supercov runs <run> tests affected"],
);
// Another runner's settings and a comment in a test change no test.
project.write("vitest.config.js", "export default { test: {} };\n");
project.write(
"test/cart.test.js",
&format!("{}\n// touched\n", common::CART_TESTS),
);
contains_all(
&said(&["runs", "latest", "tests", "affected"]),
&[
"0 of 3 tests affected",
"test/cart.test.js formatting",
"vitest.config.js declarations top level",
],
);
assert_eq!(
said(&["runs", "latest", "tests", "affected", "--names"]),
""
);
// A dependency change reaches every test.
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module", "scripts": { "test": "node --test" }, "dependencies": {"x": "1"} }"#,
);
contains_all(
&said(&["runs", "latest", "tests", "affected"]),
&[
"3 of 3 tests affected",
"dependencies or lockfile changed (every test)",
"package.json changed",
],
);
assert_eq!(
said(&["runs", "latest", "tests", "affected", "--files"]),
"test/cart.test.js\n"
);
}
#[test]
fn a_patch_counts_changed_and_untracked_lines_against_its_base() {
let project = Project::cart("patch-lines");
project.write(
"src/cart.js",
&format!(
"{}\nexport function more(x) {{\n return x ? 1 : 2;\n}}\n",
common::CART
),
);
project.write("src/new.js", "export const fresh = 1;\n");
project.measure(&[]);
let lines = [
"0 of 3 changed executable line(s) covered (0.00%)",
"src/cart.js: 23-24",
"src/new.js: 1",
];
contains_all(
&project
.supercov(&["runs", "latest", "patch", "--base", "HEAD"])
.succeeds(),
&lines,
);
let json = project
.supercov(&["runs", "latest", "patch", "--base", "HEAD", "--json"])
.json();
assert_eq!(json["data"]["patch"]["eligible"], 3, "{json}");
contains_all(
&project
.supercov(&[
"runs",
"latest",
"patch",
"--base",
"HEAD",
"--min-lines",
"90",
])
.exits(1),
&["FAIL: below 90%"],
);
let annotated = project
.supercov(&[
"runs",
"latest",
"patch",
"--base",
"HEAD",
"--annotate",
"github",
"--max-annotations",
"1",
])
.succeeds();
assert_eq!(annotated.matches("::warning").count(), 1, "{annotated}");
contains_all(
&project
.supercov(&["runs", "latest", "patch", "--base", "nope-ref"])
.exits(2),
&["git merge-base nope-ref HEAD failed"],
);
// A run of another tree cannot map this one's patch.
project.write("src/cart.js", common::CART);
contains_all(
&project
.supercov(&["runs", "latest", "patch", "--base", "HEAD"])
.exits(2),
&["the run no longer matches the current checkout"],
);
}
#[test]
fn runs_that_ran_no_tests_keep_the_command_status_and_say_so() {
let project = Project::cart("odd-js-runs");
project
.supercov(&["--", "node", "-e", "process.exit(3)"])
.exits(3);
project.supercov(&["--", "node", "-e", ""]).succeeds();
project
.supercov(&["--", "node", "--test", "test/none.test.js"])
.exits(1);
let listed = project.supercov(&["runs"]).succeeds();
contains_all(
&listed,
&[
"FAILED (exit 3); NO TESTS RAN",
"FAILED (exit 1); NO TESTS RAN",
" NO TESTS RAN",
],
);
}
/// Pages past the end, views with no tests, files and decisions that are not
/// there, and the narrower views of one run each read as what they are.
#[test]
fn odd_pages_and_empty_views_read_as_what_they_are() {
let project = Project::cart("odd-views");
project.supercov(&["--", "node", "--test"]).succeeds();
let past = project
.supercov(&["runs", "latest", "files", "--offset", "100"])
.succeeds();
assert!(
past.contains(
"every included source file\n\nshowing none of 1: --offset 100 is past the end"
),
"{past}"
);
let past = project
.supercov(&["runs", "latest", "gaps", "--offset", "100"])
.succeeds();
assert!(
past.contains("unresolved obligations\n\nshowing none of 1: --offset 100 is past the end"),
"{past}"
);
let runners = project
.supercov(&["runs", "latest", "runners", "--offset", "5"])
.succeeds();
assert!(
runners.starts_with("showing none of 1: --offset 5 is past the end"),
"{runners}"
);
let kinds = project
.supercov(&["runs", "latest", "kinds", "--filter", "failed"])
.succeeds();
assert!(
kinds.contains("No tests in this view (failed attempts only)"),
"{kinds}"
);
let directories = project
.supercov(&["runs", "latest", "files", "--group", "dir"])
.succeeds();
assert!(
directories.contains("src 1 13 76.92% 76.92%"),
"{directories}"
);
let file = project
.supercov(&["runs", "latest", "file", "src/cart.js", "--limit", "1"])
.succeeds();
contains_all(
&file,
&[
"showing 1-1 of 6 gap lines",
"file 'src/cart.js' --offset 1 --limit 1",
"all 6 at once",
],
);
let missing = project
.supercov(&["runs", "latest", "file", "package.json"])
.exits(2);
assert!(
missing.contains("Source file not found: package.json"),
"{missing}"
);
let decision = project
.supercov(&["runs", "latest", "decision", "src/cart.js:1"])
.exits(2);
assert!(
decision.contains("Decision not found: src/cart.js:1"),
"{decision}"
);
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:1"])
.succeeds();
assert!(
line.contains("Function at column 8 — covered (2 covering tests)"),
"{line}"
);
let scope = project
.supercov(&["runs", "latest", "scope", "--files", "--limit", "1"])
.succeeds();
contains_all(
&scope,
&["INCLUDED src/cart.js", "showing 1-1 of 2", "all 2 at once"],
);
let failed = project
.supercov(&["runs", "latest", "--filter", "failed"])
.succeeds();
contains_all(
&failed,
&[
"(failed attempts only)",
"No test recorded coverage",
"Total 0",
],
);
let titled = project
.supercov(&["runs", "latest", "--title", "nothing-matches"])
.exits(2);
assert!(
titled.contains("No tests match --title nothing-matches"),
"{titled}"
);
let without = project
.supercov(&["runs", "latest", "tests", "without-evidence"])
.succeeds();
assert!(without.contains("recorded no coverage: 0"), "{without}");
let source = project
.supercov(&["runs", "latest", "source", "src/cart.js", "--limit", "2"])
.succeeds();
contains_all(
&source,
&[
" 2 │ let sum = 0;",
"Showing 1-2 of 21",
"--offset 2 --limit 2",
],
);
}
/// The run list pages with its filter and marks a run with no exit status;
/// a line with no code, one that never ran and one past the end each say
/// so; a test that asserted without reaching measured source is listed with
/// why, and counts read in the singular where there is one.
#[test]
fn run_lists_lines_and_tests_read_as_what_they_are() {
let project = Project::cart("more-views");
project.write(
"test/none.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\n\ntest(\"asserts nothing measured\", () => {\n assert.ok(true);\n});\n",
);
project.commit("none");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["--", "node", "--test"]).succeeds();
let listed = project
.supercov(&["runs", "--filter", "passed", "--limit", "1"])
.succeeds();
contains_all(
&listed,
&[
"showing 1-1 of 2",
"runs --filter passed --offset 1 --limit 1",
"all 2 at once",
],
);
let blank = project
.supercov(&["runs", "latest", "line", "src/cart.js:11"])
.succeeds();
contains_all(
&blank,
&[
"NOT MEASURED",
"Nothing on this line is code the run measures",
],
);
let unrun = project
.supercov(&["runs", "latest", "line", "src/cart.js:20"])
.succeeds();
contains_all(
&unrun,
&[
"NOT COVERED",
"function not called",
"Function at column 20",
],
);
let beyond = project
.supercov(&["runs", "latest", "line", "src/cart.js:40"])
.exits(2);
assert!(
beyond.contains("src/cart.js has 21 lines; there is no line 40"),
"{beyond}"
);
let without = project
.supercov(&["runs", "latest", "tests", "without-evidence"])
.succeeds();
assert!(
without.contains("test/none.test.js > asserts nothing measured [")
&& without.contains("passed, 1 assertion; its file imports no measured source"),
"{without}"
);
let past = project
.supercov(&[
"runs",
"latest",
"tests",
"without-evidence",
"--offset",
"1",
])
.succeeds();
assert!(
past.contains("recorded no coverage: 1\n\nshowing none of 1: --offset 1 is past the end"),
"{past}"
);
let test = project
.supercov(&["runs", "latest", "test", "asserts nothing measured"])
.succeeds();
contains_all(
&test,
&[
"0 lines, 0 hits, 0 decisions, 1 phase\n",
"node:assert/strict.ok at test/none.test.js:5:3",
],
);
let unknown = project
.supercov(&["runs", "latest", "test", "nonexistent"])
.exits(2);
assert!(unknown.contains("Test not found: nonexistent"), "{unknown}");
let minimum = project
.supercov(&["runs", "latest", "minimize", "--limit", "1"])
.succeeds();
contains_all(
&minimum,
&[
"exact minimum 3/4 test(s)",
"showing 1-1 of 3",
"minimize --offset 1 --limit 1",
],
);
let impossible = project
.supercov(&["runs", "latest", "minimize", "--target", "50"])
.exits(2);
assert!(
impossible.contains("target 50% is impossible"),
"{impossible}"
);
let run = project.latest();
let path = project
.root
.join(".supercov/runs")
.join(&run)
.join("run.json");
let mut metadata: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
metadata["testExitCode"] = serde_json::Value::Null;
std::fs::write(&path, metadata.to_string()).unwrap();
let listed = project.supercov(&["runs"]).succeeds();
assert!(
listed.contains("INVALID (exit status unavailable)"),
"{listed}"
);
}
/// A diff counts in the singular where there is one and says when nothing
/// differs; a report that fails writes no progress line to a pipe; and the
/// mistakes `diff`, `merge`, `import` and `report` can be handed are named.
#[test]
fn comparisons_and_their_mistakes_read_as_what_they_are() {
let project = Project::cart("compare-views");
project.supercov(&["--", "node", "--test"]).succeeds();
let first = project.latest();
project.edit(
"test/cart.test.js",
"assert.equal(shipping(60, false), 0);",
"assert.equal(shipping(60, false), 0);\n assert.equal(shipping(10, true), 15);",
);
project.commit("express");
project.supercov(&["--", "node", "--test"]).succeeds();
let second = project.latest();
let gained = project.supercov(&["diff", &first, &second]).succeeds();
contains_all(
&gained,
&[
"gained: 1 line, 2 branches, 1 MC/DC condition\n",
"lost: 0 lines, 0 branches, 0 MC/DC conditions\n",
"+ MC/DC src/cart.js:13 C1 express",
],
);
let ran = project.supercov(&["diff", &first, &first]);
assert_eq!(
ran.stderr().matches("stale run").count(),
1,
"{}",
ran.stderr()
);
let same = ran.succeeds();
assert!(
same.contains("Nothing was gained or lost.\n") && !same.contains("showing"),
"{same}"
);
let half = project.supercov(&["diff", &first]).exits(2);
assert!(
half.contains("Usage: supercov diff <older-run> <newer-run>"),
"{half}"
);
let unknown = project.supercov(&["diff", &first, "nope"]).exits(2);
assert!(
unknown.contains("Coverage run not found: nope"),
"{unknown}"
);
let alone = project.supercov(&["merge"]).succeeds();
assert!(alone.contains("nothing to merge it with"), "{alone}");
let changed = project.supercov(&["merge", &first, &second]).exits(2);
assert!(
changed.contains("a file of its own tests, has changed"),
"{changed}"
);
let twice = project.supercov(&["merge", &first, &first]).exits(2);
assert!(twice.contains("Each merged run must be unique"), "{twice}");
let keep = project.supercov(&["runs", "clean", "--keep", "x"]).exits(2);
assert!(
keep.contains("--keep must be a non-negative integer"),
"{keep}"
);
let report = project.supercov(&["report", "nope"]);
assert_eq!(report.code(), 2);
assert_eq!(
report.stderr(),
"[supercov] report failed: coverage run not found: nope\n"
);
let unread = project
.supercov(&["import", "missing.info", "--test", "t"])
.exits(2);
assert!(unread.contains("Cannot read missing.info"), "{unread}");
project.write(
"cov.info",
"SF:src/cart.js\nDA:20,1\nend_of_record\nSF:/elsewhere/x.js\nDA:1,1\nend_of_record\n",
);
let unnamed = project.supercov(&["import", "cov.info"]).exits(2);
assert!(
unnamed.contains("--test <name> or --background"),
"{unnamed}"
);
let status = project
.supercov(&[
"import", "cov.info", "--test", "outside", "--status", "weird",
])
.exits(2);
assert!(
status.contains("--status is passed or failed, not weird"),
"{status}"
);
let imported = project.supercov(&["import", "cov.info", "--test", "outside"]);
assert_eq!(imported.code(), 0, "{}", imported.stderr());
contains_all(
&format!("{}{}", imported.stdout(), imported.stderr()),
&[
"imported 1 line(s) that ran",
"left out 1 file(s) of the evidence: /elsewhere/x.js (outside the project)",
],
);
// A file of the project the run did not measure and that is not there,
// with the project read as named when it cannot be resolved.
project.write(
"gone.info",
"SF:src/cart.js\nDA:20,1\nend_of_record\nSF:src/missing.js\nDA:1,1\nend_of_record\n",
);
let missing = project.supercov_with(
&["import", "gone.info", "--test", "missing"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.canonicalize#outside_evidence.rs:421",
)],
);
let said = format!("{}{}", missing.stdout(), missing.stderr());
assert_eq!(missing.code(), 0, "{said}");
assert!(fired_at(&said, "outside_evidence.rs:421"), "{said}");
assert!(
said.contains("src/missing.js (no such file in the project)"),
"{said}"
);
}
/// A word or a flag a command does not take is refused by name instead of
/// being read as a run id or a filter that is not one.
#[test]
fn words_and_flags_a_command_does_not_take_are_refused() {
let project = Project::cart("refused-words");
project.supercov(&["--", "node", "--test"]).succeeds();
for (args, expected) in [
(vec!["runs", "latest", "files", "-q"], "Unknown option: -q"),
(
vec!["runs", "latest", "files", "src/cart.js"],
"Unexpected argument: src/cart.js",
),
(
vec!["runs", "latest", "gaps", "x"],
"Unexpected argument: x",
),
(
vec!["runs", "latest", "file", "src/cart.js", "extra"],
"Unexpected argument: extra",
),
(
vec!["runs", "latest", "decision", "a", "b"],
"Unexpected argument: b",
),
(
vec!["runs", "latest", "decision"],
"Usage: supercov runs <run-id> decision",
),
(
vec!["runs", "abcdefghijklmnopqrst"],
"Coverage run not found: abcdefghijklmnopqrst",
),
(vec!["report", "--tag"], "--tag needs a value"),
(vec!["merge", "--tag", "x"], "Unknown option: --tag"),
] {
let refused = project.supercov(&args).exits(2);
assert!(refused.contains(expected), "{args:?}: {refused}");
}
// A test name may begin with a dash.
let named = project.supercov(&["runs", "latest", "test", "-x"]).exits(2);
assert!(named.contains("Test not found: -x"), "{named}");
}
/// An import of nothing the run measures makes no run; a line past a file's
/// end, evidence of no project file, a name already imported and both ways
/// of crediting at once are each refused by what is wrong.
#[test]
fn imports_that_cannot_add_anything_are_refused() {
let project = Project::cart("import-refusals");
project.write("lib/extra.js", "export const x = 1;\nexport const y = 2;\n");
project.commit("extra");
project.supercov(&["--", "node", "--test"]).succeeds();
project.write(
"excluded.info",
"SF:test/cart.test.js\nDA:1,1\nend_of_record\n",
);
project.write(
"extra.info",
"SF:lib/extra.js\nDA:1,1\nDA:2,0\nend_of_record\n",
);
project.write("beyond.info", "SF:src/cart.js\nDA:99,1\nend_of_record\n");
project.write(
"nothing.info",
"SF:/elsewhere/a.js\nDA:1,1\nend_of_record\n",
);
let before = project.latest();
for (args, expected) in [
(
vec!["import", "excluded.info", "--test", "t"],
"Nothing in excluded.info is a file the run measures: test/cart.test.js (the run leaves it out: test or fixture source)",
),
(
vec!["import", "beyond.info", "--test", "t"],
"records line 99 of src/cart.js, which has 21 lines",
),
(
vec!["import", "nothing.info", "--test", "t"],
"Nothing in nothing.info is a file of this project: /elsewhere/a.js (outside the project)",
),
(
vec!["import", "extra.info", "--test", "t", "--background"],
"--test and --background each name who the lines are credited to",
),
(
vec!["import", "extra.info", "--test", "t", "--run", "nope"],
"coverage run not found: nope",
),
] {
let refused = project.supercov(&args).exits(2);
assert!(refused.contains(expected), "{args:?}: {refused}");
}
assert_eq!(project.latest(), before, "a refused import makes no run");
project
.supercov(&["import", "extra.info", "--background"])
.succeeds();
project
.supercov(&["import", "extra.info", "--test", "again"])
.succeeds();
let twice = project
.supercov(&["import", "extra.info", "--test", "again"])
.exits(2);
assert!(
twice.contains("already holds an imported test named again"),
"{twice}"
);
let runners = project.supercov(&["runs", "latest", "runners"]).succeeds();
contains_all(
&runners,
&[
"background 0 test(s)",
"lines 1 test(s)",
"node:test 3 test(s)",
],
);
}
/// Go's flags reach `go test` through GOFLAGS, so a suite started from a
/// Makefile is measured, and a command that is not `go test` is left as
/// written instead of being handed `-count=1`.
#[test]
fn a_go_suite_behind_make_is_measured_and_other_go_commands_are_left_alone() {
// The Makefile runs `go` by name.
if go() != Some("go") {
eprintln!("skipping: no Go toolchain on PATH");
return;
}
let made = Project::empty("go-make");
made.write("go.mod", "module example.com/made\n\ngo 1.21\n");
made.write(
"x.go",
"package x\n\nfunc F(a bool) int {\n\tif a {\n\t\treturn 1\n\t}\n\treturn 2\n}\n",
);
made.write(
"x_test.go",
"package x\n\nimport \"testing\"\n\nfunc TestX(t *testing.T) { F(true) }\n",
);
made.write("Makefile", "test:\n\tgo test ./...\n");
let measured = made.supercov(&["--", "make", "test"]);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured.stderr().contains("added -count=1"),
"{}",
measured.stderr()
);
let summary = made.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["command: make test", "Passed 1"]);
let vetted = made.supercov(&["--", "go", "vet", "./..."]);
assert!(
!vetted.stderr().contains("malformed import path"),
"{}",
vetted.stderr()
);
}
/// A merged run is answered from the runs it was merged from, and a test
/// both of them ran is one test, counted once, with its reasons together.
#[test]
fn tests_affected_on_a_merge_counts_a_test_both_parents_ran_once() {
let project = Project::cart("merged-affected");
project.supercov(&["--", "node", "--test"]).succeeds();
let first = project.latest();
project
.supercov(&["--", "node", "--test", "test/cart.test.js"])
.succeeds();
let second = project.latest();
project.supercov(&["merge", &first, &second]).succeeds();
project.edit("src/cart.js", "return 0;", "return 1;");
let affected = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&affected,
&[
"1 of 3 tests affected by changes since the run",
"test/cart.test.js › shipping is free over fifty",
"src/cart.js: shipping (line 12) changed (this test ran it)",
],
);
let json = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json();
assert_eq!(
json["data"]["mergedFrom"],
serde_json::json!([first, second])
);
assert_eq!(json["data"]["summary"]["tests"], 3);
assert_eq!(json["data"]["summary"]["unaffected"], 2);
// The runs it was merged from are looked up in the store, listed again;
// a store that cannot be listed cannot answer.
let unlisted = project.supercov_with(
&["runs", "latest", "tests", "affected"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695@2")],
);
let said = format!("{}{}", unlisted.stdout(), unlisted.stderr());
assert_eq!(unlisted.code(), 2, "{said}");
assert!(fired_at(&said, "run_store.rs:695"), "{said}");
// A run it was merged from that is no longer stored cannot answer.
std::fs::remove_dir_all(project.root.join(".supercov/runs").join(&first)).unwrap();
let gone = project
.supercov(&["runs", "latest", "tests", "affected"])
.exits(2);
assert!(gone.contains("which is no longer stored"), "{gone}");
}
/// Output sent to one file for both streams (`> log 2>&1`) arrives through
/// one relay and names the project rather than Supercov's copy.
#[test]
fn both_streams_into_one_file_name_the_project() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("one-file");
project.write("go.mod", "module example.com/onefile\n\ngo 1.21\n");
project.write(
"x.go",
"package x\n\nfunc F(a bool) int {\n\tif a {\n\t\treturn 1\n\t}\n\treturn 2\n}\n",
);
project.write(
"x_test.go",
"package x\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestX(t *testing.T) {\n\tdir, _ := os.Getwd()\n\tfmt.Println(\"out \" + dir)\n\tfmt.Fprintln(os.Stderr, \"err \"+dir)\n\tF(true)\n}\n",
);
let log = project.root.join("both.log");
let file = std::fs::File::create(&log).unwrap();
let status = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args(["--", go, "test", "-v", "./..."])
.current_dir(&project.root)
.env_remove("SUPERCOV_SOURCE_ROOTS")
.stdout(file.try_clone().unwrap())
.stderr(file)
.status()
.unwrap();
let written = std::fs::read_to_string(&log).unwrap();
assert!(status.success(), "{written}");
// The project as given, or its long form: Windows runners' TEMP is a
// short `RUNNER~1` path, which Go names in full (canonical paths there
// carry `\\?\`). Line by line: a Windows line may end in `\r\n`.
let canonical = std::fs::canonicalize(&project.root).unwrap();
let canonical = canonical.display().to_string();
let roots = [
project.root.display().to_string(),
canonical
.strip_prefix(r"\\?\")
.unwrap_or(&canonical)
.to_owned(),
];
for stream in ["out", "err"] {
assert!(
written
.lines()
.any(|line| roots.iter().any(|root| line == format!("{stream} {root}"))),
"{written}"
);
}
// Supercov's own lines name the copy; the command's do not.
assert!(
written
.lines()
.filter(|line| !line.starts_with("[supercov]"))
.all(|line| !line.contains("workspaces/workspace/")),
"{written}"
);
}
/// A runner named alone narrows every view to its tests and says so; a
/// runner no test used is refused by name.
#[test]
fn a_runner_alone_narrows_every_view_or_is_refused() {
let project = Project::cart("runner-filters");
project.supercov(&["--", "node", "--test"]).succeeds();
let gaps = project
.supercov(&["runs", "latest", "gaps", "--runner", "node:test"])
.succeeds();
contains_all(
&gaps,
&[
"Projection: runner node:test.",
"[covered elsewhere: 0; nowhere: 15]",
],
);
for args in [
vec!["runs", "latest", "gaps", "--runner", "vitest"],
vec!["runs", "latest", "files", "--runner", "vitest"],
vec!["runs", "latest", "--runner", "vitest"],
vec![
"runs",
"latest",
"file",
"src/cart.js",
"--runner",
"vitest",
],
] {
let refused = project.supercov(&args).exits(2);
assert!(
refused.contains("No tests match runner=vitest"),
"{args:?}: {refused}"
);
}
let summary = project
.supercov(&["runs", "latest", "--runner", "node:test"])
.succeeds();
contains_all(
&summary,
&["(runner node:test)", "files --runner 'node:test'"],
);
let kinds = project
.supercov(&["runs", "latest", "kinds", "--runner", "node:test"])
.succeeds();
assert!(kinds.contains("unit 3 test(s) lines 76.92%"), "{kinds}");
let minimum = project
.supercov(&["runs", "latest", "minimize", "--runner", "node:test"])
.succeeds();
assert!(minimum.contains("exact minimum 3/3 test(s)"), "{minimum}");
let directories = project
.supercov(&[
"runs",
"latest",
"files",
"--group",
"dir",
"--runner",
"node:test",
])
.succeeds();
assert!(
directories.contains("Coverage by directory, 1 deep — runner node:test"),
"{directories}"
);
let decision = project
.supercov(&[
"runs",
"latest",
"decision",
"src/cart.js:13",
"--runner",
"node:test",
])
.succeeds();
assert!(decision.contains("FF -> F tests=1"), "{decision}");
let tests = project
.supercov(&["runs", "latest", "test", "total"])
.succeeds();
contains_all(
&tests,
&[
"total adds prices",
"total applies a coupon",
"showing 1-2 of 2 matching tests",
],
);
}
/// Nothing changed is nothing affected; a changed test file affects each of
/// its tests and `--files`/`--names` list them alone; a dependency change
/// affects every test; and a narrowing option without a list to narrow is
/// refused on standard error, leaving standard output empty for a script.
#[test]
fn tests_affected_reads_each_kind_of_change_and_refuses_on_stderr() {
let project = Project::cart("affected-shapes");
project.supercov(&["--", "node", "--test"]).succeeds();
let clean = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&clean,
&[
"0 of 3 tests affected",
"No captured file has changed.",
"Working tree: matches the run.",
],
);
let refused = project.supercov(&["runs", "latest", "tests", "affected", "--ran-changed"]);
assert_eq!(refused.code(), 2);
assert_eq!(refused.stdout(), "");
assert!(
refused.stderr().starts_with(
"[supercov] --asserting and --ran-changed narrow --names or --files\n\nUsage:"
),
"{}",
refused.stderr()
);
let unassessed = project.supercov(&[
"runs",
"latest",
"tests",
"affected",
"--files",
"--ran-changed",
]);
assert_eq!(unassessed.code(), 0);
assert!(
unassessed
.stderr()
.contains("this run has no assertion assessment")
);
project.edit(
"test/cart.test.js",
"total adds prices",
"total adds up prices",
);
let own = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&own,
&["3 of 3 tests affected", "test file changed: top level"],
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--files"])
.succeeds(),
"test/cart.test.js\n"
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds(),
"shipping is free over fifty\ntotal adds prices\ntotal applies a coupon\n"
);
project.edit(
"test/cart.test.js",
"total adds up prices",
"total adds prices",
);
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module", "scripts": { "test": "node --test" }, "dependencies": { "x": "1" } }"#,
);
let dependency = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&dependency,
&[
"3 of 3 tests affected",
"dependencies or lockfile changed (every test)",
],
);
}
/// A wider project: directories page, decisions group and page, a long
/// decision reads whole, tests without evidence page and filter, and a file
/// the scope includes with nothing in it says so instead of "not found".
#[test]
fn a_wider_project_pages_groups_and_names_an_empty_included_file() {
let project = Project::cart("wider-views");
project.write(
"lib/extra.js",
"export const extra = (value) => value + 1;\n",
);
project.write("src/notes.js", "// Nothing here runs.\n");
project.write(
"src/long.js",
"export function long(first, second, third, fourth) {\n if ((first > 10 && second < 20) || (third === 'some fairly long string value' && fourth !== null)) {\n return 1;\n }\n return 0;\n}\n",
);
project.write(
"test/more.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { long } from \"../src/long.js\";\nimport { extra } from \"../lib/extra.js\";\n\ntest(\"long\", () => {\n assert.equal(long(11, 1, '', null), 1);\n assert.equal(extra(1), 2);\n});\n\ntest(\"twice nothing\", () => {\n assert.ok(true);\n assert.ok(1);\n});\n\ntest(\"once nothing\", () => {\n assert.ok(true);\n});\n",
);
project.commit("wider");
project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "src,lib")],
)
.succeeds();
let directories = project
.supercov(&["runs", "latest", "files", "--group", "dir", "--limit", "1"])
.succeeds();
contains_all(
&directories,
&["showing 1-1 of 2", "files --group dir --offset 1 --limit 1"],
);
let none = project
.supercov(&[
"runs",
"latest",
"file",
"lib/extra.js",
"--group",
"decision",
])
.succeeds();
assert!(
none.contains("decisions 0, with missing conditions 0"),
"{none}"
);
let paged = project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--limit",
"1",
])
.succeeds();
contains_all(
&paged,
&[
"showing 1-1 of 3 decisions",
"--group decision --offset 1 --limit 1",
],
);
let long = project
.supercov(&["runs", "latest", "decision", "src/long.js:2"])
.succeeds();
contains_all(
&long,
&[
"(first > 10 && second < 20) || (third === 'some fairly long string value' && fourth !== null)",
"C4 MISSING: fourth !== null (never evaluated)",
],
);
let without = project
.supercov(&[
"runs",
"latest",
"tests",
"without-evidence",
"--limit",
"1",
])
.succeeds();
contains_all(
&without,
&["showing 1-1 of 2", "without-evidence --offset 1 --limit 1"],
);
let passed = project
.supercov(&[
"runs",
"latest",
"tests",
"without-evidence",
"--filter",
"passed",
])
.succeeds();
contains_all(
&passed,
&["2 — passed attempts only", "passed, 2 assertions"],
);
let empty = project
.supercov(&["runs", "latest", "file", "src/notes.js"])
.exits(2);
assert!(
empty.contains("src/notes.js holds nothing the run measures"),
"{empty}"
);
}
/// A merge of two kinds pages its kinds, counts a setup scope beside its
/// test, and a kind's summary counts and attributes only that kind's tests.
#[test]
fn a_merge_of_two_kinds_pages_and_narrows_by_kind() {
let project = Project::cart("merged-kinds");
project.write(
"test/hooked.test.js",
"import { test, before } from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\n\nlet base;\nbefore(() => { base = total([{ price: 1, quantity: 1 }]); });\n\ntest(\"hooked\", () => {\n assert.equal(base, 1);\n});\n",
);
project.commit("hooked");
project
.supercov(&["--", "node", "--test", "test/cart.test.js"])
.succeeds();
let first = project.latest();
project
.supercov_with(
&["--", "node", "--test", "test/hooked.test.js"],
&[("SUPERCOV_TEST_KIND", "integration")],
)
.succeeds();
let second = project.latest();
project.supercov(&["merge", &first, &second]).succeeds();
let kinds = project
.supercov(&["runs", "latest", "kinds", "--limit", "1"])
.succeeds();
contains_all(
&kinds,
&[
"integration 1 test(s) + 1 setup scope(s) lines 46.15%",
"showing 1-1 of 2",
"kinds --offset 1 --limit 1",
],
);
let integration = project
.supercov(&["runs", "latest", "--kind", "integration"])
.succeeds();
contains_all(
&integration,
&[
"(kind integration)",
"Exact for 1 test(s)",
"Total 1",
"Setup scopes 1",
],
);
}
/// First-party code outside any root it recognises is ambiguous, blocks a
/// complete measurement, is named four directories at a time in the summary
/// and in full in `scope`, and both say which roots to name.
#[test]
fn code_outside_the_source_roots_is_named_with_the_roots_to_give() {
let project = Project::empty("spread-scope");
project.write(
"package.json",
r#"{ "name": "spread", "private": true, "type": "module" }"#,
);
// Code nothing the tests load reaches: a file a test imports is source.
for dir in [
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta",
] {
project.write(
&format!("{dir}/index.js"),
&format!("export const {dir} = (x) => x ? 1 : 2;\n"),
);
}
project.write(
"test/all.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { main } from \"../src/main.js\";\n\ntest(\"main\", () => { assert.equal(main, 1); });\n",
);
project.write("src/main.js", "export const main = 1;\n");
project.git(&["init", "-q"]);
project.commit("spread");
project.supercov(&["--", "node", "--test"]).succeeds();
let roots = "SUPERCOV_SOURCE_ROOTS=src,alpha,beta,delta,epsilon,eta,gamma,theta,zeta";
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Incomplete — 8 blocking limitation(s) in 8 file(s)",
"Unclassified source: alpha 1, beta 1, delta 1, epsilon 1, 4 elsewhere",
roots,
],
);
let scope = project.supercov(&["runs", "latest", "scope"]).succeeds();
contains_all(
&scope,
&[
"included 1, excluded 1, ambiguous 8",
"1 AMBIGUOUS zeta unclassified first-party source",
roots,
],
);
}
/// A report written to an absolute path, narrowed to tests only the newest
/// run has, leaves the older run out of the comparison.
#[test]
fn a_report_to_an_absolute_path_leaves_out_runs_without_the_tests_asked_for() {
let project = Project::cart("report-filter");
project
.supercov(&["--", "node", "--test", "test/cart.test.js"])
.succeeds();
project.write(
"test/extra.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { describe } from \"../src/cart.js\";\n\ntest(\"describes\", () => {\n assert.equal(describe([{ name: \"a\" }]), \"a\");\n});\n",
);
project.commit("extra");
project.supercov(&["--", "node", "--test"]).succeeds();
let output = project.root.join("out/report.html");
std::fs::create_dir_all(output.parent().unwrap()).unwrap();
let written = project
.supercov(&[
"report",
"--no-open",
"--output",
output.to_str().unwrap(),
"--test-file",
"test/extra.test.js",
])
.succeeds();
assert!(written.contains(output.to_str().unwrap()), "{written}");
let html = std::fs::read_to_string(&output).unwrap();
assert!(
html.to_ascii_lowercase().starts_with("<!doctype html"),
"{}",
&html[..80]
);
}
/// On a terminal, a Go test's partial line is passed on after a moment and
/// the rest joins it, the terminal's size is kept up through a long test,
/// and the copy's path is named as the project's.
#[cfg(unix)]
#[test]
fn a_go_test_on_a_terminal_passes_partial_lines_on_and_names_the_project() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-terminal");
project.write("go.mod", "module example.com/term\n\ngo 1.21\n");
project.write(
"x.go",
"package x\n\nfunc F(a bool) int {\n\tif a {\n\t\treturn 1\n\t}\n\treturn 2\n}\n",
);
project.write(
"x_test.go",
"package x\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestX(t *testing.T) {\n\tfmt.Print(\"prompt> \")\n\ttime.Sleep(600 * time.Millisecond)\n\tdir, _ := os.Getwd()\n\tfmt.Println(\"done in \" + dir)\n\tF(true)\n}\n",
);
let mut terminal = common::OnTerminal::start(&project, &["--", go, "test", "-v", "./..."]);
terminal.wait_for("prompt> ");
terminal.wait_for("done in ");
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{seen}");
let root = project.root.display().to_string();
assert!(seen.contains(&format!("prompt> done in {root}")), "{seen}");
}
/// A unittest run counts each test as it ended: a pass, a failure that
/// keeps the run diagnostic, an import error, and a test its decorator
/// skipped, which never enters a phase and is still a test. A suite with no
/// tests at all is refused.
#[test]
fn unittest_outcomes_each_count_and_a_decorator_skip_is_a_test() {
let make = |label: &str, test: &str| {
let project = Project::empty(label);
project.write(
"pyproject.toml",
"[project]\nname = \"shop\"\nversion = \"0.1.0\"\n",
);
project.write("src/shop/__init__.py", "");
project.write(
"src/shop/cart.py",
"def total(a):\n if a:\n return 1\n return 2\n",
);
project.write("tests/__init__.py", "");
project.write("tests/test_cart.py", test);
project
};
let head = "import sys, unittest\nsys.path.insert(0, 'src')\nfrom shop.cart import total\n\nclass T(unittest.TestCase):\n";
let command = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
for (label, test, exit, outcome) in [
(
"ut-pass",
format!("{head} def test_total(self):\n self.assertEqual(total(True), 1)\n"),
0,
"Passed 1",
),
(
"ut-fail",
format!("{head} def test_total(self):\n self.assertEqual(total(True), 2)\n"),
1,
"Failed 1",
),
(
"ut-error",
"import nothing_here\n".to_owned(),
1,
"Failed 1",
),
(
"ut-skip",
format!("{head} @unittest.skip('later')\n def test_total(self):\n pass\n"),
0,
"Skipped 1",
),
] {
let project = make(label, &test);
let ran = project.supercov(&command);
assert_eq!(ran.code(), exit, "{label}: {}", ran.stderr());
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains(outcome), "{label}: {summary}");
}
let empty = make("ut-none", "# no tests\n");
let refused = empty.supercov(&command);
// unittest's own exit when nothing ran: 5 from Python 3.12, which
// Supercov names as the command's; before that, 1 with no outcome.
let said = refused.stderr();
match refused.code() {
5 => assert!(
said.contains("the test command exited 5 before any test reported an outcome"),
"{said}"
),
code => {
assert_eq!(code, 1, "{said}");
assert!(
said.contains("the Python run produced no test outcomes"),
"{said}"
);
}
}
}
/// A query about one file warns that the run is stale only when what it
/// reads changed: a test file's change says nothing about a source file,
/// that file's own change names it, and a dependency change names why.
#[test]
fn a_file_query_warns_of_staleness_only_for_what_it_reads() {
let project = Project::cart("scoped-stale");
project.supercov(&["--", "node", "--test"]).succeeds();
let file = |project: &Project| project.supercov(&["runs", "latest", "file", "src/cart.js"]);
project.edit(
"test/cart.test.js",
"total adds prices",
"total adds up prices",
);
let quiet = file(&project);
assert_eq!(quiet.code(), 0);
assert!(!quiet.stderr().contains("stale run"), "{}", quiet.stderr());
project.edit("src/cart.js", "return 0;", "return 1;");
let named = file(&project);
assert!(
named.stderr().contains("src/cart.js changed since the run"),
"{}",
named.stderr()
);
project.edit("src/cart.js", "return 1;", "return 0;");
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module", "scripts": { "test": "node --test" }, "dependencies": { "x": "1" } }"#,
);
let dependency = file(&project);
assert!(
dependency
.stderr()
.contains("dependencies or lockfile changed"),
"{}",
dependency.stderr()
);
}
/// Asked for the failed attempts of a run that failed nothing, each view
/// reads as that projection: nothing touched, nothing covered, a minimum of
/// no tests, and a test the run has is named as left out by the filter
/// rather than missing.
#[test]
fn a_failed_projection_of_a_passing_run_reads_as_empty_and_names_what_it_leaves_out() {
let project = Project::cart("failed-projection");
project.supercov(&["--", "node", "--test"]).succeeds();
let file = project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--filter",
"failed",
])
.succeeds();
contains_all(
&file,
&[
"Tests touching this file: 0",
"showing 1-13 of 13 gap lines",
],
);
let line = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:14",
"--filter",
"failed",
])
.succeeds();
contains_all(&line, &["NOT COVERED", "Covering tests\n None"]);
let decision = project
.supercov(&[
"runs",
"latest",
"decision",
"src/cart.js:13",
"--filter",
"failed",
])
.succeeds();
contains_all(&decision, &["confidence unexecuted", "vectors:\n none"]);
let minimum = project
.supercov(&["runs", "latest", "minimize", "--filter", "failed"])
.succeeds();
assert!(minimum.contains("exact minimum 0/0 test(s)"), "{minimum}");
let left_out = project
.supercov(&["runs", "latest", "test", "total", "--filter", "failed"])
.exits(2);
assert!(
left_out.contains("No test matching total is in this view: the run has one"),
"{left_out}"
);
let missing = project
.supercov(&[
"runs",
"latest",
"test",
"nothing-like-it",
"--filter",
"failed",
])
.exits(2);
assert!(
missing.contains("Test not found: nothing-like-it"),
"{missing}"
);
}
/// `patch` counts the changed executable lines the run covered, fails a
/// floor it misses, annotates up to the cap, passes an empty change, and
/// names a base git cannot find; `check` passes and fails floors by count.
#[test]
fn patch_and_check_read_a_change_and_a_run_by_count() {
let unchanged = Project::cart("patch-empty");
unchanged.supercov(&["--", "node", "--test"]).succeeds();
let empty = unchanged
.supercov(&["runs", "patch", "--base", "HEAD", "--min-lines", "50"])
.succeeds();
contains_all(
&empty,
&[
"No executable changes.",
"PASS: nothing executable changed, so 50% does not apply.",
],
);
let below = unchanged
.supercov(&["runs", "check", "--min-lines", "99"])
.exits(1);
contains_all(
&below,
&[
"(floor 99%)",
"FAIL: 1 floor(s) not met.",
"lines 76.92% 10/13 below 99%",
],
);
let json = unchanged
.supercov(&["runs", "check", "--min-lines", "10", "--json"])
.json();
assert_eq!(json["data"]["outcome"]["result"], "pass", "{json}");
let changed = Project::cart("patch-changed");
changed.write("src/extra.js", "export const extra = (x) => x ? 1 : 2;\n");
changed.edit("src/cart.js", "let sum = 0;", "let sum = 0 + 0;");
changed.supercov(&["--", "node", "--test"]).succeeds();
let patch = changed
.supercov(&["runs", "patch", "--base", "HEAD"])
.succeeds();
contains_all(
&patch,
&[
"1 of 2 changed executable line(s) covered (50.00%)",
"src/extra.js: 1",
],
);
let failed = changed
.supercov(&["runs", "patch", "--base", "HEAD", "--min-lines", "90"])
.exits(1);
assert!(failed.contains("FAIL: below 90%"), "{failed}");
let annotated = changed
.supercov(&[
"runs",
"patch",
"--base",
"HEAD",
"--annotate",
"github",
"--max-annotations",
"1",
])
.succeeds();
assert!(
annotated.contains("::warning file=src/extra.js,line=1,endLine=1::Changed line 1 not covered by the selected tests."),
"{annotated}"
);
let json = changed
.supercov(&["runs", "patch", "--base", "HEAD", "--json"])
.json();
assert_eq!(
(
json["data"]["patch"]["covered"].as_u64(),
json["data"]["patch"]["eligible"].as_u64()
),
(Some(1), Some(2))
);
let base = changed
.supercov(&["runs", "patch", "--base", "nope"])
.exits(2);
assert!(
base.contains("Could not find where this branch left nope"),
"{base}"
);
}
/// Many failing tests are named five at a time; a run of one test script
/// names the others the package defines.
#[test]
fn failures_are_named_five_at_a_time_and_other_scripts_are_offered() {
let failing = Project::cart("many-failing");
let mut tests = String::from(
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\n",
);
for i in 0..7 {
tests.push_str(&format!(
"test(\"fails {i}\", () => {{ assert.equal(total([]), {}); }});\n",
i + 1
));
}
failing.write("test/fail.test.js", &tests);
failing.commit("failing");
let ran = failing.supercov(&["--", "node", "--test", "test/fail.test.js"]);
assert_eq!(ran.code(), 1);
assert!(
ran.stderr()
.contains("7 test(s) failed: fails 0, fails 1, fails 2, fails 3, fails 4, and 2 more"),
"{}",
ran.stderr()
);
let scripts = Project::cart("other-scripts");
scripts.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module", "scripts": { "test": "node --test", "test:unit": "node --test test/cart.test.js", "test:e2e": "node --test" } }"#,
);
scripts.commit("scripts");
scripts
.supercov(&["--", "npm", "run", "test:unit"])
.succeeds();
let one = scripts.supercov(&["runs", "latest"]).succeeds();
assert!(
one.contains("wrapped `npm run test:unit`. Other test scripts include test:e2e."),
"{one}"
);
scripts
.supercov(&["--", "npm", "exec", "--", "node", "--test"])
.succeeds();
let exec = scripts.supercov(&["runs", "latest"]).succeeds();
assert!(
exec.contains("Other test scripts include test:unit, test:e2e."),
"{exec}"
);
}
#[test]
fn a_test_that_ran_alongside_others_is_undetermined_and_a_new_file_asks_for_the_whole_suite() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-undetermined");
project.write("go.mod", "module example.com/u\n\ngo 1.22\n");
project.write(
"sign.go",
"package u\n\nfunc Sign(n int) string {\n\tif n > 0 {\n\t\treturn \"positive\"\n\t}\n\treturn \"not positive\"\n}\n",
);
project.write(
"sign_test.go",
"package u\n\nimport \"testing\"\n\nfunc TestPositive(t *testing.T) {\n\tif Sign(1) != \"positive\" {\n\t\tt.Fatal(\"positive\")\n\t}\n}\n\nfunc TestParallel(t *testing.T) {\n\tt.Parallel()\n\tif Sign(-1) != \"not positive\" {\n\t\tt.Fatal(\"not positive\")\n\t}\n}\n",
);
project.git(&["init", "-q"]);
project.commit("u");
project.supercov(&["--", go, "test", "./..."]).succeeds();
// The parallel test has no record of its own: a change to code the run
// covered could have reached it, so it is neither affected nor not.
project.edit("sign.go", "return \"not positive\"", "return \"negative\"");
let affected = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&affected,
&[
"1 of 2 tests affected by changes since the run, 1 undetermined",
" sign_test.go › TestPositive\n sign.go: Sign (line 3) changed (this test ran it)",
"Undetermined — what these ran was not fully recorded",
" sign_test.go › TestParallel\n sign.go: Sign (line 3) changed (the run covered it)",
],
);
let json = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json();
assert_eq!(json["data"]["undetermined"][0]["attribution"], "run-wide");
// Both are for a runner to run.
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "affected", "--names"])
.succeeds(),
"TestParallel\nTestPositive\n"
);
// A file the run never captured: no record can say who loads it.
project.edit("sign.go", "return \"negative\"", "return \"not positive\"");
project.write("extra.go", "package u\n\nfunc Extra() int { return 3 }\n");
let added = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
contains_all(
&added,
&[
"No captured file has changed.",
" A source or test file exists that the run did not capture; no test's record can say whether it loads it. Run the suite in full.",
],
);
let json = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json();
assert_eq!(json["data"]["workingTree"]["sourceSetChanged"], true);
// Mistakes under --json are answered in JSON, as every --json answer is.
for (args, command, message) in [
(
&["tests", "affected", "--frob", "--json"][..],
"runs.tests.affected",
"Unknown option: --frob",
),
(
&["tests", "frob", "--json"],
"runs.tests",
"unknown tests action: frob",
),
(
&["assertions", "--frob", "--json"],
"runs.assertions",
"Unknown option: --frob",
),
] {
let mut full = vec!["runs", "latest"];
full.extend_from_slice(args);
let refused = project.supercov(&full);
assert_eq!(refused.code(), 2);
let json: serde_json::Value = serde_json::from_str(&refused.stdout()).unwrap();
assert_eq!(json["command"], command);
assert_eq!(json["error"]["message"], message);
assert_eq!(refused.stderr(), "");
}
// Without it, the usage follows the mistake on standard error.
let text = project.supercov(&["runs", "latest", "tests", "frob"]);
assert_eq!(text.code(), 2);
assert!(
text.stderr()
.starts_with("[supercov] unknown tests action: frob\n\nUsage: ")
);
}
#[test]
fn tests_whose_coverage_went_to_the_run_are_not_reported_as_missing_evidence() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-all-parallel");
project.write("go.mod", "module example.com/p\n\ngo 1.22\n");
project.write(
"sign.go",
"package p\n\nfunc Sign(n int) string {\n\tif n > 0 {\n\t\treturn \"positive\"\n\t}\n\treturn \"not positive\"\n}\n",
);
project.write(
"sign_test.go",
"package p\n\nimport \"testing\"\n\nfunc TestParallel(t *testing.T) {\n\tt.Parallel()\n\tif Sign(-1) != \"not positive\" {\n\t\tt.Fatal(\"not positive\")\n\t}\n}\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", go, "test", "./..."]).succeeds();
// The one test ran alongside nothing it could be told from: what it
// reached counts run-wide, and no view reads that as evidence lost.
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Lines 75.00% (3/4)",
" unit 1 test(s) coverage not attributable; counted run-wide",
" Attribution 1 counted run-wide",
],
);
assert!(
!summary.contains("no source-coverage evidence"),
"{summary}"
);
assert!(
project
.supercov(&["runs", "latest", "kinds"])
.succeeds()
.contains("unit 1 test(s) coverage not attributable; counted run-wide")
);
assert_eq!(
project
.supercov(&["runs", "latest", "tests", "without-evidence"])
.succeeds(),
"Tests that made assertions and recorded no coverage: 0\n"
);
}
#[test]
fn a_long_decision_is_shortened_in_its_file_and_whole_on_its_own() {
let project = Project::cart("long-decision");
project.write(
"src/long.js",
"export function check(alpha, beta, gamma) {\n if (alpha.someLongPropertyName > 10 && beta.anotherLongPropertyName < 20 && gamma.yetAnotherLongPropertyName !== 30) {\n return 1;\n }\n return 0;\n}\n",
);
project.write(
"test/long.test.js",
"import test from \"node:test\";\nimport { check } from \"../src/long.js\";\ntest(\"long\", () => { check({ someLongPropertyName: 1 }, {}, {}); });\n",
);
project.commit("long");
project.measure(&[]);
let file = project
.supercov(&[
"runs",
"latest",
"file",
"src/long.js",
"--group",
"decision",
])
.succeeds();
assert!(
file.contains(" missing 3/3 alpha.someLongPropertyName > 10 && beta.anotherLongPropertyName < 20 && gamma.yetAnotherLongPro…\n"),
"{file}"
);
let decision = project
.supercov(&["runs", "latest", "decision", "src/long.js:2"])
.succeeds();
assert!(
decision.contains("\nalpha.someLongPropertyName > 10 && beta.anotherLongPropertyName < 20 && gamma.yetAnotherLongPropertyName !== 30\n"),
"{decision}"
);
}
#[test]
fn a_comparison_of_runs_that_measure_different_code_says_why_the_percentages_moved() {
let project = Project::cart("diff-moved");
let first = project.measure(&[]);
project.write("src/added.js", "export const added = 1;\n");
let second = project.measure(&[]);
let moved = project.supercov(&["diff", &first, &second]);
let said = moved.succeeds();
contains_all(
&said,
&[
"lines -5.49pp, branches +0pp, MC/DC +0pp",
"gained: 0 lines, 0 branches, 0 MC/DC conditions",
"Nothing covered in one run is uncovered in the other: the percentages moved because the runs measure different code.",
],
);
assert!(!said.contains("showing"), "{said}");
// Each stale run of the two names what changed since it.
project.write("src/added.js", "export const added = 2;\n");
let stale = project.supercov(&["diff", &first, &second]).stderr();
contains_all(
&stale,
&[
&format!(
"[supercov] stale run {first}: instrumented source changed; changed since the run: src/added.js"
),
&format!(
"[supercov] stale run {second}: instrumented source changed; changed since the run: src/added.js"
),
],
);
}
#[test]
fn a_patch_counts_new_files_and_reads_only_the_tests_a_filter_picks() {
let project = Project::cart("patch-filtered");
project.edit("src/cart.js", "let sum = 0;", "let sum = 0 + 0;");
project.write("README.md", "# readme\n");
project.write("src/fresh.js", "export const fresh = 1;\n");
project.measure(&[]);
// A file git does not track yet is part of the change; prose is not
// executable and is no part of the count.
let patch = project
.supercov(&["runs", "latest", "patch", "--base", "HEAD"])
.succeeds();
contains_all(
&patch,
&[
" 1 of 2 changed executable line(s) covered (50.00%)",
" src/fresh.js: 1",
],
);
assert!(!patch.contains("README"), "{patch}");
let filtered = project.supercov(&[
"runs",
"latest",
"patch",
"--base",
"HEAD",
"--title",
"coupon",
"--min-lines",
"90",
]);
assert_eq!(filtered.code(), 1);
assert!(
filtered.stdout().ends_with("FAIL: below 90%\n"),
"{}",
filtered.stdout()
);
assert!(
filtered
.stderr()
.contains("reading only the tests --title coupon picks")
);
let none = project
.supercov(&[
"runs",
"latest",
"patch",
"--base",
"HEAD",
"--test-file",
"test/none.js",
])
.exits(2);
assert!(
none.contains("no test of the run matches --test-file test/none.js"),
"{none}"
);
}
#[test]
fn query_numbers_and_shapes_are_checked_before_anything_is_read() {
let project = Project::cart("query-shapes");
project.measure(&[]);
let on_run = |args: &[&str]| {
let mut full = vec!["runs", "latest"];
full.extend_from_slice(args);
project.supercov(&full)
};
for limit in ["1.5", "-1", "99999999999999999999"] {
assert!(
on_run(&["files", "--limit", limit])
.exits(2)
.contains("--limit must be a number of entries, or 0 for all of them")
);
}
assert!(
on_run(&["files", "--depth", "2"])
.exits(2)
.contains("--depth requires --group dir")
);
assert!(
on_run(&["files", "--depth", "1", "--group", "dir"])
.succeeds()
.starts_with("Coverage by directory, 1 deep\n")
);
// Each metric heads its own column, and the next page keeps the metric
// and the tests picked.
for (metric, heading) in [
("statements", "Statements"),
("functions", "Functions"),
("branches", "Branches"),
("mcdc", "MC/DC"),
] {
let areas = on_run(&[
"files", "--group", "dir", "--metric", metric, "--title", "total", "--limit", "1",
])
.succeeds();
assert!(areas.contains(heading), "{metric}: {areas}");
}
assert!(
on_run(&["files", "--files"])
.exits(2)
.contains("--files is only supported by: supercov runs <run-id> scope")
);
assert!(
on_run(&["line", "src/cart.js"])
.exits(2)
.contains("Expected <source-file>:<line>, with lines counted from 1")
);
// A line asked of `file` points at `line`.
assert!(on_run(&["file", "src/cart.js:3"]).exits(2).contains(
"Source file not found: src/cart.js:3; one line is read with `line src/cart.js:3`"
));
assert!(
on_run(&["gaps", "--metric", "all"])
.succeeds()
.contains("MC/DC conditions 4")
);
// The export writes only JSON lines, and names a place it cannot write.
assert!(
on_run(&["gaps", "--format", "csv"])
.exits(2)
.contains("gaps --format takes jsonl")
);
// An export whose run was taken for an option's value names no run.
assert!(
project
.supercov(&["runs", "--offset", "gaps", "--format", "jsonl"])
.exits(2)
.contains("usage: supercov runs <run-id> gaps --format jsonl")
);
let unwritable = on_run(&[
"gaps",
"--format",
"jsonl",
"--output",
"missing/dir/x.jsonl",
])
.exits(2);
assert!(unwritable.contains("missing/dir/x.jsonl: "), "{unwritable}");
let picked = on_run(&[
"gaps", "--format", "jsonl", "--metric", "mcdc", "--title", "coupon",
])
.succeeds();
assert!(
picked.lines().all(|line| line.contains(r#""kind":"mcdc""#)) && picked.lines().count() > 0,
"{picked}"
);
}
#[test]
fn code_outside_the_roots_counts_when_source_loads_it_and_is_named_by_check_when_not() {
let project = Project::cart("loaded-outside");
project.write(
"shared/round.js",
"export function round(value) {\n if (value < 0) return 0;\n return Math.round(value);\n}\n",
);
project.write(
"src/price.js",
"import { round } from \"../shared/round.js\";\nexport const price = (value) => round(value);\n",
);
project.write("extra/unused.js", "export const unused = 1;\n");
project.write(
"test/round.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { price } from \"../src/price.js\";\n\ntest(\"rounds\", () => assert.equal(price(1.4), 1));\n",
);
project.commit("outside");
project.measure(&[]);
// Source loads it, so it is source: measured, with its gap.
let scope = project
.supercov(&["runs", "latest", "scope", "--files"])
.succeeds();
contains_all(
&scope,
&[
"INCLUDED shared/round.js loaded by first-party source",
"AMBIGUOUS extra/unused.js unclassified first-party source",
],
);
let file = project
.supercov(&["runs", "latest", "file", "shared/round.js"])
.succeeds();
contains_all(
&file,
&[
"Statements not executed 1",
"Tests touching this file: 1",
],
);
// Nothing loads the other: check passes as the suite does, and says so.
let check = project
.supercov(&["runs", "latest", "check", "--min-lines", "10"])
.succeeds();
assert!(
check.contains(
"PASS: every floor is met.\n1 file outside the source roots that no source imports is not counted: extra/unused.js."
),
"{check}"
);
let json = project
.supercov(&["runs", "latest", "check", "--min-lines", "10", "--json"])
.json();
assert_eq!(json["data"]["view"]["complete"], false);
// Any of its lines says why, not that the line holds no code.
let line = project
.supercov(&["runs", "latest", "line", "extra/unused.js:1"])
.succeeds();
contains_all(
&line,
&[
" NOT MEASURED\n",
" - source-scope: JavaScript/TypeScript under no source root that no first-party source imports",
],
);
assert!(!line.contains("Nothing on this line is code"), "{line}");
}
#[test]
fn a_cargo_filter_that_matches_no_test_says_so_when_the_run_is_read() {
let project = Project::empty("cargo-no-match");
project.write(
"Cargo.toml",
"[package]\nname = \"nomatch\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn sign(n: i32) -> bool {\n n > 0\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn positive() {\n assert!(super::sign(1));\n }\n}\n",
);
project.git(&["init", "-q"]);
project
.supercov(&["--", "cargo", "test", "--", "nothing_matches"])
.succeeds();
let read = project.supercov(&["runs", "latest"]).exits(2);
assert!(
read.contains(
"The wrapped command passed and ran no test Supercov could record, so there is no coverage to read; check that its test filter matches a test."
),
"{read}"
);
// Libtest's own selection, skips included, is the run's.
project
.supercov(&[
"--",
"cargo",
"test",
"--",
"--exact",
"--skip",
"tests::positive",
])
.succeeds();
project
.supercov(&["--", "cargo", "test", "--", "--exact", "tests::positive"])
.succeeds();
assert!(
project
.supercov(&["runs", "latest", "test", "tests::positive"])
.succeeds()
.contains("outcome passed")
);
}
#[test]
fn minimize_refuses_background_evidence_and_names_the_filter_that_leaves_it_out() {
let project = Project::cart("minimize-background");
project.write(
"test/setup.test.js",
"import { before, test } from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\nconst loaded = total([{ price: 1, quantity: 1 }]);\nbefore(() => { total([{ price: 2, quantity: 1 }]); });\ntest(\"loaded\", () => assert.equal(loaded, 1));\n",
);
project.commit("setup");
project.measure(&[]);
let on_run = |args: &[&str]| {
let mut full = vec!["runs", "latest"];
full.extend_from_slice(args);
project.supercov(&full)
};
// Module-load work ran with no test running: no subset of tests keeps it.
let refused = on_run(&["minimize"]).exits(2);
assert!(
refused.contains("Narrow it to the tests' own evidence with --kind <kind> or --runner <runner>, which leave the background out"),
"{refused}"
);
for target in ["150", "nan"] {
assert!(
on_run(&["minimize", "--target", target])
.exits(2)
.contains("--target must be between 0 and 100")
);
}
// The filter it names: the tests alone, setup scope included.
let minimum = on_run(&["minimize", "--kind", "unit"]).succeeds();
assert!(
minimum.starts_with(
"exact minimum 3/4 test(s) keeping the coverage of all 4 tests in every measured metric"
),
"{minimum}"
);
contains_all(
&on_run(&["kinds"]).succeeds(),
&[
"background 0 test(s) lines 46.15%",
"unit 4 test(s) + 1 setup scope(s) lines 76.92%",
],
);
}
#[test]
fn a_line_past_the_end_of_its_file_fails_among_several_as_it_does_alone() {
let project = Project::cart("lines-past-end");
project.measure(&[]);
let mixed = project
.supercov(&["runs", "latest", "line", "src/cart.js:2", "src/cart.js:999"])
.succeeds();
contains_all(
&mixed,
&[
"src/cart.js:2\n",
"Not answered\n src/cart.js:999: src/cart.js has 21 lines; there is no line 999",
],
);
assert!(!mixed.contains("Nothing on this line is code"), "{mixed}");
let json = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:2",
"src/cart.js:999",
"--json",
])
.json();
assert_eq!(json["data"]["lines"].as_array().unwrap().len(), 1, "{json}");
assert_eq!(json["data"]["failed"][0]["location"], "src/cart.js:999");
// Every location failing fails the call, as one does.
let none = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:998",
"src/cart.js:999",
])
.exits(2);
assert!(
none.contains("src/cart.js has 21 lines; there is no line 998"),
"{none}"
);
}
#[cfg(unix)]
#[test]
fn a_workspace_with_nested_dependencies_and_their_links_runs_in_the_copy_as_it_does_in_place() {
let project = Project::empty("probe-nested-modules");
project.write("package.json", r#"{ "name": "mono", "private": true, "type": "module", "workspaces": ["packages/*"], "scripts": { "test": "node --test packages/a/test/a.test.js" } }"#);
project.write(
"node_modules/dep/package.json",
r#"{ "name": "dep", "type": "module", "main": "index.js" }"#,
);
project.write(
"node_modules/dep/index.js",
"export const dep = (x) => x + 1;\n",
);
project.write(
"node_modules/dep/cli.js",
"#!/usr/bin/env node\nconsole.log('dep');\n",
);
project.write(
"packages/a/package.json",
r#"{ "name": "a", "type": "module", "main": "src/index.js" }"#,
);
project.write(
"packages/a/node_modules/local-dep/package.json",
r#"{ "name": "local-dep", "type": "module", "main": "index.js" }"#,
);
project.write(
"packages/a/node_modules/local-dep/index.js",
"export const local = (x) => x * 2;\n",
);
project.write(
"packages/a/node_modules/local-dep/bin.js",
"#!/usr/bin/env node\nconsole.log('local');\n",
);
project.write("packages/a/src/index.js", "import { dep } from 'dep';\nimport { local } from 'local-dep';\nexport const both = (x) => (x > 0 ? local(dep(x)) : 0);\n");
project.write("packages/a/test/a.test.js", "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { both } from '../src/index.js';\ntest('both', () => { assert.equal(both(1), 4); assert.equal(both(0), 0); });\n");
// Links a package manager makes: commands in `.bin` at the root and in a
// workspace package, and the package itself linked into the root.
{
std::fs::create_dir_all(project.root.join("node_modules/.bin")).unwrap();
std::os::unix::fs::symlink("../dep/cli.js", project.root.join("node_modules/.bin/dep"))
.unwrap();
std::fs::create_dir_all(project.root.join("packages/a/node_modules/.bin")).unwrap();
std::os::unix::fs::symlink(
"../local-dep/bin.js",
project.root.join("packages/a/node_modules/.bin/local"),
)
.unwrap();
std::os::unix::fs::symlink("../../packages/a", project.root.join("node_modules/a"))
.unwrap();
}
project.write(".gitignore", "node_modules\n");
project.git(&["init", "-q"]);
let plain = std::process::Command::new("npm")
.arg("test")
.current_dir(&project.root)
.output()
.unwrap();
assert!(plain.status.success());
project.supercov(&["--", "npm", "test"]).succeeds();
let files = project.supercov(&["runs", "latest", "files"]).succeeds();
assert!(
files.contains("packages/a/src/index.js\n covered in this projection"),
"{files}"
);
assert!(!files.contains("node_modules"), "{files}");
}
#[test]
fn a_summary_narrowed_to_one_kind_lists_only_that_kind() {
let project = Project::cart("summary-one-kind");
project.write(
"test/ship.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { shipping } from \"../src/cart.js\";\ntest(\"ships\", () => assert.equal(shipping(10, true), 15));\n",
);
project.commit("ship");
project
.supercov_with(
&["--", "node", "--test", "test/cart.test.js"],
&[("SUPERCOV_TEST_KIND", "unit")],
)
.succeeds();
project
.supercov_with(
&["--", "node", "--test", "test/ship.test.js"],
&[("SUPERCOV_TEST_KIND", "integration")],
)
.succeeds();
project.supercov(&["merge"]).succeeds();
let whole = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&whole,
&[" integration 1 test(s)", " unit 3 test(s)"],
);
let narrowed = project
.supercov(&["runs", "latest", "--kind", "integration"])
.succeeds();
contains_all(
&narrowed,
&[
"(kind integration)",
"Lines 23.08% (3/13)",
"By test kind\n integration 1 test(s) lines 23.08%",
],
);
assert!(!narrowed.contains(" unit "), "{narrowed}");
let json = project
.supercov(&["runs", "latest", "--kind", "integration", "--json"])
.json();
assert_eq!(
json["data"]["coverageByKind"].as_array().unwrap().len(),
1,
"{json}"
);
// A test the kind leaves out is named as left out.
assert!(
project
.supercov(&["runs", "latest", "test", "ships", "--kind", "unit"])
.exits(2)
.contains("No test matching ships is in this view")
);
}
#[test]
fn filters_pages_imports_and_help_topics_read_as_a_user_reads_them() {
let project = Project::cart("broad-shapes");
let first = project.measure(&[]);
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let on_run = |args: &[&str]| {
let mut full = vec!["runs", "latest"];
full.extend_from_slice(args);
project.supercov(&full)
};
// Tests affected, narrowed every way a runner's filter wants it.
assert_eq!(
on_run(&["tests", "affected", "--kind", "unit", "--names"]).succeeds(),
"shipping is free over fifty\n"
);
assert_eq!(
on_run(&["tests", "affected", "--runner", "node:test", "--files"]).succeeds(),
"test/cart.test.js\n"
);
assert!(
on_run(&["tests", "affected", "--test-file", "test/cart.test.js"])
.succeeds()
.starts_with(&format!(
"Run {first}: 1 of 3 tests affected by changes since the run (--test-file test/cart.test.js)\n"
))
);
assert!(
on_run(&["tests", "affected", "--tag", "nothing"])
.exits(2)
.contains("No tests match --tag nothing")
);
// Pages past their end, and options that need another.
assert!(
on_run(&["scope", "--files", "--offset", "9"])
.succeeds()
.contains("showing none of 2: --offset 9 is past the end")
);
assert!(
on_run(&["file", "src/cart.js", "--sort", "missing"])
.exits(2)
.contains("--sort requires --group decision")
);
assert!(
on_run(&[
"file",
"src/cart.js",
"--group",
"decision",
"--sort",
"nonsense"
])
.exits(2)
.contains("--sort must be location or missing")
);
contains_all(
&on_run(&["test", "total", "--limit", "1"]).succeeds(),
&["showing 1-1 of 2 matching tests", "all 2 at once: "],
);
assert!(
project
.supercov(&["runs", "--limit", "1", "--offset", "5"])
.succeeds()
.contains("showing none of 1: --offset 5 is past the end")
);
assert!(
project
.supercov(&["runs", "clean", "--keep", "abc"])
.exits(2)
.contains("--keep must be a non-negative integer")
);
// An LCOV import names what it left out and keeps a failed outcome.
project.write(
"cov.info",
"TN:\nSF:src/cart.js\nFN:12,shipping\nFNDA:1,shipping\nDA:13,1\nLF:1\nLH:1\nend_of_record\nSF:lib/elsewhere.js\nDA:1,1\nend_of_record\nSF:lib/latin.js\nDA:1,1\nend_of_record\n",
);
std::fs::create_dir_all(project.root.join("lib")).unwrap();
std::fs::write(project.root.join("lib/latin.js"), b"var caf\xe9 = 1;\n").unwrap();
assert!(
project
.supercov(&[
"import", "cov.info", "--test", "imported", "--status", "maybe"
])
.exits(2)
.contains("--status is passed or failed, not maybe")
);
let imported = project.supercov(&[
"import", "cov.info", "--test", "imported", "--status", "failed",
]);
assert_eq!(imported.code(), 0, "{}", imported.stderr());
assert!(
imported.stderr().contains(
"left out 2 file(s) of the evidence: lib/elsewhere.js (no such file in the project); lib/latin.js (not a text file)"
),
"{}",
imported.stderr()
);
assert!(
on_run(&["test", "imported"])
.succeeds()
.contains("outcome failed; retry 0=failed")
);
// --gained looks for no losses, and says only what it looked for.
let gained = project
.supercov(&["diff", &first, "latest", "--gained"])
.succeeds();
assert!(
gained.contains("Nothing was gained.\n") && !gained.contains("or lost"),
"{gained}"
);
// `help <command>` is that command's help.
assert!(
project
.supercov(&["help", "runs"])
.succeeds()
.starts_with("Usage: supercov runs [options]")
);
assert!(
project
.supercov(&["help", "import"])
.succeeds()
.starts_with("Usage: supercov import")
);
assert!(
project
.supercov(&["help", "nope"])
.exits(2)
.contains("No help for nope: it is no command")
);
assert!(
project
.supercov(&["docs", "nonsense"])
.exits(2)
.contains("unknown guide \"nonsense\"")
);
}
#[test]
fn the_wrapped_command_exits_as_it_would_alone_and_a_missing_root_is_named() {
let project = Project::cart("wrapped-exits");
assert!(
project
.supercov(&["--"])
.exits(2)
.contains("Usage: supercov -- <test command>")
);
let missing = project.supercov(&["--", "definitely-not-a-command"]);
assert_eq!(missing.code(), 127);
assert!(
missing
.stderr()
.contains("could not spawn definitely-not-a-command"),
"{}",
missing.stderr()
);
assert_eq!(
project
.supercov(&["--", "node", "-e", "process.exit(3)"])
.code(),
3
);
// Ended by a signal: 128 plus the signal, as a shell says it.
#[cfg(unix)]
assert_eq!(
project
.supercov(&["--", "node", "-e", "process.kill(process.pid, 'SIGTERM')"])
.code(),
143
);
assert!(
project
.supercov(&["--exact-attribution", "frobnicate"])
.exits(2)
.contains("--exact-attribution goes before the command")
);
// Every root named missing is a mistake to name.
let roots = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "nowhere")],
);
assert_eq!(roots.code(), 1);
assert!(
roots.stderr().contains(
"SUPERCOV_SOURCE_ROOTS=nowhere left no JavaScript or TypeScript source to measure; nowhere does not exist"
),
"{}",
roots.stderr()
);
let both = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "nowhere,elsewhere")],
);
assert!(
both.stderr().contains("; nowhere, elsewhere do not exist;"),
"{}",
both.stderr()
);
// A root outside the project is named as such.
let outside = project.root.with_extension("outside-root");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("b.js"), "export const b = 1;\n").unwrap();
let away = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", outside.to_str().unwrap())],
);
assert_ne!(away.code(), 0, "{}", away.stderr());
assert!(
away.stderr().contains(&format!(
"source root is outside the project: {}",
outside.display()
)),
"{}",
away.stderr()
);
std::fs::remove_dir_all(&outside).unwrap();
// One of several missing is a checkout without that directory.
project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "src,nowhere")],
)
.succeeds();
}
#[test]
fn private_batch_protocols_and_odd_arguments_say_what_went_wrong() {
use std::io::Write;
use std::process::{Command, Stdio};
// The harnesses' batch protocols fail with a message, not a panic, when
// their output cannot be written: nothing reads the other end.
for (command, says) in [
(
"__instrument-js",
"failed to write Rust instrumenter output",
),
(
"__benchmark-js-transform",
"failed to write Rust benchmark output",
),
] {
let mut child = Command::new(env!("CARGO_BIN_EXE_supercov"))
.arg(command)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
child
.stdin
.take()
.unwrap()
.write_all(br#"[{"file":"a.js","source":"export const a = 1;\n"}]"#)
.unwrap();
let output = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{command}: {stderr}");
assert!(stderr.contains(says), "{command}: {stderr}");
}
let project = Project::cart("odd-arguments");
let first = project.measure(&[]);
// A lone `-` is no option to merge: it names a run that does not exist.
let merged = project.supercov(&["merge", &first, "-"]).exits(2);
assert!(!merged.contains("Unknown option"), "{merged}");
// An evidence path holding `=` is a path, not an option and its value.
project.write(
"cov=1.info",
"TN:\nSF:src/cart.js\nDA:13,1\nLF:1\nLH:1\nend_of_record\n",
);
let imported = project.supercov(&["import", "cov=1.info", "--test", "imported"]);
assert_eq!(imported.code(), 0, "{}", imported.stderr());
}
#[test]
fn filters_selectors_and_stray_entries_on_the_run_commands() {
let project = Project::cart("run-commands");
for directory in ["a", "b", "c", "d", "e", "f"] {
project.write(&format!("tools/{directory}.js"), "export const tool = 1;\n");
}
project.commit("tools");
let run = project.measure(&[]);
// Six files no source imports, named five at a time.
assert!(
project
.supercov(&["runs", "latest", "check", "--min-lines", "1"])
.succeeds()
.contains(
"6 files outside the source roots that no source imports are not counted: \
tools/a.js, tools/b.js, tools/c.js, tools/d.js, tools/e.js, and 1 more."
)
);
// A test filter without its value, on each command that takes one.
for (command, usage) in [
(
vec!["check", "--min-lines", "10"],
"supercov runs <run-id> check",
),
(
vec!["patch", "--base", "HEAD"],
"supercov runs <run-id> patch",
),
(
vec!["report", "--format", "lcov"],
"supercov runs <run-id> report",
),
] {
let mut args = vec!["runs", "latest"];
args.extend(command);
args.push("--kind");
contains_all(
&project.supercov(&args).exits(2),
&["--kind needs a value", usage],
);
}
// A decision by a file and something that is no line, and by its id.
assert!(
project
.supercov(&["runs", "latest", "decision", "src/cart.js:abc"])
.exits(2)
.contains("Decision not found: src/cart.js:abc")
);
let decisions = project
.supercov(&[
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--json",
])
.json();
let id = decisions["data"]["decisions"][0]["id"]
.as_str()
.unwrap()
.to_owned();
assert!(
project
.supercov(&["runs", "latest", "decision", &id])
.succeeds()
.contains("coupon && coupon.percent > 0")
);
// A run stored under a name of the pre-release store, or any name but a
// run id, is no run to list.
let runs = project.root.join(".supercov/runs");
for name in [
"2026-08-25T23-33-12-211Z",
"run_35c35ceeaf4b843Z",
"abcdefghijklmnopqrst",
] {
copy_tree(&runs.join(&run), &runs.join(name));
}
contains_all(
&project.supercov(&["runs"]).succeeds(),
&[&run, "showing 1-1 of 1"],
);
// A stale run's patch, as JSON: an error with its reason, no pass.
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let patch = project
.supercov(&["runs", "latest", "patch", "--base", "HEAD", "--json"])
.json();
assert_eq!(patch["data"]["result"], "error", "{patch}");
assert!(
patch["data"]["reasons"][0]
.as_str()
.unwrap()
.contains("instrumented source changed"),
"{patch}"
);
}
/// The `wrangler` a measured Rust test starts, outside `wrangler dev`: it
/// refuses without the real one to hand over to, and otherwise becomes it
/// with the test's arguments untouched.
#[cfg(unix)]
#[test]
fn the_wrangler_shim_hands_over_or_says_why_it_cannot() {
let project = Project::empty("wrangler-shim");
let refused = project.supercov(&["__wrangler", "--version"]);
assert_eq!(refused.code(), 127);
assert!(
refused
.stderr()
.contains("__wrangler runs only as the wrangler of a measured test"),
"{}",
refused.stderr()
);
project.write_script("real-wrangler", "#!/bin/sh\necho \"wrangler $*\"\nexit 3\n");
let real = project.root.join("real-wrangler");
let real = real.to_str().unwrap();
let handed = project.supercov_with(
&["__wrangler", "deploy", "--name", "it"],
&[("SUPERCOV_WRANGLER", real)],
);
assert_eq!(handed.code(), 3, "{}", handed.stderr());
assert_eq!(handed.stdout(), "wrangler deploy --name it\n");
// The poller wants a process, a port and where to write; given a
// process already gone, it ends.
assert_eq!(project.supercov(&["__wrangler-poll"]).code(), 2);
assert_eq!(
project
.supercov(&["__wrangler-poll", "nobody", "port", "windows"])
.code(),
2
);
let windows = project.root.join("worker.windows");
let polled = project.supercov(&[
"__wrangler-poll",
"2147483646",
"9",
windows.to_str().unwrap(),
]);
assert_eq!(polled.code(), 0, "{}", polled.stderr());
}
#[test]
fn a_run_whose_source_is_gone_is_stale_and_never_passes_a_gate() {
let project = Project::cart("source-gone");
let run = project.measure(&[]);
std::fs::rename(
project.root.join("src/cart.js"),
project.root.join("src/cart.js.bak"),
)
.unwrap();
let reason = "its source cannot be measured as it is now";
contains_all(
&project
.supercov(&["runs", "latest", "check", "--min-lines", "10"])
.exits(2),
&["ERROR: this run cannot answer the question asked.", reason],
);
let files = project.supercov(&["runs", "latest", "files"]);
assert_eq!(files.code(), 0, "{}", files.stderr());
assert!(
files
.stderr()
.contains(&format!("[supercov] stale run {run}: {reason}")),
"{}",
files.stderr()
);
assert!(
project
.supercov(&["runs"])
.succeeds()
.contains(&format!("STALE ({reason})"))
);
contains_all(
&project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds(),
&["3 of 3 tests affected", &format!("{reason} (every test)")],
);
}
#[test]
fn files_named_beyond_ascii_are_changes_like_any_other() {
let project = Project::cart("named-beyond-ascii");
let base = project.git(&["rev-parse", "HEAD"]).trim().to_owned();
project.write(
"src/é.js",
"export function hi(a) {\n if (a) { return 1; }\n return 2;\n}\n",
);
project.write(
"test/e.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { hi } from \"../src/é.js\";\ntest(\"hi\", () => assert.equal(hi(1), 1));\n",
);
project.commit("hi");
let run = project.measure(&[]);
// git quotes such a name unless asked not to; quoted, it was no file the
// run measured, and the patch had no executable change.
contains_all(
&project
.supercov(&["runs", "latest", "patch", "--base", &base])
.succeeds(),
&["2 of 3 changed executable line(s) covered", "src/é.js: 3"],
);
project.write("src/ü.js", "export const x = 1;\n");
let files = project.supercov(&["runs", "latest", "files"]);
assert!(
files.stderr().contains(&format!(
"[supercov] stale run {run}: instrumented source changed; changed since the run: src/ü.js"
)),
"{}",
files.stderr()
);
}
#[test]
fn a_patch_names_new_source_it_did_not_measure_and_not_new_tests() {
let project = Project::cart("patch-unmeasured");
let base = project.git(&["rev-parse", "HEAD"]).trim().to_owned();
project.edit("src/cart.js", " let sum = 0;", " let sum = 0 + 0;");
project.write("src/cart.bench.js", "export const bench = 1;\n");
project.write("src/helper.spec.js", "export const spec = 1;\n");
project.commit("branch");
project.measure(&[]);
let patch = project
.supercov(&[
"runs",
"latest",
"patch",
"--base",
&base,
"--min-lines",
"50",
])
.succeeds();
contains_all(
&patch,
&[
"Changed but not measured by this run:\n src/cart.bench.js\n",
"PASS: at or above 50%",
],
);
assert!(!patch.contains("helper.spec.js"), "{patch}");
}
#[test]
fn a_run_left_out_of_a_merge_or_read_stale_says_what_moved() {
// A source file added and a test file edited: the source is said to
// have changed by the file it gained, and the test file is not named.
let project = Project::cart("merge-moved");
let run = project.measure(&[]);
project.write("src/extra.js", "export const extra = 1;\n");
project.edit(
"test/cart.test.js",
"total adds prices",
"total sums prices",
);
let said = project.supercov(&["merge"]).exits(2);
assert!(
said.contains(&format!(
"left out {run} (node --test): the source has changed (1 file(s) added). Measure it again"
)),
"{said}"
);
assert!(!said.contains("test/cart.test.js"), "{said}");
// A measured file edited, with no record of the run's files to judge it
// by: left out, as the measured source has changed.
let project = Project::cart("merge-no-record");
let run = project.measure(&[]);
project.edit("src/cart.js", "let sum = 0;", "let sum = 0; // edited");
let said = project
.supercov_with(
&["merge"],
&[("SUPERCOV_TEST_FAULT", "manifest-unreadable")],
)
.exits(2);
assert!(
said.contains(&format!(
"left out {run} (node --test): the source has changed. Measure it again"
)),
"{said}"
);
// A test file the run measured, gone since: the run is left out by it.
let project_g = Project::cart("merge-test-gone");
project_g.write(
"test/extra.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\ntest('extra', () => assert.equal(1, 1));\n",
);
project_g.commit("extra test");
let run_g = project_g.measure(&[]);
std::fs::remove_file(project_g.root.join("test/extra.test.js")).unwrap();
let said_g = project_g.supercov(&["merge"]).exits(2);
assert!(
said_g.contains(&format!(
"left out {run_g} (node --test): test/extra.test.js, a file of its own tests, is gone"
)),
"{said_g}"
);
// Only a test file changed, its manifest unreadable.
let project_t = Project::cart("merge-test-only-unread");
let run_t = project_t.measure(&[]);
project_t.edit("test/cart.test.js", "import test", "// note\nimport test");
let said_t = project_t
.supercov_with(
&["merge"],
&[("SUPERCOV_TEST_FAULT", "manifest-unreadable")],
)
.exits(2);
assert!(
said_t.contains(&format!(
"left out {run_t} (node --test): the tests have changed, and its record of its files cannot be read"
)),
"{said_t}"
);
// A measured file removed whose name reads as configuration.
let project = Project::cart("merge-config-named");
project.write("src/app.config.js", "export const rate = 1;\n");
project.commit("config-named source");
let run = project.measure(&[]);
std::fs::remove_file(project.root.join("src/app.config.js")).unwrap();
let said = project.supercov(&["merge"]).exits(2);
assert!(
said.contains(&format!(
"left out {run} (node --test): the source has changed. Measure it again"
)),
"{said}"
);
// Only configuration added: stale for it, no file to name; a diff with
// a run after it says what it compared.
let project = Project::cart("stale-configuration");
let older = project.measure(&[]);
project.write(".npmrc", "fund=false\n");
project.commit("npmrc");
let files = project.supercov(&["runs", "latest", "files"]);
assert!(
files.stderr().contains(&format!(
"[supercov] stale run {older}: test/build configuration changed\n"
)),
"{}",
files.stderr()
);
let newer = project.measure(&[]);
let diff = project.supercov(&["diff", &older, &newer, "--json"]).json();
assert_eq!(
diff["data"]["inputs"],
serde_json::json!({"sourceChanged": true, "testsChanged": false})
);
// Without the run's history, or without any repository, what changed is
// still named from the run's own record.
let project = Project::cart("stale-without-history");
let run = project.measure(&[]);
project.edit("src/cart.js", "return 0;", "return 0; // free");
project.write("src/new.js", "export const n = 1;\n");
std::fs::rename(project.root.join(".git"), project.root.join("away.git")).unwrap();
let files = project.supercov(&["runs", "latest", "files"]);
assert!(
files.stderr().contains(&format!(
"stale run {run}: instrumented source changed; changed since the run: src/cart.js\n"
)),
"{}",
files.stderr()
);
project.git(&["init", "-q"]);
project.git(&["add", "package.json", "src/cart.js"]);
project.git(&["commit", "-q", "-m", "fresh"]);
assert!(
project
.supercov(&["runs", "latest", "files"])
.stderr()
.contains("changed since the run: src/cart.js, src/new.js")
);
}
#[test]
fn tests_without_evidence_are_explained_by_what_they_load() {
let noop = "import test from \"node:test\";\nimport assert from \"node:assert/strict\";\ntest(\"asserts a constant\", () => { assert.equal(1, 1); });\n";
let project = Project::cart("without-evidence");
project.write("test/noop.test.js", noop);
project.write("test/plain", noop);
project.write(
"test/dyn.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nconst name = \"node:\" + \"path\";\nconst path = await import(name);\ntest(\"dyn import\", () => { assert.equal(typeof path.join, \"function\"); });\n",
);
project.commit("tests");
let without = |command: &[&str], env: &[(&str, &str)]| {
let mut args = vec!["--"];
args.extend_from_slice(command);
project.supercov_with(&args, env).succeeds();
project
.supercov(&["runs", "latest", "tests", "without-evidence", "--json"])
.json()["data"]["tests"][0]
.clone()
};
// A unit test that imports no source says so.
let unit = without(&["node", "--test", "test/noop.test.js"], &[]);
assert_eq!(unit["importsMeasured"], false, "{unit}");
// An end-to-end test reaches source by other means than imports, a file
// with no extension cannot be read for them, and a computed import names
// no module: none of them is said to import nothing.
let e2e = without(
&["node", "--test", "test/noop.test.js"],
&[("SUPERCOV_TEST_KIND", "e2e")],
);
assert_eq!(e2e["kind"], "e2e");
assert!(e2e.get("importsMeasured").is_none(), "{e2e}");
let plain = without(&["node", "--test", "test/plain"], &[]);
assert_eq!(plain["file"], "test/plain");
assert!(plain.get("importsMeasured").is_none(), "{plain}");
let dynamic = without(&["node", "--test", "test/dyn.test.js"], &[]);
assert!(dynamic.get("importsMeasured").is_none(), "{dynamic}");
}
// Its package-manager stand-in is a shell script.
#[cfg(unix)]
#[test]
fn line_queries_and_commands_at_their_edges() {
// A command that only mentions another language's runner, and runs node.
let project = Project::cart("command-edges");
let ran = project.supercov(&["--", "sh", "-c", "echo phpunit && node --test"]);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
// Several lines from past their end: none, and none failed.
let lines = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:2",
"src/cart.js:3",
"--offset",
"5",
"--json",
])
.json();
assert_eq!(lines["data"]["lines"], serde_json::json!([]));
assert_eq!(lines["pagination"]["total"], 2);
// A script of a package manager other than npm, and the others it has.
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module", "scripts": { "test": "node --test", "test:unit": "node --test", "test:e2e": "node --test" } }"#,
);
project.write_script("bin/pnpm", "#!/bin/sh\nexec node --test\n");
project.commit("scripts");
project
.supercov(&["--", "bin/pnpm", "test:unit"])
.succeeds();
assert!(project.supercov(&["runs", "latest"]).succeeds().contains(
"wrapped `bin/pnpm test:unit`. Other test scripts include test:e2e. For whole-project"
));
// One line whose tests alone outgrow a reply.
let mut tests = String::from(
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { total } from \"../src/cart.js\";\n",
);
for name in ["a", "b", "c", "d", "e", "f"] {
tests.push_str(&format!(
"test(\"{}\", () => assert.equal(total([]), 0));\n",
name.repeat(30_000)
));
}
project.write("test/long.test.js", &tests);
project.commit("long names");
project.measure(&[]);
assert!(
project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:2",
"src/cart.js:3",
"--json"
])
.exits(2)
.contains("\"code\":\"RESPONSE_TOO_LARGE\"")
);
}
/// The trash a run starts emptying is empty when the run is over, however
/// long the sweep it started with takes: the end waits for that sweep rather
/// than starting another that finds the trash locked and leaves at once.
#[test]
fn the_trash_is_empty_when_a_run_ends() {
let project = Project::cart("trash-at-end");
let trash = project.root.join(".supercov/.trash/old-workspace");
std::fs::create_dir_all(&trash).unwrap();
for directory in 0..200 {
let directory = trash.join(directory.to_string());
std::fs::create_dir(&directory).unwrap();
for file in 0..400 {
std::fs::write(directory.join(file.to_string()), "").unwrap();
}
}
project.measure(&[]);
assert!(!project.root.join(".supercov/.trash/old-workspace").exists());
}
/// The read views' odd inputs and thin corners, read as a user meets them:
/// a depth of nothing, a lone dash, a colon in a file's name, a decision
/// line holding two, a line with nothing measured on it, and an unassessed
/// run read through a filter.
#[test]
fn the_read_views_name_their_odd_inputs_and_thin_corners() {
let project = Project::cart("read-corners");
project.write("util/name.js", "export const name = (item) => item.name;\n");
project.write(
"src/pick.js",
"export const pick = (a, b) => ((a && b) ? 1 : (a || b) ? 2 : 3);\n",
);
project.write(
"test/extra.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { name } from \"../util/name.js\";\nimport { pick } from \"../src/pick.js\";\n\ntest(\"names and picks\", () => {\n assert.equal(name({ name: \"a\" }), \"a\");\n assert.equal(pick(true, true), 1);\n});\n",
);
project.commit("corners");
let run = project.measure(&[]);
let on_run = |args: &[&str]| {
let mut full = vec!["runs", "latest"];
full.extend_from_slice(args);
project.supercov(&full)
};
for depth in ["0", "-0"] {
assert!(
on_run(&["files", "--group", "dir", "--depth", depth])
.exits(2)
.contains("--depth must be a positive integer")
);
}
// A lone dash is a file to look for, not an option.
let dash = on_run(&["file", "-"]).exits(2);
assert!(dash.contains("Source file not found: -"), "{dash}");
assert!(!dash.contains("Unknown option"), "{dash}");
// The line is after the last colon; the rest is the file.
assert!(
on_run(&["line", "no:such.js:2"])
.exits(2)
.contains("Source file not found: no:such.js")
);
assert!(
on_run(&["gaps", "--format", "jsonl", "--metric"])
.exits(2)
.contains("--metric must be all, lines, statements, functions, branches, or mcdc")
);
// A directory with no branch at all has no share of them.
let branches = on_run(&["files", "--group", "dir", "--metric", "branches"]).succeeds();
assert!(
branches
.lines()
.any(|line| line.starts_with("util ") && line.trim_end().ends_with("—")),
"{branches}"
);
// Two decisions on one line are listed a page at a time.
let decisions = on_run(&["decision", "src/pick.js:1", "--limit", "1"]).succeeds();
contains_all(
&decisions,
&[
"showing 1-1 of 2 matching decisions",
&format!(
"next page: supercov runs '{run}' decision 'src/pick.js:1' --offset 1 --limit 1"
),
],
);
// A line holding only the brace that closes a loop: nothing on it was
// measured, and its source is today's.
let brace = on_run(&["line", "src/cart.js:5"]).succeeds();
contains_all(
&brace,
&["(read from the current working tree)", "NOT MEASURED"],
);
assert!(!brace.contains("Coverage details"), "{brace}");
// A run never assessed, read through a filter, says how to assess
// those tests.
let unassessed = on_run(&["assertions", "--kind", "unit"]).succeeds();
contains_all(
&unassessed,
&[
"assertions not assessed for this run",
&format!("Assess it with `supercov runs {run} assertions assess --kind 'unit'`"),
],
);
}
/// A line's gap is exported with the line it is on, under `--metric lines`
/// as under every metric, and an export that cannot be written says why.
#[cfg(target_os = "linux")]
#[test]
fn exported_line_gaps_quote_their_line_and_a_failed_export_says_why() {
let project = Project::cart("export-lines");
let run = project.measure(&[]);
let rows = |metric: &str| {
project
.supercov(&[
"runs", &run, "gaps", "--format", "jsonl", "--metric", metric,
])
.succeeds()
.lines()
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
.collect::<Vec<_>>()
};
let lines = rows("lines");
// `describe` never ran: its body is a line gap, quoted by what first
// goes unrun on it.
let body = lines
.iter()
.find(|row| row["line"] == 20)
.expect("line 20 is a gap");
assert_eq!(body["kind"], "line");
assert_eq!(body["lineSource"], "(item) => item.name");
assert!(
lines.iter().all(|row| row["lineSource"].is_string()),
"{lines:?}"
);
// Each line reads as `--metric all` quotes it.
let all = rows("all");
for row in &lines {
let same = all
.iter()
.find(|other| other["line"] == row["line"])
.unwrap();
assert_eq!(row["lineSource"], same["lineSource"], "{row}");
}
let file = project
.supercov(&["runs", &run, "file", "src/cart.js", "--metric", "lines"])
.succeeds();
assert!(
file.contains(" 20 NOT COVERED (item) => item.name"),
"{file}"
);
assert!(!file.contains("(source unavailable)"), "{file}");
// Standard output on a full disk: exit 2, and the reason.
let output = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args([
"runs", &run, "gaps", "--format", "jsonl", "--metric", "mcdc",
])
.current_dir(&project.root)
.stdout(std::fs::File::create("/dev/full").unwrap())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains("could not write the gaps to standard output: No space left on device"),
"{stderr}"
);
}
/// A runner's configuration written since the run reaches only that
/// runner's tests, as an edit to one that was there does; a configuration
/// any runner reads reaches every test.
#[test]
fn a_configuration_added_since_the_run_affects_the_tests_of_its_runner() {
let project = Project::cart("config-added");
project.write("playwright.config.js", "export default {};\n");
project.commit("playwright");
project.measure(&[]);
let affected = || {
project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json()["data"]
.clone()
};
// node:test runs none of them under Playwright or Vitest.
project.write("playwright.config.js", "export default { retries: 2 };\n");
project.write("vitest.config.js", "export default {};\n");
let other = affected();
assert_eq!(other["summary"]["affected"], 0, "{other}");
assert_eq!(other["workingTree"]["runWide"], serde_json::json!([]));
assert_eq!(
other["workingTree"]["reasons"],
serde_json::json!(["test/build configuration changed"])
);
// With no record of the runners the run used, or of its files, the
// change cannot be put on other runners: it reaches every test.
for fault in [
"fs.open#evidence_archive.rs:697=50",
"fs.open#source_manifest.rs:381@2",
] {
let unjudged = project
.supercov_with(
&["runs", "latest", "tests", "affected", "--json"],
&[("SUPERCOV_TEST_FAULT", fault)],
)
.json();
assert_eq!(
unjudged["data"]["workingTree"]["runWide"],
serde_json::json!(["test/build configuration changed"]),
"{fault}: {unjudged}"
);
}
// A TypeScript configuration is read whatever the runner.
project.write("tsconfig.json", "{}\n");
let every = affected();
assert_eq!(every["summary"]["affected"], 3, "{every}");
assert_eq!(
every["workingTree"]["runWide"],
serde_json::json!(["test/build configuration changed"])
);
let text = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
assert!(
text.contains("test/build configuration changed (every test)"),
"{text}"
);
}
/// A runner's configuration named where it is not named as one -- a
/// settings file `SUPERCOV_VITEST_CONFIG` points at -- changes the
/// configuration without any configuration file to blame: no runner can be
/// ruled out, and every test is affected.
#[test]
fn a_configuration_no_file_is_named_for_affects_every_test() {
let project = Project::cart("affected-unnamed-configuration");
project.write("runner-settings.mjs", "export default {};\n");
project.commit("runner settings");
let named = [("SUPERCOV_VITEST_CONFIG", "runner-settings.mjs")];
let measured = project.supercov_with(&["--", "node", "--test"], &named);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
project.write("runner-settings.mjs", "export default { test: {} };\n");
let every = project
.supercov_with(&["runs", "latest", "tests", "affected", "--json"], &named)
.json()["data"]
.clone();
assert_eq!(every["summary"]["affected"], 3, "{every}");
assert_eq!(
every["workingTree"]["runWide"],
serde_json::json!(["test/build configuration changed"])
);
}
/// A change to hundreds of files no test ran affects no test and still
/// lists every one of them: the JSON keeps the first files and counts the
/// rest, rather than refusing the reply.
#[test]
fn tests_affected_shortens_a_long_list_of_changed_files_to_fit_one_reply() {
const FILES: usize = 600;
let project = Project::cart("affected-files");
let path = |index: usize| {
format!(
"src/features/a/directory/named/at/the/length/real/projects/nest/their/modules/module{index}.js"
)
};
for index in 0..FILES {
project.write(&path(index), &format!("export const value = {index};\n"));
}
project.commit("modules");
project.measure(&[]);
for index in 0..FILES {
project.write(
&path(index),
&format!("export const value = {};\n", index + 1),
);
}
let data = project
.supercov(&["runs", "latest", "tests", "affected", "--json"])
.json()["data"]
.clone();
assert_eq!(data["summary"]["affected"], 0, "{}", data["summary"]);
assert_eq!(data["changedFilesCount"], FILES, "{}", data["truncated"]);
let listed = data["changedFiles"].as_array().unwrap().len();
assert!(0 < listed && listed < FILES, "{listed}");
assert!(
data["truncated"].as_array().unwrap().iter().any(|note| note
== "the changed files keep their first entries; the text view lists every one"),
"{}",
data["truncated"]
);
let text = project
.supercov(&["runs", "latest", "tests", "affected"])
.succeeds();
assert!(
text.contains(&path(FILES - 1)),
"the text view lists every file"
);
}
/// The report says why it will not compare a run with itself, fills its
/// runs without repeating one, writes nothing where its file is a
/// directory, opens in the browser, and shows its progress on a terminal.
#[cfg(unix)]
#[test]
fn the_report_refuses_a_run_compared_with_itself_and_opens_when_it_can() {
let project = Project::cart("report-edges");
let oldest = project.measure(&["--test-name-pattern=total"]);
let middle = project.measure(&["--test-name-pattern=shipping"]);
let newest = project.measure(&[]);
let refused = project
.supercov(&[
"report",
"--no-open",
"--compare",
"latest",
"--output",
"r.html",
])
.exits(2);
assert!(
refused.contains(&format!(
"report failed: --compare latest is {newest}, the run this report shows; compare it with another run"
)),
"{refused}"
);
assert!(!project.root.join("r.html").exists());
project
.supercov(&[
"report",
"--no-open",
"--compare",
&oldest,
"--output",
"r.html",
])
.succeeds();
let data = report_data(&project.read("r.html"));
let ids = data["runs"]
.as_array()
.unwrap()
.iter()
.map(|run| run["id"].as_str().unwrap().to_owned())
.collect::<Vec<_>>();
assert_eq!(
ids,
[newest.clone(), oldest.clone(), middle],
"the comparison once"
);
assert_eq!(data["comparisonRunId"], oldest.as_str());
// A directory where the report goes: the rename fails and the
// temporary file goes with it.
std::fs::create_dir_all(project.root.join("reports/supercov-report.html")).unwrap();
let blocked = project
.supercov(&["report", "--no-open", "--output", "reports"])
.exits(2);
assert!(
blocked.contains(&format!(
"report failed: {}: ",
project.root.join("reports/supercov-report.html").display()
)),
"{blocked}"
);
let left = std::fs::read_dir(project.root.join("reports"))
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect::<Vec<_>>();
assert_eq!(left, ["supercov-report.html"]);
// Opened the way the desktop opens a file.
project.write_script(
if cfg!(target_os = "macos") {
"bin/open"
} else {
"bin/xdg-open"
},
"#!/bin/sh\necho \"$1\" > \"$(dirname \"$0\")/../opened.txt\"\n",
);
let path = format!(
"{}:{}",
project.root.join("bin").display(),
std::env::var("PATH").unwrap()
);
let opened = project
.supercov_with(&["report", "--output", "r.html"], &[("PATH", &path)])
.succeeds();
assert!(
opened.contains("[supercov] opened the report in your browser"),
"{opened}"
);
let started = std::time::Instant::now();
while !project.root.join("opened.txt").exists() {
assert!(started.elapsed() < std::time::Duration::from_secs(30));
std::thread::sleep(std::time::Duration::from_millis(20));
}
let started = std::time::Instant::now();
while !project.read("opened.txt").contains("r.html") {
assert!(started.elapsed() < std::time::Duration::from_secs(30));
std::thread::sleep(std::time::Duration::from_millis(20));
}
// On a terminal, each run as it is prepared; a filter no test of the
// run passes ends it with why.
let shown = common::OnTerminal::start(&project, &["report", "--no-open", "--output", "t.html"]);
let (code, seen) = shown.finish();
assert_eq!(code, 0, "{seen}");
assert!(
seen.contains(&format!("[supercov] preparing report run 1/3: {newest}")),
"{seen}"
);
let none = common::OnTerminal::start(&project, &["report", "--no-open", "--tag", "nothing"]);
let (code, seen) = none.finish();
assert_eq!(code, 2, "{seen}");
assert!(seen.contains("report failed: "), "{seen}");
}
/// The report details a file whose only gap is code outside measurement,
/// and draws a run's multi-line statements from its coverage when the run
/// was published before their spans were saved beside it.
#[test]
fn the_report_details_an_unmeasured_gap_and_spans_a_run_never_saved() {
let project = Project::empty("report-limited");
project.write("package.json", r#"{ "name": "limited" }"#);
project.write(
"src/scoped.js",
"const scope = { value: 7 };\nfunction sloppy() {\n with (scope) {\n return value;\n }\n}\nfunction sum(a, b) {\n return [\n a,\n b,\n ].reduce((x, y) => x + y, 0);\n}\nmodule.exports = { sloppy, sum };\n",
);
project.write(
"test/scoped.test.js",
"const test = require(\"node:test\");\nconst assert = require(\"node:assert/strict\");\nconst { sloppy, sum } = require(\"../src/scoped.js\");\ntest(\"sloppy reads the scope\", () => assert.equal(sloppy(), 7));\ntest(\"sum adds\", () => assert.equal(sum(1, 2), 3));\n",
);
project.git(&["init", "-q"]);
project.commit("scoped");
let run = project.measure(&[]);
let files = project
.supercov(&["runs", "latest", "files", "--json"])
.json();
let scoped = &files["data"]["files"][0];
assert_eq!(scoped["file"], "src/scoped.js", "{files}");
// Every line ran: what is left is the `with` body, outside measurement.
assert_eq!(scoped["uncoveredLines"], 0, "{scoped}");
assert!(
scoped["measurementLimitations"].as_u64() > Some(0),
"{scoped}"
);
let report = |output: &str| {
project
.supercov(&["report", "--no-open", "--output", output])
.succeeds();
report_data(&project.read(output))
};
let first = report("first.html");
assert!(
first["runs"][0]["fileDetails"]["src/scoped.js"].is_object(),
"{}",
first["runs"][0]["fileDetails"]
);
let spans = first["runs"][0]["statementSpans"].clone();
assert!(
spans.as_array().is_some_and(|spans| !spans.is_empty()),
"{spans}"
);
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&run)
.join("statement-spans.json"),
)
.unwrap();
let again = report("again.html");
assert_eq!(again["runs"][0]["statementSpans"], spans);
}
#[cfg(unix)]
#[test]
fn a_tools_change_to_a_file_edited_while_the_command_ran_is_kept_back() {
let project = Project::empty("kept-back");
project.write(
"package.json",
r#"{ "name": "kept-back", "scripts": { "test": "oxlint --fix src && node edit.cjs && node --test test/fee.test.js" } }"#,
);
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/fee.js",
"function fee(sum) {\n var rate = 5;\n return sum > 100 ? 0 : rate;\n}\nmodule.exports = { fee };\n",
);
project.write(
"test/fee.test.js",
"const { test } = require('node:test');\nconst { equal } = require('node:assert/strict');\nconst { fee } = require('../src/fee.js');\ntest('small orders pay', () => equal(fee(1), 5));\n",
);
project.write_script(
"node_modules/.bin/oxlint",
"#!/bin/sh\nsed 's/var rate/const rate/' \"$2\"/fee.js > fixed.tmp && mv fixed.tmp \"$2\"/fee.js\n",
);
// Someone edits the project's own file while the command runs.
project.write(
"edit.cjs",
"const fs = require('node:fs');\nconst file = process.env.EDITED_PROJECT + '/src/fee.js';\nfs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('var rate = 5', 'let rate = 5'));\n",
);
// An empty directory of the project is walked as one with nothing in it.
std::fs::create_dir_all(project.root.join("src/empty")).unwrap();
project.git(&["init", "-q"]);
let root = project.root.display().to_string();
let run = project.supercov_with(&["--", "npm", "test"], &[("EDITED_PROJECT", &root)]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(
run.stderr().contains(
"the command's tools changed 1 source file(s) that were edited in the project while it ran; those changes were not applied"
),
"{}",
run.stderr()
);
assert!(project.read("src/fee.js").contains("let rate = 5"));
// A change the run cannot read back is not applied, and the run says so
// without failing the command that passed.
project.edit("src/fee.js", "let rate = 5", "var rate = 5");
let unread = project.supercov_with(
&["--", "npm", "test"],
&[
("EDITED_PROJECT", &root),
("SUPERCOV_TEST_FAULT", "fs.read#source_tools.rs:685"),
],
);
let said = unread.stderr();
assert_eq!(unread.code(), 0, "{said}");
assert!(fired_at(&said, "source_tools.rs:685"), "{said}");
assert!(
said.contains("the source changes the command's tools made could not be applied"),
"{said}"
);
// The source view's directories that cannot be listed part way: the
// tools' changes are not applied, the tool reads the instrumented copy,
// or what it wrote stays out of the workspace, and the command passes.
for (fault, told) in [
(
"fs.read_dir entry#source_tools.rs:678",
"the source changes the command's tools made could not be applied",
),
(
"fs.read_dir entry#source_tools.rs:403",
"reads the instrumented files",
),
(
"fs.read_dir entry#source_tools.rs:443",
"reads the instrumented files",
),
(
"fs.read_dir entry#source_tools.rs:493",
"could not be brought into the workspace",
),
] {
project.edit("src/fee.js", "let rate = 5", "var rate = 5");
let ran = project.supercov_with(
&["--", "npm", "test"],
&[("EDITED_PROJECT", &root), ("SUPERCOV_TEST_FAULT", fault)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 0, "{fault}: {said}");
let place = fault.split('#').nth(1).unwrap();
assert!(
fired_at(&said, place) && said.contains(told),
"{fault}: {said}"
);
}
}
/// A run whose Docker daemon is a local socket gives the tests a relay to
/// it in its place; a relay that cannot start leaves the tests the daemon as
/// it was, and the run says the containers they start are not measured.
#[cfg(unix)]
#[test]
fn a_docker_relay_that_cannot_start_leaves_the_daemon_as_it_was() {
let project = Project::cart("docker-relay");
project.write(
"test/docker.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\ntest('daemon', () => {\n const relayed = process.env.DOCKER_HOST !== process.env.DAEMON;\n assert.equal(relayed, process.env.RELAYED === '1');\n});\n",
);
project.commit("docker");
let daemon = format!("unix://{}/daemon.sock", project.root.display());
let relayed = project.supercov_with(
&["--", "node", "--test"],
&[
("DOCKER_HOST", &daemon),
("DAEMON", &daemon),
("RELAYED", "1"),
],
);
assert_eq!(
relayed.code(),
0,
"{}{}",
relayed.stdout(),
relayed.stderr()
);
let unrelayed = project.supercov_with(
&["--", "node", "--test"],
&[
("DOCKER_HOST", &daemon),
("DAEMON", &daemon),
("RELAYED", "0"),
(
"SUPERCOV_TEST_FAULT",
"fs.create_dir_all#docker_proxy.rs:219",
),
],
);
let said = unrelayed.stderr();
assert_eq!(unrelayed.code(), 0, "{}{said}", unrelayed.stdout());
assert!(fired_at(&said, "docker_proxy.rs:219"), "{said}");
assert!(
said.contains(
"containers the tests start are not measured: the Docker relay could not start"
),
"{said}"
);
}
#[test]
fn a_repository_the_workspace_cannot_mirror_is_named_under_debug() {
let project = Project::empty("unmirrored");
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module" }"#,
);
project.write("src/cart.js", common::CART);
project.write("test/cart.test.js", common::CART_TESTS);
// A worktree whose repository is gone.
project.write(".git", "gitdir: /nonexistent/supercov/worktree\n");
let run = project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_DEBUG", "1")]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(
run.stderr()
.contains("the workspace has no git repository of its own"),
"{}",
run.stderr()
);
let quiet = project.supercov(&["--", "node", "--test"]);
assert_eq!(quiet.code(), 0, "{}{}", quiet.stdout(), quiet.stderr());
assert!(!quiet.stderr().contains("no git repository of its own"));
}
#[test]
fn settings_a_suite_chose_for_docker_playwright_and_uv_reach_it_unchanged() {
// A daemon reached over TCP has no socket to relay, and a Playwright
// cache or a uv sync someone chose is theirs.
let project = Project::cart("chosen-settings");
project.write(".venv/pyvenv.cfg", "home = /usr/bin\n");
project.write(
"test/environment.test.js",
"import { test } from 'node:test';\nimport { equal } from 'node:assert/strict';\ntest('settings', () => {\n equal(process.env.DOCKER_HOST, 'tcp://127.0.0.1:2375');\n equal(process.env.PWTEST_CACHE_DIR, '/tmp/chosen-playwright-cache');\n equal(process.env.UV_NO_SYNC, '0');\n});\n",
);
let run = project.supercov_with(
&["--", "node", "--test"],
&[
("DOCKER_HOST", "tcp://127.0.0.1:2375"),
("PWTEST_CACHE_DIR", "/tmp/chosen-playwright-cache"),
("UV_NO_SYNC", "0"),
],
);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(run.stdout().contains("pass 4"), "{}", run.stdout());
}
#[test]
fn a_direct_javascript_run_with_no_command_is_refused() {
let project = Project::cart("empty-direct-command");
let input = project.root.join("input.json");
std::fs::write(
&input,
serde_json::json!({ "root": project.root, "command": [] }).to_string(),
)
.unwrap();
let refused = project
.supercov_with(
&["__run-js-direct"],
&[("SUPERCOV_INTERNAL_INPUT_FILE", input.to_str().unwrap())],
)
.exits(2);
assert!(
refused.contains("direct JavaScript run failed: test command must not be empty"),
"{refused}"
);
assert!(!project.root.join(".supercov").exists());
}
#[test]
fn a_browser_suite_beside_servers_with_nothing_to_measure_measures_its_javascript() {
// A Go workspace and a Maven build with no source: each server language
// is looked for, and neither has anything to measure.
let project = Project::cart("servers-unmeasured");
project.write("playwright.config.js", "export default {};\n");
project.write("go.work", "go 1.22\n\nuse ./svc\n");
project.write("svc/go.mod", "module example.com/svc\n\ngo 1.22\n");
project.write("pom.xml", "<project></project>\n");
let run = project.supercov(&["--", "node", "--test"]);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(
!run.stderr().contains("server the tests start"),
"{}",
run.stderr()
);
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("76.92%"), "{summary}");
// Without JavaScript source there is nothing left to measure.
std::fs::remove_dir_all(project.root.join("src")).unwrap();
project.write(
"test/cart.test.js",
"import { test } from 'node:test';\ntest('nothing', () => {});\n",
);
let empty = project.supercov(&["--", "node", "--test"]).exits(1);
assert!(
empty.contains("No application source files were discovered"),
"{empty}"
);
}
/// Source roots named for a browser suite's JavaScript leave the Python,
/// Ruby, Java and Go beside it no server to measure: the run measures its
/// JavaScript instead of refusing the roots as a run of their own would.
#[test]
fn source_roots_naming_only_javascript_leave_no_python_or_ruby_server() {
let project = Project::cart("roots-javascript-only");
project.write("playwright.config.js", "export default {};\n");
project.write("server.py", "def handle():\n return 1\n");
project.write("app.rb", "def handle\n 1\nend\n");
project.write(
"pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>e</groupId><artifactId>w</artifactId><version>1</version></project>\n",
);
project.write(
"server/src/main/java/w/W.java",
"package w;\npublic class W { public static int one() { return 1; } }\n",
);
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write("cmd/main.go", "package main\n\nfunc main() {}\n");
let run = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "src")],
);
assert_eq!(run.code(), 0, "{}{}", run.stdout(), run.stderr());
assert!(!run.stderr().contains("left no"), "{}", run.stderr());
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("76.92%"), "{summary}");
}
/// A run whose query index cannot be written back says the index could not
/// be opened, and why, instead of blaming the command that ran.
#[test]
fn a_query_index_that_cannot_be_rebuilt_is_named_as_the_failure() {
let project = Project::cart("index-unwritable");
project.supercov(&["--", "node", "--test"]).succeeds();
let runs = project.root.join(".supercov/runs");
let run = std::fs::read_dir(&runs)
.unwrap()
.filter_map(Result::ok)
.find(|entry| entry.path().is_dir())
.unwrap()
.path();
let index = run.join("query-index.v1.bin");
std::fs::remove_file(&index).unwrap();
std::fs::create_dir(&index).unwrap();
let refused = project.supercov(&["runs", "latest", "files"]).exits(2);
assert!(
refused.contains("Failed to open coverage index"),
"{refused}"
);
assert!(!refused.contains("wrapped command"), "{refused}");
}
/// Each query's own read of the index failing -- a decision looked up by its
/// place, the older and newer run of a diff, the summary's runners, the
/// areas' kinds and tested files -- refuses the query, and names where.
#[test]
fn a_query_whose_own_index_read_fails_is_refused() {
let project = Project::cart("index-read-places");
// A file with no decisions, for a decision query that finds none.
project.write("src/plain.js", "export const plain = 1;\n");
project.commit("plain");
project.supercov(&["--", "node", "--test"]).succeeds();
let runs = project.supercov(&["runs", "--json"]).json();
let older = runs["data"]["runs"][0]["id"].as_str().unwrap().to_owned();
project.supercov(&["--", "node", "--test"]).succeeds();
for (command, place) in [
(
vec!["runs", "latest", "decision", "src/cart.js:3"],
"coverage_query.rs:1684",
),
(vec!["diff", &older, "latest"], "coverage_query.rs:2861"),
(vec!["diff", &older, "latest"], "coverage_query.rs:2955@2"),
(vec!["diff", &older, "latest"], "coverage_query.rs:2847@2"),
(vec!["runs", "latest", "summary"], "coverage_query.rs:3279"),
// Every file's details, the scope read last of all.
(
vec!["runs", "latest", "gaps", "--format", "jsonl"],
"coverage_query.rs:2228@2",
),
(
vec!["runs", "latest", "summary", "--kind", "unit"],
"coverage_query.rs:3816",
),
// The dimensions read again, by runner.
(
vec!["runs", "latest", "summary", "--kind", "unit"],
"coverage_query.rs:3816@2",
),
(
vec![
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--kind",
"unit",
],
"coverage_query.rs:3959",
),
(
vec![
"runs",
"latest",
"file",
"src/cart.js",
"--group",
"decision",
"--kind",
"unit",
],
"coverage_query.rs:4009",
),
(
vec!["runs", "latest", "files", "--group", "dir"],
"coverage_query.rs:3557",
),
(
vec!["runs", "latest", "files", "--group", "dir"],
"coverage_query.rs:3565",
),
// A line's anchors; a file with no decisions under a kind, its gaps
// read to tell it from a kind no test has.
(
vec!["runs", "latest", "line", "src/cart.js:14"],
"coverage_query.rs:874",
),
(
vec![
"runs",
"latest",
"file",
"src/plain.js",
"--group",
"decision",
"--kind",
"unit",
],
"coverage_query.rs:3964",
),
] {
let fault = format!("coverage-index-read#{place}");
let ran = project.supercov_with(&command, &[("SUPERCOV_TEST_FAULT", &fault)]);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 2, "{fault}: {said}");
let at = place.split('@').next().unwrap();
assert!(fired_at(&said, at), "{fault}: {said}");
}
// The store of runs that cannot be listed refuses the query too.
let unlisted = project
.supercov_with(
&["runs", "latest", "files", "--json"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695")],
)
.exits(2);
assert!(
unlisted.contains("Failed to read local coverage runs"),
"{unlisted}"
);
}
/// Listing runs reads each run's index for its summary: an index, its
/// summary or its test counts that cannot be read leave the run listed with
/// the error instead of its numbers.
#[test]
fn a_run_listed_whose_index_cannot_be_read_carries_the_error() {
let project = Project::cart("listed-index");
project.measure(&[]);
for fault in [
"coverage-index",
"coverage-index@2",
"coverage-index-read#run_query.rs:72",
"coverage-index-read#run_query.rs:73",
] {
let listed = project
.supercov_with(&["runs", "--json"], &[("SUPERCOV_TEST_FAULT", fault)])
.json();
let run = &listed["data"]["runs"][0];
assert!(
run["coverageError"]
.as_str()
.is_some_and(|error| error.contains("invalid coverage index")),
"{fault}: {run}"
);
assert!(run["lines"].is_null(), "{fault}: {run}");
}
}
/// A run whose index cannot be built is still published, without one; a
/// query that cannot build it either says so, and one that can answers.
#[test]
fn a_run_whose_index_cannot_be_built_is_published_and_built_when_asked() {
let project = Project::cart("index-unbuilt");
let fault = [("SUPERCOV_TEST_FAULT", "coverage-index-build")];
project
.supercov_with(&["--", "node", "--test"], &fault)
.succeeds();
let refused = project.supercov_with(&["runs", "latest"], &fault);
assert_ne!(refused.code(), 0, "{}", refused.stderr());
assert!(
format!("{}{}", refused.stdout(), refused.stderr())
.contains("coverage index exceeds format limits"),
"{}{}",
refused.stdout(),
refused.stderr()
);
project.supercov(&["runs", "latest"]).succeeds();
}
/// An index whose header or file cannot be read when a query opens it is
/// built again from the run's evidence, and the query answers.
#[cfg(unix)]
#[test]
fn an_index_that_cannot_be_opened_is_built_again() {
let project = Project::cart("index-reopened");
project.measure(&[]);
for (fault, place) in [
("fs.open#query_index.rs:337", "query_index.rs:337"),
(
"fs.read_exact_from#query_index.rs:337",
"query_index.rs:337",
),
("fs.open#query_index.rs:354", "query_index.rs:354"),
] {
let ran = project.supercov_with(
&["runs", "latest", "files"],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 0, "{fault}: {said}");
assert!(fired_at(&said, place), "{fault}: {said}");
assert!(said.contains("src/cart.js"), "{fault}: {said}");
}
}
/// An index that cannot be read partway through a command is named as the
/// failure: the tests a filter picks, the newer run a diff compares with,
/// read or opened. A failed run whose index cannot be read still exits as
/// its command did, naming no test it cannot read.
#[test]
fn an_index_that_cannot_be_read_mid_command_is_named() {
let project = Project::cart("index-mid-command");
project.supercov(&["--", "node", "--test"]).succeeds();
let runs = project.supercov(&["runs", "--json"]).json();
let older = runs["data"]["runs"][0]["id"].as_str().unwrap().to_owned();
project.supercov(&["--", "node", "--test"]).succeeds();
// The filter's picks are read from the second index the command opens.
let picked = project
.supercov_with(
&["runs", "latest", "tests", "affected", "--title", "shipping"],
&[("SUPERCOV_TEST_FAULT", "coverage-index@2")],
)
.exits(2);
assert!(picked.contains("invalid coverage index"), "{picked}");
// The older run's index, then the newer one's: the fourth open.
let newer = project
.supercov_with(
&["diff", &older, "latest", "--json"],
&[("SUPERCOV_TEST_FAULT", "coverage-index@4")],
)
.exits(2);
assert!(
newer.contains("Failed to read newer coverage index"),
"{newer}"
);
let latest = project.supercov(&["runs", "--json"]).json();
let latest = latest["data"]["runs"][0]["id"].as_str().unwrap().to_owned();
let index = project
.root
.join(".supercov/runs")
.join(&latest)
.join("query-index.v1.bin");
std::fs::remove_file(&index).unwrap();
std::fs::create_dir(&index).unwrap();
let unopened = project
.supercov(&["diff", &older, "latest", "--json"])
.exits(2);
assert!(
unopened.contains("Failed to open newer coverage index"),
"{unopened}"
);
// Nor whose published run cannot be found again to read.
for (fault, place) in [
("coverage-index@2", "coverage-index"),
("fs.symlink_metadata#run_store.rs:641", "run_store.rs:641"),
] {
let project = Project::cart("index-failed-run");
project.edit("test/cart.test.js", "20);", "21);");
let failed =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = failed.stderr();
assert_eq!(failed.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault}: {stderr}");
assert!(!stderr.contains("test(s) failed"), "{fault}: {stderr}");
}
}
/// A script standing in for rustdoc while Supercov stands in for it during
/// `cargo test --doc`. It reads what to do from the files of the scenario
/// directory `FAKE_RUSTDOC_DIR` names: `standalone` and `merged` are the
/// doctests it lists (`name: test` lines), the second through Supercov's
/// runtool as a merged harness does; `merged.out` is what that harness
/// prints; and a per-name pass runs `doctest` through the runtool (`twice`
/// does so twice, `no-run` not at all) and prints `named.out`, or the name it
/// was given as passing.
#[cfg(unix)]
const FAKE_RUSTDOC: &str = r#"#!/bin/sh
fake="$FAKE_RUSTDOC_DIR"
printf '%s\n' "$*" >> "$fake/calls"
tool= pkg= mode= n=0
while [ $# -gt 0 ]; do
case "$1" in
--test-runtool) tool="$2"; shift ;;
--test-runtool-arg)
n=$((n + 1))
[ $n -eq 2 ] && pkg="$2"
[ $n -eq 3 ] && mode="$2"
shift ;;
esac
shift
done
# Not a pass of Supercov's: a documentation build, or a listing the user
# asked for.
[ -z "$mode" ] && exit 0
case "$mode" in
list)
if [ -f "$fake/list.status" ]; then
cat "$fake/list.err" >&2
exit "$(cat "$fake/list.status")"
fi
cat "$fake/standalone" 2>/dev/null
[ -f "$fake/merged" ] && "$tool" __doctest-runner "$pkg" list "$fake/../bin/harness-list"
[ -f "$fake/vanish" ] && rm -f "$0"
exit 0 ;;
merged)
[ -f "$fake/merged-no-run" ] && exit 0
"$tool" __doctest-runner "$pkg" merged "$fake/../bin/harness"
exit $? ;;
named)
if [ ! -f "$fake/no-run" ]; then
"$tool" __doctest-runner "$pkg" named "$fake/../bin/doctest" > /dev/null
[ -f "$fake/twice" ] && "$tool" __doctest-runner "$pkg" named "$fake/../bin/doctest" > /dev/null
fi
if [ -f "$fake/named.out" ]; then cat "$fake/named.out"; else printf 'test %s ... ok\n' "$SUPERCOV_DOCTEST_NAME"; fi
exit "$(cat "$fake/named.status" 2>/dev/null || echo 0)" ;;
esac
"#;
/// A project holding the stand-ins: rustdoc, the merged harness (listing
/// and running) and a standalone doctest binary.
#[cfg(unix)]
fn fake_rustdoc_project(label: &str) -> Project {
let project = Project::empty(label);
project.write_script(
"bin/harness-list",
"#!/bin/sh\ncat \"$FAKE_RUSTDOC_DIR/merged\"\n",
);
project.write_script(
"bin/harness",
"#!/bin/sh\n[ -f \"$FAKE_RUSTDOC_DIR/merged.sh\" ] && . \"$FAKE_RUSTDOC_DIR/merged.sh\"\ncat \"$FAKE_RUSTDOC_DIR/merged.out\"\nexit \"$(cat \"$FAKE_RUSTDOC_DIR/merged.status\" 2>/dev/null || echo 0)\"\n",
);
project.write_script(
"bin/doctest",
"#!/bin/sh\ncat \"$FAKE_RUSTDOC_DIR/doctest.out\" 2>/dev/null\nexit 0\n",
);
project
}
/// Supercov as rustdoc for one package, in a scenario of its own: the
/// files it starts with, and rustdoc's arguments. The outcome, and what
/// the wrapper recorded for the package (`.json`) or why it could not
/// (`.error`).
#[cfg(unix)]
fn wrap_rustdoc(
project: &Project,
scenario: &str,
files: &[(&str, &str)],
args: &[&str],
) -> (common::Ran, String) {
wrap_rustdoc_with(project, scenario, files, args, &[])
}
/// [`wrap_rustdoc`], with more of the environment set.
#[cfg(unix)]
fn wrap_rustdoc_with(
project: &Project,
scenario: &str,
files: &[(&str, &str)],
args: &[&str],
more: &[(&str, &str)],
) -> (common::Ran, String) {
for (file, contents) in files {
project.write(&format!("{scenario}/{file}"), contents);
}
project.write(&format!("{scenario}/calls"), "");
project.write_script(&format!("{scenario}/rustdoc"), FAKE_RUSTDOC);
let directory = project.root.join(scenario);
let results = directory.join("results");
let mut environment = more.to_vec();
let ran = project.supercov_with(
args,
&[
("SUPERCOV_DOCTEST_WRAPPER_ROOT", results.to_str().unwrap()),
(
"SUPERCOV_DOCTEST_REAL_RUSTDOC",
directory.join("rustdoc").to_str().unwrap(),
),
("FAKE_RUSTDOC_DIR", directory.to_str().unwrap()),
("CARGO_PKG_NAME", "fixture"),
("CARGO_MANIFEST_DIR", project.root.to_str().unwrap()),
// The run that starts rustdoc names its instrumentation.
("SUPERCOV_RUST_PROBE_TOKEN", "0123456789abcdef"),
]
.into_iter()
.chain(environment.drain(..))
.collect::<Vec<_>>(),
);
let recorded = ["00000000.json", "00000000.error"]
.iter()
.find_map(|file| std::fs::read_to_string(results.join("packages").join(file)).ok())
.unwrap_or_default();
(ran, recorded)
}
#[cfg(unix)]
#[test]
fn rustdoc_runs_untouched_when_it_is_not_running_doctests_for_supercov() {
let project = fake_rustdoc_project("rustdoc-passthrough");
for (scenario, args) in [
("docs", &["--crate-name", "fixture", "src/lib.rs"][..]),
(
"listing",
&["--test", "src/lib.rs", "--test-args", "--list"][..],
),
] {
let (ran, recorded) = wrap_rustdoc(&project, scenario, &[], args);
ran.succeeds();
assert_eq!(recorded, "", "{scenario}");
assert_eq!(
project.read(&format!("{scenario}/calls")),
format!("{}\n", args.join(" ")),
"{scenario}"
);
}
// A listing rustdoc cannot produce stops the package as rustdoc did.
let (ran, recorded) = wrap_rustdoc(
&project,
"unlisted",
&[
("list.status", "3"),
("list.err", "error: cannot read crate"),
],
&["--test", "src/lib.rs"],
);
let output = ran.exits(3);
assert!(output.contains("error: cannot read crate"), "{output}");
assert_eq!(recorded, "");
}
#[cfg(unix)]
#[test]
fn a_merged_doctest_harness_must_report_what_its_listing_and_arguments_select() {
let project = fake_rustdoc_project("rustdoc-merged");
let listed = "src/lib.rs - a (line 1): test\nsrc/lib.rs - b (line 5): test\n";
let a = "test src/lib.rs - a (line 1) ... ok\n";
for (scenario, out, error) in [
(
"ghost",
format!("{a}test src/lib.rs - ghost (line 9) ... ok\n"),
"the merged doctest harness reported a case the listing lacks: src/lib.rs - ghost (line 9)",
),
(
"twice",
format!("{a}{a}"),
"doctest src/lib.rs - a (line 1) was reported more than once",
),
(
"short",
a.to_owned(),
"the merged doctest harness ran a different selection than its arguments describe: src/lib.rs - b (line 5)",
),
// A harness that names no case, and one rustdoc never ran.
(
"silent",
String::new(),
"the merged doctest harness ran a different selection than its arguments describe: src/lib.rs - a (line 1), src/lib.rs - b (line 5)",
),
(
"unrun",
String::new(),
"the merged doctest harness ran a different selection than its arguments describe: src/lib.rs - a (line 1), src/lib.rs - b (line 5)",
),
] {
if scenario == "unrun" {
project.write(&format!("{scenario}/merged-no-run"), "");
}
let (ran, recorded) = wrap_rustdoc(
&project,
scenario,
&[("merged", listed), ("merged.out", &out)],
&["--test", "src/lib.rs"],
);
ran.exits(101);
assert_eq!(recorded, error, "{scenario}");
}
// The package's failure that cannot be written down ends the pass,
// saying where.
let (ran, _) = wrap_rustdoc_with(
&project,
"unrecorded",
&[("merged", listed), ("merged.out", a)],
&["--test", "src/lib.rs"],
&[("SUPERCOV_TEST_FAULT", "fs.write#rust_owned_doctests.rs:931")],
);
let said = ran.stderr();
assert_ne!(ran.code(), 0, "{said}");
assert!(
said.contains("test fault at fs (rust_owned_doctests.rs:931"),
"{said}"
);
// A harness that failed may have stopped short: it is not held to its
// selection, and its exit is the package's.
let (ran, recorded) = wrap_rustdoc(
&project,
"failing",
&[
("merged", listed),
("merged.out", a),
("merged.status", "101"),
],
&["--test", "src/lib.rs"],
);
ran.exits(101);
let recorded: serde_json::Value = serde_json::from_str(&recorded).unwrap();
assert_eq!(recorded["exit_code"], 101, "{recorded}");
assert_eq!(
recorded["cases"],
serde_json::json!([{"name": "src/lib.rs - a (line 1)", "status": "passed", "evidence": null}])
);
// Under `--ignored` a harness runs the ignored doctests of its selection.
let (ran, recorded) = wrap_rustdoc(
&project,
"ignored",
&[
("merged", listed),
("merged.out", "test src/lib.rs - a (line 1) ... ignored\n"),
],
&["--test", "src/lib.rs", "--test-args", "--ignored"],
);
ran.succeeds();
let recorded: serde_json::Value = serde_json::from_str(&recorded).unwrap();
assert_eq!(
recorded["cases"],
serde_json::json!([{"name": "src/lib.rs - a (line 1)", "status": "skipped", "evidence": null}])
);
}
#[cfg(unix)]
#[test]
fn a_per_name_doctest_pass_must_run_its_doctest_alone_and_once() {
let project = fake_rustdoc_project("rustdoc-named");
let listed = "src/lib.rs - s (line 3): test\n";
for (scenario, files, error) in [
(
"twice",
&[("twice", "")][..],
"doctest src/lib.rs - s (line 3) ran more than once",
),
(
"another",
&[("named.out", "test src/lib.rs - other (line 7) ... ok\n")][..],
"the pass for doctest src/lib.rs - s (line 3) ran src/lib.rs - other (line 7) instead",
),
] {
let mut files = files.to_vec();
files.push(("standalone", listed));
let (ran, recorded) = wrap_rustdoc(&project, scenario, &files, &["--test", "src/lib.rs"]);
ran.exits(101);
assert_eq!(recorded, error, "{scenario}");
}
// Two doctests run by one pass, and two no filter can tell apart.
let (ran, recorded) = wrap_rustdoc(
&project,
"both",
&[
("standalone", listed),
(
"named.out",
"test src/lib.rs - s (line 3) ... ok\ntest src/lib.rs - s (line 3) ... ok\n",
),
],
&["--test", "src/lib.rs"],
);
ran.exits(101);
assert!(
recorded.starts_with("the pass for doctest src/lib.rs - s (line 3) ran 2 doctest(s)"),
"{recorded}"
);
let (ran, recorded) = wrap_rustdoc(
&project,
"alike",
&[(
"standalone",
"src/lib.rs - a b (line 3): test\nsrc/lib.rs - b a (line 3): test\n",
)],
&["--test", "src/lib.rs"],
);
ran.exits(101);
assert_eq!(
recorded,
"doctest src/lib.rs - a b (line 3) cannot be told apart from another doctest by a filter"
);
// Under `--ignored` a pass that runs and reports nothing passed over a
// doctest that is not ignored...
let (ran, recorded) = wrap_rustdoc(
&project,
"passed-over",
&[("standalone", listed), ("no-run", ""), ("named.out", "")],
&["--test", "src/lib.rs", "--test-args", "--ignored"],
);
ran.succeeds();
let recorded: serde_json::Value = serde_json::from_str(&recorded).unwrap();
assert_eq!(recorded["cases"], serde_json::json!([]), "{recorded}");
// ... reports an ignored one as skipped ...
let (ran, recorded) = wrap_rustdoc(
&project,
"ignored",
&[
("standalone", listed),
("no-run", ""),
("named.out", "test src/lib.rs - s (line 3) ... ignored\n"),
],
&["--test", "src/lib.rs", "--test-args", "--ignored"],
);
ran.succeeds();
let recorded: serde_json::Value = serde_json::from_str(&recorded).unwrap();
assert_eq!(recorded["cases"][0]["status"], "skipped", "{recorded}");
// ... and one that failed without naming a doctest ran none alone.
let (ran, recorded) = wrap_rustdoc(
&project,
"failed-silently",
&[
("standalone", listed),
("no-run", ""),
("named.out", ""),
("named.status", "101"),
],
&["--test", "src/lib.rs", "--test-args", "--ignored"],
);
ran.exits(101);
assert_eq!(
recorded,
"the pass for doctest src/lib.rs - s (line 3) ran 0 doctest(s) instead of that one alone: "
);
// A doctest binary that ran for a pass reporting nothing is not
// attributed to a guess.
let (ran, recorded) = wrap_rustdoc(
&project,
"unclaimed",
&[("standalone", listed), ("named.out", "")],
&["--test", "src/lib.rs", "--test-args", "--ignored"],
);
ran.exits(101);
assert_eq!(
recorded,
"a doctest ran that no pass selected: src/lib.rs - s (line 3)"
);
// A rustdoc that cannot be started for a pass stops the package.
let (ran, _) = wrap_rustdoc(
&project,
"vanished",
&[("standalone", listed), ("vanish", "")],
&["--test", "src/lib.rs"],
);
let output = ran.exits(101);
assert!(output.contains("could not launch"), "{output}");
}
#[cfg(unix)]
#[test]
fn the_doctest_runtool_records_each_binary_rustdoc_hands_it() {
let project = fake_rustdoc_project("doctest-runtool");
let runtool = |package: &str, mode: &str, binary: &str, files: &[(&str, &str)], fault: &str| {
for (file, contents) in files {
project.write(&format!("{package}/{file}"), contents);
}
let directory = project.root.join(package);
let ran = project.supercov_with(
&[
"__doctest-runner",
directory.to_str().unwrap(),
mode,
project.root.join(binary).to_str().unwrap(),
],
&[
("FAKE_RUSTDOC_DIR", directory.to_str().unwrap()),
// Neither makes this the wrapper or a merged harness's
// child: the runtool is named by its argument, and a child
// by both variables.
("SUPERCOV_DOCTEST_WRAPPER_ROOT", directory.to_str().unwrap()),
("RUSTDOC_DOCTEST_RUN_NB_TEST", "0"),
("SUPERCOV_RUST_PROBE_TOKEN", "0123456789abcdef"),
("SUPERCOV_TEST_FAULT", fault),
],
);
let record = std::fs::read_to_string(directory.join("invocations/00000000.json"))
.map(|text| serde_json::from_str::<serde_json::Value>(&text).unwrap())
.unwrap_or_default();
(ran, record)
};
// A binary listing nothing leaves no listing behind.
let (ran, record) = runtool("empty-list", "list", "bin/doctest", &[], "");
ran.succeeds();
assert_eq!(record, serde_json::json!({"kind": "listed"}));
assert!(!project.root.join("empty-list/listed").exists());
// A per-name pass whose binary is a merged harness that matched nothing.
let (ran, record) = runtool(
"empty-harness",
"named",
"bin/doctest",
&[("doctest.out", "\nrunning 0 tests\n")],
"",
);
ran.succeeds();
assert_eq!(record, serde_json::json!({"kind": "empty-harness"}));
// Its record that cannot be written fails the pass.
let (ran, _) = runtool(
"empty-harness-unrecorded",
"named",
"bin/doctest",
&[("doctest.out", "\nrunning 0 tests\n")],
"fs.write#rust_owned_doctests.rs:1265",
);
let output = ran.exits(101);
assert!(
output.contains("test fault at fs (rust_owned_doctests.rs:1265"),
"{output}"
);
// A merged harness whose children's records went missing reports its
// cases without evidence.
let order = r#"["src/lib.rs - a (line 1)"]"#;
let (ran, record) = runtool(
"children-gone",
"merged",
"bin/harness",
&[
("merged-order.json", order),
("merged.sh", "rm -rf \"$SUPERCOV_DOCTEST_CHILD_DIR\"\n"),
("merged.out", "test src/lib.rs - a (line 1) ... ok\n"),
],
"",
);
ran.succeeds();
assert_eq!(
record,
serde_json::json!({"kind": "merged", "cases": [{"name": "src/lib.rs - a (line 1)", "status": "passed", "evidence": null}]})
);
// A child ran for a case the harness never reported.
let (ran, _) = runtool(
"stray-child",
"merged",
"bin/harness",
&[
("merged-order.json", order),
(
"merged.sh",
"printf '{\"index\":5,\"exit_code\":0,\"evidence\":\"/x\"}' > \"$SUPERCOV_DOCTEST_CHILD_DIR/00000005.json\"\n",
),
("merged.out", "test src/lib.rs - a (line 1) ... ok\n"),
],
"",
);
let output = ran.exits(101);
assert!(
output.contains("merged doctest child 5 ran for a case the harness did not report"),
"{output}"
);
// The order the wrapper wrote, or a child's record, that does not read
// as one fails the pass.
for (package, files) in [
("order-garbled", vec![("merged-order.json", "not json")]),
(
"child-garbled",
vec![
("merged-order.json", order),
(
"merged.sh",
"printf 'not json' > \"$SUPERCOV_DOCTEST_CHILD_DIR/00000000.json\"\n",
),
],
),
] {
let (ran, _) = runtool(package, "merged", "bin/harness", &files, "");
let output = ran.exits(101);
assert!(output.contains("expected"), "{package}: {output}");
}
}
#[test]
fn a_crate_builds_with_the_rustflags_its_cargo_configuration_sets() {
// Supercov sets `RUSTFLAGS` to cap lints, and Cargo then ignores
// `build.rustflags`: the crate was built without its own `--cfg`.
let project = Project::empty("config-rustflags");
project.write(
"Cargo.toml",
"[package]\nname = \"configured\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lints.rust]\nunexpected_cfgs = \"allow\"\n",
);
project.write(
".cargo/config.toml",
"[build]\nrustflags = [\"--cfg\", \"configured\"]\n",
);
project.write(
"src/lib.rs",
"pub fn configured() -> bool {\n cfg!(configured)\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn sees_its_configured_flag() {\n assert!(super::configured());\n }\n}\n",
);
project.git(&["init", "-q"]);
let output = project
.supercov_with(&["--", "cargo", "test", "--lib"], &[("RUSTFLAGS", "")])
.exits(101);
// An empty `RUSTFLAGS` is the user's choice, and Cargo honours it.
assert!(output.contains("1 failed"), "{output}");
// Run as `supercov_with` runs it, but with no `RUSTFLAGS` of the test's.
let output = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args(["--", "cargo", "test", "--lib"])
.current_dir(&project.root)
.env_remove("RUSTFLAGS")
.env_remove("SUPERCOV_SOURCE_ROOTS")
.env_remove("SUPERCOV_TEST_KIND")
.output()
.unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(output.status.success(), "{text}");
assert!(text.contains("1 passed"), "{text}");
}
/// A Ruby new enough for Supercov's Ruby frontend (3.3 or newer).
#[cfg(unix)]
fn ruby() -> Option<String> {
let candidates = std::env::var("SUPERCOV_RUBY").ok().into_iter().chain(
[
"/opt/homebrew/opt/ruby@3.4/bin/ruby",
"/opt/homebrew/opt/ruby/bin/ruby",
"ruby",
]
.map(str::to_owned),
);
candidates.into_iter().find(|ruby| {
std::process::Command::new(ruby)
.args(["-e", "exit(RUBY_VERSION >= '3.3' ? 0 : 1)"])
.status()
.is_ok_and(|status| status.success())
})
}
/// Each system call that starts and contains a command, made to fail
/// (`SUPERCOV_TEST_FAULT`): a failure to set up says what could not be done
/// and runs nothing, and an interrupted call is made again. Each case checks
/// its fault was reached: Supercov says so when one fires.
#[cfg(unix)]
#[test]
fn a_failing_system_call_while_starting_a_command_is_named_or_retried() {
// The watchdog's own sites cannot say so: it has no standard error.
let silent = [
"watchdog-orphaned",
"watchdog-setsid",
"watchdog-exec",
"watchdog-read",
"proc-fd",
"fs.read_dir#process_supervision.rs",
];
let reached = |fault: &str, said: &str| {
for site in fault.split(',') {
let site = site.split([':', '=']).next().unwrap();
if silent.contains(&site) {
continue;
}
assert!(
said.contains(&format!("[supercov] test fault at {site}")),
"{site} was never reached:\n{said}"
);
}
};
let project = Project::cart("start-faults");
let run = |fault: &str| {
let output =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
reached(fault, &output.stderr());
output
};
let watchdog = "could not start the watchdog that stops the command if Supercov is killed: it ended before the command started";
for (fault, said) in [
(
"parent-death-pipe",
"could not create parent-death supervision pipe",
),
(
"parent-death-cloexec",
"could not protect parent-death supervision pipe across exec",
),
(
"command-setpgid",
"could not spawn node: Operation not permitted",
),
("ready-pipe", "could not spawn node: Too many open files"),
(
"watchdog-fork",
"could not spawn node: Resource temporarily unavailable",
),
("watchdog-dup-input", watchdog),
("watchdog-dup-ready", watchdog),
("watchdog-exec", watchdog),
("watchdog-orphaned", watchdog),
("watchdog-setsid", watchdog),
// Its descriptors not listed, to close.
("fs.read_dir#process_supervision.rs:1620", watchdog),
// A readiness read that fails other than by being interrupted.
(&format!("ready-read:{}", libc::EIO), watchdog),
] {
let failed = run(fault);
assert_eq!(failed.code(), 1, "{fault}: {}", failed.stderr());
assert!(
failed.stderr().contains(said),
"{fault}: {}",
failed.stderr()
);
}
assert!(
!project.root.join(".supercov/runs").exists() || {
let runs = project.supercov(&["runs", "--json"]).json();
runs["data"]["runs"].as_array().is_some_and(Vec::is_empty)
}
);
// A command that could not start, its run's state not recorded either:
// the failure is still the one said.
let unrecorded = run("command-setpgid,failed-run-state");
assert_eq!(unrecorded.code(), 1, "{}", unrecorded.stderr());
assert!(
unrecorded.stderr().contains("could not spawn node"),
"{}",
unrecorded.stderr()
);
// Interrupted once, then made again; no /proc to list descriptors from;
// a copy taken by another run, with no server to prepare again.
for fault in ["ready-read=1", "watchdog-read=1", "proc-fd", "copy-moved"] {
let passed = run(fault);
assert_eq!(passed.code(), 0, "{fault}: {}", passed.stderr());
}
// A source tool on PATH, and a PATH for its launchers that is not text:
// the command keeps the PATH it had.
project.write_script("bin/biome", "#!/bin/sh\n");
let path = format!(
"{}:{}",
project.root.join("bin").display(),
std::env::var("PATH").unwrap()
);
let kept = project.supercov_with(
&["--", "node", "--test"],
&[
("SUPERCOV_TEST_FAULT", "launcher-path-text"),
("PATH", &path),
],
);
assert_eq!(kept.code(), 0, "{}", kept.stderr());
reached("launcher-path-text", &kept.stderr());
// So does a run that cannot find its own path to launch tools with.
let kept = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "current-exe"), ("PATH", &path)],
);
assert_eq!(kept.code(), 0, "{}", kept.stderr());
reached("current-exe", &kept.stderr());
// And a launcher directory that cannot be cleared, or made, or a
// launcher that cannot be written.
for (fault, place) in [
(
"fs.symlink_metadata#source_tools.rs:211",
"source_tools.rs:211",
),
(
"fs.create_dir_all#source_tools.rs:232",
"source_tools.rs:232",
),
("fs.write#source_tools.rs:240", "source_tools.rs:240"),
] {
let kept = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", fault), ("PATH", &path)],
);
assert_eq!(kept.code(), 0, "{fault}: {}", kept.stderr());
assert!(
fired_at(&kept.stderr(), place),
"{fault}: {}",
kept.stderr()
);
}
// A Go run passes the command's output on itself, so its relay is what
// the remaining faults reach.
let Some(go) = go() else {
eprintln!("skipping the relay's faults: no Go toolchain found");
return;
};
let project = Project::empty("start-faults-go");
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write(
"w.go",
"package w\n\nfunc Double(n int) int { return n * 2 }\n",
);
project.write(
"w_test.go",
"package w\n\nimport \"testing\"\n\nfunc TestDouble(t *testing.T) {\n\tif Double(2) != 4 {\n\t\tt.Fatal(\"double\")\n\t}\n}\n",
);
project.git(&["init", "-q"]);
// Output and errors to one file: one pipe for both, or, when it cannot be
// made, one for each, and the file gets both either way.
for fault in ["output-pipe", "output-clone"] {
let log = project.root.join(format!("log-{fault}.txt"));
let file = std::fs::File::create(&log).unwrap();
let status = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args(["--", go, "test", "-v", "./..."])
.current_dir(&project.root)
.env("SUPERCOV_TEST_FAULT", fault)
.stdout(file.try_clone().unwrap())
.stderr(file)
.status()
.unwrap();
let written = std::fs::read_to_string(&log).unwrap();
assert!(status.success(), "{fault}: {written}");
reached(fault, &written);
assert!(
written.contains("--- PASS: TestDouble"),
"{fault}: {written}"
);
}
// On a terminal: one that cannot be sized or opened leaves the command
// the streams it had; an interrupted read is read again.
for fault in [
"terminal-size",
"openpty",
"terminal-clone",
"terminal-read=1",
] {
let terminal = common::OnTerminal::start_with(
&project,
&["--", go, "test", "-v", "./..."],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{fault}: {seen}");
reached(fault, &seen);
assert!(seen.contains("PASS"), "{fault}: {seen}");
}
}
/// A Rust run whose evidence cannot be published says so, and leaves none
/// of its work behind, even when its copy cannot be found again to clear.
#[test]
fn a_rust_run_that_cannot_publish_says_so_and_clears_its_work() {
let project = Project::empty("rust-unpublished");
project.write(
"Cargo.toml",
"[package]\nname = \"p\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"src/lib.rs",
"pub fn half(x: i32) -> i32 { x / 2 }\n#[cfg(test)]\nmod tests { #[test] fn h() { assert_eq!(super::half(4), 2); } }\n",
);
project.git(&["init", "-q"]);
let failed = project.supercov_with(
&["--", "cargo", "test"],
&[("SUPERCOV_TEST_FAULT", "published-copy-differs")],
);
assert_ne!(failed.code(), 0, "{}", failed.stderr());
assert!(
failed
.stderr()
.contains("evidence changed during publication"),
"{}",
failed.stderr()
);
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(
runs["data"]["runs"].as_array().map(Vec::len),
Some(0),
"{runs}"
);
}
/// A trash too large to empty within the command's patience is left to the
/// sweep it started, which empties it after the command has gone.
#[test]
fn a_sweep_that_outlasts_the_command_empties_the_trash_after_it() {
let project = Project::cart("sweep-outlasts");
let big = project.root.join(".supercov/.trash/big");
std::fs::create_dir_all(&big).unwrap();
for i in 0..20_000 {
std::fs::write(big.join(i.to_string()), b"x").unwrap();
}
let measured = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "sweep-impatient,sweep-outlasts")],
);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured.stderr().contains("test fault at sweep-outlasts"),
"{}",
measured.stderr()
);
let started = std::time::Instant::now();
while big.exists() {
assert!(
started.elapsed() < std::time::Duration::from_secs(120),
"the sweep the command left never emptied the trash"
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
// A sweep that cannot be started leaves the trash for a later one; the
// command is measured all the same.
std::fs::create_dir_all(&big).unwrap();
let measured = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "sweep-exe")],
);
assert_eq!(measured.code(), 0, "{}", measured.stderr());
assert!(
measured.stderr().contains("test fault at sweep-exe"),
"{}",
measured.stderr()
);
}
#[cfg(unix)]
#[test]
fn the_parent_death_watchdog_kills_its_parents_group_when_its_input_ends() {
use std::io::{Read, Write};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::process::{Command, Stdio};
// A shell leading its own process group stands in for the command: the
// watchdog says it is ready on descriptor 3, watches its input, and when
// the input ends kills the shell's group. Only the watchdog holds the
// input; the shell's own is moved away.
let watch = |script: &str| {
Command::new("sh")
.args(["-c", script, env!("CARGO_BIN_EXE_supercov")])
.process_group(0)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap()
};
let killed = |mut shell: std::process::Child| {
let started = std::time::Instant::now();
loop {
if let Some(status) = shell.try_wait().unwrap() {
return status.signal();
}
assert!(
started.elapsed() < std::time::Duration::from_secs(20),
"the watchdog never ended its parent's group"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
// Input that sends a byte, then ends.
let mut shell = watch(
"exec 4<&0 0</dev/null; \"$0\" __watch-process-group 3>&1 <&4 4<&- & exec 4<&-; sleep 30",
);
let mut ready = [0_u8; 1];
shell.stdout.take().unwrap().read_exact(&mut ready).unwrap();
assert_eq!(ready, [1]);
let mut input = shell.stdin.take().unwrap();
input.write_all(b"x").unwrap();
drop(input);
assert_eq!(killed(shell), Some(libc::SIGKILL));
// Input it cannot read counts as ended.
let shell =
watch("exec 0</dev/null; \"$0\" __watch-process-group 3>/dev/null 0>/dev/null & sleep 30");
assert_eq!(killed(shell), Some(libc::SIGKILL));
// With nowhere to say it is ready, it refuses, and kills nothing.
let shell = watch("\"$0\" __watch-process-group 3>&- </dev/null; echo \"watchdog $?\"");
let output = shell.wait_with_output().unwrap();
assert!(output.status.success(), "{:?}", output.status);
assert_eq!(String::from_utf8_lossy(&output.stdout), "watchdog 125\n");
}
#[cfg(unix)]
#[test]
fn ctrl_c_during_a_go_python_ruby_or_jvm_run_exits_as_the_signal_and_publishes_nothing() {
// As a JavaScript run does: 128 plus the signal, the signal named, and no
// run recorded for a suite that never finished.
let interrupt = |project: &Project, args: &[&str], waiting: &str| {
let mut terminal = common::OnTerminal::start(project, args);
terminal.wait_for(waiting);
terminal.press("\u{3}");
let (code, seen) = terminal.finish();
assert_eq!(code, 130, "{args:?}\n{seen}");
assert!(
seen.contains("the test command was interrupted by SIGINT; no run was published"),
"{args:?}\n{seen}"
);
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(
runs["data"]["runs"].as_array().map(Vec::len),
Some(0),
"{runs}"
);
};
if let Some(go) = go() {
let project = Project::empty("interrupt-go");
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write(
"w.go",
"package w\n\nfunc Double(n int) int { return n * 2 }\n",
);
project.write("w_test.go", "package w\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWaits(t *testing.T) {\n\tif Double(2) != 4 {\n\t\tt.Fatal(\"double\")\n\t}\n\tfmt.Println(\"waiting now\")\n\ttime.Sleep(60 * time.Second)\n}\n");
project.git(&["init", "-q"]);
interrupt(&project, &["--", go, "test", "-v", "./..."], "waiting now");
}
let project = Project::empty("interrupt-python");
project.write("pkg/__init__.py", "");
project.write("pkg/w.py", "def double(n):\n return n * 2\n");
project.write("tests/__init__.py", "");
project.write("tests/test_w.py", "import time\nimport unittest\nfrom pkg.w import double\n\nclass W(unittest.TestCase):\n def test_waits(self):\n self.assertEqual(double(2), 4)\n print('waiting now', flush=True)\n time.sleep(60)\n");
project.git(&["init", "-q"]);
interrupt(
&project,
&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
],
"waiting now",
);
if let Some(ruby) = ruby() {
let project = Project::empty("interrupt-ruby");
project.write("lib/w.rb", "module W\n def self.double(n) = n * 2\nend\n");
project.write("test/w_test.rb", "require 'minitest/autorun'\nrequire 'w'\n\nclass WTest < Minitest::Test\n def test_waits\n assert_equal 4, W.double(2)\n puts 'waiting now'\n $stdout.flush\n sleep 60\n end\nend\n");
project.git(&["init", "-q"]);
interrupt(
&project,
&["--", &ruby, "-Ilib", "test/w_test.rb"],
"waiting now",
);
}
let maven = std::process::Command::new("mvn")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success());
if maven {
let project = Project::empty("interrupt-jvm");
project.write("pom.xml", "<project xmlns=\"http://maven.apache.org/POM/4.0.0\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>example</groupId>\n <artifactId>w</artifactId>\n <version>1.0</version>\n <properties>\n <maven.compiler.source>17</maven.compiler.source>\n <maven.compiler.target>17</maven.compiler.target>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.junit.jupiter</groupId>\n <artifactId>junit-jupiter</artifactId>\n <version>5.10.2</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>3.2.5</version>\n </plugin>\n </plugins>\n </build>\n</project>\n");
project.write(
"src/main/java/w/W.java",
"package w;\n\npublic class W {\n public static int twice(int n) {\n return n * 2;\n }\n}\n",
);
project.write("src/test/java/w/WTest.java", "package w;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\n\nclass WTest {\n @Test\n void waits() throws InterruptedException {\n assertEquals(4, W.twice(2));\n System.out.println(\"waiting now\");\n System.out.flush();\n Thread.sleep(60_000);\n }\n}\n");
project.git(&["init", "-q"]);
interrupt(&project, &["--", "mvn", "test"], "waiting now");
}
}
/// The processes Supercov stands in as for `cargo test --doc` -- rustdoc,
/// its runtool, a merged harness's child -- each refuse what they were not
/// given, say why, and exit as rustdoc's harness does on an error.
#[test]
fn a_doctest_stand_in_missing_what_it_needs_says_so() {
let project = Project::empty("doctest-stand-ins");
let missing = project.root.join("missing");
let missing = missing.to_str().unwrap();
let root = project.root.to_str().unwrap();
// A program that prints and exits, as a doctest binary does.
let supercov = env!("CARGO_BIN_EXE_supercov");
for (args, env, said) in [
(
&["__doctest-runner", "only"][..],
&[][..],
"needs a package directory, a mode and a binary",
),
(
&["__doctest-runner", root, "bogus", missing],
&[],
"unknown doctest runtool mode bogus",
),
// A per-name pass needs the run's token and the doctest's name.
(
&["__doctest-runner", root, "named", supercov],
&[],
"has no instrumentation token",
),
(
&["__doctest-runner", root, "named", supercov],
&[("SUPERCOV_RUST_PROBE_TOKEN", "doctests")],
"did not name its doctest",
),
(
&[],
&[("SUPERCOV_DOCTEST_WRAPPER_ROOT", root)],
"does not know the real rustdoc",
),
(
&["--version"],
&[
("SUPERCOV_DOCTEST_WRAPPER_ROOT", root),
("SUPERCOV_DOCTEST_REAL_RUSTDOC", missing),
],
"[supercov]",
),
(
&[],
&[
("RUSTDOC_DOCTEST_RUN_NB_TEST", "first"),
("SUPERCOV_DOCTEST_CHILD_DIR", root),
],
"no case index",
),
(
&[],
&[
("RUSTDOC_DOCTEST_RUN_NB_TEST", "0"),
("SUPERCOV_DOCTEST_CHILD_DIR", root),
],
"no harness binary",
),
(
&[],
&[
("RUSTDOC_DOCTEST_RUN_NB_TEST", "0"),
("SUPERCOV_DOCTEST_CHILD_DIR", root),
("SUPERCOV_DOCTEST_CHILD_BINARY", missing),
("SUPERCOV_RUST_PROBE_TOKEN", "doctests"),
],
"[supercov]",
),
] {
let ran = project.supercov_with(args, env);
assert_eq!(ran.code(), 101, "{args:?} {env:?}");
assert!(
ran.stderr().contains(said),
"{args:?} {env:?}: {}",
ran.stderr()
);
}
}
/// Supercov as nextest's target runner refuses what it was not given: no
/// root, target and binary; no plan; a target the plan does not name; and a
/// start without nextest's identity, wrapping the runner the user set or not.
#[test]
fn the_nextest_runner_missing_what_it_needs_says_so() {
let project = Project::empty("nextest-runner");
let root = project.root.to_str().unwrap();
let missing = project.root.join("missing");
let missing = missing.to_str().unwrap();
let ran = project.supercov(&["__nextest-runner"]);
assert_eq!(ran.code(), 2);
assert!(
ran.stderr()
.contains("needs an evidence root, a target and a binary"),
"{}",
ran.stderr()
);
let ran = project.supercov(&["__nextest-runner", root, "x86_64", missing]);
assert_eq!(ran.code(), 2, "{}", ran.stderr());
project.write(
"runner-plan.json",
r#"{"token":"t","targets":[{"target":"wasm32","underlying":{"program":"/bin/echo","arguments":["wrapped"]}}]}"#,
);
let ran = project.supercov(&["__nextest-runner", root, "x86_64", missing]);
assert!(
ran.stderr()
.contains("invoked for an unplanned target: x86_64"),
"{}",
ran.stderr()
);
let ran = project.supercov(&["__nextest-runner", root, "wasm32", missing]);
assert_eq!(ran.code(), 2);
assert!(
ran.stderr().contains("without nextest's identity"),
"{}",
ran.stderr()
);
// An identity that is not nextest's own.
let ran = project.supercov_with(
&["__nextest-runner", root, "wasm32", missing],
&[("NEXTEST", "2")],
);
assert_eq!(ran.code(), 2);
assert!(
ran.stderr().contains("NEXTEST must equal 1"),
"{}",
ran.stderr()
);
}
/// `--exact-attribution` goes before the command, and the run is the
/// command's as any other.
#[test]
fn exact_attribution_runs_the_command_after_it() {
let project = Project::cart("exact-attribution");
let measured = project
.supercov(&["--exact-attribution", "--", "node", "--test"])
.succeeds();
contains_all(&measured, &["pass 3", "[coverage] evidence:"]);
}
/// Each place a language's run makes a file operation of its own -- the
/// root resolved, the lock and recovery, the runtime and evidence written,
/// the plan, the work cleared, publication -- failing alone, and the test
/// command unable to start: the run says so and fails, never panicking, and
/// runs again cleanly. Each fault names the operation and which of its calls
/// in the run it is; each runs on a project of its own, since what a failed
/// run leaves behind would change which call the next one's fault names.
/// A fault written `fault => place` must fail the call made there.
fn each_step_of_a_run_fails(label: &str, write: fn(&Project), command: &[&str], faults: &[&str]) {
for (number, entry) in faults.iter().enumerate() {
let (fault, place) = entry.split_once(" => ").unwrap_or((entry, ""));
let project = Project::empty(&format!("{label}-{number}"));
write(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(command, &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert!(!said.contains("panicked at"), "{label} {fault}: {said}");
assert_ne!(ran.code(), 0, "{label} {fault}: {said}");
assert!(fired_at(&said, place), "{label} {fault} at {place}: {said}");
project.supercov(command).succeeds();
}
}
#[cfg(unix)]
#[test]
fn a_python_run_whose_own_step_fails_says_so() {
each_step_of_a_run_fails(
"own-step-py",
python_project,
&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
],
&[
"fs.canonicalize@1",
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.create_dir_all@3",
"fs.create_dir_all@4",
"fs.create_dir_all@6",
"fs.create_dir_all@14",
"fs.write@2",
"fs.write@10 => python_run.rs:449",
"fs.rename@2",
"fs.rename@9",
"fs.open@7",
"fs.symlink_metadata@12",
"fs.create_dir_all@5",
"fs.open_with@5",
"fs.rename@1",
// The project walked and read; the evidence listed and read back.
"fs.read_dir@2",
"fs.file_type@1",
"fs.read@4",
"fs.read_dir@5",
"fs.symlink_metadata@15",
"fs.open@5",
"fs.read@10",
"fs.read@6 => source_capture.rs:54",
"fs.read_dir entry#1 => python_project.rs:125",
"fs.read_dir entry#2 => python_evidence.rs:374",
// The report the run built, refused as one Supercov got wrong.
"report-request",
"spawn",
],
);
}
#[cfg(unix)]
#[test]
fn a_javascript_run_whose_own_step_fails_says_so() {
each_step_of_a_run_fails(
"own-step-js",
javascript_project,
&["--", "node", "--test"],
&[
// The project's packages looked for: a directory, one below it,
// an entry's type; then the source walk's root.
"fs.read_dir@2",
"fs.read_dir@3",
"fs.file_type@1",
"fs.symlink_metadata@9",
"fs.canonicalize@2",
"fs.create_dir_all@13",
"fs.rename@5",
"fs.open@8",
"fs.open@9",
"fs.open@11",
"fs.open@13",
"fs.open@1",
"fs.read_from@1",
"fs.read@11",
"fs.read_dir@16",
"fs.file_type@15",
"fs.open@10",
"fs.open_with@11",
"fs.create_dir_all@3",
"fs.create_dir_all@4",
"fs.create_dir_all@7",
"fs.write@2",
"fs.rename@1",
"fs.rename@2",
"fs.copy@1",
"fs.read_dir@36 => workspace.rs:1157",
"fs.read_dir@37 => workspace.rs:706",
"fs.read_dir@51 => workspace.rs:1358",
"spawn",
// Supercov's own executable unresolved: no watchdog to contain
// a crash.
"fs.canonicalize#main.rs:2679 => main.rs:2679",
// The runtime the copy's sources load, read back to inline.
"fs.read_to_string#javascript_frontend.rs:2057 => javascript_frontend.rs:2057",
],
);
}
/// A Rust run of a crate with no doctest writes its unit tests' report,
/// then its doctests' (none ran): either that cannot be written ends the
/// run rather than leaving the tests' outcomes unsaid.
#[test]
fn a_rust_run_that_cannot_write_its_tests_reports_says_so() {
for fault in ["diagnostics@3", "diagnostics@4"] {
let project = Project::empty("rust-reports-unwritten");
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"pub fn double(n: u32) -> u32 {\n if n == 0 { 0 } else { n * 2 }\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let ran =
project.supercov_with(&["--", "cargo", "test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, "diagnostics"), "{fault}: {stderr}");
}
}
#[test]
fn a_rust_run_whose_own_step_fails_says_so() {
each_step_of_a_run_fails(
"own-step-rs",
small_crate,
&["--", "cargo", "test", "-q"],
&[
"fs.canonicalize@1",
"fs.read_dir@2",
"fs.file_type@1",
"fs.create_dir_all@9",
"fs.rename@6",
"fs.open@10",
"fs.canonicalize@9",
"fs.canonicalize@10",
"fs.canonicalize@11",
"fs.canonicalize@12",
"fs.read_to_string@4",
"fs.read_to_string@5",
"fs.read_to_string@6",
"fs.write@3",
"fs.write@4",
"fs.create_dir_all@8",
"fs.create_dir_all@10",
"fs.rename@3",
"fs.open@5",
"fs.file_type@9",
"fs.read@10",
"fs.read@11",
// The lock and recovery, the inputs captured and digested, the
// copy recovered, the target directory, the outputs before and
// after, the archive, the trash; the runner's target, test
// binary and source resolved, a test's evidence directory, the
// probe evidence listed. Past the build, a call is named by its
// place (`#N`, `#N@M`): how many calls a walk of the target
// directory makes differs between systems.
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.read@5",
"fs.open@1",
"fs.read_dir@5",
"fs.create_dir_all@7",
"fs.read_dir@11",
"fs.read_dir#7@3",
"fs.create_dir_all#10",
"fs.create_dir_all#11",
"fs.create_dir_all#17",
"fs.canonicalize#12",
"fs.canonicalize#13",
"fs.canonicalize#14",
"fs.create_dir#2",
"fs.read_dir#9",
// The doctest runner: Supercov's own path resolved, the packages
// it recorded listed and read, a doctest's evidence listed.
"fs.canonicalize#15",
"fs.read_dir#10",
"fs.read#9 => rust_owned_doctests.rs:289",
"fs.read_dir#9@2",
// The processes the run starts: Cargo's metadata, the test
// build, rustc's libdir and sysroot, a test binary's listing,
// the test processes and the doctests'.
"spawn#rust_project.rs:182 => rust_project.rs:182",
// The copy's own path, resolved to read its module tree.
"fs.canonicalize#rust_project.rs:320 => rust_project.rs:320",
"spawn#rust_test_runner.rs:947 => rust_test_runner.rs:947",
"spawn#rust_test_runner.rs:1570 => rust_test_runner.rs:1570",
"spawn#rust_test_runner.rs:1570@2 => rust_test_runner.rs:1570",
"spawn#rust_test_runner.rs:1268 => rust_test_runner.rs:1268",
"spawn#child_signal_guard.rs:255 => child_signal_guard.rs:255",
"spawn#child_signal_guard.rs:255@2 => child_signal_guard.rs:255",
"spawn",
// The store of copies made.
"fs.create_dir_all#workspace.rs:445 => workspace.rs:445",
],
);
// A binary none of whose tests were asked for is listed again for how
// many it has.
each_step_of_a_run_fails(
"own-step-rs-unasked",
small_crate,
&["--", "cargo", "test", "-q", "--lib", "--", "none"],
&["spawn#rust_test_runner.rs:1268@2 => rust_test_runner.rs:1268"],
);
if nextest_installed() {
// Nextest's runner fails the attempt, and nextest exits 100.
each_step_of_a_run_fails(
"own-step-nextest",
small_crate,
&["--", "cargo", "nextest", "run"],
&[
"fs.write@5",
// The attempts' directory, Supercov's own path, Cargo's
// runner configuration resolved, the attempts listed and
// read, an attempt's evidence listed.
"fs.create_dir_all#8",
"fs.canonicalize#12",
"fs.canonicalize#5@3",
"fs.read_dir#9",
"fs.read#7",
"fs.read_dir#10",
// nextest's version, rustc through Cargo's configuration,
// the test list, Cargo's metadata, the run.
"spawn#rust_owned_nextest.rs:136 => rust_owned_nextest.rs:136",
"spawn#rust_cargo_configuration.rs:620@3 => rust_cargo_configuration.rs:620",
"spawn#rust_owned_nextest.rs:190 => rust_owned_nextest.rs:190",
"spawn#rust_owned_nextest.rs:203 => rust_owned_nextest.rs:203",
"spawn#child_signal_guard.rs:328 => child_signal_guard.rs:328",
"__nextest-runner/spawn@1",
// An attempt's own start, the listing having passed.
"__nextest-runner/spawn#rust_owned_nextest.rs:604",
"__nextest-runner/fs.read@1",
"__nextest-runner/fs.create_dir_all@1",
"__nextest-runner/fs.create_dir_all@2",
"__nextest-runner/fs.open_with@1",
"__nextest-runner/fs.write@1",
],
);
}
}
/// A crate holding a Rust Worker, with a `wrangler` installed: the run puts
/// its own `wrangler` first on the tests' PATH. Each step of that failing --
/// the tools directory made, the stand-in written and made runnable, the
/// inspector hook written -- ends the run, naming the file it could not make.
#[cfg(unix)]
#[test]
fn a_rust_run_that_cannot_put_its_wrangler_in_place_says_so() {
for fault in [
"fs.create_dir_all@11",
"fs.write@5",
"fs.set_permissions@1",
"fs.write@6",
] {
let project = Project::empty("worker-stand-in");
small_crate(&project);
project.write(
"worker/Cargo.toml",
"[package]\nname = \"edge\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write("worker/src/lib.rs", "pub fn edge() {}\n");
project.write(
"worker/wrangler.toml",
"name = \"edge\"\nmain = \"build/worker/shim.mjs\"\ncompatibility_date = \"2026-10-01\"\n\n[build]\ncommand = \"worker-build --release\"\n",
);
project.write_script("bin/wrangler", "#!/bin/sh\necho wrangler\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let path = format!(
"{}:{}",
project.root.join("bin").display(),
std::env::var("PATH").unwrap()
);
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_TEST_FAULT", fault), ("PATH", &path)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {said}");
assert!(
said.contains("rust-evidence")
&& said.contains("wrangler")
&& !said.contains("panicked at"),
"{fault}: {said}"
);
// And as `cargo test` alone: a command of no arguments past it.
project
.supercov_with(&["--", "cargo", "test"], &[("PATH", &path)])
.succeeds();
// With no wrangler installed there is none to stand in for: a test
// that looks for one finds none, as it would without Supercov.
if fault != "fs.write@6" {
continue;
}
let bare = std::env::split_paths(&std::env::var_os("PATH").unwrap())
.filter(|directory| !directory.join("wrangler").exists())
.collect::<Vec<_>>();
let bare = std::env::join_paths(bare).unwrap();
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("PATH", bare.to_str().unwrap())],
);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
}
// Supercov's own program not found, and a project whose path cannot go
// on a PATH: neither leaves a stand-in to put first.
for (label, fault, expected) in [
("worker-exe", "worker-exe", "injected fault at worker-exe"),
("worker:colon", "", "separator"),
] {
let project = Project::empty(label);
small_crate(&project);
project.write(
"worker/Cargo.toml",
"[package]\nname = \"edge\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write("worker/src/lib.rs", "pub fn edge() {}\n");
project.write(
"worker/wrangler.toml",
"name = \"edge\"\nmain = \"build/worker/shim.mjs\"\n\n[build]\ncommand = \"worker-build --release\"\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
// Installed where a PATH can name it.
let tools = Project::empty("worker-tools");
tools.write_script("wrangler", "#!/bin/sh\necho wrangler\n");
let path = format!(
"{}:{}",
tools.root.display(),
std::env::var("PATH").unwrap()
);
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_TEST_FAULT", fault), ("PATH", &path)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 1, "{label}: {said}");
assert!(said.contains(expected), "{label}: {said}");
}
}
/// A browser suite beside a Rust Worker: the run instruments the Worker in
/// its copy and points its configuration at Supercov's entry before the
/// suite starts. Each step of that failing -- the evidence and inspector
/// directories made, the inspector hook, registry and entry written, the
/// configuration read and rewritten -- ends the run and says what failed.
#[cfg(unix)]
#[test]
fn a_browser_suite_whose_rust_worker_cannot_be_prepared_says_so() {
for (fault, said) in [
("fs.create_dir_all@17", "injected fault at fs"),
("fs.write@6", "rust-worker-0"),
("fs.create_dir_all@18", "injected fault at fs"),
("fs.write@7", "injected fault at fs"),
("fs.write@8", "injected fault at fs"),
("fs.read_to_string@21", "wrangler.toml"),
("fs.write@9", "wrangler.toml"),
// The Worker crate's inputs captured and digested, and the crate
// prepared for its build.
("fs.canonicalize@12", "injected fault at fs"),
("fs.open@6", "worker/src/lib.rs"),
("fs.canonicalize@20", "injected fault at fs"),
// The Worker workspace's inputs walked, and a port found for its
// inspector.
("fs.read_dir#rust_run.rs:88", "rust_run.rs:88"),
("free-port", "injected fault at free-port"),
] {
let project = Project::cart("worker-server-steps");
project.write("playwright.config.js", "export default {};\n");
project.write(
"worker/Cargo.toml",
"[package]\nname = \"edge\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write("worker/src/lib.rs", "pub fn edge() {}\n");
project.write(
"worker/wrangler.toml",
"name = \"edge\"\nmain = \"build/worker/shim.mjs\"\ncompatibility_date = \"2026-10-01\"\n\n[build]\ncommand = \"worker-build --release\"\n",
);
project.commit("worker");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(
stderr.contains(said) && !stderr.contains("panicked at"),
"{fault}: {stderr}"
);
}
// A Worker that names its own inspector port is polled there, and its
// configuration is rewritten for its entry alone.
let project = Project::cart("worker-server-port");
project.write("playwright.config.js", "export default {};\n");
project.write(
"worker/Cargo.toml",
"[package]\nname = \"edge\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write("worker/src/lib.rs", "pub fn edge() {}\n");
project.write(
"worker/wrangler.toml",
"name = \"edge\"\nmain = \"build/worker/shim.mjs\"\n\n[build]\ncommand = \"worker-build --release\"\n\n[dev]\ninspector_port = 9339\n",
);
project.commit("worker");
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "fs.write@9")],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{stderr}");
assert!(stderr.contains("wrangler.toml"), "{stderr}");
}
/// A run started with no PATH at all puts no launchers on one: the suite
/// runs as it would have, from the program it names.
#[cfg(unix)]
#[test]
fn a_javascript_run_with_no_path_runs_its_suite_as_named() {
let project = Project::cart("no-path");
let node = String::from_utf8(
std::process::Command::new("sh")
.args(["-c", "command -v node"])
.output()
.unwrap()
.stdout,
)
.unwrap();
let mut command = project.supercov_command(&["--", node.trim(), "--test"]);
command.env_remove("PATH");
let output = command.output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{stderr}");
assert!(stderr.contains("running in isolated workspace"), "{stderr}");
}
/// What a run digests to judge later whether it is current -- the tests,
/// the dependency manifests, the configuration -- unreadable: the run ends
/// and names the file.
#[test]
fn a_python_run_that_cannot_digest_its_inputs_names_the_file() {
for (fault, file) in [
("fs.open@3", "tests/__init__.py"),
("fs.open@5", "setup.cfg"),
("fs.open@6", "pytest.ini"),
] {
let project = Project::empty("digest-inputs");
python_project(&project);
project.write("setup.cfg", "[metadata]\nname = w\n");
project.write("pytest.ini", "[pytest]\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(
&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {said}");
assert!(
said.contains(file) && said.contains("injected fault at fs"),
"{fault}: {said}"
);
}
}
/// A JavaScript run walks the project for its tests, dependency manifests
/// and configuration twice: for the files that carry assertions, and for
/// what it digests. A directory any of those walks cannot list ends the run.
#[test]
fn a_javascript_run_that_cannot_walk_its_inputs_says_so() {
for fault in [
"fs.read_dir@16",
"fs.read_dir@19",
"fs.read_dir@22",
"fs.read_dir@25",
"fs.read_dir@28",
"fs.read_dir@31",
"fs.read_dir@34",
"fs.read_dir@37",
] {
let project = Project::cart("walk-inputs");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {said}");
assert!(said.contains("injected fault at fs"), "{fault}: {said}");
}
}
/// Asked to keep its work, a Python run copies its work directory beside
/// the store for diagnosis. Each step of that copy failing -- the directory
/// made, listed, one below it, an entry's type, a file copied -- ends the run
/// saying so; and a run with nothing failing keeps the copy.
#[test]
fn a_python_run_that_cannot_keep_its_work_says_so() {
let command = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
for entry in [
"fs.create_dir_all@6 => python_run.rs:569",
"fs.read_dir@6 => python_run.rs:112",
"fs.read_dir@7 => python_run.rs:112",
"fs.file_type@9 => python_run.rs:115",
"fs.create_dir_all@7 => python_run.rs:119",
"fs.copy@1 => python_run.rs:122",
"fs.read_dir entry#3 => python_run.rs:112",
] {
let (fault, place) = entry.split_once(" => ").unwrap_or((entry, ""));
let project = Project::empty("python-keep-work");
python_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(
&command,
&[("SUPERCOV_KEEP_WORK", "1"), ("SUPERCOV_TEST_FAULT", fault)],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
assert!(
stderr.contains("injected fault at fs") && !stderr.contains("panicked at"),
"{fault}: {stderr}"
);
}
let project = Project::empty("python-kept-work");
python_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov_with(&command, &[("SUPERCOV_KEEP_WORK", "1")])
.succeeds();
assert!(project.root.join(".supercov/python-debug").is_dir());
}
#[test]
fn a_go_run_whose_own_step_fails_says_so() {
let Some(go) = go() else {
return;
};
each_step_of_a_run_fails(
"own-step-go",
go_project,
&["--", go, "test", "./..."],
&[
"fs.canonicalize@1",
"fs.create_dir_all@8",
"fs.create_dir_all@9",
"fs.create_dir_all@10",
"fs.create_dir_all@11",
"fs.create_dir_all@12",
"fs.write@2",
"fs.write@3",
"fs.write@4",
"fs.write@5",
"fs.write@6",
"fs.write@7",
"fs.read_to_string@7",
"fs.read_to_string@8",
// The module walked and read: a directory, an entry, a source, go.mod.
"fs.read_dir@2",
"fs.file_type@1",
"fs.read@4",
"fs.read_to_string@3",
"fs.read_to_string@6",
// The lock and recovery, the inputs captured and digested, the
// copy recovered, its outputs before and after, the archive, the
// trash.
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.read@6",
"fs.open@1",
"fs.read_dir@3",
"fs.read_dir@9",
"fs.read_dir@13",
"fs.create_dir_all@15",
"fs.create_dir_all@24",
// The project's Go listed again as the run prepares it.
"fs.read_dir#go_project.rs:142@2 => go_project.rs:142",
// The harness a test package is given.
"fs.write#go_run.rs:527 => go_run.rs:527",
// The run's evidence archive.
"fs.create_dir_all#evidence_archive.rs:484 => evidence_archive.rs:484",
// The report the run built, refused as one Supercov got wrong.
"report-request",
"spawn",
],
);
// A source that is not UTF-8 is left unmeasured, and named.
let project = Project::empty("go-not-utf8");
go_project(&project);
std::fs::write(project.root.join("bytes.go"), [0xff, 0xfe, b'\n']).unwrap();
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", go, "test", "./..."]);
assert!(
ran.stderr().contains("bytes.go") && ran.stderr().contains("UTF-8"),
"{}",
ran.stderr()
);
}
#[test]
fn a_maven_run_whose_own_step_fails_says_so() {
if !std::process::Command::new("mvn")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
return;
}
each_step_of_a_run_fails(
"own-step-mvn",
small_maven_project,
&["--", "mvn", "-q", "test"],
&[
"fs.canonicalize@1",
"fs.read_dir@2",
"fs.write@3",
"fs.write@4",
"fs.write@5",
"fs.write@6",
"fs.write@7",
"fs.write@8",
"fs.read@10",
"fs.rename@10",
// The lock and recovery, the inputs captured and digested, the
// copy recovered, an instrumented source's directory, the
// evidence directory, the outputs before and after, the archive,
// the trash.
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.read@4",
"fs.open@1",
"fs.read_dir@10",
"fs.create_dir_all@14",
"fs.create_dir_all@13",
"fs.read_dir@28",
"fs.create_dir_all@20",
"fs.create_dir_all@22",
"fs.open@18",
// The report the run built, refused as one Supercov got wrong.
"report-request",
"spawn",
// The store of copies made, and the copy released after a run
// that passed.
"fs.create_dir_all#workspace.rs:445 => workspace.rs:445",
"copy-release",
],
);
}
#[cfg(unix)]
#[test]
fn a_ruby_run_whose_own_step_fails_says_so() {
let Some(ruby) = ruby() else {
return;
};
each_step_of_a_run_fails(
"own-step-rb",
ruby_project,
&["--", ruby.as_str(), "-Ilib", "test/w_test.rb"],
&[
"fs.canonicalize@1",
"fs.create_dir_all@3",
"fs.create_dir_all@4",
"fs.create_dir_all@5",
"fs.write@2",
"fs.write@7",
"fs.rename@1",
// The project walked and read; the evidence listed and read back.
"fs.read_dir@2",
"fs.file_type@1",
"fs.read@4",
"fs.read_dir@5",
"fs.symlink_metadata@11",
"fs.open@3",
// The lock and recovery, the inputs digested and captured, the
// archive's directory, the trash.
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.open@1",
"fs.read@7",
"fs.create_dir_all@6",
"fs.create_dir_all@14",
"fs.read_dir entry#1 => ruby_project.rs:106",
"fs.read_dir entry#2 => ruby_evidence.rs:343",
// The report the run built, refused as one Supercov got wrong.
"report-request",
"spawn",
],
);
}
/// A Ruby run asked to keep its work copies it for diagnosis: each step of
/// that copy failing ends the run saying so, and a run with nothing failing
/// keeps the copy.
#[cfg(unix)]
#[test]
fn a_ruby_run_that_cannot_keep_its_work_says_so() {
let Some(ruby) = ruby() else {
return;
};
let command = ["--", ruby.as_str(), "-Ilib", "test/w_test.rb"];
for entry in [
"fs.create_dir_all@5 => ruby_run.rs:335",
"fs.read_dir@5 => ruby_run.rs:98",
"fs.read_dir@6 => ruby_run.rs:98",
"fs.file_type@7 => ruby_run.rs:101",
"fs.create_dir_all@6 => ruby_run.rs:105",
"fs.copy@1 => ruby_run.rs:108",
"fs.read_dir entry#2 => ruby_run.rs:98",
] {
let (fault, place) = entry.split_once(" => ").unwrap_or((entry, ""));
let project = Project::empty("ruby-keep-work");
ruby_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(
&command,
&[("SUPERCOV_KEEP_WORK", "1"), ("SUPERCOV_TEST_FAULT", fault)],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
assert!(
stderr.contains("injected fault at fs") && !stderr.contains("panicked at"),
"{fault}: {stderr}"
);
}
let project = Project::empty("ruby-kept-work");
ruby_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov_with(&command, &[("SUPERCOV_KEEP_WORK", "1")])
.succeeds();
assert!(project.root.join(".supercov/ruby-debug").is_dir());
}
/// Each query refuses, with exit code 2 and the reason, when a read it makes
/// fails: each record of the run's index it reads, the run store's metadata,
/// listing and evidence, and the file a query writes. Each case names the
/// call: an index read by the place that makes it, a file operation by its
/// name and turn.
#[test]
fn each_query_refuses_when_a_read_or_write_it_makes_fails() {
// Measured twice, the first run's id read in between: a project in the
// same state for every case, so a fault names the same call each time.
let measured = |label: &str| {
let project = Project::cart(label);
project.supercov(&["--", "node", "--test"]).succeeds();
let first = project.supercov(&["runs", "latest", "--json"]).json()["data"]["run"]
.as_str()
.unwrap()
.to_owned();
project.supercov(&["--", "node", "--test"]).succeeds();
(project, first)
};
let (project, first) = measured("query-steps");
let cases: Vec<(Vec<&str>, &str)> = vec![
// The run's index, each record a query reads.
(vec!["runs", "latest"], "coverage-index-read#1"),
(vec!["runs", "latest"], "coverage-index-read#2"),
(vec!["runs", "latest"], "coverage-index-read#3"),
(vec!["runs", "latest"], "coverage-index-read#4"),
(vec!["runs", "latest"], "coverage-index-read#5"),
(vec!["runs", "latest"], "coverage-index-read#6"),
(vec!["runs", "latest", "scope"], "coverage-index-read#2"),
(vec!["runs", "latest", "gaps"], "coverage-index-read#1"),
(vec!["runs", "latest", "gaps"], "coverage-index-read#2"),
(
vec!["runs", "latest", "test", "total"],
"coverage-index-read#1",
),
(
vec!["runs", "latest", "test", "total"],
"coverage-index-read#2",
),
(
vec!["runs", "latest", "tests", "without-evidence"],
"coverage-index-read#1",
),
(
vec!["runs", "latest", "tests", "without-evidence"],
"coverage-index-read#2",
),
(
vec!["runs", "latest", "tests", "without-evidence"],
"coverage-index-read#3",
),
(
vec!["runs", "latest", "tests", "affected", "--title", "total"],
"coverage-index-read#1",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#1",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#2",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#3",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#4",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#5",
),
(
vec!["runs", "latest", "file", "src/cart.js"],
"coverage-index-read#6",
),
(vec!["diff", &first, "latest"], "coverage-index-read#1"),
(vec!["diff", &first, "latest"], "coverage-index-read#2"),
(vec!["diff", &first, "latest"], "coverage-index-read#3"),
(vec!["diff", &first, "latest"], "coverage-index-read#4"),
(vec!["diff", &first, "latest"], "coverage-index-read#5"),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "g.jsonl",
],
"coverage-index-read#3",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "g.jsonl",
],
"coverage-index-read#4",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "g.jsonl",
],
"coverage-index-read#5",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "g.jsonl",
],
"coverage-index-read#6",
),
// A report and an export: each record they read.
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#1",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#2",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#3",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#4",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#5",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#6",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#7",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#8",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#9",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"coverage-index-read#10",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"coverage-index-read#11",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"coverage-index-read#12",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"coverage-index-read#13",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"coverage-index-read#14",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#1",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#2",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#3",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#4",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#5",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#6",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#7",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#8",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "j.jsonl", "--json",
],
"coverage-index-read#9",
),
// The run store: its listing, a run's metadata and its evidence.
(vec!["runs"], "fs.symlink_metadata@1"),
(vec!["runs"], "fs.read_dir@1"),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"fs.symlink_metadata@2",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"fs.symlink_metadata@3",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"fs.symlink_metadata@4",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"fs.open@1",
),
(
vec![
"report",
"--no-open",
"--output",
"c.html",
"--compare",
&first,
],
"fs.read_to_end_from@1",
),
(
vec!["report", "--no-open", "--output", "w.html"],
"fs.write_all@1",
),
(
vec!["report", "--no-open", "--output", "w.html"],
"fs.sync_all@1",
),
// What a query writes: a report, a tracefile, an export.
(
vec!["report", "--no-open", "--output", "r.html"],
"fs.create_dir_all@1",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"fs.open_with@1",
),
(
vec!["report", "--no-open", "--output", "r.html"],
"fs.rename@1",
),
(
vec![
"runs", "latest", "report", "--format", "lcov", "--output", "f.info", "--force",
"--title", "total",
],
"fs.write@1",
),
(
vec![
"runs", "latest", "report", "--format", "lcov", "--output", "f.info", "--force",
"--title", "total",
],
"fs.rename@1",
),
(
vec![
"runs", "latest", "gaps", "--format", "jsonl", "--output", "g.jsonl",
],
"fs.write@1",
),
];
for (number, (command, fault)) in cases.into_iter().enumerate() {
// A file operation's turn depends on what earlier queries cached: a
// project of its own for each; an index read is counted by place.
let fresh;
let (project, first_id) = if fault.starts_with("fs.") {
fresh = measured(&format!("query-steps-{number}"));
(&fresh.0, fresh.1.as_str())
} else {
(&project, first.as_str())
};
let command = command
.iter()
.map(|part| if *part == first { first_id } else { part })
.collect::<Vec<_>>();
let ran = project.supercov_with(&command, &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 2, "{command:?} {fault}: {said}");
assert!(
said.contains("[supercov]") && !said.contains("panicked at"),
"{command:?} {fault}: {said}"
);
}
// A run whose index is gone builds it again from its evidence, hashed
// first, after the four files its integrity reads: that read failing
// refuses the query.
let (rebuilt, _) = measured("query-steps-rebuilt");
let run = rebuilt.latest();
std::fs::remove_file(
rebuilt
.root
.join(".supercov/runs")
.join(&run)
.join("query-index.v1.bin"),
)
.unwrap();
let ran = rebuilt.supercov_with(
&["runs", "latest"],
&[("SUPERCOV_TEST_FAULT", "fs.read_from@5")],
);
assert_eq!(ran.code(), 2, "{}", ran.stderr());
}
/// An import refuses, with exit code 2 and the reason, when a step it takes
/// fails: reading the tracefile, the project's lock, the evidence archived,
/// copied and hashed, and the run published and recorded. Each case on a
/// project measured the same way, so its fault names the same call.
#[cfg(unix)]
#[test]
fn an_import_whose_step_fails_says_so() {
for fault in [
"fs.read@1",
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.create_dir_all@3",
"fs.create_dir_all@4",
"fs.create_dir_all@5",
"fs.create_dir_all@6",
"fs.open_with@1",
"fs.open_with@2",
"fs.open_with@4",
"fs.open_with@5",
"fs.write@1",
"fs.symlink_metadata@8",
"fs.symlink_metadata@10",
"fs.open@5",
"fs.open@7",
"fs.open@8",
"fs.open@10",
"fs.rename@1",
"fs.rename@2",
"fs.rename@3",
"fs.rename@4",
// The store of runs listed, and the lock released after importing.
"fs.read_dir#run_store.rs:695",
"copy-release",
] {
let project = Project::cart("import-steps");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
project.supercov(&["--", "node", "--test"]).succeeds();
project.write(
"lcov.info",
"TN:\nSF:src/cart.js\nDA:2,1\nDA:3,0\nend_of_record\n",
);
let ran = project.supercov_with(
&["import", "lcov.info", "--test", "device"],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 2, "{fault}: {said}");
assert!(
said.contains("[supercov]") && !said.contains("panicked at"),
"{fault}: {said}"
);
}
}
/// The latest run's evidence archive, its entries changed by `change` and
/// written back as a store damaged on disk would hold it, with the length
/// its record names: a mismatched one is not listed at all.
fn rewrite_evidence(
project: &Project,
change: impl FnOnce(&mut Vec<supercov_engine::evidence_archive::EvidenceArchiveEntry>),
) {
use supercov_engine::evidence_archive::{read_archive, write_archive};
let listed = project.supercov(&["runs", "--limit", "1", "--json"]).json();
let run = listed["data"]["runs"][0]["id"].as_str().unwrap();
let archive = project
.root
.join(".supercov/runs")
.join(run)
.join("evidence.raw.gz");
let mut entries = read_archive(&archive).unwrap();
change(&mut entries);
let written = write_archive(entries, &archive).unwrap();
let record = format!(".supercov/runs/{run}/run.json");
let mut metadata: serde_json::Value = serde_json::from_str(&project.read(&record)).unwrap();
metadata["rawEvidence"]["compressedBytes"] = written.compressed_bytes.into();
project.write(&record, &metadata.to_string());
}
/// A run's source record read back for a query: absent, of another schema,
/// not a record, naming a file it cannot hold, or with statement exclusions
/// that are not a list. Each is refused, saying why.
#[test]
fn a_run_whose_source_record_cannot_be_read_back_is_refused() {
type Change = fn(&mut serde_json::Value);
let cases: [(Option<Change>, &str); 6] = [
(None, "This run has no source manifest"),
(
Some(|manifest| manifest["schemaVersion"] = 99.into()),
"Unsupported source manifest schema",
),
(
Some(|manifest| manifest["files"] = "none".into()),
"invalid type",
),
(
Some(|manifest| {
let files = manifest["files"].as_object_mut().unwrap();
let (_, file) = files.iter_mut().next().unwrap();
file["sha256"] = "short".into();
}),
"Invalid source manifest",
),
(Some(|_| {}), "invalid type"),
(Some(|_| {}), "EOF while parsing"),
];
for (number, (change, said)) in cases.into_iter().enumerate() {
let project = Project::cart("source-record");
project.supercov(&["--", "node", "--test"]).succeeds();
rewrite_evidence(&project, |entries| {
let at = entries
.iter()
.position(|entry| entry.path == "source-inputs.json")
.expect("the run keeps its source record");
match change {
None => {
entries.remove(at);
}
Some(change) => {
let mut manifest: serde_json::Value =
serde_json::from_slice(&entries[at].contents).unwrap();
change(&mut manifest);
entries[at].contents = serde_json::to_vec(&manifest).unwrap();
}
}
// The last two keep the record and garble its exclusions: not a
// list, then not JSON at all.
let exclusions: Option<&[u8]> = match number {
4 => Some(b"{}"),
5 => Some(b"{"),
_ => None,
};
if let Some(contents) = exclusions {
entries.retain(|entry| entry.path != "statement-exclusions.json");
entries.push(supercov_engine::evidence_archive::EvidenceArchiveEntry {
path: "statement-exclusions.json".into(),
contents: contents.to_vec(),
});
}
});
let ran = project.supercov(&["runs", "latest", "source", "src/cart.js"]);
assert_ne!(ran.code(), 0, "{said}: {}", ran.stderr());
assert!(ran.stderr().contains(said), "{said}: {}", ran.stderr());
// A line no obligation holds is read from the checkout, which with
// no record to compare against is taken as current.
if number == 0 {
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:10", "--json"])
.json();
assert_eq!(
line["data"]["sourceOrigin"], "working-tree-current",
"{line}"
);
}
}
// So is one of a file the record does not name.
let project = Project::cart("source-record-unnamed");
project.supercov(&["--", "node", "--test"]).succeeds();
rewrite_evidence(&project, |entries| {
let record = entries
.iter_mut()
.find(|entry| entry.path == "source-inputs.json")
.expect("the run keeps its source record");
let mut manifest: serde_json::Value = serde_json::from_slice(&record.contents).unwrap();
manifest["files"]
.as_object_mut()
.unwrap()
.remove("src/cart.js");
record.contents = serde_json::to_vec(&manifest).unwrap();
});
let line = project
.supercov(&["runs", "latest", "line", "src/cart.js:10", "--json"])
.json();
assert_eq!(
line["data"]["sourceOrigin"], "working-tree-current",
"{line}"
);
}
/// `tests affected` answers from what a run recorded. A run without its
/// per-test record, or without its source record, is refused, saying so;
/// a merged run is answered by its parts, and refused when it no longer
/// names them or one of them cannot answer.
#[test]
fn tests_affected_names_the_record_it_cannot_read() {
let affected = |project: &Project, run: &str| {
let ran = project.supercov(&["runs", run, "tests", "affected"]);
assert_ne!(ran.code(), 0, "{}", ran.stderr());
ran.stderr()
};
let project = Project::cart("affected-no-record");
let run = project.measure(&[]);
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&run)
.join("test-executions.json"),
)
.unwrap();
let said = affected(&project, &run);
assert!(said.contains("no per-test execution record"), "{said}");
let project = Project::cart("affected-no-sources");
let run = project.measure(&[]);
rewrite_evidence(&project, |entries| {
entries.retain(|entry| entry.path != "source-inputs.json");
});
let said = affected(&project, &run);
assert!(said.contains("no source manifest"), "{said}");
let merged = |label: &str| {
let project = Project::cart(label);
let first = project.measure(&["--test-name-pattern=total"]);
let second = project.measure(&["--test-name-pattern=shipping"]);
project.supercov(&["merge", &first, &second]).succeeds();
let listed = project.supercov(&["runs", "--limit", "1", "--json"]).json();
let merged = listed["data"]["runs"][0]["id"].as_str().unwrap().to_owned();
(project, first, merged)
};
let (project, first, run) = merged("affected-merge-part");
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&first)
.join("test-executions.json"),
)
.unwrap();
let said = affected(&project, &run);
assert!(said.contains("no per-test execution record"), "{said}");
let (project, _, run) = merged("affected-merge-unnamed");
let record = format!(".supercov/runs/{run}/run.json");
let mut metadata: serde_json::Value = serde_json::from_str(&project.read(&record)).unwrap();
metadata.as_object_mut().unwrap().remove("parents");
project.write(&record, &metadata.to_string());
let said = affected(&project, &run);
assert!(
said.contains("does not say which runs it was merged from"),
"{said}"
);
}
/// The workspace gets a git repository of its own, cloned from the
/// project's: its HEAD, branch or detached commit, remotes and their
/// branches, and an index. Each step of that failing leaves the workspace
/// without one and the run goes on; asked to, it says which step failed.
#[test]
fn a_workspace_whose_git_repository_cannot_be_made_runs_without_one() {
let on_branch = [
("git@1", "git clone --quiet --shared --bare"),
("git@2", "git config core.bare false"),
("git@4", "git symbolic-ref HEAD refs/heads/"),
("git@5", "git remote remove origin"),
("git@6", "git remote: injected fault at git"),
("git@7", "git config --get remote.origin.url"),
("git@8", "git remote add origin https://example.com/w.git"),
("git@9", "git fetch --quiet --no-tags"),
("git@10", "git read-tree HEAD"),
("fs.create_dir_all@8", "injected fault at fs"),
("fs.write@3", "injected fault at fs"),
];
let detached = [
("git@4", "git rev-parse HEAD"),
("git@5", "git update-ref --no-deref HEAD"),
// HEAD set, the next step failing.
("git@6", "git remote remove origin"),
];
for (detach, cases) in [(false, &on_branch[..]), (true, &detached[..])] {
for (fault, said) in cases {
let project = Project::cart("workspace-git");
project.git(&["remote", "add", "origin", "https://example.com/w.git"]);
if detach {
project.git(&["checkout", "-q", "--detach"]);
}
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", fault), ("SUPERCOV_DEBUG", "1")],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 0, "{fault}: {stderr}");
assert!(
stderr.contains(&format!(
"the workspace has no git repository of its own: {said}"
)),
"{fault}: {stderr}"
);
}
}
}
/// What a test writes in the copy is brought back to the project: a file
/// that names the copy written naming the project, others copied, each into
/// its directory. A step of that failing -- the copy walked, a directory
/// below it, a written file read, the destination made, written or copied --
/// ends the run, naming the file.
#[cfg(unix)]
#[test]
fn a_run_that_cannot_bring_back_what_its_tests_wrote_says_so() {
for (fault, said) in [
("fs.read_dir@54", "workspaces"),
("fs.read_dir@55", "/out"),
("fs.read#workspace.rs:1646", "workspaces"),
("fs.create_dir_all@18", "/out: injected fault at fs"),
("fs.write@5", "out/note.txt"),
("fs.copy@6", "out/data.bin"),
] {
let project = Project::cart("outputs-back");
project.write(
"test/outputs.test.js",
"import test from \"node:test\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\ntest(\"writes its outputs\", () => {\n mkdirSync(\"out/deeper\", { recursive: true });\n writeFileSync(\"out/note.txt\", `ran in ${process.cwd()}\\n`);\n writeFileSync(\"out/data.bin\", Buffer.from([0, 1, 2]));\n writeFileSync(\"out/deeper/more.txt\", \"more\\n\");\n});\n",
);
project.write(".gitignore", "out/\n");
project.commit("outputs");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(
stderr.contains(said) && stderr.contains("injected fault at fs"),
"{fault}: {stderr}"
);
}
}
/// The copy's dependencies: the project's `node_modules` linked package by
/// package, a scope's packages each, the tools in `.bin`, and a workspace
/// package's own `node_modules` -- hard-linked where the system can, linked
/// one package at a time where it cannot. A step of that failing
/// ends the run, naming where.
#[cfg(unix)]
#[test]
fn a_run_whose_dependencies_cannot_be_linked_into_the_copy_says_so() {
let linked = [
// A listing's first entry unreadable: the copy's tree, the
// project's dependencies, their tools, a scope, the outputs.
(
"fs.read_dir entry#6",
"injected fault at fs",
"workspace.rs:706",
),
(
"fs.read_dir entry#9",
"injected fault at fs",
"workspace.rs:1053",
),
(
"fs.read_dir entry#10",
"injected fault at fs",
"workspace.rs:990",
),
(
"fs.read_dir entry#11",
"injected fault at fs",
"workspace.rs:937",
),
(
"fs.read_dir entry#15",
"injected fault at fs",
"workspace.rs:1358",
),
("fs.read_dir@53", "injected fault at fs", "workspace.rs:706"),
(
"fs.read_dir@62",
"/node_modules: injected",
"workspace.rs:1053",
),
(
"fs.read_dir@63",
"node_modules/.bin: injected",
"workspace.rs:990",
),
(
"fs.read_dir@64",
"node_modules/@scope: injected",
"workspace.rs:937",
),
("fs.create_dir_all@4", "staging", "workspace.rs:705"),
(
"fs.create_dir_all@9",
"/node_modules: injected",
"workspace.rs:1052",
),
(
"fs.create_dir_all@10",
"node_modules/.bin: injected",
"workspace.rs:987",
),
(
"fs.create_dir_all@11",
"node_modules/@scope: injected",
"workspace.rs:936",
),
];
let unlinkable = [
(
"fs.read_dir entry#8",
"injected fault at fs",
"workspace.rs:769",
),
(
"fs.read_dir@58",
"packages/web/node_modules: injected",
"workspace.rs:769",
),
(
"fs.read_dir@59",
"packages/web/node_modules/.bin: injected",
"workspace.rs:990",
),
(
"fs.create_dir_all@7",
"packages/web/node_modules: injected",
"workspace.rs:768",
),
(
"fs.create_dir_all@8",
"packages/web/node_modules/.bin: injected",
"workspace.rs:987",
),
(
"fs.symlink@1",
"packages/web/node_modules/.bin/webtool",
"workspace.rs:1009",
),
(
"fs.symlink@2",
"packages/web/node_modules/dep",
"workspace.rs:780",
),
(
"fs.symlink@3",
"node_modules/.bin/tool",
"workspace.rs:1009",
),
(
"fs.symlink@4",
"node_modules/@scope/pkg",
"workspace.rs:972",
),
("fs.symlink@5", "node_modules/plain", "workspace.rs:972"),
];
// A directory is never cloned, so every system links the same way:
// hard links where it can, one link per package where it cannot.
for (prefix, cases) in [
("directory-clone,", &linked[..]),
("directory-clone,fs.hard_link,", &unlinkable[..]),
] {
for (fault, said, place) in cases {
let project = Project::cart("dependencies-linked");
project.write(
"node_modules/@scope/pkg/package.json",
"{\"name\":\"@scope/pkg\"}\n",
);
project.write("node_modules/@scope/pkg/index.js", "export default 1;\n");
project.write("node_modules/plain/index.js", "module.exports = 1;\n");
project.write_script("node_modules/.bin/tool", "#!/bin/sh\necho tool\n");
project.write(
"packages/web/package.json",
"{\"name\":\"web\",\"private\":true}\n",
);
project.write(
"packages/web/node_modules/dep/index.js",
"module.exports = 2;\n",
);
project.write_script(
"packages/web/node_modules/.bin/webtool",
"#!/bin/sh\necho web\n",
);
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("dependencies");
let faults = format!("{prefix}{fault}");
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", &faults)],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{faults}: {stderr}");
assert!(
stderr.contains(said) && stderr.contains("injected fault at fs"),
"{faults}: {stderr}"
);
assert!(fired_at(&stderr, place), "{faults} at {place}: {stderr}");
}
}
}
/// A run of an unchanged project reuses what the last one instrumented: a
/// new copy is made beside the old, the instrumented files are carried into
/// it, and the old copy goes to the trash. A step of that failing ends the
/// run, and the next run is a clean one.
#[test]
fn a_run_that_cannot_reuse_the_last_copy_says_so() {
for entry in [
"fs.canonicalize@10 => workspace.rs:1286",
"fs.create_dir_all@6 => workspace.rs:1301",
"fs.copy@1 => workspace.rs:551",
"fs.rename@1 => workspace.rs:562",
"fs.rename@3 => workspace.rs:1320",
"fs.create_dir_all@10 => workspace.rs:1320",
] {
let (fault, place) = entry.split_once(" => ").unwrap_or((entry, ""));
let project = Project::cart("reuse-copy");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
project.supercov(&["--", "node", "--test"]).succeeds();
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
assert!(stderr.contains("injected fault at fs"), "{fault}: {stderr}");
project.supercov(&["--", "node", "--test"]).succeeds();
}
}
/// A JavaScript run's own records -- the abandoned runs recovered, the run's
/// state at each phase, the runtime's settings, the parent-death watchdog,
/// the evidence gathered and archived, the trash, the publication -- each
/// failing ends the run and names what failed, and the next run is clean.
#[cfg(unix)]
#[test]
fn a_javascript_run_whose_record_step_fails_says_so() {
// Each by its place: counted, a step's number moved with the platform
// and with the query index, which is written beside the publication.
for fault in [
"fs.create_dir_all#lifecycle.rs:1434",
"fs.create_dir_all#javascript_run.rs:764",
"fs.write#javascript_run.rs:1116",
"fs.canonicalize#process_supervision.rs:1889",
"fs.create_dir_all#javascript_run.rs:1199",
"fs.create_dir_all#javascript_run.rs:1398",
"fs.read_dir#evidence_archive.rs:263",
"fs.create_dir_all#evidence_archive.rs:484",
"fs.create_dir_all#javascript_run.rs:1677",
"fs.create_dir_all#javascript_run.rs:1679",
"fs.create_dir_all#lifecycle.rs:1038",
"fs.create_dir_all#javascript_run.rs:1780",
"fs.create_dir_all#javascript_run.rs:1782",
] {
let project = Project::cart("js-records");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(
stderr.contains("injected fault at fs") && !stderr.contains("panicked at"),
"{fault}: {stderr}"
);
project.supercov(&["--", "node", "--test"]).succeeds();
}
}
/// An HTML export shows each file's source beside its coverage, read from
/// the checkout: a file that cannot be read is shown without it, and the
/// export is still written. A run store that cannot be listed is refused.
/// A run recorded before runs kept their source scope still has its HTML
/// report, with no scope to show.
#[test]
fn an_html_export_of_a_run_without_a_source_scope_shows_none() {
use supercov_engine::evidence_archive::{read_archive, write_archive};
let project = Project::cart("export-unscoped");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
let run = project.supercov(&["runs", "--json"]).json()["data"]["runs"][0]["id"]
.as_str()
.unwrap()
.to_owned();
let directory = project.root.join(".supercov/runs").join(&run);
let mut entries = read_archive(&directory.join("evidence.raw.gz")).unwrap();
let manifest = entries
.iter_mut()
.find(|entry| entry.path == "manifest.json")
.expect("the run keeps its manifest");
let mut value: serde_json::Value = serde_json::from_slice(&manifest.contents).unwrap();
value.as_object_mut().unwrap().remove("scope");
manifest.contents = serde_json::to_vec(&value).unwrap();
let written = write_archive(entries, &directory.join("evidence.raw.gz")).unwrap();
let record = format!(".supercov/runs/{run}/run.json");
let mut metadata: serde_json::Value = serde_json::from_str(&project.read(&record)).unwrap();
metadata["rawEvidence"]["compressedBytes"] = written.compressed_bytes.into();
metadata["rawEvidence"]["uncompressedBytes"] = written.uncompressed_bytes.into();
metadata["rawEvidence"]["files"] = written.files.into();
project.write(&record, &metadata.to_string());
project
.supercov(&["report", "--no-open", "--output", "out/r.html"])
.succeeds();
let data = report_data(&project.read("out/r.html"));
assert!(data["runs"][0]["scope"].is_null(), "{}", data["runs"][0]);
}
#[test]
fn an_html_export_leaves_out_a_source_it_cannot_read() {
let project = Project::cart("export-unreadable");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
let export = |output: &str, fault: &str| {
project
.supercov_with(
&[
"runs", "latest", "report", "--format", "html", "--output", output,
],
&[("SUPERCOV_TEST_FAULT", fault)],
)
.succeeds();
project.read(output)
};
// `item.name` is a line of src/cart.js.
assert!(!export("unread.html", "fs.read_to_string@4").contains("item.name"));
assert!(export("read.html", "").contains("item.name"));
let refused = project
.supercov_with(
&[
"runs",
"latest",
"report",
"--format",
"html",
"--output",
"none.html",
],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir@1")],
)
.exits(2);
assert!(refused.contains("injected fault at fs"), "{refused}");
}
/// A stored query refuses when it cannot list the runs, rebuild the index of
/// the run it reads or of the newer run a diff compares, analyse the run a
/// minimisation reads, or read the index while answering.
#[test]
fn a_stored_query_that_cannot_read_its_runs_is_refused() {
let project = Project::cart("stored-query-reads");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
let older = project.supercov(&["runs", "latest", "--json"]).json()["data"]["run"]
.as_str()
.unwrap()
.to_owned();
project.supercov(&["--", "node", "--test"]).succeeds();
let newer = project.supercov(&["runs", "latest", "--json"]).json()["data"]["run"]
.as_str()
.unwrap()
.to_owned();
let input = project.root.join("query.json");
let ask = |command: &str, compared: Option<&str>, fault: &str, unindexed: bool| {
if unindexed {
for run in [&older, &newer] {
let _ = std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(run.as_str())
.join("query-index.v1.bin"),
);
}
}
let request = serde_json::json!({
"root": project.root,
"query": {"runId": older, "filter": "passed", "command": command, "target": 20.0},
"newerRunId": compared,
});
std::fs::write(&input, request.to_string()).unwrap();
project
.supercov_with(
&["__query-stored-run"],
&[
("SUPERCOV_INTERNAL_INPUT_FILE", input.to_str().unwrap()),
("SUPERCOV_TEST_FAULT", fault),
],
)
.exits(2)
};
for (command, compared, fault, unindexed) in [
("summary", None, "fs.read_dir@1", false),
("minimize", None, "fs.open@7", false),
("diff", Some(newer.as_str()), "fs.open@5", true),
("diff", Some(newer.as_str()), "fs.open@8", true),
("diff", Some(newer.as_str()), "coverage-index-read#1", false),
] {
let refused = ask(command, compared, fault, unindexed);
assert!(
refused.contains("stored query failed"),
"{command} {fault}: {refused}"
);
}
}
/// What a JavaScript run writes into its copy before the command starts --
/// the runtime's types, the Playwright adapter, the Playwright and Vitest
/// configurations, Vitest's commands, an authored test kept and its
/// instrumented form, the authored-source map, the statement exclusions, the
/// manifest, the completion mark, a cached artifact -- each failing ends the
/// run naming the file, and the next run is clean.
#[cfg(unix)]
#[test]
fn a_javascript_run_that_cannot_write_its_copy_says_so() {
for (fault, file) in [
("fs.rename@44", "runtime.d.mts"),
("fs.rename@45", "playwright.mjs"),
("fs.rename@47", "playwright.config.mjs"),
("fs.rename@48", "vitest.config.mjs"),
("fs.rename@51", "vitestCommands.mjs"),
("fs.create_dir_all@12", ".authored/test"),
("fs.rename@53", "test/cart.test.js"),
("fs.rename@54", "authored-sources.json"),
("fs.rename@55", "statement-exclusions.json"),
("fs.rename@56", "mutants.json"),
("fs.rename@57", "manifest.json"),
("fs.rename@58", "instrumentation-complete"),
("fs.rename@59", "injected fault at fs"),
] {
let project = Project::cart("js-copy-writes");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(
stderr.contains(file) && stderr.contains("injected fault at fs"),
"{fault}: {stderr}"
);
project.supercov(&["--", "node", "--test"]).succeeds();
}
}
/// A command started in a directory removed since cannot say where it is:
/// each refuses, saying so, rather than reading some other project.
#[cfg(unix)]
#[test]
fn a_command_whose_directory_was_removed_is_refused() {
let project = Project::empty("removed-directory");
for args in [
"runs latest report --format lcov",
"runs latest check",
"runs latest gaps --format jsonl",
"runs latest tests affected",
"runs latest source src/cart.js",
"runs latest assertions",
] {
let ran = std::process::Command::new("sh")
.arg("-c")
.arg(format!(
"mkdir gone && cd gone && rmdir ../gone && exec '{}' {args}",
env!("CARGO_BIN_EXE_supercov")
))
.current_dir(&project.root)
.output()
.unwrap();
let said = format!(
"{}{}",
String::from_utf8_lossy(&ran.stdout),
String::from_utf8_lossy(&ran.stderr)
);
assert_eq!(ran.status.code(), Some(2), "{args}: {said}");
assert!(said.contains("No such file or directory"), "{args}: {said}");
}
}
/// The gaps export reads every file's detail from one opening of the run's
/// index, after the gaps themselves: that index failing to open, or a read
/// of it failing, refuses the export.
#[test]
fn a_gaps_export_that_cannot_read_file_details_is_refused() {
let project = Project::cart("gaps-export-details");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
for fault in [
"coverage-index@4",
"coverage-index-read#3",
// The index opened again for the details, and rebuilt from evidence
// that cannot be read.
"fs.open#query_index.rs:354@2,fs.open#query_index.rs:354@3,fs.read_from#evidence_archive.rs:677",
// The runs listed again for the details.
"fs.read_dir#run_store.rs:695@2",
] {
let refused = project
.supercov_with(
&["runs", "latest", "gaps", "--format", "jsonl"],
&[("SUPERCOV_TEST_FAULT", fault)],
)
.exits(2);
assert!(refused.contains("[supercov]"), "{fault}: {refused}");
// The index read the file details make first.
if fault.starts_with("coverage-index-read") {
assert!(
refused.contains("coverage_query.rs:2301"),
"{fault}: {refused}"
);
}
}
}
/// The report carries each file's source from the checkout: one whose path
/// cannot be resolved, or that cannot be read, is left out and listed as
/// such. A run index that cannot be read refuses the report, and so does a
/// report file that cannot be written beside where it goes.
#[test]
fn the_report_leaves_out_a_source_it_cannot_read() {
let project = Project::cart("report-sources");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
for (fault, output, place) in [
("fs.canonicalize@2", "unresolved.html", "html_report.rs:388"),
("fs.read_to_string@6", "unread.html", "html_report.rs:423"),
(
"fs.metadata#html_report.rs:410",
"unsized.html",
"html_report.rs:410",
),
] {
let ran = project.supercov_with(
&["report", "--no-open", "--output", output],
&[("SUPERCOV_TEST_FAULT", fault)],
);
assert!(
fired_at(&ran.stderr(), place),
"{fault} at {place}: {}",
ran.stderr()
);
ran.succeeds();
let data = report_data(&project.read(output)).to_string();
assert!(
data.contains(r#""omittedSources":["src/cart.js"]"#),
"{fault}: {data}"
);
}
// Spans not kept at publication are read from the evidence, and
// evidence that cannot be read leaves them out.
let spanless = project.supercov_with(
&["report", "--no-open", "--output", "spanless.html"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.read#run_store.rs:1370,fs.read_from#evidence_archive.rs:677",
)],
);
assert!(
fired_at(&spanless.stderr(), "evidence_archive.rs:677"),
"{}",
spanless.stderr()
);
spanless.succeeds();
let data = report_data(&project.read("spanless.html"));
assert_eq!(
data["runs"][0]["statementSpans"],
serde_json::json!([]),
"{data}"
);
let refused = project
.supercov_with(
&["report", "--no-open", "--output", "unindexed.html"],
&[("SUPERCOV_TEST_FAULT", "coverage-index@2")],
)
.exits(2);
assert!(refused.contains("could not read run"), "{refused}");
// Every name taken: the system's "already exists", by its number there.
let exists = if cfg!(windows) { 80 } else { 17 };
let crowded = project
.supercov_with(
&["report", "--no-open", "--output", "crowded.html"],
&[("SUPERCOV_TEST_FAULT", &format!("fs.open_with:{exists}"))],
)
.exits(2);
assert!(
crowded.contains("could not allocate a temporary file"),
"{crowded}"
);
}
/// A line asked for under a kind no test has is refused as such; a line
/// query, and a test looked for under a kind, refuse when the index read
/// they make fails.
#[test]
fn line_and_test_queries_refuse_what_they_cannot_read() {
let project = Project::cart("line-test-reads");
project.write(".gitignore", "out/\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
project.supercov(&["--", "node", "--test"]).succeeds();
let empty = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:3",
"--kind",
"nope",
"--json",
])
.exits(2);
assert!(empty.contains("TEST_FILTER_EMPTY"), "{empty}");
for (args, fault) in [
(&["line", "src/cart.js:3"][..], "coverage-index-read#14"),
(
&["test", "nosuch", "--kind", "unit"][..],
"coverage-index-read#3",
),
] {
let mut asked = vec!["runs", "latest"];
asked.extend(args);
asked.push("--json");
let refused = project
.supercov_with(&asked, &[("SUPERCOV_TEST_FAULT", fault)])
.exits(2);
assert!(refused.contains("\"ok\":false"), "{args:?}: {refused}");
}
}
/// A browser suite beside servers in other languages prepares each before
/// the suite starts: its runtime and evidence directories, its runtime, its
/// plan. Each step failing ends the run, and says where.
#[test]
fn a_browser_suite_whose_servers_cannot_be_prepared_says_so() {
for (fault, place) in [
("fs.create_dir_all#python_run.rs:711", "python_run.rs:711"),
("fs.create_dir_all#python_run.rs:712", "python_run.rs:712"),
("fs.create_dir_all#ruby_run.rs:515", "ruby_run.rs:515"),
("fs.create_dir_all#ruby_run.rs:516", "ruby_run.rs:516"),
("fs.create_dir_all#go_run.rs:324", "go_run.rs:324"),
("fs.create_dir_all#go_run.rs:374", "go_run.rs:374"),
("fs.create_dir_all#go_run.rs:413", "go_run.rs:413"),
] {
let project = Project::cart("browser-servers");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write("server/app.py", "def hello():\n return 1\n");
project.write("web/app.rb", "def hello = 1\n");
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write("main.go", "package w\n\nfunc Hello() int { return 1 }\n");
project.commit("servers");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
}
}
/// A browser suite beside a Go server prepares the server in the copy: the
/// project found and its sources captured and digested, the file that
/// serves a main package's evidence written, its evidence directory made.
/// Each step failing ends the run, and says where.
#[test]
fn a_browser_suite_whose_go_server_cannot_be_prepared_says_so() {
if go().is_none() {
return;
}
for (fault, place) in [
("fs.read_dir#go_project.rs:142", "go_project.rs:142"),
(
"fs.canonicalize#source_capture.rs:25@2",
"source_capture.rs:25",
),
("fs.open#integrity.rs:427@4", "integrity.rs:427"),
("fs.write#go_run.rs:1233", "go_run.rs:1233"),
("fs.create_dir_all#go_run.rs:1243", "go_run.rs:1243"),
] {
let project = Project::cart("browser-go");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write(
"main.go",
"package main\n\nfunc hello() int { return 1 }\n\nfunc main() { hello() }\n",
);
project.commit("go");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
}
}
/// A browser suite beside a Java server prepares the server in the copy:
/// the project found and its sources captured and digested, the copy's
/// project read, its instrumented sources, their directories, its evidence
/// directory. Each step failing ends the run, and says where.
#[test]
fn a_browser_suite_whose_java_server_cannot_be_prepared_says_so() {
for (fault, place) in [
// The project's tree walked, then the copy's: the seventh listing.
("fs.read_dir#jvm_project.rs:281", "jvm_project.rs:281"),
("fs.read_dir#jvm_project.rs:281@7", "jvm_project.rs:281"),
(
"fs.canonicalize#source_capture.rs:25@2",
"source_capture.rs:25",
),
("fs.open#integrity.rs:427@4", "integrity.rs:427"),
("fs.create_dir_all#jvm_run.rs:2490", "jvm_run.rs:2490"),
("fs.create_dir_all#jvm_run.rs:2506", "jvm_run.rs:2506"),
("fs.create_dir_all#jvm_run.rs:2516", "jvm_run.rs:2516"),
("fs.write#jvm_run.rs:2490", "jvm_run.rs:2490"),
("fs.write#jvm_run.rs:2506", "jvm_run.rs:2506"),
] {
let project = Project::cart("browser-java");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write(
"pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>e</groupId><artifactId>w</artifactId><version>1</version></project>\n",
);
project.write(
"src/main/java/w/W.java",
"package w;\npublic class W { public static int one() { return 1; } }\n",
);
project.commit("java");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
}
}
/// A second run reuses the first's instrumented frontend from its cache: a
/// cached file or the cached manifest that cannot be read, or a cached
/// path that cannot be looked at as the copy takes it over, ends the run,
/// naming where.
#[test]
fn a_cached_frontend_that_cannot_be_read_ends_the_run() {
for (fault, place) in [
(
"fs.read#javascript_frontend.rs:363",
"javascript_frontend.rs:363",
),
(
"fs.read#javascript_frontend.rs:375",
"javascript_frontend.rs:375",
),
("fs.symlink_metadata#workspace.rs:1284", "workspace.rs:1284"),
] {
let project = Project::cart("frontend-cache-unread");
project.supercov(&["--", "node", "--test"]).succeeds();
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_ne!(ran.code(), 0, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault}: {stderr}");
project.supercov(&["--", "node", "--test"]).succeeds();
}
}
/// A test file the run cannot read to mark its assertions is run as it is:
/// the run goes on, and its assertions are not attributed.
#[test]
fn a_test_file_whose_assertions_cannot_be_read_runs_unattributed() {
let project = Project::cart("assertions-unread");
let read = project.supercov(&["--", "node", "--test"]).exits(0);
assert!(
read.contains("attributed 3 native node:assert call(s)"),
"{read}"
);
let project = Project::cart("assertions-unread-fault");
let ran = project.supercov_with(
&["--", "node", "--test"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.read_to_string#javascript_frontend.rs:1839@2",
)],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 0, "{stderr}");
assert!(fired_at(&stderr, "javascript_frontend.rs:1839"), "{stderr}");
assert!(!stderr.contains("attributed 3"), "{stderr}");
}
/// A JavaScript run whose diagnostics cannot be written once its command is
/// set up -- the line naming the copy it runs in, the line before the
/// tests start -- ends the run rather than going on unseen.
#[test]
fn a_javascript_run_that_cannot_write_its_diagnostics_says_so() {
for fault in ["diagnostics@2", "diagnostics@3"] {
let project = Project::cart("js-diagnostics");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, "diagnostics"), "{fault}: {stderr}");
}
}
/// A browser suite beside a Python server reads the server's project before
/// the suite starts: its sources, digested and captured, and the plan the
/// server's probes are given. Each failing ends the run, naming the file.
#[test]
fn a_browser_suite_whose_python_server_cannot_read_its_project_says_so() {
for (fault, place, file) in [
(
"fs.read#python_project.rs:269@1",
"python_project.rs:269",
"server/app.py",
),
(
"fs.open#integrity.rs:427@4",
"integrity.rs:427",
"server/app.py",
),
(
"fs.read#source_capture.rs:54@5",
"source_capture.rs:54",
"server/app.py",
),
(
"fs.write#python_run.rs:718@1",
"python_run.rs:718",
"plan.json",
),
] {
let project = Project::cart("browser-python");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write("server/app.py", "def hello():\n return 1\n");
project.commit("server");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
assert!(stderr.contains(file), "{fault}: {stderr}");
}
}
/// A browser suite beside a Ruby server reads the server's project and writes
/// its runtime and plan before the suite starts: each failing ends the run,
/// naming the file.
#[test]
fn a_browser_suite_whose_ruby_server_cannot_read_its_project_says_so() {
for (fault, place, file) in [
(
"fs.read#ruby_project.rs:233@1",
"ruby_project.rs:233",
"web/app.rb",
),
(
"fs.open#integrity.rs:427@4",
"integrity.rs:427",
"web/app.rb",
),
(
"fs.read#source_capture.rs:54@5",
"source_capture.rs:54",
"web/app.rb",
),
(
"fs.write#ruby_run.rs:93@1",
"ruby_run.rs:93",
"supercov_runtime.rb",
),
("fs.write#ruby_run.rs:520@1", "ruby_run.rs:520", "plan.rb"),
] {
let project = Project::cart("browser-ruby");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write("web/app.rb", "def hello = 1\n");
project.commit("server");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
assert!(stderr.contains(file), "{fault}: {stderr}");
}
}
/// Supercov forwards the user's signals to the command and waits on it: a
/// run, and the supervisor alone, that cannot install the forwarding or wait
/// for the command end, saying which.
#[cfg(unix)]
#[test]
fn a_run_that_cannot_forward_signals_or_wait_for_its_command_says_so() {
for (fault, said) in [
("signal-install", "could not install signal forwarding"),
("child-wait", "could not wait for test command"),
] {
let project = Project::cart("supervision-steps");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
assert_eq!(ran.code(), 1, "{fault}: {}", ran.stderr());
assert!(ran.stderr().contains(said), "{fault}: {}", ran.stderr());
let supervised = project.supercov_with(
&["__supervise", "--", "sh", "-c", "exit 0"],
&[("SUPERCOV_TEST_FAULT", fault)],
);
assert_eq!(supervised.code(), 1, "{fault}: {}", supervised.stderr());
assert!(
supervised.stderr().contains(said),
"{fault}: {}",
supervised.stderr()
);
}
}
/// An import refuses a run whose stored record it cannot read: its manifest,
/// frontend declaration or source record garbled on disk. And a file the
/// evidence names that the project does not have is skipped and named.
#[test]
fn an_import_reads_what_the_run_stored() {
for (entry, said) in [
("manifest.json", "its manifest is invalid"),
("frontend.json", "its frontend declaration is invalid"),
("source-inputs.json", "its source record is invalid"),
] {
let project = Project::cart("import-stored");
project.supercov(&["--", "node", "--test"]).succeeds();
rewrite_evidence(&project, |entries| {
let stored = entries.iter_mut().find(|stored| stored.path == entry);
stored.expect("the run keeps the entry").contents = b"{".to_vec();
});
project.write("lcov.info", "TN:\nSF:src/cart.js\nDA:2,1\nend_of_record\n");
let ran = project.supercov(&["import", "lcov.info", "--test", "device"]);
assert_eq!(ran.code(), 2, "{entry}: {}", ran.stderr());
assert!(ran.stderr().contains(said), "{entry}: {}", ran.stderr());
}
let project = Project::cart("import-absent-file");
project.supercov(&["--", "node", "--test"]).succeeds();
project.write(
"lcov.info",
"TN:\nSF:src/cart.js\nDA:2,1\nend_of_record\nSF:src/gone.js\nDA:1,1\nend_of_record\n",
);
let ran = project.supercov(&["import", "lcov.info", "--test", "device"]);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
assert!(
ran.stderr().contains("src/gone.js")
&& ran.stderr().contains("no such file in the project"),
"{}",
ran.stderr()
);
}
/// A merge refuses, with exit code 2 and the reason, when a step it takes
/// fails: the run store listed and read, the project's lock, the merged
/// evidence archived and published, and the merged run recorded. Each case
/// on a project measured the same way: the whole suite, then each of two
/// test files on its own.
#[test]
fn a_merge_whose_step_fails_says_so() {
for fault in [
"fs.symlink_metadata@1",
"fs.read_dir@1",
"fs.create_dir_all@1",
"fs.create_dir_all@2",
"fs.create_dir_all@3",
"fs.create_dir_all@4",
"fs.create_dir_all@5",
"fs.create_dir_all@6",
"fs.open_with@1",
"fs.open_with@2",
"fs.open_with@4",
"fs.open_with@5",
"fs.write@1",
"fs.rename@1",
"fs.rename@2",
"fs.rename@3",
"fs.rename@4",
] {
let project = Project::cart("merge-steps");
project.supercov(&["--", "node", "--test"]).succeeds();
project.supercov(&["runs", "latest", "--json"]).succeeds();
project.supercov(&["--", "node", "--test"]).succeeds();
project.write(
"test/more.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { describe } from \"../src/cart.js\";\ntest(\"describe names\", () => assert.equal(describe([{ name: \"a\" }]), \"a\"));\n",
);
project.commit("more");
project
.supercov(&["--", "node", "--test", "test/cart.test.js"])
.succeeds();
project
.supercov(&["--", "node", "--test", "test/more.test.js"])
.succeeds();
let ran = project.supercov_with(&["merge"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 2, "{fault}: {said}");
assert!(
said.contains("[supercov]") && !said.contains("panicked at"),
"{fault}: {said}"
);
}
// A run the store cannot read its record of is named, with why.
let project = Project::cart("merge-unreadable-run");
let first = project.measure(&["--test-name-pattern=total"]);
let second = project.measure(&["--test-name-pattern=shipping"]);
project.write(&format!(".supercov/runs/{first}/run.json"), "{");
let refused = project.supercov(&["merge", &first, &second]).exits(2);
assert!(
refused.contains(&format!("Cannot merge coverage run {first}: ")),
"{refused}"
);
}
/// The report carries a run's scope where the run has one -- measured under
/// given source roots -- and refuses when reading that scope fails; it reads
/// a run published before statement spans were kept by analysing it again;
/// and it refuses a comparison run that does not exist.
#[test]
fn the_report_reads_what_each_run_kept() {
let project = Project::cart("report-kept");
project
.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_SOURCE_ROOTS", "src")],
)
.succeeds();
project
.supercov(&["report", "--no-open", "--output", "scoped.html"])
.succeeds();
let data = report_data(&std::fs::read_to_string(project.root.join("scoped.html")).unwrap());
assert!(data["runs"][0]["scope"].is_object(), "{}", data["runs"][0]);
// The scope is the last record the report reads from the index.
let refused = project.supercov_with(
&["report", "--no-open", "--output", "unread.html"],
&[("SUPERCOV_TEST_FAULT", "coverage-index-read#16")],
);
assert_eq!(refused.code(), 2, "{}", refused.stderr());
assert!(
refused.stderr().contains("could not read scope"),
"{}",
refused.stderr()
);
// Spans written before this version kept them are worked out again.
let run = project.latest();
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&run)
.join("statement-spans.json"),
)
.unwrap();
project
.supercov(&["report", "--no-open", "--output", "again.html"])
.succeeds();
let unknown = project.supercov(&["report", "--no-open", "--compare", "run_missing"]);
assert_eq!(unknown.code(), 2, "{}", unknown.stderr());
}
/// A run that succeeds and then cannot release its copy: each language
/// says so and fails, or, where it gives the lock up when it ends
/// (JavaScript), still answers; none panics. A sweep failing every place in
/// one run fails the release only after something that already ended it.
#[test]
fn a_run_that_cannot_release_its_copy_says_so() {
let python = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
// A label, the project, its command, and whether the run fails.
type ReleaseRun<'a> = (&'a str, fn(&Project), Vec<&'a str>, bool);
let mut runs: Vec<ReleaseRun> = vec![
(
"release-rs",
small_crate,
vec!["--", "cargo", "test", "-q"],
true,
),
(
"release-js",
javascript_project,
vec!["--", "node", "--test"],
false,
),
("release-py", python_project, python.to_vec(), true),
];
let go = go();
if let Some(go) = go {
runs.push((
"release-go",
go_project,
vec!["--", go, "test", "./..."],
true,
));
}
#[cfg(unix)]
let ruby = ruby();
#[cfg(unix)]
if let Some(ruby) = &ruby {
runs.push((
"release-rb",
ruby_project,
vec!["--", ruby.as_str(), "-Ilib", "test/w_test.rb"],
true,
));
}
for (label, write, command, fails) in runs {
let project = Project::empty(label);
write(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(&command, &[("SUPERCOV_TEST_FAULT", "copy-release")]);
let said = ran.stderr();
assert!(!said.contains("panicked at"), "{label}: {said}");
assert!(
said.contains("test fault at copy-release"),
"{label}: {said}"
);
assert_eq!(ran.code() != 0, fails, "{label}: {said}");
}
}
/// A run whose standard error stops being read after its first line --
/// `supercov -- npm test 2>&1 | head -1` -- goes on without it and never
/// panics. The command's own tools write there too, and may fail for it as
/// they would without Supercov: Cargo's 101 is then the command's, and the
/// run is still published, which a run that panicked is not.
fn close_diagnostics_after_one_line(project: &Project, command: &[&str]) {
use std::io::BufRead;
let runs = || {
let listed = project.supercov(&["runs", "--json"]);
if listed.code() == 0 {
listed.json()["data"]["runs"].as_array().map_or(0, Vec::len)
} else {
0
}
};
let before = runs();
let mut child = project
.supercov_command(command)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let mut reader = std::io::BufReader::new(child.stderr.take().unwrap());
let mut line = String::new();
assert!(reader.read_line(&mut line).unwrap() > 0);
drop(reader);
let status = child.wait().unwrap();
assert!(
status.code() != Some(101) || runs() > before,
"panicked after {line}"
);
}
#[test]
fn a_run_whose_output_stops_being_read_goes_on_without_a_panic() {
let project = Project::cart("closed-diagnostics");
close_diagnostics_after_one_line(&project, &["--", "node", "--test"]);
let crate_project = Project::empty("closed-diagnostics-rust");
small_crate(&crate_project);
crate_project.git(&["init", "-q"]);
crate_project.commit("fixture");
close_diagnostics_after_one_line(&crate_project, &["--", "cargo", "test", "-q"]);
if nextest_installed() {
close_diagnostics_after_one_line(&crate_project, &["--", "cargo", "nextest", "run"]);
}
}
/// A file a Rust test writes in its crate comes back to the project, and
/// the run says so.
#[test]
fn a_file_a_rust_test_writes_comes_back_to_the_project() {
let project = Project::empty("rust-writes");
small_crate(&project);
project.write(
"tests/writes.rs",
"#[test]\nfn writes() {\n std::fs::write(\"written.txt\", \"x\").unwrap();\n}\n",
);
project.write(".gitignore", "target/\nwritten.txt\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", "cargo", "test", "-q"]);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
assert!(
ran.stderr().contains(
"synced 1 file(s) the command created or changed back to the project: written.txt"
),
"{}",
ran.stderr()
);
assert_eq!(
std::fs::read_to_string(project.root.join("written.txt")).unwrap(),
"x"
);
}
/// An argument that is not text is refused by name, never a panic.
#[cfg(unix)]
#[test]
fn an_argument_that_is_not_utf_8_is_refused() {
use std::os::unix::ffi::OsStrExt;
let project = Project::empty("not-utf-8-argument");
let output = project
.supercov_command(&["runs"])
.arg(std::ffi::OsStr::from_bytes(b"run\xff"))
.output()
.unwrap();
let said = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{said}");
assert!(
said.contains("is not UTF-8") && !said.contains("panicked"),
"{said}"
);
}
/// A Rust project holding a name that is not text is refused, naming it:
/// what a run is judged current against is read by name. Only Linux lets a
/// file be named so.
#[cfg(target_os = "linux")]
#[test]
fn a_rust_project_holding_a_name_that_is_not_utf_8_is_refused() {
use std::os::unix::ffi::OsStrExt;
let project = Project::empty("rust-not-utf-8");
small_crate(&project);
std::fs::write(
project
.root
.join(std::ffi::OsStr::from_bytes(b"notes\xff.txt")),
"",
)
.unwrap();
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", "cargo", "test", "-q"]);
let said = ran.stderr();
assert_ne!(ran.code(), 0, "{said}");
assert!(
said.contains("Rust project contains a non-UTF-8 path") && !said.contains("panicked"),
"{said}"
);
}
/// Supercov run from a directory whose name is not text cannot name itself
/// as nextest's runner, and says so. Only Linux lets a directory be named so.
#[cfg(target_os = "linux")]
#[test]
fn a_nextest_run_from_a_supercov_whose_path_is_not_utf_8_says_so() {
use std::os::unix::ffi::OsStrExt;
if !nextest_installed() {
return;
}
let project = Project::empty("nextest-not-utf-8");
small_crate(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
// Outside the project, whose own walk would refuse the name first.
let elsewhere = Project::empty("nextest-not-utf-8-bin");
let directory = elsewhere.root.join(std::ffi::OsStr::from_bytes(b"bin\xff"));
std::fs::create_dir(&directory).unwrap();
let copied = directory.join("supercov");
std::fs::copy(env!("CARGO_BIN_EXE_supercov"), &copied).unwrap();
// The helper's command, with the copy as its program.
let helper = project.supercov_command(&["--", "cargo", "nextest", "run"]);
let mut command = std::process::Command::new(&copied);
command.args(helper.get_args()).current_dir(&project.root);
for (name, value) in helper.get_envs() {
match value {
Some(value) => command.env(name, value),
None => command.env_remove(name),
};
}
let output = command.output().unwrap();
let said = String::from_utf8_lossy(&output.stderr);
assert_ne!(output.status.code(), Some(0), "{said}");
assert!(
said.contains("the Supercov executable path is not UTF-8") && !said.contains("panicked"),
"{said}"
);
}
/// A nextest run refuses an option it cannot tell the selected tests from,
/// and a Cargo configuration it cannot read, before running anything.
#[test]
fn a_nextest_run_refuses_what_it_cannot_read() {
if !nextest_installed() {
return;
}
let project = Project::empty("nextest-refuses");
small_crate(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let option = project.supercov(&["--", "cargo", "nextest", "run", "--wat"]);
assert_ne!(option.code(), 0);
assert!(option.stderr().contains("--wat"), "{}", option.stderr());
project.write(".cargo/config.toml", "[build\n");
let configuration = project.supercov(&["--", "cargo", "nextest", "run"]);
assert_ne!(configuration.code(), 0);
assert!(
!configuration.stderr().contains("panicked at"),
"{}",
configuration.stderr()
);
}
/// Whether `cargo nextest` runs here.
fn nextest_installed() -> bool {
std::process::Command::new("cargo")
.args(["nextest", "--version"])
.output()
.is_ok_and(|output| output.status.success())
}
/// A Python source that does not parse carries no obligations, and the run
/// says which file it was.
#[test]
fn a_python_source_that_does_not_parse_is_named() {
let project = Project::empty("python-unparsed");
project.write("pkg/__init__.py", "");
project.write("pkg/w.py", "def double(n):\n return n * 2 if n else 0\n");
std::fs::write(project.root.join("pkg/binary.py"), [0xff, 0xfe, b'\n']).unwrap();
project.write("tests/__init__.py", "");
project.write(
"tests/test_w.py",
"import unittest\nfrom pkg.w import double\n\nclass W(unittest.TestCase):\n def test_doubles(self):\n self.assertEqual(double(2), 4)\n",
);
project.git(&["init", "-q"]);
project.commit("python");
let ran = project.supercov(&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
]);
let said = ran.stderr();
ran.succeeds();
assert!(
said.contains("[supercov] could not parse pkg/binary.py: source is not valid UTF-8"),
"{said}"
);
}
/// A Ruby source that does not parse carries no obligations, and the run
/// says which file it was, under the roots it was told to measure.
#[cfg(unix)]
#[test]
fn a_ruby_source_that_does_not_parse_is_named() {
let Some(ruby) = ruby() else {
return;
};
let project = Project::empty("ruby-unparsed");
project.write(
"lib/w.rb",
"module W\n def self.double(n) = n ? n * 2 : 0\nend\n",
);
project.write("lib/broken.rb", "def (\n");
project.write(
"test/w_test.rb",
"require 'minitest/autorun'\nrequire 'w'\n\nclass WTest < Minitest::Test\n def test_doubles\n assert_equal 4, W.double(2)\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("ruby");
let ran = project.supercov_with(
&["--", ruby.as_str(), "-Ilib", "test/w_test.rb"],
&[("SUPERCOV_SOURCE_ROOTS", "lib")],
);
let said = ran.stderr();
ran.succeeds();
assert!(
said.contains("[supercov] could not parse lib/broken.rb"),
"{said}"
);
}
/// A JavaScript project of one test, run by `node --test`.
fn javascript_project(project: &Project) {
project.write(
"package.json",
r#"{ "name": "cart", "private": true, "type": "module" }"#,
);
project.write(
"src/cart.js",
"export const total = (a, b) => (a && b ? a + b : 0);\n",
);
project.write(
"test/cart.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { total } from '../src/cart.js';\ntest('adds', () => assert.equal(total(1, 2), 3));\n",
);
}
/// A Python project of one test, run by unittest.
fn python_project(project: &Project) {
project.write("pkg/__init__.py", "");
project.write("pkg/w.py", "def double(n):\n return n * 2 if n else 0\n");
project.write("tests/__init__.py", "");
project.write(
"tests/test_w.py",
"import unittest\nfrom pkg.w import double\n\nclass W(unittest.TestCase):\n def test_doubles(self):\n self.assertEqual(double(2), 4)\n",
);
}
/// A Ruby project of one test, run by minitest. Ruby runs are measured on
/// Unix only, so every use is too.
#[cfg(unix)]
fn ruby_project(project: &Project) {
project.write(
"lib/w.rb",
"module W\n def self.double(n) = n ? n * 2 : 0\nend\n",
);
project.write(
"test/w_test.rb",
"require 'minitest/autorun'\nrequire 'w'\n\nclass WTest < Minitest::Test\n def test_doubles\n assert_equal 4, W.double(2)\n end\nend\n",
);
}
/// A Go module of one test.
fn go_project(project: &Project) {
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write(
"w.go",
"package w\n\nfunc Double(n int) int {\n\tif n == 0 {\n\t\treturn 0\n\t}\n\treturn n * 2\n}\n",
);
project.write(
"w_test.go",
"package w\n\nimport \"testing\"\n\nfunc TestDouble(t *testing.T) {\n\tif Double(2) != 4 {\n\t\tt.Fatal(\"double\")\n\t}\n}\n",
);
// What the toolchain ignores, walked on its own: a test's data, and an
// empty directory in it.
project.write("testdata/sample.go", "package sample\n");
std::fs::create_dir_all(project.root.join("testdata/empty")).unwrap();
}
/// A workspace whose member lives outside the project is refused, naming
/// the member: its code is outside what the run copies and measures.
#[test]
fn a_rust_workspace_with_a_member_outside_the_project_is_refused() {
let project = Project::empty("outside-member");
let lib = "pub fn f() -> u32 {\n 1\n}\n";
project.write(
"proj/Cargo.toml",
"[package]\nname = \"proj\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\nmembers = [\"../member\"]\nresolver = \"2\"\n",
);
project.write("proj/src/lib.rs", lib);
project.write(
"member/Cargo.toml",
"[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2021\"\nworkspace = \"../proj\"\n",
);
project.write("member/src/lib.rs", lib);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = std::process::Command::new(env!("CARGO_BIN_EXE_supercov"))
.args(["--", "cargo", "test", "-q"])
.current_dir(project.root.join("proj"))
.env_remove("SUPERCOV_SOURCE_ROOTS")
.output()
.unwrap();
let said = String::from_utf8_lossy(&ran.stderr);
assert_ne!(ran.status.code(), Some(0), "{said}");
assert!(
said.contains("Cargo reported an unsafe workspace path") && said.contains("member"),
"{said}"
);
}
/// A crate with a unit test and a doctest.
fn small_crate(project: &Project) {
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"/// ```\n/// assert_eq!(w::double(1), 2);\n/// ```\npub fn double(n: u32) -> u32 {\n if n == 0 { 0 } else { n * 2 }\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.write(".gitignore", "target/\n");
}
/// A project's label, the fixture that writes it, and the command it runs.
type LanguageRun = (&'static str, fn(&Project), Vec<String>);
/// A run of each language refuses a source root that is not there and a
/// timeout that is no number of milliseconds, before it measures anything.
#[test]
fn each_language_refuses_a_missing_source_root_and_an_unreadable_timeout_or_interval() {
let python = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
let mut runs: Vec<LanguageRun> = vec![
(
"refuse-js",
javascript_project,
vec!["--".into(), "node".into(), "--test".into()],
),
(
"refuse-py",
python_project,
python.iter().map(|part| part.to_string()).collect(),
),
(
"refuse-rs",
small_crate,
["--", "cargo", "test", "-q"].map(String::from).to_vec(),
),
];
if let Some(go) = go() {
runs.push((
"refuse-go",
go_project,
vec!["--".into(), go.into(), "test".into(), "./...".into()],
));
}
if std::process::Command::new("mvn")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
runs.push((
"refuse-mvn",
small_maven_project,
["--", "mvn", "-q", "test"].map(String::from).to_vec(),
));
}
#[cfg(unix)]
if let Some(ruby) = ruby() {
runs.push((
"refuse-rb",
ruby_project,
vec!["--".into(), ruby, "-Ilib".into(), "test/w_test.rb".into()],
));
}
for (label, write, command) in runs {
let project = Project::empty(label);
write(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let command = command.iter().map(String::as_str).collect::<Vec<_>>();
for (name, value) in [
("SUPERCOV_SOURCE_ROOTS", "missing"),
("SUPERCOV_COMMAND_TIMEOUT_MS", "soon"),
("SUPERCOV_DIAGNOSTIC_INTERVAL_MS", "often"),
] {
let ran = project.supercov_with(&command, &[(name, value)]);
let said = ran.stderr();
assert!(!said.contains("panicked at"), "{label} {name}: {said}");
assert_ne!(ran.code(), 0, "{label} {name}: {said}");
}
// A root outside the project beside one in it, which leaves files to
// measure.
let outside = Project::empty(&format!("{label}-outside"));
let roots = format!(".,{}", outside.root.display());
let ran = project.supercov_with(&command, &[("SUPERCOV_SOURCE_ROOTS", &roots)]);
let said = ran.stderr();
assert_ne!(ran.code(), 0, "{label}: {said}");
assert!(said.contains("outside the project"), "{label}: {said}");
}
}
/// A Rust run keeps `SUPERCOV_COMMAND_TIMEOUT_MS` as every supervised command
/// does: past it, the test still running is stopped, no other starts, and
/// the run ends 124, saying why. One well inside it runs as it would.
#[cfg(unix)]
#[test]
fn a_rust_run_past_its_timeout_is_stopped_and_ends_124() {
let project = Project::empty("rust-timeout");
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"pub fn one() -> u32 { 1 }\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn hangs() {\n std::thread::sleep(std::time::Duration::from_secs(120));\n }\n #[test]\n fn is_one() {\n assert_eq!(super::one(), 1);\n }\n}\n",
);
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
// Built once without a deadline, so the next run's time goes to its tests.
project
.supercov_with(
&["--", "cargo", "test", "-q", "is_one"],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "600000")],
)
.succeeds();
let started = std::time::Instant::now();
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "20000")],
);
assert_eq!(ran.code(), 124, "{}", ran.stderr());
assert!(ran.stderr().contains("20000 ms"), "{}", ran.stderr());
assert!(started.elapsed() < std::time::Duration::from_secs(90));
// Past the build, what ran is published, as the command that timed out.
if ran
.stderr()
.contains("the tests still running were stopped")
{
let run = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(run["data"]["testExitCode"], 124, "{run}");
}
// A deadline that passes before any test reports publishes nothing.
let early = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "1")],
);
assert_eq!(early.code(), 124, "{}", early.stderr());
assert!(
early.stderr().contains("no run was published"),
"{}",
early.stderr()
);
}
/// A Rust run told to stop (SIGTERM, as a supervisor or `kill` sends it)
/// takes the test it is running down with it rather than leaving it to
/// run on, and ends by that signal.
#[cfg(unix)]
#[test]
fn a_rust_run_told_to_stop_takes_its_test_with_it() {
use std::os::unix::process::ExitStatusExt;
let project = Project::empty("rust-terminated");
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"#[cfg(test)]\nmod tests {\n #[test]\n fn waits() {\n let marker = std::env::var(\"SUPERCOV_TEST_MARKER\").unwrap();\n std::fs::write(marker, std::process::id().to_string()).unwrap();\n std::thread::sleep(std::time::Duration::from_secs(120));\n }\n}\n",
);
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let marker = project.root.with_extension("marker");
let _ = std::fs::remove_file(&marker);
let mut supercov = project
.supercov_command(&["--", "cargo", "test", "-q"])
.env("SUPERCOV_TEST_MARKER", &marker)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let started = std::time::Instant::now();
while !marker.exists() {
assert!(
started.elapsed() < std::time::Duration::from_secs(240),
"the test never started"
);
std::thread::sleep(std::time::Duration::from_millis(100));
}
std::thread::sleep(std::time::Duration::from_millis(200));
let test = std::fs::read_to_string(&marker).unwrap();
// SAFETY: a signal to the process this test started.
unsafe { libc::kill(supercov.id() as i32, libc::SIGTERM) };
let status = supercov.wait().unwrap();
assert_eq!(status.signal(), Some(libc::SIGTERM), "{status:?}");
let gone = (0..50).any(|_| {
std::thread::sleep(std::time::Duration::from_millis(100));
// SAFETY: probing a pid with signal 0 sends nothing.
let probed = unsafe { libc::kill(test.trim().parse().unwrap(), 0) };
probed != 0
});
let _ = std::fs::remove_file(&marker);
assert!(gone, "test process {test} outlived the run");
}
/// A `wasm-pack test` that stops before it runs `cargo test` is refused with
/// what it said; one that cannot start says so.
#[cfg(unix)]
#[test]
fn a_wasm_pack_test_that_never_runs_cargo_says_what_it_said() {
let project = Project::empty("wasm-pack-stops");
small_crate(&project);
project.write_script(
"tools/wasm-pack",
"#!/bin/sh\necho 'no wasm32 target installed' >&2\nexit 1\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
let tool = project.root.join("tools/wasm-pack");
let stopped = project.supercov(&["--", tool.to_str().unwrap(), "test", "--node"]);
assert_ne!(stopped.code(), 0);
assert!(
stopped.stderr().contains(
"`wasm-pack test` stopped before it ran `cargo test`:\nno wasm32 target installed"
),
"{}",
stopped.stderr()
);
let missing = project.root.join("tools/missing/wasm-pack");
let refused = project.supercov(&["--", missing.to_str().unwrap(), "test", "--node"]);
assert_ne!(refused.code(), 0);
assert!(
refused.stderr().contains("could not run"),
"{}",
refused.stderr()
);
}
/// A Python or Ruby run measured under the source roots it was given is
/// read back under the same roots, and is current while the project is.
#[test]
fn a_run_under_given_source_roots_is_read_back_under_them() {
let python = Project::empty("roots-py");
python_project(&python);
python.git(&["init", "-q"]);
python.commit("fixture");
python
.supercov_with(
&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
],
&[("SUPERCOV_SOURCE_ROOTS", "pkg")],
)
.succeeds();
let read = python.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(read["ok"], true, "{read}");
#[cfg(unix)]
if let Some(ruby) = ruby() {
let project = Project::empty("roots-rb");
ruby_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov_with(
&["--", ruby.as_str(), "-Ilib", "test/w_test.rb"],
&[("SUPERCOV_SOURCE_ROOTS", "lib")],
)
.succeeds();
let read = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(read["ok"], true, "{read}");
}
}
/// Each place a doctest's helper processes write, read or list, failing
/// on its own: rustdoc's stand-in, the doctest runner, and a merged
/// harness's child. The run ends, never panicking, and runs again cleanly.
#[cfg(unix)]
#[test]
fn a_doctest_helper_whose_file_operation_fails_ends_cleanly() {
let stand_in = "env:SUPERCOV_DOCTEST_WRAPPER_ROOT/";
let runner = "__doctest-runner/";
let child = "env:SUPERCOV_DOCTEST_CHILD_DIR/";
for (edition, faults) in [
(
"2021",
vec![
format!("{stand_in}fs.create_dir_all@1"),
format!("{stand_in}fs.open_with@1"),
format!("{stand_in}fs.create_dir_all@2"),
format!("{stand_in}fs.write@1"),
format!("{stand_in}fs.read_dir@1"),
format!("{stand_in}fs.read_dir@2"),
format!("{stand_in}fs.read@1"),
format!("{runner}fs.create_dir_all@2"),
format!("{runner}fs.write@1"),
format!("{runner}fs.create_dir_all@3"),
],
),
(
"2024",
vec![
format!("{stand_in}fs.write@1"),
format!("{stand_in}fs.write@2"),
format!("{stand_in}fs.write@3"),
format!("{stand_in}fs.write@4"),
format!("{stand_in}fs.read_to_string@1"),
format!("{runner}fs.write@1"),
format!("{runner}fs.write@2"),
format!("{runner}fs.create_dir_all@3"),
format!("{runner}fs.read@1"),
format!("{runner}fs.read@2"),
format!("{runner}fs.read@3"),
format!("{runner}fs.read_dir@1"),
format!("{runner}fs.read_to_string@1"),
format!("{child}fs.create_dir_all@1"),
format!("{child}fs.write@1"),
],
),
] {
let project = Project::empty(&format!("doctest-helper-faults-{edition}"));
small_crate(&project);
project.edit(
"Cargo.toml",
"edition = \"2021\"",
&format!("edition = \"{edition}\""),
);
project.git(&["init", "-q"]);
project.commit("fixture");
for fault in faults {
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_TEST_FAULT", fault.as_str())],
);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert!(!said.contains("panicked at"), "{edition} {fault}:\n{said}");
}
project.supercov(&["--", "cargo", "test", "-q"]).succeeds();
}
}
/// The runtool rustdoc hands each doctest to: its invocation claimed, a
/// merged harness's children's directory, the harness started, the order of
/// its cases read, a child's record read, its cases recorded; a standalone
/// doctest started. Each failing ends the run, naming where.
#[cfg(unix)]
#[test]
fn a_doctest_runtool_step_that_fails_is_named() {
let runner = "__doctest-runner/";
for (edition, fault, place) in [
(
"2024",
"fs.create_dir_all#rust_owned_doctests.rs:1189",
"rust_owned_doctests.rs:1189",
),
(
"2024",
"spawn#rust_owned_doctests.rs:1194",
"rust_owned_doctests.rs:1194",
),
(
"2024",
"fs.read#rust_owned_doctests.rs:1202",
"rust_owned_doctests.rs:1202",
),
(
"2024",
"fs.read#rust_owned_doctests.rs:1213",
"rust_owned_doctests.rs:1213",
),
(
"2024",
"fs.create_dir_all#rust_owned_doctests.rs:1158",
"rust_owned_doctests.rs:1158",
),
(
"2024",
"fs.write#rust_owned_doctests.rs:1248",
"rust_owned_doctests.rs:1248",
),
(
"2021",
"spawn#rust_owned_doctests.rs:1258",
"rust_owned_doctests.rs:1258",
),
(
"2024",
"spawn#rust_owned_doctests.rs:1171",
"rust_owned_doctests.rs:1171",
),
] {
let project = Project::empty("doctest-runtool-steps");
small_crate(&project);
project.edit(
"Cargo.toml",
"edition = \"2021\"",
&format!("edition = \"{edition}\""),
);
project.git(&["init", "-q"]);
project.commit("fixture");
let fault = format!("{runner}{fault}");
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_TEST_FAULT", fault.as_str())],
);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_ne!(ran.code(), 0, "{edition} {fault}: {said}");
assert!(fired_at(&said, place), "{edition} {fault}: {said}");
}
}
/// Two standalone doctests of one item, at lines 1 and 11: every word of
/// either name is in the other's (`1)` in `11)`), so each is run alone by a
/// filter and a skip of the other, and both are measured.
#[test]
fn standalone_doctests_named_alike_are_each_run_alone() {
let project = Project::empty("standalone-alike");
project.write(
"Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace]\n",
);
let doctest = "/// ```standalone_crate\n/// assert_eq!(w::a(), 1);\n/// ```\n";
project.write(
"src/lib.rs",
&format!(
"{doctest}{}{doctest}pub fn a() -> u32 {{\n 1\n}}\n",
"///\n".repeat(7)
),
);
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", "cargo", "test", "-q"]);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
assert!(
ran.stderr().contains("Rust coverage: 2 test(s)"),
"{}",
ran.stderr()
);
}
/// A Maven project with one class and its test.
/// A JVM test whose class is declared in a file of another name has no
/// file to name, and is listed without evidence all the same.
#[test]
fn a_jvm_test_without_evidence_whose_class_names_no_file_is_listed() {
if !std::process::Command::new("mvn")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
return;
}
let project = Project::empty("jvm-no-file");
small_maven_project(&project);
project.write(
"src/test/java/w/Tests.java",
"package w;\n\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nimport org.junit.jupiter.api.Test;\n\nclass HiddenTest {\n @Test\n void nothing() {\n assertTrue(true);\n }\n}\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project.supercov(&["--", "mvn", "-q", "test"]).succeeds();
let listed = project
.supercov(&["runs", "latest", "tests", "without-evidence", "--json"])
.json();
let tests = listed["data"]["tests"].as_array().unwrap();
assert!(
tests.iter().any(|test| test["name"]
.as_str()
.is_some_and(|name| name.contains("nothing"))
&& test["file"].is_null()),
"{listed}"
);
}
fn small_maven_project(project: &Project) {
project.write("pom.xml", "<project xmlns=\"http://maven.apache.org/POM/4.0.0\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>example</groupId>\n <artifactId>w</artifactId>\n <version>1.0</version>\n <properties>\n <maven.compiler.source>17</maven.compiler.source>\n <maven.compiler.target>17</maven.compiler.target>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.junit.jupiter</groupId>\n <artifactId>junit-jupiter</artifactId>\n <version>5.10.2</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>3.2.5</version>\n </plugin>\n </plugins>\n </build>\n</project>\n");
project.write(
"src/main/java/w/W.java",
"package w;\n\npublic class W {\n public static int twice(int n) {\n return n == 0 ? 0 : n * 2;\n }\n}\n",
);
project.write(
"src/test/java/w/WTest.java",
"package w;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\n\nclass WTest {\n @Test\n void twice() {\n assertEquals(4, W.twice(2));\n }\n}\n",
);
project.write(".gitignore", "target/\n");
}
/// A Python run beside a test file that does not parse measures the rest:
/// the file holds no assertion line to arm. Roots that name nothing are
/// refused before anything runs. A later query that cannot recompute the
/// run's inputs reads the run as stale.
#[test]
fn a_python_run_reads_past_what_it_cannot_parse_and_refuses_roots_naming_nothing() {
let project = Project::empty("python-unparsed");
python_project(&project);
project.write("tests/helper_broken.py", "def broken(:\n pass\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let command = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
project.supercov(&command).succeeds();
let refused = project.supercov_with(&command, &[("SUPERCOV_SOURCE_ROOTS", "nowhere")]);
assert_ne!(refused.code(), 0, "{}", refused.stderr());
assert!(refused.stderr().contains("nowhere"), "{}", refused.stderr());
// A root named that is a link is no root.
#[cfg(unix)]
{
std::os::unix::fs::symlink("pkg", project.root.join("linked")).unwrap();
let linked = project.supercov_with(&command, &[("SUPERCOV_SOURCE_ROOTS", "linked")]);
assert_ne!(linked.code(), 0, "{}", linked.stderr());
assert!(linked.stderr().contains("linked"), "{}", linked.stderr());
std::fs::remove_file(project.root.join("linked")).unwrap();
}
for (fault, place) in [
("fs.canonicalize#python_run.rs:213", "python_run.rs:213"),
("fs.read_dir#python_project.rs:125", "python_project.rs:125"),
] {
let read = project.supercov_with(&["runs", "latest"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = format!("{}{}", read.stdout(), read.stderr());
assert!(fired_at(&said, place), "{fault}: {said}");
assert!(said.contains("stale run"), "{fault}: {said}");
}
}
/// A query recomputes a run's inputs to judge whether it is current: the
/// project's root resolved, its tree walked, its files digested. Each
/// failing, for a Rust, Go, Ruby or Java run, reads the run as stale rather
/// than failing the query; so does a source root the run was measured under
/// that is a link now.
#[test]
fn a_run_whose_inputs_cannot_be_recomputed_reads_stale() {
let stale_when = |project: &Project, faults: &[(&str, &str)]| {
for (fault, place) in faults {
let read =
project.supercov_with(&["runs", "latest"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = format!("{}{}", read.stdout(), read.stderr());
assert!(fired_at(&said, place), "{fault}: {said}");
assert!(said.contains("stale run"), "{fault}: {said}");
}
};
let measured = |label: &str, write: fn(&Project), command: &[&str]| {
let project = Project::empty(label);
write(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
project.supercov(command).succeeds();
project
};
// A run under a root that is a link is refused, naming it.
#[cfg(unix)]
let refused_under_a_link = |project: &Project, target: &str, command: &[&str]| {
std::os::unix::fs::symlink(target, project.root.join("linked")).unwrap();
let ran = project.supercov_with(command, &[("SUPERCOV_SOURCE_ROOTS", "linked")]);
assert_ne!(ran.code(), 0, "{command:?}: {}", ran.stderr());
assert!(
ran.stderr().contains("linked"),
"{command:?}: {}",
ran.stderr()
);
std::fs::remove_file(project.root.join("linked")).unwrap();
};
let project = measured("stale-rust", small_crate, &["--", "cargo", "test", "-q"]);
stale_when(
&project,
&[
("fs.canonicalize#rust_run.rs:244", "rust_run.rs:244"),
("fs.read_dir#rust_run.rs:88", "rust_run.rs:88"),
("fs.read_dir entry#rust_run.rs:88", "rust_run.rs:88"),
("fs.open#integrity.rs:427", "integrity.rs:427"),
],
);
#[cfg(unix)]
refused_under_a_link(&project, "src", &["--", "cargo", "test", "-q"]);
if let Some(go) = go() {
let project = measured("stale-go", go_project, &["--", go, "test", "./..."]);
stale_when(
&project,
&[
("fs.canonicalize#go_run.rs:746", "go_run.rs:746"),
("fs.read_dir#go_project.rs:142", "go_project.rs:142"),
("fs.open#integrity.rs:427", "integrity.rs:427"),
],
);
#[cfg(unix)]
refused_under_a_link(&project, "testdata", &["--", go, "test", "./..."]);
}
#[cfg(unix)]
if let Some(ruby) = ruby() {
let project = Project::empty("stale-ruby");
ruby_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
let command = ["--", ruby.as_str(), "-Ilib", "test/w_test.rb"];
project
.supercov_with(&command, &[("SUPERCOV_SOURCE_ROOTS", "lib")])
.succeeds();
stale_when(
&project,
&[
("fs.canonicalize#ruby_run.rs:182", "ruby_run.rs:182"),
("fs.read_dir#ruby_project.rs:106", "ruby_project.rs:106"),
("fs.open#integrity.rs:427", "integrity.rs:427"),
],
);
refused_under_a_link(&project, "lib", &command);
// The root it was measured under is a link now: no root.
std::fs::rename(project.root.join("lib"), project.root.join("moved")).unwrap();
std::os::unix::fs::symlink("moved", project.root.join("lib")).unwrap();
let read = project.supercov(&["runs", "latest"]);
let said = format!("{}{}", read.stdout(), read.stderr());
assert!(said.contains("stale run"), "{said}");
}
if std::process::Command::new("mvn")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
let project = measured(
"stale-jvm",
small_maven_project,
&["--", "mvn", "-q", "test"],
);
stale_when(
&project,
&[
("fs.canonicalize#jvm_run.rs:1962", "jvm_run.rs:1962"),
("fs.read_dir#jvm_project.rs:281", "jvm_project.rs:281"),
("fs.open#integrity.rs:427", "integrity.rs:427"),
],
);
// A run under a root that is a link is refused.
#[cfg(unix)]
{
std::os::unix::fs::symlink("src", project.root.join("linked")).unwrap();
let linked = project.supercov_with(
&["--", "mvn", "-q", "test"],
&[("SUPERCOV_SOURCE_ROOTS", "linked")],
);
assert_ne!(linked.code(), 0, "{}", linked.stderr());
assert!(linked.stderr().contains("linked"), "{}", linked.stderr());
}
}
// And a Python run measured under roots that are gone.
let project = Project::empty("stale-python-roots");
python_project(&project);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov_with(
&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
],
&[("SUPERCOV_SOURCE_ROOTS", "pkg")],
)
.succeeds();
std::fs::rename(project.root.join("pkg"), project.root.join("moved")).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("moved", project.root.join("pkg")).unwrap();
let read = project.supercov(&["runs", "latest"]);
let said = format!("{}{}", read.stdout(), read.stderr());
assert!(said.contains("stale run"), "{said}");
}
/// A Python test skipped where it is declared, or a Ruby one as it runs, is
/// in the run, skipped.
#[test]
fn a_skipped_python_or_ruby_test_is_counted_skipped() {
let project = Project::empty("python-skips");
python_project(&project);
project.write(
"tests/test_later.py",
"import unittest\nfrom pkg.w import double\n\nclass Later(unittest.TestCase):\n @unittest.skip(\"later\")\n def test_later(self):\n double(0)\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov(&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
])
.succeeds();
let run = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(run["data"]["testOutcomes"]["skipped"], 1, "{run}");
assert_eq!(run["data"]["testOutcomes"]["passed"], 1, "{run}");
// And a Ruby test skipped as it runs.
#[cfg(unix)]
if let Some(ruby) = ruby() {
let project = Project::empty("ruby-skips");
ruby_project(&project);
project.write(
"test/later_test.rb",
"require 'minitest/autorun'\nrequire 'w'\n\nclass LaterTest < Minitest::Test\n def test_later\n skip 'later'\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov(&[
"--",
ruby.as_str(),
"-Ilib",
"-e",
"Dir['test/*_test.rb'].each { |f| require_relative f }",
])
.succeeds();
let run = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(run["data"]["testOutcomes"]["skipped"], 1, "{run}");
}
}
/// A Python test whose process ends during it reported no outcome, but what
/// it ran was recorded: the test is in the run, failed, credited with that.
#[test]
fn a_python_test_whose_process_ends_during_it_is_failed_and_credited() {
let project = Project::empty("python-dies");
project.write("pkg/__init__.py", "");
project.write("pkg/w.py", "def double(n):\n return n * 2 if n else 0\n");
project.write("tests/__init__.py", "");
project.write(
"tests/test_w.py",
"import os\nimport unittest\nfrom pkg.w import double\n\nclass W(unittest.TestCase):\n def test_a_passes(self):\n self.assertEqual(double(2), 4)\n\n def test_b_dies(self):\n double(0)\n os._exit(3)\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project.supercov(&[
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
]);
let dies = project
.supercov(&["runs", "latest", "test", "test_b_dies"])
.succeeds();
contains_all(&dies, &["outcome failed", "line: pkg/w.py:2"]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Passed 1", "Failed 1"]);
}
/// The same of a Ruby test: its process ends during it, after a test that
/// passed.
#[cfg(unix)]
#[test]
fn a_ruby_test_whose_process_ends_during_it_is_failed_and_credited() {
let Some(ruby) = ruby() else {
return;
};
let project = Project::empty("ruby-dies");
project.write(
"lib/w.rb",
"module W\n def self.double(n) = n ? n * 2 : 0\nend\n",
);
project.write(
"test/w_test.rb",
"require 'minitest/autorun'\nrequire 'w'\n\nclass WTest < Minitest::Test\n i_suck_and_my_tests_are_order_dependent!\n\n def test_a_passes\n assert_equal 4, W.double(2)\n end\n\n def test_b_dies\n W.double(nil)\n exit!(3)\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project.supercov(&["--", &ruby, "-Ilib", "test/w_test.rb"]);
// Its probes were read; its lines are not, as Ruby gives them when a
// test ends and this one never did.
let dies = project
.supercov(&["runs", "latest", "test", "test_b_dies"])
.succeeds();
contains_all(&dies, &["outcome failed", "1 decision"]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Passed 1", "Failed 1"]);
}
/// Started in a directory removed since, every command says it cannot
/// read where it is, not a panic or a run it never found.
#[cfg(unix)]
#[test]
fn a_command_started_in_a_removed_directory_says_so() {
let project = Project::cart("removed-cwd");
project.measure(&[]);
let commands: &[&[&str]] = &[
&["runs", "latest"],
&["runs", "latest", "gaps"],
&["runs", "latest", "file", "src/cart.js"],
&["runs", "latest", "source", "src/cart.js"],
&["runs", "latest", "assertions"],
&["runs", "patch", "--base", "HEAD"],
&["runs", "patch", "--base", "HEAD", "--json"],
&["runs", "check"],
&["runs", "check", "--lines", "50"],
&["runs", "clean"],
&["report", "--no-open"],
&["report", "latest", "--no-open"],
&["diff", "latest", "latest"],
&["merge"],
&["import", "coverage.lcov", "--test", "imported"],
&["quality", "gaps"],
&["security"],
&["security", "--run", "latest"],
&["quality", "--run", "latest"],
&["tests", "affected"],
&["--", "node", "--test"],
&["runs", "latest", "--json"],
&["runs", "latest", "gaps", "--json"],
&["report", "--no-open"],
&["report", "--no-open", "--output", "r.html"],
];
for command in commands {
let gone = project
.root
.join(format!("gone-{}", command.join("-").replace('/', "_")));
std::fs::create_dir(&gone).unwrap();
let script = format!(
"cd \"{}\" && rmdir \"{}\" && exec \"$0\" \"$@\"",
gone.display(),
gone.display()
);
let ran = std::process::Command::new("sh")
.arg("-c")
.arg(&script)
.arg(env!("CARGO_BIN_EXE_supercov"))
.args(*command)
.output()
.unwrap();
let said = format!(
"{}{}",
String::from_utf8_lossy(&ran.stdout),
String::from_utf8_lossy(&ran.stderr)
);
assert!(!said.contains("panicked at"), "{command:?}: {said}");
assert!(!ran.status.success(), "{command:?} succeeded: {said}");
}
}
/// With every index refused, and with no room for any reply, each query
/// says what failed: a fault the engine injects stands in for an index from
/// another version and for an answer too large to send.
#[test]
fn each_query_says_so_when_its_index_or_its_reply_fails() {
let project = Project::cart("index-faults");
project.measure(&[]);
let older = project.latest();
project.measure(&[]);
let commands: &[&[&str]] = &[
&["runs", "latest"],
&["runs", "latest", "--json"],
&["runs", "latest", "gaps"],
&["runs", "latest", "gaps", "--json"],
&["runs", "latest", "file", "src/cart.js", "--json"],
&["runs", "latest", "line", "src/cart.js:1", "--json"],
&["runs", "latest", "tests", "--json"],
&["runs", "latest", "scope", "--json"],
&["runs", "latest", "summary", "--json"],
&["runs", "--json"],
&["runs", "patch", "--json"],
&["runs", "check"],
&["runs", "check", "--json"],
&["runs", "check", "--lines", "100", "--json"],
&["runs", "latest", "assertions", "--kind", "unit"],
&[
"runs",
"latest",
"assertions",
"assess",
"--dry-run",
"--kind",
"unit",
],
&["tests", "affected", "--kind", "unit"],
&["runs", "latest", "tests", "affected", "--json"],
&["runs", "latest", "gaps", "--format", "jsonl"],
&["runs", "latest", "gaps", "--kind", "unit", "--json"],
&["diff", &older, "latest", "--json"],
&["diff", &older, "latest"],
&["report", "--no-open"],
];
for fault in ["coverage-index", "reply-too-large"] {
let mut reached = 0;
for command in commands {
let ran = project.supercov_with(command, &[("SUPERCOV_TEST_FAULT", fault)]);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert!(!said.contains("panicked at"), "{fault} {command:?}: {said}");
reached += usize::from(said.contains(&format!("test fault at {fault}")));
}
assert!(
reached * 3 > commands.len(),
"{fault} reached {reached} commands"
);
}
// A reply too large is asked for again with a smaller page, and that
// ask's index open (the fourth) can fail too.
let ran = project.supercov_with(
&["runs", "latest", "file", "src/cart.js", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large=2,coverage-index@4")],
);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_eq!(ran.code(), 2, "{said}");
assert!(said.contains("test fault at reply-too-large"), "{said}");
assert!(said.contains("test fault at coverage-index"), "{said}");
}
/// The quality scope reads a manifest's declared files past values that are
/// no paths, stops descending at its depth, and with roots the engine cannot
/// resolve keeps them as given and leaves the rest out.
#[cfg(unix)]
#[test]
fn the_quality_scope_reads_past_what_it_cannot_use() {
let project = Project::empty("quality-scope-edges");
project.git(&["init", "-q"]);
project.write(
"package.json",
r#"{"name":"s","bin":{"x":1,"y":"bin/y.js"},"main":"lib/index.js"}"#,
);
project.write("lib/index.js", "x\n");
project.write("bin/y.js", "x\n");
project.write("a/b/c/d/e/f/g/package.json", "{}");
// An ignored directory that cannot be listed holds no package.
use std::os::unix::fs::PermissionsExt;
project.write(".gitignore", "locked/\n");
std::fs::create_dir(project.root.join("locked")).unwrap();
std::fs::set_permissions(
project.root.join("locked"),
std::fs::Permissions::from_mode(0o000),
)
.unwrap();
let scope = project.supercov(&["quality", "scope"]);
std::fs::set_permissions(
project.root.join("locked"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
let scope = scope.succeeds();
assert!(scope.contains("Roots: bin, lib"), "{scope}");
std::os::unix::fs::symlink("lib", project.root.join("linked")).unwrap();
let linked = project
.supercov_with(
&["quality", "scope"],
&[("SUPERCOV_SOURCE_ROOTS", "linked")],
)
.succeeds();
assert!(
linked.contains("Roots: linked") && linked.contains("outside explicit source roots"),
"{linked}"
);
}
/// The quality scope takes the source roots it is given, and reads roots
/// that name nothing as none given.
#[test]
fn the_quality_scope_takes_the_roots_it_is_given() {
let project = Project::cart("quality-roots");
let explicit = project
.supercov_with(&["quality", "scope"], &[("SUPERCOV_SOURCE_ROOTS", "src")])
.succeeds();
assert!(explicit.contains("explicit mode"), "{explicit}");
let blank = project
.supercov_with(&["quality", "scope"], &[("SUPERCOV_SOURCE_ROOTS", " , ")])
.succeeds();
assert!(blank.contains("automatic mode"), "{blank}");
}
/// `runs <run> source` refuses a run that is not stored, no file, an offset
/// that is no number and a word it does not know, and says when its reply
/// cannot fit; `runs check` refuses a floor too large to read.
#[test]
fn source_and_check_refuse_what_they_cannot_read() {
let project = Project::cart("source-check-refusals");
project.measure(&[]);
for (arguments, said) in [
(
&["runs", "run_0000000000000009", "source", "src/cart.js"][..],
"run_0000000000000009",
),
(&["runs", "latest", "source"][..], "source"),
(
&["runs", "latest", "source", "src/cart.js", "--offset", "x"][..],
"Invalid --offset",
),
(
&["runs", "latest", "source", "src/cart.js", "--wat"][..],
"Unexpected argument: --wat",
),
] {
let ran = project.supercov(arguments);
let text = format!("{}{}", ran.stdout(), ran.stderr());
assert_ne!(ran.code(), 0, "{arguments:?}: {text}");
assert!(text.contains(said), "{arguments:?}: {text}");
}
let large = project.supercov_with(
&["runs", "latest", "source", "src/cart.js", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large")],
);
assert_eq!(large.code(), 2, "{}", large.stdout());
assert!(
large.stdout().contains("RESPONSE_TOO_LARGE"),
"{}",
large.stdout()
);
// An assertions listing halved down to one entry that still cannot fit.
let assertions = project.supercov_with(
&["runs", "latest", "assertions", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large")],
);
assert_eq!(assertions.code(), 2, "{}", assertions.stdout());
assert!(
assertions.stdout().contains("RESPONSE_TOO_LARGE"),
"{}",
assertions.stdout()
);
// A diff narrowed by a title keeps the narrowing in its paging.
let older = project.latest();
project.measure(&[]);
project
.supercov(&["diff", &older, "latest", "--title", "total"])
.succeeds();
let huge = project.supercov(&[
"runs",
"latest",
"check",
"--min-lines",
"99999999999999999999",
]);
let text = format!("{}{}", huge.stdout(), huge.stderr());
assert!(text.contains("is too large"), "{text}");
}
/// A line asked about after its file was cut short is past its end; after
/// the file was removed, it is answered from the run, with no source.
#[test]
fn a_line_whose_file_was_cut_or_removed_since_the_run_is_refused_or_answered_without_text() {
let project = Project::cart("line-gone");
project.measure(&[]);
// Cut short, the line is past its end: no line to answer for.
project.write("src/cart.js", "export const total = 0;\n");
let short = project
.supercov(&["runs", "latest", "line", "src/cart.js:3", "--json"])
.json();
assert_eq!(short["error"]["code"], "INVALID_ARGUMENT", "{short}");
// Removed, a line the run kept no text of (a closing brace) has none.
std::fs::remove_file(project.root.join("src/cart.js")).unwrap();
let gone = project
.supercov(&["runs", "latest", "line", "src/cart.js:5", "--json"])
.json();
assert_eq!(gone["ok"], true, "{gone}");
assert!(gone["data"]["source"].is_null(), "{gone}");
}
/// `import` with nothing to import names what it needs.
#[test]
fn import_with_no_arguments_names_what_it_needs() {
let project = Project::cart("import-nothing");
let ran = project.supercov(&["import"]);
assert_ne!(ran.code(), 0, "{}", ran.stderr());
assert!(ran.stderr().contains("import"), "{}", ran.stderr());
}
/// A patch asked of a run whose suite failed, of a run whose source has
/// changed, and of a run with nothing to annotate: each says what it can,
/// and an unknown base or a reply too large is named.
#[test]
fn a_patch_of_a_failed_or_stale_run_says_what_it_can() {
let project = Project::cart("patch-blocked");
project.write(
"test/fails.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\ntest('fails', () => assert.equal(1, 2));\n",
);
project.commit("a failing test");
project.supercov(&["--", "node", "--test"]).exits(1);
let unknown = project.supercov(&["runs", "patch", "--base", "no-such-ref"]);
assert_ne!(unknown.code(), 0, "{}", unknown.stderr());
let faulted = project.supercov_with(
&["runs", "patch", "--base", "HEAD", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large")],
);
assert!(
faulted.stderr().contains("response exceeds"),
"{}",
faulted.stderr()
);
// Stale: the source changed since the run.
project.write("src/cart.js", "export const total = () => 0;\n");
let stale = project.supercov_with(
&["runs", "patch", "--base", "HEAD", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large")],
);
assert!(
stale.stderr().contains("response exceeds"),
"{}",
stale.stderr()
);
let human = project.supercov(&["runs", "patch", "--base", "HEAD"]);
assert!(
human.stderr().contains("this run cannot"),
"{}",
human.stderr()
);
// Nothing changed against HEAD on a passing run: nothing to annotate.
let clean = Project::cart("patch-clean");
clean.measure(&[]);
let annotated = clean.supercov(&["runs", "patch", "--base", "HEAD", "--annotate", "github"]);
assert!(
!annotated.stdout().contains("::warning"),
"{}",
annotated.stdout()
);
let faulted = clean.supercov_with(
&["runs", "patch", "--base", "HEAD", "--json"],
&[("SUPERCOV_TEST_FAULT", "reply-too-large")],
);
assert!(
faulted.stderr().contains("response exceeds"),
"{}",
faulted.stderr()
);
}
/// After its build a Rust run says which files the build did not compile
/// and reads back what its builds settled of each `#[cfg]` gate: either
/// failing ends the run, by `cargo test` or by nextest.
#[test]
fn a_rust_run_whose_step_after_the_build_fails_says_so() {
for (command, fault, place) in [
(&["cargo", "test"][..], "diagnostics@3", "diagnostics"),
(
&["cargo", "test"][..],
"fs.read_dir#rust_runtime.rs:391",
"rust_runtime.rs:391",
),
(
&["cargo", "nextest", "run"][..],
"fs.read_dir#rust_runtime.rs:391",
"rust_runtime.rs:391",
),
] {
let project = Project::empty("rust-settlement");
project.write(
"Cargo.toml",
"[package]\nname = \"s\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[features]\nextra = []\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"#[cfg(feature = \"extra\")]\nmod gated;\n\npub fn double(n: u32) -> u32 {\n n * 2\n}\n\n#[cfg(feature = \"extra\")]\npub fn extra() -> u32 {\n 1\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn doubles() {\n assert_eq!(super::double(2), 4);\n }\n}\n",
);
project.write("src/gated.rs", "pub fn gated() -> u32 {\n 2\n}\n");
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let mut arguments = vec!["--"];
arguments.extend(command);
let ran = project.supercov_with(&arguments, &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{command:?} {fault}: {stderr}");
assert!(fired_at(&stderr, place), "{command:?} {fault}: {stderr}");
}
}
/// A test binary of the project's own harness answers `--list` as it likes:
/// one that fails to list, or lists a name no test can have, ends the run.
#[test]
fn a_rust_test_binary_that_cannot_list_its_tests_ends_the_run() {
for (main, said) in [
(
"fn main() {\n std::process::exit(3);\n}\n",
"when asked to --list",
),
(
"fn main() {\n println!(\"bad\\0name: test\");\n}\n",
"test name",
),
] {
let project = Project::empty("rust-own-harness");
project.write(
"Cargo.toml",
"[package]\nname = \"h\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[[test]]\nname = \"own\"\nharness = false\n\n[workspace]\n",
);
project.write("src/lib.rs", "pub fn one() -> u32 {\n 1\n}\n");
project.write("tests/own.rs", main);
project.write(".gitignore", "target/\n");
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov(&["--", "cargo", "test"]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{stderr}");
assert!(stderr.contains(said), "{said}: {stderr}");
}
}
/// A browser suite's JavaScript run beside a Python server that no browser
/// test reached: the JavaScript is the run, and the server publishes none.
#[test]
fn a_server_no_browser_test_reached_publishes_no_run_beside_the_javascript() {
let project = Project::cart("javascript-beside-idle-server");
project.write("playwright.config.js", "export default {};\n");
project.write("server/app.py", "def hello():\n return 1\n");
project.commit("server");
let run = project.supercov(&["--", "node", "--test"]);
assert_eq!(run.code(), 0, "{}", run.stderr());
assert!(
!run.stderr().contains("server's coverage is run"),
"{}",
run.stderr()
);
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(runs["data"]["runs"].as_array().unwrap().len(), 1, "{runs}");
// So does a Java server, and a Go one where Go is installed.
let mut servers: Vec<(&str, Vec<(&str, &str)>)> = vec![(
"javascript-beside-idle-java",
vec![
(
"pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>e</groupId><artifactId>w</artifactId><version>1</version></project>\n",
),
(
"src/main/java/w/W.java",
"package w;\npublic class W { public static int one() { return 1; } }\n",
),
],
)];
if go().is_some() {
servers.push((
"javascript-beside-idle-go",
vec![
("go.mod", "module example.com/w\n\ngo 1.22\n"),
(
"main.go",
"package main\n\nfunc hello() int { return 1 }\n\nfunc main() { hello() }\n",
),
],
));
}
for (label, files) in servers {
let project = Project::cart(label);
project.write("playwright.config.js", "export default {};\n");
for (file, text) in files {
project.write(file, text);
}
project.commit("server");
let run = project.supercov(&["--", "node", "--test"]);
assert_eq!(run.code(), 0, "{label}: {}", run.stderr());
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(
runs["data"]["runs"].as_array().unwrap().len(),
1,
"{label}: {runs}"
);
}
}
/// A Rust project whose Cargo metadata is no JSON, whose module file is a
/// link to nothing, or whose library lies outside it is refused before a
/// test runs, saying what was wrong.
#[cfg(unix)]
#[test]
fn a_rust_project_supercov_cannot_lay_out_is_refused() {
let crate_toml =
"[package]\nname = \"r\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n";
let lib = "pub fn one() -> u8 {\n 1\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn one() {\n assert_eq!(super::one(), 1);\n }\n}\n";
let refused = |project: &Project, environment: &[(&str, &str)], said: &str| {
project.git(&["init", "-q"]);
let ran = project.supercov_with(&["--", "cargo", "test"], environment);
assert_eq!(ran.code(), 1, "{said}: {}", ran.stderr());
assert!(ran.stderr().contains(said), "{said}: {}", ran.stderr());
};
let project = Project::empty("rust-metadata-garbage");
project.write("Cargo.toml", crate_toml);
project.write("src/lib.rs", lib);
// Cargo names itself to a test it starts; a test started otherwise
// finds it on PATH.
let real = std::env::var_os("CARGO")
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::split_paths(&std::env::var_os("PATH").unwrap())
.map(|directory| directory.join("cargo"))
.find(|candidate| candidate.is_file())
})
.unwrap();
let real = real.display();
project.write_script(
"bin/cargo",
&format!(
"#!/bin/sh\nif [ \"$1\" = metadata ]; then echo not-json; exit 0; fi\nexec '{real}' \"$@\"\n"
),
);
let path = format!(
"{}:{}",
project.root.join("bin").display(),
std::env::var("PATH").unwrap()
);
refused(&project, &[("PATH", &path)], "invalid cargo metadata");
let project = Project::empty("rust-dangling-module");
project.write("Cargo.toml", crate_toml);
project.write("src/lib.rs", &format!("mod gone;\n{lib}"));
std::os::unix::fs::symlink("nowhere.rs", project.root.join("src/gone.rs")).unwrap();
refused(&project, &[], "src/gone.rs: No such file or directory");
let project = Project::empty("rust-lib-outside");
let outside = project.root.with_extension("outside.rs");
std::fs::write(&outside, lib).unwrap();
project.write(
"Cargo.toml",
&format!("{crate_toml}\n[lib]\npath = \"{}\"\n", outside.display()),
);
refused(&project, &[], "unsafe workspace path");
std::fs::remove_file(outside).unwrap();
}
/// A proc-macro crate runs in the compiler, never in a test: its files,
/// and the macros in them no probe could open, leave the run.
#[test]
fn a_proc_macro_crate_and_its_limitations_leave_the_run() {
let project = Project::empty("rust-proc-macro-limitation");
project.write(
"Cargo.toml",
"[workspace]\nmembers = [\"pm\", \"app\"]\nresolver = \"2\"\n",
);
project.write(
"pm/Cargo.toml",
"[package]\nname = \"pm\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\nproc-macro = true\n",
);
project.write(
"pm/src/lib.rs",
"use proc_macro::TokenStream;\n\nmacro_rules! same {\n ($e:expr) => {\n $e\n };\n}\n\n#[proc_macro]\npub fn keep(input: TokenStream) -> TokenStream {\n same!(input)\n}\n",
);
project.write(
"app/Cargo.toml",
"[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
);
project.write(
"app/src/lib.rs",
"pub fn one() -> u8 {\n 1\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn one() {\n assert_eq!(super::one(), 1);\n }\n}\n",
);
project.git(&["init", "-q"]);
project.supercov(&["--", "cargo", "test"]).succeeds();
let file = project
.supercov(&["runs", "latest", "file", "pm/src/lib.rs"])
.succeeds();
// One limitation, the crate's own; `same!` no longer counts.
assert!(
file.contains("Statements not executed 0")
&& file.contains("Measurement limitations 1"),
"{file}"
);
}
/// A report beside quality snapshots leaves out one whose files cannot be
/// read, and `quality scope` whose project cannot be looked at says so.
#[test]
fn a_quality_snapshot_or_scope_that_cannot_be_read_is_left_out_or_refused() {
let project = Project::cart("quality-unreadable");
project.supercov(&["--", "node", "--test"]).succeeds();
let directory = ".supercov/quality/snapshots/q_0000000000000001";
project.write(
&format!("{directory}/manifest.json"),
&serde_json::json!({
"created_at": "2026-01-01T00-00-01-000000Z",
"instrument": "catalog",
"catalog_version": "v1",
"model": "m",
"catalog": [],
})
.to_string(),
);
project.write(&format!("{directory}/files.json"), "not json");
project
.supercov(&["report", "--output", "out/report.html", "--no-open"])
.succeeds();
let scope = project.supercov_with(
&["quality", "scope"],
&[("SUPERCOV_TEST_FAULT", "fs.symlink_metadata#quality.rs:1094")],
);
let said = scope.stderr();
assert_ne!(scope.code(), 0, "{said}");
assert!(fired_at(&said, "quality.rs:1094"), "{said}");
}
/// A report names what it cannot show: a run to compare with where there is
/// none, a run that is not there, runs that cannot be listed. Beside a
/// quality snapshot with no files, or a file it gave no digest, the report
/// is made all the same.
#[test]
fn a_report_of_runs_it_cannot_find_is_refused_and_odd_snapshots_are_shown() {
let snapshot = |project: &Project, id: &str, files: serde_json::Value| {
let directory = format!(".supercov/quality/snapshots/{id}");
project.write(
&format!("{directory}/manifest.json"),
&serde_json::json!({
"created_at": format!("2026-01-01T00-00-0{}-000000Z", &id[id.len() - 1..]),
"instrument": "catalog",
"catalog_version": "v1",
"model": "m",
"catalog": [],
})
.to_string(),
);
project.write(
&format!("{directory}/files.json"),
&serde_json::json!({ "files": files }).to_string(),
);
};
let empty = Project::empty("report-without-runs");
empty.git(&["init", "-q"]);
snapshot(&empty, "q_0000000000000001", serde_json::json!([]));
let report = ["report", "--output", "r.html", "--no-open"];
let compared = empty
.supercov(&[&report[..], &["--compare", "run_0000000000000000"]].concat())
.exits(2);
assert!(compared.contains("no local coverage runs"), "{compared}");
let project = Project::cart("report-cases");
project.write(".gitignore", "r.html\nnode_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
let missing = project
.supercov(&[
"report",
"run_0000000000000000",
"--output",
"r.html",
"--no-open",
])
.exits(2);
assert!(missing.contains("coverage run not found"), "{missing}");
let unlisted = project.supercov_with(
&report,
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695")],
);
assert_eq!(unlisted.code(), 2, "{}", unlisted.stderr());
assert!(fired_at(&unlisted.stderr(), "run_store.rs:695"));
snapshot(&project, "q_0000000000000001", serde_json::json!([]));
snapshot(
&project,
"q_0000000000000002",
serde_json::json!([{"path": "src/cart.js", "status": "completed", "health": 5.0}]),
);
project.supercov(&report).succeeds();
}
/// `tests affected` resolves the project and reads each file it recorded as
/// it is now: the project that cannot be resolved refuses it, and a file
/// that cannot be read is read as gone.
#[test]
fn tests_affected_that_cannot_read_the_project_is_refused_or_reads_less() {
let project = Project::cart("affected-unread");
project.write(".gitignore", "node_modules/\n");
project.commit("ignore");
project.supercov(&["--", "node", "--test"]).succeeds();
project.edit(
"src/cart.js",
"return express ? 15 : 5;",
"return express ? 20 : 5;",
);
let unresolved = project.supercov_with(
&["runs", "latest", "tests", "affected"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.canonicalize#source_manifest.rs:816",
)],
);
assert_ne!(unresolved.code(), 0, "{}", unresolved.stderr());
assert!(fired_at(&unresolved.stderr(), "source_manifest.rs:816"));
let unread = project.supercov_with(
&["runs", "latest", "tests", "affected"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.read_to_string#source_manifest.rs:827",
)],
);
let said = format!("{}{}", unread.stdout(), unread.stderr());
assert!(!said.contains("panicked"), "{said}");
assert!(fired_at(&said, "source_manifest.rs:827"), "{said}");
}
/// A JavaScript run beside a wasm library prepares the library in the copy:
/// its Cargo metadata read and its work directory made. Either failing ends
/// the run, and says where.
#[test]
fn a_javascript_run_whose_wasm_library_cannot_be_prepared_says_so() {
for (fault, place) in [
("spawn#rust_project.rs:182", "rust_project.rs:182"),
("fs.create_dir_all#rust_wasm.rs:185", "rust_wasm.rs:185"),
] {
let project = Project::cart("wasm-library-unprepared");
project.write(".gitignore", "out/\nnode_modules/\ntarget/\n");
project.write(
"wasm/Cargo.toml",
"[package]\nname = \"w\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\nwasm-bindgen = \"0.2\"\n\n[workspace]\n",
);
project.write("wasm/src/lib.rs", "pub fn one() -> u32 {\n 1\n}\n");
project.commit("wasm");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let stderr = ran.stderr();
assert_eq!(ran.code(), 1, "{fault}: {stderr}");
assert!(fired_at(&stderr, place), "{fault} at {place}: {stderr}");
}
}
/// A source root outside the project names nothing in the copy a Rust run
/// measures, and the run says the roots left it no source.
#[test]
fn a_rust_run_whose_source_root_lies_outside_the_project_says_so() {
let project = Project::empty("roots-outside-rust");
let outside = project.root.with_extension("outside");
std::fs::create_dir_all(&outside).unwrap();
project.write(
"Cargo.toml",
"[package]\nname = \"r\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
);
project.write(
"src/lib.rs",
"pub fn one() -> u8 {\n 1\n}\n#[cfg(test)]\nmod tests {\n #[test]\n fn one() {\n assert_eq!(super::one(), 1);\n }\n}\n",
);
project.git(&["init", "-q"]);
let ran = project.supercov_with(
&["--", "cargo", "test"],
&[("SUPERCOV_SOURCE_ROOTS", outside.to_str().unwrap())],
);
std::fs::remove_dir_all(&outside).unwrap();
assert_eq!(ran.code(), 1, "{}", ran.stderr());
assert!(
ran.stderr().contains("left no Rust source to measure"),
"{}",
ran.stderr()
);
}
/// What each test ran is published with the run, in the same step: a record
/// that cannot be written leaves the run unpublished, and says why.
#[test]
fn a_run_whose_execution_record_cannot_be_written_is_not_published() {
let project = Project::cart("executions-unwritten");
let ran = project.supercov_with(
&["--", "node", "--test"],
&[(
"SUPERCOV_TEST_FAULT",
"fs.create_dir_all#source_manifest.rs:465",
)],
);
assert_eq!(ran.code(), 1, "{}", ran.stderr());
assert!(
ran.stderr()
.contains("invalid run state: source manifest publication: "),
"{}",
ran.stderr()
);
let runs = project.supercov(&["runs", "--json"]).json();
assert_eq!(
runs["data"]["runs"].as_array().map(Vec::len),
Some(0),
"{runs}"
);
}
/// The index publication writes beside the run is a cache: one that cannot
/// be written leaves the run published, and a query builds it.
#[test]
fn a_run_whose_index_cannot_be_written_is_still_published() {
let project = Project::cart("index-unwritten");
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "fs.rename#query_index.rs:323")],
);
assert_eq!(ran.code(), 0, "{}", ran.stderr());
assert!(
ran.stderr()
.contains("test fault at fs (query_index.rs:323 rename)"),
"{}",
ran.stderr()
);
let run = project.latest();
assert!(
project
.supercov(&["runs", &run, "files"])
.succeeds()
.contains("src/cart.js")
);
}
/// A run with source under no root names it in its summary, from the scope's
/// entries: entries that cannot be read refuse the summary.
#[test]
fn a_summary_whose_unclassified_source_cannot_be_read_is_refused() {
let project = Project::cart("summary-unclassified");
project.write("misc/tool.js", "export const tool = 1;\n");
project.commit("misc");
project.measure(&[]);
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(summary.contains("Unclassified source: misc 1"), "{summary}");
let refused = project.supercov_with(
&["runs", "latest"],
&[(
"SUPERCOV_TEST_FAULT",
"coverage-index-read#coverage_query.rs:3404",
)],
);
let said = format!("{}{}", refused.stdout(), refused.stderr());
assert_eq!(refused.code(), 2, "{said}");
assert!(fired_at(&said, "coverage_query.rs:3404"), "{said}");
}
/// A record the run's evidence holds that is no JSON -- a process that tore
/// it as it died -- refuses the run and names the file and line.
#[test]
fn a_run_whose_evidence_holds_a_torn_record_is_refused() {
let project = Project::cart("torn-record");
project.write(
"test/tear.test.js",
"import test from \"node:test\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\ntest(\"tears a record\", () => {\n const directory = path.join(process.env.SUPERCOV_SERVER_EVIDENCE_ROOT, process.env.SUPERCOV_RUN_ID);\n fs.mkdirSync(directory, { recursive: true });\n fs.writeFileSync(path.join(directory, \"torn.mcdc.jsonl\"), \"{\\\"test\\\":\\n\");\n});\n",
);
project.commit("tear");
let ran = project.supercov(&["--", "node", "--test"]);
assert_ne!(ran.code(), 0, "{}", ran.stderr());
assert!(
ran.stderr()
.contains("invalid server/torn.mcdc.jsonl record at line 1"),
"{}",
ran.stderr()
);
}
/// A query of a run the checkout has moved past names the files that moved
/// from the run's record of them; a record that cannot be read names none,
/// and the query still answers, as stale.
#[test]
fn a_stale_query_whose_record_cannot_be_read_still_answers() {
let project = Project::cart("stale-unrecorded");
project.measure(&[]);
project.edit("src/cart.js", "let sum = 0;", "let sum = 0; // edited");
let ran = project.supercov_with(
&["runs", "latest", "files", "--json"],
&[("SUPERCOV_TEST_FAULT", "fs.open#source_manifest.rs:381")],
);
assert!(
ran.stderr()
.contains("test fault at fs (source_manifest.rs:381 open)"),
"{}",
ran.stderr()
);
let json = ran.json();
assert_eq!(json["ok"], true, "{json}");
}
/// A merged run is judged against the command of the runs it was merged
/// from; a store that cannot be listed again for them leaves it judged by
/// its own, and the query still answers.
#[test]
fn a_merged_run_whose_parents_cannot_be_listed_is_judged_by_its_own_command() {
let project = Project::cart("merged-unlisted");
let first = project.measure(&[]);
let second = project.measure(&[]);
project.supercov(&["merge", &first, &second]).succeeds();
let ran = project.supercov_with(
&["runs", "latest", "files"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695@2")],
);
assert!(
ran.stderr()
.contains("test fault at fs (run_store.rs:695 read_dir)"),
"{}",
ran.stderr()
);
assert!(ran.succeeds().contains("src/cart.js"));
}
/// rustdoc's stand-in starts rustdoc for the list pass and again for the
/// merged harness, and the run reads back what each package recorded: each
/// failing ends the run, naming where.
#[cfg(unix)]
#[test]
fn a_doctest_stand_ins_rustdoc_or_a_package_record_that_fails_is_named() {
let stand_in = "env:SUPERCOV_DOCTEST_WRAPPER_ROOT/";
for (edition, fault, place) in [
(
"2024",
format!("{stand_in}spawn#rust_owned_doctests.rs:820@1"),
"rust_owned_doctests.rs:820",
),
(
"2024",
format!("{stand_in}spawn#rust_owned_doctests.rs:820@2"),
"rust_owned_doctests.rs:820",
),
(
"2021",
"fs.read#rust_owned_doctests.rs:289".to_owned(),
"rust_owned_doctests.rs:289",
),
(
"2024",
format!("{stand_in}fs.read#rust_owned_doctests.rs:1104@1"),
"rust_owned_doctests.rs:1104",
),
// The stand-in's own path, and the merged harness runner's: each
// resolves itself first.
(
"2024",
format!("{stand_in}fs.canonicalize@1"),
"canonicalize",
),
(
"2024",
"__doctest-runner/fs.canonicalize@1".to_owned(),
"canonicalize",
),
// The merged harness's order, and a child's record, read back.
(
"2024",
"__doctest-runner/fs.read#rust_owned_doctests.rs:1202".to_owned(),
"rust_owned_doctests.rs:1202",
),
(
"2024",
"__doctest-runner/fs.read#rust_owned_doctests.rs:1213".to_owned(),
"rust_owned_doctests.rs:1213",
),
] {
let project = Project::empty("doctest-stand-in-steps");
small_crate(&project);
project.edit(
"Cargo.toml",
"edition = \"2021\"",
&format!("edition = \"{edition}\""),
);
project.git(&["init", "-q"]);
project.commit("fixture");
let ran = project.supercov_with(
&["--", "cargo", "test", "-q"],
&[("SUPERCOV_TEST_FAULT", fault.as_str())],
);
let said = format!("{}{}", ran.stdout(), ran.stderr());
assert_ne!(ran.code(), 0, "{edition} {fault}: {said}");
assert!(fired_at(&said, place), "{edition} {fault}: {said}");
assert!(!said.contains("panicked at"), "{edition} {fault}: {said}");
}
}
/// A line the index holds no text of is read from the working tree, said
/// stale when its file changed since the run; with no record of the run's
/// files to judge by, it is read as current.
#[test]
fn a_line_read_from_the_working_tree_is_stale_only_by_the_runs_record() {
let project = Project::cart("line-origin");
project.measure(&[]);
project.edit("src/cart.js", "let sum = 0;", "let sum = 0; // edited");
let origin = |faults: &str| {
project
.supercov_with(
&["runs", "latest", "line", "src/cart.js:5", "--json"],
&[("SUPERCOV_TEST_FAULT", faults)],
)
.json()["data"]["sourceOrigin"]
.clone()
};
assert_eq!(origin(""), "working-tree-stale");
assert_eq!(
origin("fs.open#source_manifest.rs:381=10"),
"working-tree-current"
);
}
/// A failing command whose run cannot be read back keeps its exit code,
/// with no failed tests named.
#[test]
fn a_failing_run_that_cannot_be_read_back_names_no_failed_tests() {
let project = Project::cart("failed-unread");
project.write(
"test/wrong.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\ntest('wrong', () => assert.equal(1, 2));\n",
);
let ran = project.supercov_with(
&["--", "node", "--test"],
&[("SUPERCOV_TEST_FAULT", "coverage-index=50")],
);
assert_eq!(ran.code(), 1, "{}", ran.stderr());
assert!(
fired_at(&ran.stderr(), "coverage-index"),
"{}",
ran.stderr()
);
assert!(!ran.stderr().contains("test(s) failed"), "{}", ran.stderr());
}
/// Several lines asked at once: a line that holds only the anchors of its
/// statement's other lines is answered beside one that ran.
#[test]
fn several_lines_answer_a_line_of_anchors_beside_a_line_that_ran() {
let project = Project::cart("several-anchors");
project.measure(&[]);
let answer = project
.supercov(&[
"runs",
"latest",
"line",
"src/cart.js:5",
"src/cart.js:14",
"--json",
])
.json();
let lines = answer["data"]["lines"].as_array().unwrap();
let asked = lines
.iter()
.map(|line| line["location"]["line"].as_u64().unwrap())
.collect::<Vec<_>>();
assert_eq!(asked, [5, 14], "{answer}");
}
/// The source roots named, read again in the copy for a Go server beside a
/// browser suite: roots the copy cannot answer for leave the server
/// unmeasured, and the suite is measured all the same.
#[test]
fn a_go_server_whose_roots_cannot_be_read_in_the_copy_is_left_unmeasured() {
if go().is_none() {
return;
}
let project = Project::cart("browser-go-roots");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write("go.mod", "module example.com/w\n\ngo 1.22\n");
project.write(
"main.go",
"package main\n\nfunc hello() int { return 1 }\n\nfunc main() { hello() }\n",
);
project.commit("go");
// The suite's own discovery reads both roots; the server's, the third.
let ran = project.supercov_with(
&["--", "node", "--test"],
&[
(
"SUPERCOV_TEST_FAULT",
"fs.symlink_metadata#source_discovery.rs:475@3",
),
("SUPERCOV_SOURCE_ROOTS", "src,main.go"),
],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 0, "{stderr}");
assert!(fired_at(&stderr, "source_discovery.rs:475"), "{stderr}");
}
/// The source roots named, read again in the copy for a Java server beside
/// a browser suite: roots the copy cannot answer for leave the server
/// unmeasured, and the suite is measured all the same.
#[test]
fn a_java_server_whose_roots_cannot_be_read_in_the_copy_is_left_unmeasured() {
let project = Project::cart("browser-java-roots");
project.write(".gitignore", "out/\nnode_modules/\n");
project.write("playwright.config.js", "export default {};\n");
project.write(
"pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>e</groupId><artifactId>w</artifactId><version>1</version></project>\n",
);
project.write(
"src/main/java/w/W.java",
"package w;\npublic class W { public static int one() { return 1; } }\n",
);
project.commit("java");
// The suite's own discovery reads the root; the server's, the second.
let ran = project.supercov_with(
&["--", "node", "--test"],
&[
(
"SUPERCOV_TEST_FAULT",
"fs.symlink_metadata#source_discovery.rs:475@2",
),
("SUPERCOV_SOURCE_ROOTS", "src"),
],
);
let stderr = ran.stderr();
assert_eq!(ran.code(), 0, "{stderr}");
assert!(fired_at(&stderr, "source_discovery.rs:475"), "{stderr}");
}
/// A directory discovery cannot list, or whose listing breaks off, while
/// looking for a nested Playwright configuration holds none: the run goes on.
#[test]
fn a_directory_discovery_cannot_list_holds_no_configuration() {
for fault in [
"fs.read_dir#project_discovery.rs:349",
"fs.read_dir entry#project_discovery.rs:349",
] {
let project = Project::cart("discovery-unlisted");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 0, "{fault}: {said}");
assert!(
fired_at(&said, "project_discovery.rs:349"),
"{fault}: {said}"
);
}
}
/// A check reads each condition no test showed deciding its decision, file
/// by file, where it is.
#[test]
fn a_check_names_each_missing_condition_by_its_place() {
let project = Project::cart("check-conditions");
project.measure(&[]);
let checked = project
.supercov(&["runs", "check", "--min-mcdc", "100", "--json"])
.json();
let files = checked["data"]["view"]["files"].as_array().unwrap();
let cart = files
.iter()
.find(|file| file["file"] == "src/cart.js")
.unwrap();
let missing = cart["missingConditions"].as_array().unwrap();
assert!(!missing.is_empty(), "{checked}");
assert!(missing.iter().all(|place| place["line"].as_u64().is_some()));
}
/// A condition a decision's tests saw both ways but never alone deciding it
/// is said to be that, and one never seen true is said to be that.
#[test]
fn a_decision_names_a_condition_seen_both_ways_that_never_decided_alone() {
let project = Project::empty("masked-condition");
project.write(
"package.json",
r#"{ "name": "masked", "private": true, "type": "module" }"#,
);
project.write(
"src/a.js",
"export function f(a, b) {\n if (a && b) return 1;\n return 2;\n}\n",
);
project.write(
"test/a.test.js",
"import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { f } from '../src/a.js';\ntest('tf', () => assert.equal(f(true, false), 2));\ntest('ff', () => assert.equal(f(false, false), 2));\n",
);
project.git(&["init", "-q"]);
project.measure(&[]);
contains_all(
&project
.supercov(&["runs", "latest", "decision", "src/a.js:2"])
.succeeds(),
&[
"C1 MISSING: a (seen both ways, never deciding alone)",
"C2 MISSING: b (never true)",
],
);
}
#[test]
fn bun_native_callback_arity_is_preserved_inside_describe() {
if !bun_is_available() {
return;
}
let project = bun_project("bun-arity-probe", false);
project.write(
"src/clamp.test.ts",
r#"import { test, describe } from 'bun:test';
const run = test.concurrent ?? test;
const callback = async () => { await new Promise(r => setTimeout(r, 1)); };
function wrapped() { return Reflect.apply(callback, this, arguments); }
Object.defineProperty(wrapped, 'length', {value:0});
describe('group', () => { run('wrapped', wrapped); });
"#,
);
let native = std::process::Command::new("bun")
.args(["test"])
.current_dir(&project.root)
.output()
.unwrap();
assert!(
native.status.success(),
"native Bun: {}",
String::from_utf8_lossy(&native.stderr)
);
let adapter = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../runtime/javascript/bunTest.mjs");
let adapted = std::process::Command::new("bun")
.args(["test", "--preload"])
.arg(adapter)
.current_dir(&project.root)
.output()
.unwrap();
assert!(
adapted.status.success(),
"adapted Bun: {}",
String::from_utf8_lossy(&adapted.stderr)
);
}
/// An Ant build is read before it runs: what it compiles is its product code,
/// what it writes into is not, and `SUPERCOV_TEST_ROOTS` says where its tests
/// are when its own words cannot. A stand-in for Ant shows what Supercov
/// decided without needing one: it runs no task, so it records nothing, and
/// the run says what an Ant build has to reach.
#[cfg(unix)]
#[test]
fn an_ant_build_is_read_before_it_runs() {
let project = Project::empty("ant-read");
project.write(
"build.xml",
r#"<project default="test"><target name="test"><javac srcdir="src" destdir="classes"/><junit><batchtest><fileset dir="checks"/></batchtest></junit></target></project>"#,
);
project.write(
"src/app/Calc.java",
"package app;\npublic class Calc { public static int twice(int x) { return 2 * x; } }\n",
);
project.write(
"checks/app/CalcTest.java",
"package app;\npublic class CalcTest {}\n",
);
// Java the build compiled into place earlier is output, not source.
project.write("classes/app/Stale.java", "package app;\nclass Stale {}\n");
// A file whose package is not where it sits says nothing of its root.
project.write(
"src/misplaced/Odd.java",
"package elsewhere;\nclass Odd {}\n",
);
project.write_script("ant", "#!/bin/sh\nexit 0\n");
project.write_script("ant.bat", "#!/bin/sh\nexit 0\n");
let ran = project.supercov(&["--", "./ant", "test"]);
let stderr = ran.stderr();
assert_ne!(ran.code(), 0, "{stderr}");
contains_all(
&stderr,
&[
"instrumenting 2 source file(s)",
"An Ant build reports through its <junit>, <junitlauncher> and <testng> tasks",
],
);
// A blank override is no override.
let blank = project.supercov_with(&["--", "./ant", "test"], &[("SUPERCOV_TEST_ROOTS", " ")]);
assert!(
blank.stderr().contains("instrumenting 2 source file(s)"),
"{}",
blank.stderr()
);
// Named as tests, the product code leaves nothing to measure.
let named = project.supercov_with(&["--", "./ant", "test"], &[("SUPERCOV_TEST_ROOTS", "src")]);
assert!(
named
.stderr()
.contains("no source root of this Ant build holds product code"),
"{}",
named.stderr()
);
// A build that runs its tests through none of the tasks Supercov reads
// leaves them unattributed, and says so in Ant's terms.
project.write(
"build.xml",
r#"<project default="test"><target name="test"><javac srcdir="src" destdir="classes"/><java classname="Runner"/></target></project>"#,
);
let untasked = project.supercov_with(
&["--", "./ant", "test"],
&[("SUPERCOV_TEST_ROOTS", "checks")],
);
contains_all(
&untasked.stderr(),
&["through no <junit>, <junitlauncher> or <testng> task Supercov can find"],
);
assert!(
!untasked.stderr().contains("junit-vintage-engine"),
"{}",
untasked.stderr()
);
// Without tests to run there is nothing left unattributed to mention.
let testless = project.supercov_with(
&["--", "./ant", "test"],
&[("SUPERCOV_TEST_ROOTS", "nothing")],
);
let stderr = testless.stderr();
assert!(
stderr.contains("instrumenting 2 source file(s)"),
"{stderr}"
);
assert!(!stderr.contains("Supercov can find"), "{stderr}");
// A build file holding Supercov's own changes is one an earlier run left,
// and patching it again would run that run's compilation.
for leftover in [
r#"<formatter classname="com.supercorp.supercov.SupercovAntFormatter"/>"#,
r#"<listener classname="com.supercorp.supercov.SupercovListener"/>"#,
r#"<testng listeners="com.supercorp.supercov.SupercovTestNGListener"/>"#,
] {
project.write(
"build.xml",
&format!(r#"<project default="test"><target name="test"><junit>{leftover}<batchtest><fileset dir="checks"/></batchtest></junit></target></project>"#),
);
let left = project.supercov(&["--", "./ant", "test"]);
assert!(
left.stderr()
.contains("still holds an earlier run's changes"),
"{leftover}: {}",
left.stderr()
);
}
// Ant run on another build file is refused: the build Supercov reads is
// the one where it runs.
project.write("sub/build.xml", "<project/>");
let elsewhere = project.supercov(&["--", "./ant.bat", "-f", "sub/build.xml"]);
assert_ne!(elsewhere.code(), 0, "{}", elsewhere.stderr());
assert!(
elsewhere
.stderr()
.contains("run Supercov from that file's directory"),
"{}",
elsewhere.stderr()
);
}
/// A process the suite starts that a crash signal ends says nothing of it:
/// on 2026-11-06 a backend that died so right after it listened read as one
/// that never became ready. The run names it, and a child its test stops
/// with SIGTERM is not named.
#[cfg(unix)]
#[test]
fn a_child_a_crash_signal_ends_is_named() {
let project = Project::cart("crashed-child");
project.write(
"test/server.test.js",
r#"import { test } from "node:test";
import { spawn, spawnSync } from "node:child_process";
test("the helper server crashes, the test does not", () => {
spawnSync(process.execPath, ["-e", "process.kill(process.pid, 'SIGSEGV')"]);
});
test("a server the test stops is not a crash", async () => {
const server = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"]);
server.kill("SIGTERM");
await new Promise((done) => server.once("exit", done));
});
"#,
);
project.commit("a crashing helper");
let measured = project.supercov(&["--", "node", "--test"]);
let output = measured.exits(0);
let named: Vec<&str> = output
.lines()
.filter(|line| line.contains("crashed with"))
.collect();
assert_eq!(named.len(), 1, "{output}");
contains_all(
named[0],
&[
"[supercov] warning:",
"crashed with SIGSEGV",
"s after it started",
],
);
assert!(!output.contains("SIGTERM"), "{output}");
}
/// A mocha project whose tests leave a boundary unhit and a function
/// uncalled, with node_modules from the repository.
#[cfg(unix)]
fn mutants_project(label: &str) -> Project {
let project = Project::empty(label);
project.write(
"package.json",
r#"{ "name": "mutants", "type": "module", "scripts": { "test": "mocha" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n");
project.write(
"src/cart.js",
"export function shipping(sum) {\n if (sum >= 50) {\n return 0;\n }\n return 5;\n}\n\nexport function label(name) {\n return name.trim().toUpperCase();\n}\n\nexport function refund(sum) {\n return sum > 100 ? sum * 0.9 : sum;\n}\n",
);
project.write(
"test/cart.test.js",
"import assert from \"node:assert/strict\";\nimport { shipping, label } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => assert.equal(shipping(80), 0));\n it(\"charges small orders\", () => assert.equal(shipping(10), 5));\n it(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n});\n",
);
project.git(&["init", "-q"]);
project.commit("mutants");
project
}
/// Each mutant's status in a `mutants --json` reply, by id.
#[cfg(unix)]
fn mutant_statuses(reply: &serde_json::Value) -> std::collections::BTreeMap<String, String> {
reply["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["id"].as_str().unwrap().to_owned(),
mutant["status"].as_str().unwrap().to_owned(),
)
})
.collect()
}
/// `mutants --diff`: only the mutants on lines a change added or modified
/// since it left a base, the tests' survivors first, as a pull request's
/// comment, and as a gate.
#[cfg(unix)]
#[test]
fn mutants_on_a_change_are_those_on_its_lines() {
let project = mutants_project("mutants-diff");
project.write(".gitignore", "node_modules\n.supercov\n");
project.commit("ignore the runs");
project.git(&["branch", "base"]);
// The change: a new module and its test, and one line of the old one.
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import assert from \"node:assert/strict\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => assert.equal(tax(20), 4));\n",
);
project.edit("src/cart.js", "return 5;", "return 6;");
project.edit("test/cart.test.js", "shipping(10), 5", "shipping(10), 6");
project.commit("tax");
let head = project.git(&["rev-parse", "HEAD"]).trim().to_owned();
let merge_base = project.git(&["rev-parse", "base"]).trim().to_owned();
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let reply = project
.supercov(&[
"runs", "latest", "mutants", "--diff", "base", "--json", "--limit", "0",
])
.json();
let data = &reply["data"];
assert_eq!(data["diff"]["base"], "base");
assert_eq!(data["diff"]["mergeBase"], merge_base.as_str());
assert_eq!(data["diff"]["commit"], head.as_str());
// tax.js's three lines, and cart.js's changed `return`, whose only
// mutant is the body around it, emptied.
assert_eq!(data["diff"]["changedLines"], 4, "{data}");
assert_eq!(data["diff"]["linesWithMutants"], 4, "{data}");
let mutants = data["mutants"].as_array().unwrap();
assert!(!mutants.is_empty());
assert!(
mutants.iter().all(|mutant| mutant["file"] == "src/tax.js"
|| mutant["id"].as_str().is_some_and(
|id| id.starts_with("src/cart.js:1:") && id.ends_with("-6:2:BlockStatement:{}")
)),
"{data}"
);
// The survivors first: `sum` was 20, never 10.
assert_eq!(mutants[0]["status"], "not-infected", "{data}");
assert!(
mutants.iter().any(
|mutant| mutant["id"] == "src/tax.js:2:10-2:19:EqualityOperator:>"
&& mutant["status"] == "not-infected"
),
"{data}"
);
let ranks = mutants
.iter()
.map(|mutant| match mutant["status"].as_str() {
Some("not-infected") => 0,
Some("not-reached") => 1,
_ => 2,
})
.collect::<Vec<_>>();
assert!(ranks.is_sorted(), "{data}");
assert_eq!(data["summary"]["mutants"], mutants.len());
let human = project
.supercov(&["runs", "latest", "mutants", "--diff", "base"])
.succeeds();
contains_all(
&human,
&[
"Change ",
"(where it left base)",
"Lines 4 added or changed, 4 with mutants",
"Not infected",
"src/tax.js:2:10",
"sum >= 10 → sum > 10",
"why: `sum` never equal to `10`",
"Not listed: ",
"--diff 'base' --status infected",
],
);
assert!(!human.contains("src/cart.js:"), "{human}");
let markdown = project
.supercov(&[
"runs", "latest", "mutants", "--diff", "base", "--format", "markdown",
])
.succeeds();
contains_all(
&markdown,
&[
"### Mutants on this change",
"on 4 of 4 changed lines since `base`",
"| Where | Mutant | Status | Why |",
"| `src/tax.js:2:10` | `sum >= 10 → sum > 10` | not infected | `sum` never equal to `10` |",
],
);
// A gate: a mutant the tests leave alive on the change fails it.
let failed = project
.supercov(&[
"runs",
"latest",
"mutants",
"--diff",
"base",
"--fail-on",
"not-infected,not-reached",
])
.exits(1);
assert!(
failed.contains("FAILED --fail-on not-infected,not-reached"),
"{failed}"
);
project
.supercov(&[
"runs",
"latest",
"mutants",
"--diff",
"base",
"--fail-on",
"equivalent",
])
.succeeds();
project
.supercov(&[
"runs",
"latest",
"mutants",
"--diff",
"base",
"--format",
"markdown",
"--fail-on",
"not-infected",
])
.exits(1);
let gated = project
.supercov(&[
"runs",
"latest",
"mutants",
"--diff",
"base",
"--fail-on",
"not-infected",
"--json",
])
.exits(1);
assert!(gated.contains("\"failOn\""), "{gated}");
// A base git does not know is refused, saying why.
let refused = project
.supercov(&["runs", "latest", "mutants", "--diff", "no-such-branch"])
.exits(2);
assert!(
refused.contains("git knows no commit by that name"),
"{refused}"
);
}
#[cfg(unix)]
#[test]
fn mutants_say_how_far_the_tests_got_toward_killing_each() {
let project = mutants_project("mutants");
// Listed by default.
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(
&summary,
&[
"Mutants 15 · weak score 53.3% · 1 not infected · 6 not reached · 0 unknown · 0 equivalent",
],
);
let summary = project.supercov(&["runs", "latest", "--json"]).json();
assert_eq!(summary["data"]["mutants"]["mutantSet"], "stryker-js@10.1.1");
assert_eq!(summary["data"]["mutants"]["mutants"], 15);
let reply = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
assert_eq!(reply["command"], "coverage.mutants");
let data = &reply["data"];
assert_eq!(data["mutantSet"], "stryker-js@10.1.1");
assert_eq!(
data["levels"],
serde_json::json!({"weak": true, "strong": false})
);
assert_eq!(
data["summary"],
serde_json::json!({
"mutants": 15,
"status": {"not-reached": 6, "not-infected": 1, "infected": 8, "unknown": 0, "equivalent": 0},
"untestable": 0,
"weakScore": 0.5333,
"weakScoreReached": 0.8889,
"mutationScore": null,
})
);
assert_eq!(data["stryker"], serde_json::Value::Null);
let statuses = mutant_statuses(&reply);
for (id, status) in [
// `sum` was 80 and 10, never 50.
("src/cart.js:2:7-2:16:EqualityOperator:>", "not-infected"),
("src/cart.js:2:7-2:16:EqualityOperator:<", "infected"),
(
"src/cart.js:2:7-2:16:ConditionalExpression:false",
"infected",
),
// No test calls `refund`.
(
"src/cart.js:13:10-13:19:ConditionalExpression:true",
"not-reached",
),
(
"src/cart.js:13:22-13:31:ArithmeticOperator:/",
"not-reached",
),
("src/cart.js:9:10-9:21:MethodExpression:removed", "infected"),
] {
assert_eq!(
statuses.get(id).map(String::as_str),
Some(status),
"{id}: {statuses:?}"
);
}
let boundary = data["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "src/cart.js:2:7-2:16:EqualityOperator:>")
.unwrap();
assert_eq!(
boundary,
&serde_json::json!({
"id": "src/cart.js:2:7-2:16:EqualityOperator:>",
"file": "src/cart.js",
"span": {"start": [2, 7], "end": [2, 16]},
"mutator": "EqualityOperator",
"original": "sum >= 50",
"replacement": "sum > 50",
"status": "not-infected",
"weak": {
"reach": "reached",
"infection": "not-infected",
"code": "operands-never-equal",
"reason": "`sum` never equal to `50`",
},
"strong": null,
"stryker": null,
})
);
// The table, a file by line, and a line with its reasons.
let table = project.supercov(&["runs", "latest", "mutants"]).succeeds();
contains_all(
&table,
&[
"Mutants of run",
"(stryker-js@10.1.1, weak mutation)",
"Weak score 53.3% · 88.9% of reached mutants",
"File Mutants Not infected Not reached Infected Unknown",
"src/cart.js 15 1 6 8 0",
"showing 1-1 of 1 files",
],
);
let file = project
.supercov(&["runs", "latest", "mutants", "src/cart.js"])
.succeeds();
contains_all(
&file,
&[
"sum >= 50 → sum > 50",
"not-infected `sum` never equal to `50`",
"13:22 ArithmeticOperator",
"sum * 0.9 → sum / 0.9",
"no test ran its statement",
"showing 1-15 of 15",
],
);
let line = project
.supercov(&["runs", "latest", "mutants", "src/cart.js:2"])
.succeeds();
contains_all(
&line,
&[
"in src/cart.js:2 ",
"2:7 EqualityOperator not-infected",
" why: `sum` never equal to `50` (operands-never-equal)",
" id: src/cart.js:2:7-2:16:EqualityOperator:>",
],
);
assert!(!line.contains("13:10"), "{line}");
// `--status` picks mutants across files; the summary stays the run's.
let picked = project
.supercov(&[
"runs",
"latest",
"mutants",
"--status",
"not-infected,not-reached",
"--json",
])
.json();
let statuses = mutant_statuses(&picked);
assert_eq!(statuses.len(), 7, "{statuses:?}");
assert!(
statuses
.values()
.all(|status| status == "not-infected" || status == "not-reached"),
"{statuses:?}"
);
assert_eq!(picked["data"]["summary"]["mutants"], 15);
let listed = project
.supercov(&["runs", "latest", "mutants", "--status", "not-infected"])
.succeeds();
contains_all(&listed, &["src/cart.js:2:7", "showing 1-1 of 1"]);
// A strong verdict picks the mutants a strong pass gave it: none ran.
let killed = project
.supercov(&["runs", "latest", "mutants", "--status", "killed"])
.succeeds();
assert!(killed.contains("No mutants match."), "{killed}");
// Only the tests a title picks: the boundary they never cross.
let narrowed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js:2",
"--title",
"ships big",
"--json",
])
.json();
let statuses = mutant_statuses(&narrowed);
assert_eq!(
statuses
.get("src/cart.js:2:7-2:16:ConditionalExpression:true")
.map(String::as_str),
Some("not-infected"),
"{statuses:?}"
);
// StrykerJS's results joined by id: one kill this run agrees with, one it
// says was impossible, one survivor it explains, one mutant it lacks.
let source = project.read("src/cart.js");
let mutant =
|mutator: &str, start: [u32; 2], end: [u32; 2], replacement: &str, status: &str| {
serde_json::json!({
"id": "1",
"mutatorName": mutator,
"replacement": replacement,
"location": {
"start": {"line": start[0], "column": start[1]},
"end": {"line": end[0], "column": end[1]},
},
"status": status,
})
};
project.write(
"reports/mutation.json",
&serde_json::json!({
"schemaVersion": "1",
"thresholds": {"high": 80, "low": 60},
"files": {"src/cart.js": {"language": "javascript", "source": source, "mutants": [
mutant("ConditionalExpression", [2, 7], [2, 16], "true", "Killed"),
mutant("EqualityOperator", [2, 7], [2, 16], "sum > 50", "Killed"),
mutant("ConditionalExpression", [13, 10], [13, 19], "true", "Survived"),
mutant("StringLiteral", [9, 3], [9, 4], "\"\"", "Survived"),
mutant("EqualityOperator", [13, 10], [13, 19], "sum >= 100", "CompileError"),
]}},
})
.to_string(),
);
let joined = project
.supercov(&[
"runs",
"latest",
"mutants",
"--stryker",
"reports/mutation.json",
])
.exits(1);
contains_all(
&joined,
&[
"StrykerJS (reports/mutation.json)",
"Matched 3",
"Only in StrykerJS 1 (StringLiteral 1)",
"Survivors explained 1 of 1",
"SOUNDNESS VIOLATIONS 1",
"src/cart.js:2:7-2:16:EqualityOperator:> not-infected here, Killed by StrykerJS",
],
);
let joined = project.supercov(&[
"runs",
"latest",
"mutants",
"--stryker",
"reports/mutation.json",
"--json",
"--limit",
"0",
]);
assert_eq!(joined.code(), 1, "{}", joined.stderr());
let joined = joined.json();
let stryker = &joined["data"]["stryker"];
assert_eq!(stryker["matched"], 3);
assert_eq!(stryker["onlyStryker"]["byMutator"]["StringLiteral"], 1);
assert_eq!(stryker["onlySupercov"]["total"], 12);
assert_eq!(stryker["soundnessViolations"]["total"], 1);
assert_eq!(
stryker["soundnessViolations"]["mutants"][0]["id"],
"src/cart.js:2:7-2:16:EqualityOperator:>"
);
assert_eq!(
stryker["survivorsExplained"],
serde_json::json!({"survivors": 1, "explained": 1})
);
let killed = joined["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "src/cart.js:2:7-2:16:ConditionalExpression:true")
.unwrap();
assert_eq!(killed["stryker"], "Killed");
// Paths relative to another directory are named from the project root.
project.write(
"reports/nested/mutation.json",
&project
.read("reports/mutation.json")
.replace("\"src/cart.js\"", "\"../../src/cart.js\""),
);
let rooted = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js:2",
"--stryker",
"reports/nested/mutation.json",
"--stryker-root",
"reports/nested",
"--json",
])
.json();
assert_eq!(rooted["data"]["stryker"]["matched"], 2);
assert_eq!(rooted["data"]["stryker"]["onlyStryker"]["total"], 0);
// A report in chunks: several after one --stryker, or their directory.
let report: serde_json::Value =
serde_json::from_str(&project.read("reports/mutation.json")).unwrap();
let chunk_mutants = report["files"]["src/cart.js"]["mutants"]
.as_array()
.unwrap()
.clone();
for (number, mutants) in chunk_mutants.chunks(2).enumerate() {
let mut chunk = report.clone();
chunk["files"]["src/cart.js"]["mutants"] = serde_json::Value::from(mutants.to_vec());
project.write(&format!("chunks/part/r0{number}.json"), &chunk.to_string());
}
project.write("chunks/notes.txt", "not a report");
let matched = |arguments: &[&str]| {
let mut command = vec!["runs", "latest", "mutants", "--json", "--limit", "0"];
command.extend(arguments);
let joined = project.supercov(&command);
assert_eq!(joined.code(), 1, "{arguments:?}: {}", joined.stderr());
let joined = joined.json();
(
joined["data"]["stryker"]["matched"].clone(),
joined["data"]["stryker"]["reports"].clone(),
)
};
let chunks = serde_json::json!([
"chunks/part/r00.json",
"chunks/part/r01.json",
"chunks/part/r02.json"
]);
assert_eq!(
matched(&["--stryker", "chunks"]),
(3.into(), chunks.clone())
);
assert_eq!(
matched(&[
"--stryker",
"chunks/part/r00.json",
"chunks/part/r01.json",
"chunks/part/r02.json",
"chunks/part/r00.json",
]),
(3.into(), chunks)
);
// More than a few reports are not repeated in every command shown.
project.write(
"chunks/part/r03.json",
&project.read("reports/mutation.json"),
);
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"--stryker",
"chunks/part/r00.json",
"chunks/part/r01.json",
"chunks/part/r02.json",
"chunks/part/r03.json",
])
.exits(1);
contains_all(
&listed,
&[
"StrykerJS (4 reports)",
"mutants 'src/cart.js' --stryker <4 reports>",
"<4 reports> in these commands: the reports given to --stryker",
],
);
assert!(!listed.contains("r01.json"), "{listed}");
let directory = project
.supercov(&["runs", "latest", "mutants", "--stryker", "chunks/part"])
.exits(1);
contains_all(
&directory,
&[
"StrykerJS (4 reports in chunks/part)",
"mutants 'src/cart.js' --stryker 'chunks/part'",
],
);
// Every mutant at once, one per line, each as --json lists it.
let all = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let exported = project
.supercov(&["runs", "latest", "mutants", "--format", "jsonl"])
.succeeds();
let lines = exported
.lines()
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
.collect::<Vec<_>>();
assert_eq!(serde_json::Value::from(lines), all["data"]["mutants"]);
project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--status",
"not-infected",
"--format",
"jsonl",
"--output",
"not-infected.jsonl",
])
.succeeds();
let written = project.read("not-infected.jsonl");
assert_eq!(written.lines().count(), 1, "{written}");
assert!(
written.contains("\"id\":\"src/cart.js:2:7-2:16:EqualityOperator:>\""),
"{written}"
);
// A soundness violation fails the export as it fails the query.
let violated = project.supercov(&[
"runs",
"latest",
"mutants",
"--format",
"jsonl",
"--stryker",
"reports/mutation.json",
]);
assert_eq!(violated.code(), 1, "{}", violated.stderr());
assert!(
violated.stdout().contains("\"stryker\":\"Killed\""),
"{}",
violated.stdout()
);
project
.supercov(&["runs", "latest", "mutants", "--format", "csv"])
.exits(2);
// A plain run lists no mutants and costs nothing for them. Asked for
// them, it lists them from its sources, decided from its coverage alone.
project.supercov(&["--", "npx", "mocha"]).succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(!summary.contains("Mutants "), "{summary}");
let listed = project
.supercov(&["runs", "latest", "mutants", "--json"])
.json();
assert_eq!(listed["data"]["mutantSet"], "stryker-js@10.1.1", "{listed}");
assert!(
listed["data"]["summary"]["mutants"].as_u64() > Some(0),
"{listed}"
);
}
/// node:test records its tests' evidence as a server process does, in
/// records rather than snapshots: the values its probes saw are recorded
/// with them, and decide its mutants as Mocha's snapshots do.
#[cfg(unix)]
#[test]
fn mutants_under_node_test_are_decided_from_the_values_its_records_carry() {
let project = Project::empty("mutants-node-test");
project.write("package.json", r#"{ "name": "mutants", "type": "module" }"#);
project.write(
"src/cart.js",
"export function shipping(sum) {\n if (sum >= 50) {\n return 0;\n }\n return 5;\n}\n\nexport function label(name) {\n return name.trim().toUpperCase();\n}\n\nexport function refund(sum) {\n return sum > 100 ? sum * 0.9 : sum;\n}\n",
);
project.write(
"test/cart.test.js",
"import assert from \"node:assert/strict\";\nimport test from \"node:test\";\nimport { shipping, label } from \"../src/cart.js\";\ntest(\"ships big orders free\", () => assert.equal(shipping(80), 0));\ntest(\"charges small orders\", () => assert.equal(shipping(10), 5));\ntest(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n",
);
project.git(&["init", "-q"]);
project.commit("mutants");
project
.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let statuses = mutant_statuses(&reply);
for (id, status) in [
// `sum` was 80 and 10, never 50: a boundary only values decide.
("src/cart.js:2:7-2:16:EqualityOperator:>", "not-infected"),
("src/cart.js:2:7-2:16:EqualityOperator:<", "infected"),
("src/cart.js:9:10-9:21:MethodExpression:removed", "infected"),
(
"src/cart.js:13:22-13:31:ArithmeticOperator:/",
"not-reached",
),
] {
assert_eq!(
statuses.get(id).map(String::as_str),
Some(status),
"{id}: {statuses:?}"
);
}
// What Mocha's run of the same tests says, mutant for mutant.
assert_eq!(
reply["data"]["summary"],
serde_json::json!({
"mutants": 15,
"status": {"not-reached": 6, "not-infected": 1, "infected": 8, "unknown": 0, "equivalent": 0},
"untestable": 0,
"weakScore": 0.5333,
"weakScoreReached": 0.8889,
"mutationScore": null,
}),
"{statuses:?}"
);
}
/// A test that writes a file of the run's own name into the run's evidence
/// directory -- the declaration beside the evidence -- does not get it into
/// the archive under that name: the run stops and names the file.
#[test]
fn a_test_writing_one_of_the_run_s_own_files_into_its_evidence_stops_the_run() {
let project = Project::cart("evidence-collision");
project.write(
"test/collide.test.js",
"import test from 'node:test';\nimport { mkdirSync, writeFileSync } from 'node:fs';\ntest('writes beside the evidence', () => {\n const directory = `.supercov/evidence/${process.env.SUPERCOV_RUN_ID}`;\n mkdirSync(directory, { recursive: true });\n writeFileSync(`${directory}/frontend.json`, '{}');\n});\n",
);
let ran = project.supercov(&["--", "node", "--test"]);
let said = ran.stderr();
assert_ne!(ran.code(), 0, "{said}");
assert!(
said.contains("duplicate Supercov evidence archive path: frontend.json"),
"{said}"
);
}
/// The workspace a run replaces is swept from the trash while the tests run.
/// A part of it already gone -- removed by hand meanwhile, its listing or
/// itself -- is as swept as one removed here, and the trash is left empty; a
/// part that cannot be removed leaves the rest of that tree in the trash, for
/// a later sweep.
#[test]
fn a_replaced_workspace_is_swept_whatever_is_gone_meanwhile() {
for (fault, emptied) in [
("fs.remove_file:2#lifecycle.rs:1762", true),
("fs.read_dir:2#lifecycle.rs:1731", true),
("fs.remove_file#lifecycle.rs:1762", false),
] {
let project = Project::cart("sweep");
assert_eq!(project.supercov(&["--", "node", "--test"]).code(), 0);
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 0, "{fault}: {said}");
let place = &fault[fault.find('#').unwrap() + 1..];
assert!(fired_at(&said, place), "{fault}: {said}");
let trash = project.root.join(".supercov/.trash");
let left = std::fs::read_dir(&trash)
.map(|entries| {
entries
.map(|entry| entry.unwrap().file_name())
.filter(|name| name != ".deleter.lock")
.count()
})
.unwrap_or(0);
assert_eq!(left == 0, emptied, "{fault}: {left} left");
}
}
/// A run prunes the sources from its workspace copy into the trash as it
/// ends, best effort: when one cannot be moved there the prune stops, what
/// it had not moved stays in the copy, which the next run copies over, and
/// the run is not failed for it.
#[test]
fn a_copied_source_that_cannot_be_pruned_stays_in_the_copy() {
let left_in_copy = |fault: &str| {
let project = Project::cart("prune");
let ran =
project.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_TEST_FAULT", fault)]);
let said = ran.stderr();
assert_eq!(ran.code(), 0, "{said}");
assert_eq!(
fired_at(&said, "workspace.rs:2226"),
!fault.is_empty(),
"{said}"
);
let copies = project.root.join(".supercov/workspaces/workspace");
std::fs::read_dir(&copies)
.unwrap()
.map(|copy| copy.unwrap().path())
.filter(|copy| copy.is_dir())
.map(|copy| {
std::fs::read_dir(copy)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.filter(|name| name != "node_modules" && name != ".supercov")
.count()
})
.sum::<usize>()
};
assert_eq!(left_in_copy(""), 0);
// The prune stops there: that source and those after it stay.
assert!(left_in_copy("fs.rename#workspace.rs:2226") > 0);
}
/// `mutants test --plan`: a mutant no test infected is decided without
/// running, one no test reached has no coverage, and an infected one runs
/// against the tests that infected it, and no other.
#[cfg(unix)]
#[test]
fn the_strong_plan_runs_each_infected_mutant_against_the_tests_that_infected_it() {
let project = mutants_project("strong-plan");
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--plan", "--json"])
.json();
let tests = reply["tests"].as_array().unwrap();
let name = |index: &serde_json::Value| {
tests[index.as_u64().unwrap() as usize]["name"]
.as_str()
.unwrap()
.to_owned()
};
let mutants = reply["mutants"].as_array().unwrap();
let find = |id: &str| {
mutants
.iter()
.find(|mutant| mutant["id"] == id)
.unwrap_or_else(|| panic!("no {id} in {reply}"))
};
// `sum >= 50` to `sum > 50`: the tests use 80 and 10, never 50.
let boundary = find("src/cart.js:2:7-2:16:EqualityOperator:>");
assert_eq!(boundary["decided"], "survived", "{boundary}");
assert_eq!(boundary["candidates"], serde_json::json!([]));
// `refund` is never called.
let refund = find("src/cart.js:13:10-13:19:ConditionalExpression:true");
assert_eq!(refund["decided"], "no-coverage", "{refund}");
// `name.trim()` to `name`: only the label test gives it a padded name.
let trim = find("src/cart.js:9:10-9:21:MethodExpression:removed");
assert!(trim["decided"].is_null(), "{trim}");
let candidates = trim["candidates"]
.as_array()
.unwrap()
.iter()
.map(|candidate| name(&candidate["test"]))
.collect::<Vec<_>>();
assert_eq!(candidates, ["cart > labels"], "{trim}");
// `sum >= 50` always true: only the test it changes runs it.
let always = find("src/cart.js:2:7-2:16:ConditionalExpression:true");
let candidates = always["candidates"]
.as_array()
.unwrap()
.iter()
.map(|candidate| name(&candidate["test"]))
.collect::<Vec<_>>();
assert_eq!(candidates, ["cart > charges small orders"], "{always}");
assert_eq!(reply["summary"]["mutants"], 15);
}
/// A run whose mutants are of a language no strong driver runs yet: the
/// plan still decides them, and each it would run is an error that says so.
#[cfg(unix)]
#[test]
fn mutants_of_a_language_no_driver_runs_are_errors_that_say_so() {
let project = vitest_mutants_project("strong-undriven");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let run = project.latest();
// Listed beside the run, as `supercov mutants` lists a plain run's.
project.write(
&format!(".supercov/runs/{run}/mutants-listed.json"),
r#"{"schemaVersion": 1, "mutantSet": "cobol-mutants@1",
"mutantSets": {"cobol": "cobol-mutants@1"},
"languages": {"src/cart.js": "cobol"},
"files": {"src/cart.js": [{"mutator": "BooleanLiteral", "replacement": "false",
"start": [2, 7], "end": [2, 16], "original": "sum >= 50"}]}}"#,
);
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
assert_eq!(reply["summary"]["error"], 1, "{reply}\n{said}");
assert!(
said.contains("no strong mutation driver for cobol yet: its mutants are errors"),
"{said}"
);
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let strong = &listed["data"]["mutants"][0]["strong"];
assert_eq!(strong["status"], "error", "{listed}");
assert_eq!(
strong["reason"], "no strong mutation driver for cobol yet",
"{listed}"
);
}
/// A strong pass saves its verdicts as it makes them, so one a signal ends
/// keeps them and the next runs the rest; it keeps only its logs; after an
/// edit, only what the edit could move runs again; a run whose command
/// failed is answered and exits 2, and one that recorded no test is
/// refused; `supercov mutants` checks its options before it measures, and
/// writes its answer as markdown when asked.
#[cfg(unix)]
#[test]
fn a_strong_pass_keeps_what_it_decides_and_says_what_cannot_gate() {
let project = vitest_mutants_project("strong-keeps");
// Options are checked before anything is measured: there is no run yet.
let mistaken = project
.supercov(&["mutants", "--diff", "HEAD", "--bogus"])
.exits(2);
assert!(
mistaken.contains("Unknown option: --bogus")
&& mistaken.contains("Usage: supercov mutants"),
"{mistaken}"
);
assert!(project.root.join(".supercov/runs").read_dir().is_err());
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import { expect, it } from \"vitest\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => expect(tax(20)).toBe(4));\n",
);
// Kills each mutant it is given, noting their ids; with FAKE_HALF, half
// of them and then ends as Ctrl-C ends a pass.
project.write(
"fake-strong.mjs",
"import { appendFileSync, readFileSync } from \"node:fs\";\nconst plan = JSON.parse(readFileSync(process.env.SUPERCOV_STRONG_PLAN, \"utf8\"));\nconst mutants = plan.mutants.filter((mutant) => !mutant.decided);\nconst kill = process.env.FAKE_HALF ? mutants.slice(0, Math.ceil(mutants.length / 2)) : mutants;\nappendFileSync(process.env.FAKE_ASKED, mutants.map((mutant) => mutant.id + \"\\n\").join(\"\"));\nfor (const mutant of kill) appendFileSync(process.env.SUPERCOV_STRONG_RESULTS, JSON.stringify({ id: mutant.id, status: \"killed\", tests: 1 }) + \"\\n\");\nif (process.env.FAKE_HALF) process.exit(130);\n",
);
project.commit("tax");
project
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let run = project.latest();
let asked = project.root.join("asked.txt");
let asked_path = asked.to_str().unwrap();
let fake = [
"runs",
"latest",
"mutants",
"test",
"--json",
"--",
"node",
"fake-strong.mjs",
];
let take_asked = || {
let ids = std::fs::read_to_string(&asked).unwrap_or_default();
let _ = std::fs::remove_file(&asked);
ids.lines().map(str::to_owned).collect::<Vec<_>>()
};
// Ended by a signal: what it killed is saved, and the next pass runs
// the rest.
let ended = project.supercov_with(
&fake,
&[
("FAKE_ASKED", asked_path),
("FAKE_HALF", "1"),
("SUPERCOV_STRONG_KEEP", "1"),
],
);
assert_eq!(ended.code(), 130, "{}", ended.stderr());
assert!(
ended
.stderr()
.contains("interrupted: the verdicts the pass reached are saved"),
"{}",
ended.stderr()
);
let first = take_asked();
// Asked to, the pass kept its directory whole; the next pass removes it.
let kept_plan = std::fs::read_dir(project.root.join(".supercov/strong"))
.unwrap()
.any(|pass| pass.unwrap().path().join("plan.json").is_file());
assert!(kept_plan);
let reply = project
.supercov_with(&fake, &[("FAKE_ASKED", asked_path)])
.json();
let second = take_asked();
assert_eq!(second.len(), first.len() / 2, "{first:?}\n{second:?}");
assert!(second.iter().all(|id| first.contains(id)), "{second:?}");
assert_eq!(reply["summary"]["ran"], second.len(), "{reply}");
// The pass keeps no plan, results or jobs, only its logs.
for pass in std::fs::read_dir(project.root.join(".supercov/strong")).unwrap() {
for entry in std::fs::read_dir(pass.unwrap().path()).unwrap() {
let name = entry.unwrap().file_name().into_string().unwrap();
assert!(name.ends_with(".log"), "{name}");
}
}
// The summary of the run shows the score.
let summary = project.supercov(&["runs", "latest"]).succeeds();
assert!(
summary.contains(" mutation score ")
&& summary.contains("mutants --status survived"),
"{summary}"
);
// Runs between that one and the next, none of which can lend their
// verdicts: one of another command, one with none, one of another
// mutant set.
let measure = |command: &[&str]| {
let mut words = vec!["--"];
words.extend(command);
project
.supercov_with(&words, &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
project.latest()
};
measure(&["npx", "vitest", "run", "test/cart.test.js"]);
measure(&["npx", "vitest", "run"]);
let other = measure(&["npx", "vitest", "run"]);
project.write(
&format!(".supercov/runs/{other}/strong-mutation.json"),
r#"{"schemaVersion": 1, "run": "x", "mutantSet": "other@1", "mutants": {}}"#,
);
// An edit of tax.js's code: `supercov mutants` measures again, and runs
// tax.js's mutants alone; cart.js's keep their verdicts, as no cart test
// ran tax.js. (`runs <id> mutants test` tests the run it names whole.)
project.edit("src/tax.js", "sum * 0.2", "sum / 5");
project
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let to_run = project
.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--plan",
"--json",
"--file",
"src/tax.js",
])
.json()["summary"]["toRun"]
.clone();
let kept = project.supercov(&["mutants"]).succeeds();
assert!(
kept.contains(&format!("verdict(s) kept from run {run}")),
"{kept}"
);
assert!(
kept.contains(&format!(" ran {to_run} mutant(s)")),
"{to_run}: {kept}"
);
let edited = project.latest();
// An edit of both sources keeps nothing; where the latest earlier run's
// record of what each test ran is gone, it lends nothing, and an older
// run of tax.js as it is again lends tax.js's verdicts.
project.edit("src/tax.js", "sum / 5", "sum / 5.0");
project.edit("src/cart.js", "return 5;", "return 5.0;");
let none_kept = project.supercov(&["mutants"]).succeeds();
assert!(!none_kept.contains("kept from run"), "{none_kept}");
let previous = project.latest();
std::fs::remove_file(
project
.root
.join(format!(".supercov/runs/{previous}/test-executions.json")),
)
.unwrap();
project.edit("src/tax.js", "sum / 5.0", "sum / 5");
let unrecorded = project.supercov(&["mutants"]).succeeds();
assert!(
unrecorded.contains(&format!("verdict(s) kept from run {edited}: ")),
"{unrecorded}"
);
assert!(!unrecorded.contains(&previous), "{unrecorded}");
// `--plan` keeps nothing and runs nothing.
project.supercov(&["mutants", "--plan"]).succeeds();
// As a pull request's comment, the change's, to a file or one that
// cannot be written.
let markdown = project
.supercov(&["mutants", "--format", "markdown"])
.succeeds();
assert!(markdown.starts_with("### Mutants"), "{markdown}");
let change = project
.supercov(&["mutants", "--diff", "HEAD", "--format", "markdown"])
.succeeds();
assert!(change.starts_with("### Mutants on this change"), "{change}");
let unwritable = project.supercov(&[
"mutants",
"--format",
"markdown",
"--output",
"missing/dir/mutants.md",
]);
assert_eq!(unwritable.code(), 2, "{}", unwritable.stderr());
// A failing test: the pass answers, and cannot gate.
project.write(
"test/fails.test.js",
"import { expect, it } from \"vitest\";\nit(\"fails\", () => expect(1).toBe(2));\n",
);
project.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
);
let failing = project.supercov_with(&fake, &[("FAKE_ASKED", asked_path)]);
assert_eq!(failing.code(), 2, "{}", failing.stderr());
assert_eq!(failing.json()["result"], "error");
assert!(
failing.stderr().contains("1 of its") && failing.stderr().contains("did not pass (fails)"),
"{}",
failing.stderr()
);
// A command that decides nothing: no mutant could be run.
std::fs::remove_file(project.root.join("test/fails.test.js")).unwrap();
project.edit("src/cart.js", "return 0;", "return 0 * 1;");
project
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let nothing = project.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/cart.js",
"--",
"node",
"-e",
"0",
]);
assert_eq!(nothing.code(), 2, "{}", nothing.stdout());
assert!(
nothing.stderr().contains("no mutant of the"),
"{}",
nothing.stderr()
);
// A run that recorded no test, its command running the code: refused,
// naming what ran it.
project.write(
"run-cart.mjs",
"import { shipping } from \"./src/cart.js\";\nshipping(80);\n",
);
project.supercov(&["--", "node", "run-cart.mjs"]).succeeds();
let refused = project
.supercov(&["runs", "latest", "mutants", "test"])
.exits(2);
assert!(
refused.contains("recorded no test")
&& refused.contains("no strong driver for run-cart.mjs"),
"{refused}"
);
}
/// A strong pass split across machines: each shard's run holds its share of
/// the verdicts, `merge` keeps them all in the merged run, so a pass over it
/// runs nothing, and after an edit `supercov mutants` keeps each unchanged
/// mutant's verdict from whichever shard's run holds it, and runs the edited
/// file's mutants again.
#[cfg(unix)]
#[test]
fn a_strong_pass_split_across_runs_merges_and_is_kept_after_an_edit() {
let project = vitest_mutants_project("strong-shards");
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import { expect, it } from \"vitest\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => expect(tax(20)).toBe(4));\n",
);
// Gives each mutant it is given FAKE_STATUS, noting their ids.
project.write(
"fake-strong.mjs",
"import { appendFileSync, readFileSync } from \"node:fs\";\nconst plan = JSON.parse(readFileSync(process.env.SUPERCOV_STRONG_PLAN, \"utf8\"));\nconst mutants = plan.mutants.filter((mutant) => !mutant.decided);\nappendFileSync(process.env.FAKE_ASKED, mutants.map((mutant) => mutant.id + \"\\n\").join(\"\"));\nfor (const mutant of mutants) appendFileSync(process.env.SUPERCOV_STRONG_RESULTS, JSON.stringify({ id: mutant.id, status: process.env.FAKE_STATUS, tests: 1 }) + \"\\n\");\n",
);
project.commit("tax");
// Each shard's job measures the whole suite on its own machine.
let measure = || {
project
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
project.latest()
};
let (first, second) = (measure(), measure());
let asked = project.root.join("asked.txt");
let asked_path = asked.to_str().unwrap();
let take_asked = || {
let ids = std::fs::read_to_string(&asked).unwrap_or_default();
let _ = std::fs::remove_file(&asked);
ids.lines().map(str::to_owned).collect::<Vec<_>>()
};
let shard = |run: &str, shard: &str, status: &str| {
project
.supercov_with(
&[
"runs",
run,
"mutants",
"test",
"--shard",
shard,
"--json",
"--",
"node",
"fake-strong.mjs",
],
&[("FAKE_ASKED", asked_path), ("FAKE_STATUS", status)],
)
.json()
};
shard(&first, "1/2", "killed");
let killed = take_asked();
shard(&second, "2/2", "survived");
let survived = take_asked();
assert!(!killed.is_empty() && !survived.is_empty(), "{killed:?}");
let merged = project.supercov(&["merge", &first, &second]).succeeds();
assert!(
merged.contains(&format!(
"strong verdict(s) kept from runs {first}, {second}"
)),
"{merged}"
);
// Every mutant has its verdict: a pass over the merged run runs none.
let pass = project
.supercov_with(
&[
"runs",
"latest",
"mutants",
"test",
"--json",
"--",
"node",
"fake-strong.mjs",
],
&[("FAKE_ASKED", asked_path), ("FAKE_STATUS", "killed")],
)
.json();
assert!(take_asked().is_empty(), "{pass}");
assert_eq!(pass["summary"]["ran"], 0, "{pass}");
assert_eq!(pass["summary"]["killed"], killed.len(), "{pass}");
assert!(
pass["summary"]["survived"].as_u64().unwrap() >= survived.len() as u64,
"{pass}"
);
// After an edit of tax.js, cart.js's mutants keep their verdicts, each
// from the shard's run that holds it, and tax.js's run again.
project.edit("src/tax.js", "sum * 0.2", "sum / 5");
measure();
let to_run = project
.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--plan",
"--json",
"--file",
"src/tax.js",
])
.json()["summary"]["toRun"]
.clone();
let kept = project
.supercov(&["mutants", "--json", "--", "npx", "vitest", "run"])
.json();
assert_eq!(
kept["carried"]["from"],
serde_json::json!([second, first]),
"{kept}"
);
let carried = killed
.iter()
.chain(&survived)
.filter(|id| id.starts_with("src/cart.js:"))
.count();
assert_eq!(kept["carried"]["mutants"], carried, "{kept}");
assert_eq!(kept["summary"]["ran"], to_run, "{kept}");
// Measured again as it is: the latest run lends every verdict, and the
// shards' runs are not read.
let whole = kept["run"].as_str().unwrap().to_owned();
measure();
let again = project
.supercov(&["mutants", "--json", "--", "npx", "vitest", "run"])
.json();
assert_eq!(
again["carried"]["from"],
serde_json::json!([whole]),
"{again}"
);
assert_eq!(again["summary"]["ran"], 0, "{again}");
// A shard of this checkout continues the newest run of it that passed
// with the command given: not a merge, not a run whose command failed,
// not one of another command, not one measured before the edit.
let latest_measured = again["run"].as_str().unwrap().to_owned();
let run_json = |run: &str| format!(".supercov/runs/{run}/run.json");
let mut failed =
serde_json::from_str::<serde_json::Value>(&project.read(&run_json(&first))).unwrap();
failed["testExitCode"] = serde_json::json!(1);
project.write(&run_json(&first), &failed.to_string());
project
.supercov_with(
&["--", "npx", "vitest", "run", "--silent"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let shard = |command: &[&str]| {
let mut args = vec!["mutants", "--shard", "1/1", "--json", "--"];
args.extend(command);
let ran = project.supercov(&args);
(ran.json(), ran.stderr())
};
let (continued, said) = shard(&["npx", "vitest", "run"]);
assert!(
said.contains(&format!(
"[supercov] not measuring: the checkout is unchanged since run {latest_measured}, so this shard saves its verdicts into run {}, made from it",
continued["run"].as_str().unwrap()
)),
"{said}"
);
// None of this command: measured.
let (_, said) = shard(&["npx", "vitest", "run", "--reporter=dot"]);
assert!(
said.contains("measuring first (a shard saves its verdicts into a run of its own, and no run of this checkout that recorded its mutants' values and whose command passed can be made into one): npx vitest run --reporter=dot"),
"{said}"
);
// After an edit: measured.
project.edit("src/tax.js", "sum / 5", "sum * 0.2");
let (_, said) = shard(&["npx", "vitest", "run"]);
assert!(
said.contains("measuring first (the checkout changed since the latest run)"),
"{said}"
);
}
/// A split strong pass continued round after round on the same commit:
/// each job restores the earlier round's runs and runs `supercov mutants
/// --shard k/n -- <command>`. Each job saves into a run of its own, rather
/// than into the latest restored run, a copy of which every job held: those
/// copies shared one id and could not be merged. On the unchanged checkout
/// that run is made from a restored one, with no measuring, and keeps every
/// verdict the restored runs hold, though the first round's two
/// measurements recorded different evidence (a test whose path depends on
/// when it runs). The last job's `supercov merge` takes the round's runs,
/// keeps the union of their verdicts, a kill over a survival where they
/// differ, and says how many came from each, and a third round runs
/// nothing. A run named twice is refused, saying why and what to do.
#[cfg(unix)]
#[test]
fn a_continuation_round_of_a_split_pass_merges_each_job_s_run() {
let project = vitest_mutants_project("strong-shards-continued");
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import { expect, it } from \"vitest\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => expect(tax(20)).toBe(4));\n",
);
// A test whose path depends on when it runs: here, on a variable one
// job's machine sets.
project.write(
"test/refund.test.js",
"import { expect, it } from \"vitest\";\nimport { refund } from \"../src/cart.js\";\nit(\"refunds\", () => {\n expect(refund(50)).toBe(50);\n if (process.env.LATE) expect(refund(200)).toBe(180);\n});\n",
);
project.commit("tax");
let runs = project.root.join(".supercov/runs");
let away = project.root.join(".supercov/elsewhere");
// A job on a machine of its own: the store holds what it restored and
// nothing another job of its round made.
let job_at = |shard: &str, more: &[&str], hidden: &[&str], late: bool| {
for (n, hidden) in hidden.iter().enumerate() {
std::fs::create_dir_all(&away).unwrap();
std::fs::rename(runs.join(hidden), away.join(n.to_string())).unwrap();
}
let mut args = vec!["mutants", "--shard", shard, "--json"];
args.extend(more);
args.extend(["--", "npx", "vitest", "run"]);
let ran = project.supercov_with(&args, &[("LATE", if late { "1" } else { "" })]);
for (n, hidden) in hidden.iter().enumerate() {
std::fs::rename(away.join(n.to_string()), runs.join(hidden)).unwrap();
}
(ran.json(), ran.stderr())
};
let job = |shard: &str, more: &[&str], hidden: Option<&str>| {
job_at(shard, more, hidden.as_slice(), false)
};
// The verdicts a pass reached that a run holds, by mutant id: not
// those the run's plan decides, with no test run.
let reached = |run: &str| {
let saved = serde_json::from_str::<serde_json::Value>(
&project.read(&format!(".supercov/runs/{run}/strong-mutation.json")),
)
.unwrap();
saved["mutants"]
.as_object()
.unwrap()
.iter()
.filter(|(_, verdict)| {
["killed", "survived", "timeout"].contains(&verdict["status"].as_str().unwrap())
&& verdict["tests"] != 0
})
.map(|(id, verdict)| (id.clone(), verdict.clone()))
.collect::<std::collections::BTreeMap<_, _>>()
};
// The first round leaves tax.js's mutants for the next. Its jobs each
// measure, at different times: the second job's refund test takes the
// path the first's did not.
let (first_a, _) = job("1/2", &["--file", "src/cart.js"], None);
let a1 = first_a["run"].as_str().unwrap().to_owned();
let (first_b, _) = job_at("2/2", &["--file", "src/cart.js"], &[a1.as_str()], true);
let b1 = first_b["run"].as_str().unwrap().to_owned();
assert_ne!(a1, b1);
let decided = |reply: &serde_json::Value| reply["summary"]["ran"].as_u64().unwrap();
assert!(
decided(&first_a) > 0 && decided(&first_b) > 0,
"{first_a}\n{first_b}"
);
let evidence = |run: &str| std::fs::read(runs.join(run).join("test-executions.json")).unwrap();
// The two measurements differ: refund's discount ran in the second
// alone.
let discount = "src/cart.js:13:22-13:31:ArithmeticOperator:/";
let reached_in = |run: &str| {
project
.supercov(&["runs", run, "mutants", "--json", "--limit", "0"])
.json()["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == discount)
.unwrap_or_else(|| panic!("no {discount} in {run}"))["weak"]["reach"]
.clone()
};
assert_ne!(reached_in(&a1), reached_in(&b1));
// Every verdict the first round reached, the newer run's where both
// have one.
let mut first = reached(&a1);
first.extend(reached(&b1));
// A plan writes nothing, and reads the latest run as it is.
let plan = project.supercov(&[
"mutants", "--shard", "1/2", "--plan", "--", "npx", "vitest", "run",
]);
assert_eq!(plan.code(), 0, "{}", plan.stderr());
assert!(
!plan.stderr().contains("measuring first"),
"{}",
plan.stderr()
);
assert_eq!(project.latest(), b1);
// The second round, on the unchanged checkout, with both runs restored:
// each job makes its own run from the newest, measuring nothing, and
// keeps every verdict both shards reached.
let (second_a, said) = job("1/2", &[], None);
let a2 = second_a["run"]
.as_str()
.unwrap_or_else(|| panic!("{second_a}\n{said}"))
.to_owned();
assert!(
said.contains(&format!("[supercov] not measuring: the checkout is unchanged since run {b1}, so this shard saves its verdicts into run {a2}, made from it")) && !said.contains("measuring first"),
"{said}"
);
assert_eq!(
second_a["measurement"]["derivedFrom"],
b1.as_str(),
"{second_a}"
);
assert_eq!(evidence(&a2), evidence(&b1));
let (second_b, said) = job("2/2", &[], Some(a2.as_str()));
assert!(!said.contains("measuring first"), "{said}");
let b2 = second_b["run"].as_str().unwrap().to_owned();
let restored = [a1.as_str(), b1.as_str()];
assert!(
a2 != b2 && !restored.contains(&a2.as_str()) && !restored.contains(&b2.as_str()),
"{a1} {b1} {a2} {b2}"
);
let carried = |reply: &serde_json::Value| reply["carried"]["mutants"].as_u64().unwrap();
for (reply, run) in [(&second_a, &a2), (&second_b, &b2)] {
assert_eq!(
reply["carried"]["from"],
serde_json::json!([b1, a1]),
"{reply}"
);
assert_eq!(reply["carried"]["unchanged"], true, "{reply}");
assert_eq!(carried(reply), first.len() as u64, "{reply}");
// Kept as they were.
let now = reached(run);
assert!(
first
.iter()
.all(|(id, verdict)| now.get(id) == Some(verdict)),
"{reply}"
);
}
// What no pass reached is not a verdict to keep: a mutant the first
// job's run had no test for, which the second job's tests reach.
assert!(
second_a["carried"]["notKept"]
.as_object()
.unwrap()
.keys()
.all(|reason| reason == "notRunThen"),
"{second_a}"
);
assert!(
decided(&second_a) > 0 && decided(&second_b) > 0,
"{second_a}\n{second_b}"
);
// The two jobs' runs disagree on a verdict both kept from the first
// round: the first run the merge reads let it survive, the other
// killed it.
let verdicts_of = |run: &str| format!(".supercov/runs/{run}/strong-mutation.json");
let mut of_b2 =
serde_json::from_str::<serde_json::Value>(&project.read(&verdicts_of(&b2))).unwrap();
let mut of_a2 =
serde_json::from_str::<serde_json::Value>(&project.read(&verdicts_of(&a2))).unwrap();
let contested = of_b2["mutants"]
.as_object()
.unwrap()
.iter()
.find(|(id, verdict)| {
id.starts_with("src/cart.js:")
&& verdict["status"] == "killed"
&& of_a2["mutants"][id.as_str()] == **verdict
})
.map(|(id, _)| id.clone())
.expect("a kill both jobs kept from the first round");
of_b2["mutants"][&contested]["status"] = serde_json::json!("survived");
project.write(&verdicts_of(&b2), &of_b2.to_string());
of_a2["mutants"][&contested]["status"] = serde_json::json!("killed");
project.write(&verdicts_of(&a2), &of_a2.to_string());
// The last job: the second round's runs replace the first's, and the
// merge keeps every verdict of both.
let merged = project.supercov(&["merge"]).succeeds();
contains_all(&merged, &["merging 2 runs", &a2, &b2]);
let merged_id = project.latest();
let kept =
serde_json::from_str::<serde_json::Value>(&project.read(&verdicts_of(&merged_id))).unwrap();
let kept = kept["mutants"].as_object().unwrap();
assert_eq!(kept[&contested]["status"], "killed", "{merged}");
let total = kept.len();
// Each run counts what was taken from it: b2, read first, the first
// round's verdicts and its share, a2 its share and the contested kill.
let from_b2 = carried(&second_b) - 1 + decided(&second_b);
let from_a2 = decided(&second_a) + 1;
let planned = total as u64 - from_b2 - from_a2;
assert!(
merged.contains(&format!(
"[supercov] {total} strong verdict(s) kept from runs {b2}, {a2}: {from_b2} from {b2}, {from_a2} from {a2}, {planned} the merged run's plan decides\n"
)),
"{merged}"
);
let left = project
.supercov(&["runs", "latest", "mutants", "test", "--plan", "--json"])
.json();
assert_eq!(left["summary"]["toRun"], 0, "{left}");
// A third round, from the second's runs alone: nothing to run, nothing
// measured, every verdict kept.
let second = reached(&a2)
.into_iter()
.chain(reached(&b2))
.collect::<std::collections::BTreeMap<_, _>>();
let (third, said) = job_at(
"1/2",
&[],
&[a1.as_str(), b1.as_str(), merged_id.as_str()],
false,
);
assert!(!said.contains("measuring first"), "{said}");
assert_eq!(third["summary"]["ran"], 0, "{third}");
assert_eq!(carried(&third), second.len() as u64, "{third}");
assert!(
third["carried"]["notKept"].as_object().unwrap().is_empty(),
"{third}"
);
// Copies of one run cannot be merged: said, with what to do instead.
let twice = project.supercov(&["merge", &b2, &b2]).exits(2);
assert!(
twice.contains(&format!(
"Each merged run must be unique: {b2} is named more than once. Copies of one run"
)) && twice.contains("Run that round again and merge its jobs' runs"),
"{twice}"
);
}
/// A shard's run made from a restored one, on an unchanged checkout, that
/// could not be made -- the store unlisted, its staging not created, the
/// restored run's files unread or not copied, its record, its rename into
/// place or the store's sync failing -- stops the command before any pass,
/// saying from which run and why, and leaves no run behind.
#[cfg(unix)]
#[test]
fn a_shard_s_run_that_cannot_be_made_from_a_restored_one_stops_the_command() {
let project = vitest_mutants_project("strong-derive-faults");
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import { expect, it } from \"vitest\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => expect(tax(20)).toBe(4));\n",
);
project.commit("tax");
project
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let restored = project.latest();
for fault in [
"run-store-unlisted",
"fs.create_dir_all#lifecycle.rs:1256",
"fs.read_dir#lifecycle.rs:1257",
"fs.symlink_metadata#lifecycle.rs:892",
"fs.create_dir_all#lifecycle.rs:1279",
"fs.rename#lifecycle.rs:1281",
"fs.open#lifecycle.rs:1282",
] {
let ran = project.supercov_with(
&["mutants", "--shard", "1/2", "--", "npx", "vitest", "run"],
&[("SUPERCOV_TEST_FAULT", fault)],
);
let said = ran.stderr();
assert_eq!(ran.code(), 2, "{fault}\n{said}");
assert!(
said.contains(&format!(
"[supercov] could not make this shard's run from {restored}: "
)) && !said.contains("strong pass"),
"{fault}\n{said}"
);
// Only the restored run and, past the rename, the one made.
let runs = std::fs::read_dir(project.root.join(".supercov/runs"))
.unwrap()
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("run_"))
.count();
assert_eq!(
runs,
if fault.ends_with(":1282") { 2 } else { 1 },
"{fault}"
);
if runs == 2 {
let made = project.latest();
std::fs::remove_dir_all(project.root.join(".supercov/runs").join(made)).unwrap();
}
}
// A run made from it holds cart.js's verdicts; a shard of tax.js's
// mutants keeps none of them, and runs its own.
let job = |file: &str| {
project
.supercov(&[
"mutants", "--shard", "1/1", "--file", file, "--json", "--", "npx", "vitest", "run",
])
.json()
};
let cart = job("src/cart.js");
assert!(cart["summary"]["ran"].as_u64() > Some(0), "{cart}");
let tax = job("src/tax.js");
assert!(
tax["carried"].is_null() && tax["summary"]["ran"].as_u64() > Some(0),
"{tax}"
);
}
/// A Vitest project like `mutants_project`'s, with the repository's
/// node_modules.
#[cfg(unix)]
fn vitest_mutants_project(label: &str) -> Project {
let project = Project::empty(label);
project.write(
"package.json",
r#"{ "name": "mutants", "type": "module", "scripts": { "test": "vitest run" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/cart.js",
"export function shipping(sum) {\n if (sum >= 50) {\n return 0;\n }\n return 5;\n}\n\nexport function label(name) {\n return name.trim().toUpperCase();\n}\n\nexport function refund(sum) {\n return sum > 100 ? sum * 0.9 : sum;\n}\n",
);
project.write(
"test/cart.test.js",
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n});\n",
);
project.git(&["init", "-q"]);
project.commit("mutants");
project
}
/// `mutants test` over a Vitest run: each mutant the tests infected runs
/// against the tests that infected it, and the verdicts are StrykerJS's:
/// killed where a test fails, survived where none can, no coverage where
/// none ran it. `mutants` then shows them and the mutation score.
#[cfg(unix)]
#[test]
fn mutants_test_kills_and_keeps_what_the_vitest_tests_can_and_cannot_tell() {
let project = vitest_mutants_project("strong-vitest");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
let summary = &reply["summary"];
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
assert_eq!(summary["mutants"], 15, "{reply}");
assert_eq!(summary["error"], 0, "{reply}\n{said}\n{listed}");
let strong = |id: &str| {
listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == id)
.unwrap_or_else(|| panic!("no {id} in {listed}"))["strong"]
.clone()
};
// No test gives `shipping` 50: `>=` to `>` survives, decided unrun.
assert_eq!(
strong("src/cart.js:2:7-2:16:EqualityOperator:>")["status"],
"survived"
);
assert_eq!(
strong("src/cart.js:13:10-13:19:ConditionalExpression:true")["status"],
"no-coverage"
);
let trim = strong("src/cart.js:9:10-9:21:MethodExpression:removed");
assert_eq!(trim["status"], "killed", "{trim}");
let always = strong("src/cart.js:2:7-2:16:ConditionalExpression:true");
assert_eq!(always["status"], "killed", "{always}");
let lower = strong("src/cart.js:9:10-9:35:MethodExpression:toLowerCase");
assert_eq!(lower["status"], "killed", "{lower}");
// 8 infected mutants all killed; 1 survived; 6 not covered.
assert_eq!(summary["killed"], 8, "{reply}");
assert_eq!(summary["survived"], 1, "{reply}");
assert_eq!(summary["noCoverage"], 6, "{reply}");
assert_eq!(listed["data"]["summary"]["mutationScore"], 0.5333);
assert_eq!(listed["data"]["levels"]["strong"], true);
// A second pass has nothing left to run.
let again = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(again["summary"]["ran"], 0, "{again}");
assert_eq!(again["summary"]["killed"], 8, "{again}");
}
/// The cart of `mutants_project`, and a countdown whose `i--` made `i++`
/// never ends, tested by `test/cart.test.*` and `test/count.test.*` under
/// another runner. `module` is the package's `type`.
#[cfg(unix)]
fn job_runner_project(label: &str, module: &str, tests: &[(&str, &str)]) -> Project {
let project = Project::empty(label);
project.write(
"package.json",
&format!(r#"{{ "name": "cart", "type": "{module}" }}"#),
);
// The repository's packages, where it has them: Bun's tests need none
// and run where they were never installed (the Bun bootstrap job).
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
if let Ok(modules) = modules.canonicalize() {
std::os::unix::fs::symlink(modules, project.root.join("node_modules")).unwrap();
}
project.write(".gitignore", "node_modules\n.supercov\n");
let exports = if module == "module" {
("export function", "")
} else {
(
"function",
"\nmodule.exports = { shipping, label, refund, countdown };\n",
)
};
project.write(
"src/cart.js",
&format!(
"{0} shipping(sum) {{\n if (sum >= 50) {{\n return 0;\n }}\n return 5;\n}}\n\n{0} label(name) {{\n return name.trim().toUpperCase();\n}}\n\n{0} refund(sum) {{\n return sum > 100 ? sum * 0.9 : sum;\n}}\n\n{0} countdown(n) {{\n let i = n;\n while (i > 0) {{\n i--;\n }}\n return i;\n}}\n{1}",
exports.0, exports.1
),
);
for (file, source) in tests {
project.write(file, source);
}
project.git(&["init", "-q"]);
project.commit("cart");
project
}
/// Each mutant's strong verdict in a `mutants --json` reply, by id.
#[cfg(unix)]
fn strong_statuses(project: &Project) -> std::collections::BTreeMap<String, String> {
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["id"].as_str().unwrap().to_owned(),
mutant["strong"]["status"]
.as_str()
.unwrap_or("-")
.to_owned(),
)
})
.collect()
}
/// The verdicts every runner's cart gives: the tests tell `trim()` and the
/// shipping condition apart, never give `shipping` 50, never call `refund`,
/// and a countdown that never ends is a timeout. Only the jobs driver ran.
#[cfg(unix)]
fn assert_cart_verdicts(project: &Project, command: &[&str], runner: &str) {
let mut measure = vec!["--"];
measure.extend_from_slice(command);
project
.supercov_with(&measure, &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
assert_eq!(reply["summary"]["error"], 0, "{runner}: {reply}\n{said}");
assert_eq!(reply["passes"][0]["driver"], "jobs", "{runner}: {reply}");
let statuses = strong_statuses(project);
for (id, status) in [
("src/cart.js:9:10-9:21:MethodExpression:removed", "killed"),
("src/cart.js:2:7-2:16:ConditionalExpression:true", "killed"),
("src/cart.js:2:7-2:16:EqualityOperator:>", "survived"),
(
"src/cart.js:13:10-13:19:ConditionalExpression:true",
"no-coverage",
),
("src/cart.js:19:5-19:8:UpdateOperator:++", "timeout"),
] {
assert_eq!(
statuses.get(id).map(String::as_str),
Some(status),
"{runner} {id}: {statuses:?}\n{said}"
);
}
}
/// What a strong pass let survive is named in every view, not only counted:
/// the pass's summary ends with the survivors, the text listing shows each
/// mutant's strong verdict beside its weak status and `--status survived`
/// picks the survivors, and the markdown for a pull request lists them under
/// the mutation score.
#[cfg(unix)]
#[test]
fn surviving_mutants_are_named_in_every_view() {
let project = job_runner_project(
"strong-survivors-named",
"module",
&[(
"test/cart.test.js",
"import assert from \"node:assert/strict\";\nimport { it } from \"node:test\";\nimport { shipping, label } from \"../src/cart.js\";\nit(\"ships big orders free\", () => assert.equal(shipping(80), 0));\nit(\"charges small orders\", () => assert.equal(shipping(10), 5));\nit(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n",
)],
);
project
.supercov_with(&["--", "node", "--test"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let pass = project
.supercov(&["runs", "latest", "mutants", "test"])
.succeeds();
// `sum >= 50` to `sum > 50` changes neither 80 nor 10.
let survivors = pass.split("Survived:\n").nth(1).unwrap_or_default();
assert!(
survivors.contains("src/cart.js:2 EqualityOperator sum >= 50 → sum > 50"),
"{pass}"
);
let listed = project
.supercov(&["runs", "latest", "mutants", "src/cart.js"])
.succeeds();
assert!(listed.contains(" Strong score "), "{listed}");
let line = listed
.lines()
.find(|line| line.contains("sum >= 50 → sum > 50"))
.unwrap_or_default();
assert!(line.contains("survived"), "{listed}");
let killed = listed
.lines()
.find(|line| line.contains("trim() → name"))
.unwrap_or_default();
assert!(killed.contains("killed"), "{listed}");
let only = project
.supercov(&["runs", "latest", "mutants", "--status", "survived"])
.succeeds();
assert!(only.contains("sum >= 50 → sum > 50"), "{only}");
assert!(!only.contains("trim() → name"), "{only}");
// The table of files says how to list them, and a line's view gives
// each mutant's verdict.
let table = project.supercov(&["runs", "latest", "mutants"]).succeeds();
assert!(
table.contains("list the mutants the tests let survive: ")
&& table.contains(" --status survived"),
"{table}"
);
let line = project
.supercov(&["runs", "latest", "mutants", "src/cart.js:2"])
.succeeds();
assert!(line.contains(" strong: survived"), "{line}");
let markdown = project
.supercov(&["runs", "latest", "mutants", "--format", "markdown"])
.succeeds();
assert!(markdown.contains("Mutation score **"), "{markdown}");
assert!(
markdown
.lines()
.any(|line| line.contains("sum >= 50 → sum > 50") && line.contains(" | survived | ")),
"{markdown}"
);
assert!(!markdown.contains("trim() → name"), "{markdown}");
}
/// `mutants test` under node:test, Mocha, Jest and AVA: each job starts the
/// run's command for one test file with the mutant on and only its tests. A
/// node:test file that asserts at its top level, with no test() in it, is a
/// test of its own, as node:test counts it.
#[cfg(unix)]
#[test]
fn mutants_test_runs_node_test_mocha_jest_and_ava_mutants_one_job_at_a_time() {
let esm_cart = |import: &str, describe: bool| {
let (open, close) = if describe {
("describe(\"cart\", () => {\n", "});\n")
} else {
("", "")
};
format!(
"{import}import {{ shipping, label }} from \"../src/cart.js\";\n{open}it(\"ships big orders free\", () => assert.equal(shipping(80), 0));\nit(\"charges small orders\", () => assert.equal(shipping(10), 5));\nit(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n{close}"
)
};
let node = job_runner_project(
"strong-jobs-node-test",
"module",
&[
(
"test/cart.test.js",
&esm_cart(
"import assert from \"node:assert/strict\";\nimport { it } from \"node:test\";\n",
false,
),
),
(
"test/count.test.js",
"import assert from \"node:assert/strict\";\nimport { countdown } from \"../src/cart.js\";\nassert.equal(countdown(3), 0);\n",
),
],
);
assert_cart_verdicts(&node, &["node", "--test"], "node:test");
// A suite of ES modules runs each job in a fresh thread of a resident
// Mocha.
let mocha = job_runner_project(
"strong-jobs-mocha",
"module",
&[
(
"test/cart.test.js",
&esm_cart("import assert from \"node:assert/strict\";\n", true),
),
(
"test/count.test.js",
"import assert from \"node:assert/strict\";\nimport { countdown } from \"../src/cart.js\";\nit(\"counts down\", () => assert.equal(countdown(3), 0));\n",
),
],
);
assert_cart_verdicts(&mocha, &["npx", "mocha", "--check-leaks"], "mocha");
// A CommonJS suite runs in resident Mochas, its modules loaded afresh for
// each job.
let commonjs = job_runner_project(
"strong-jobs-mocha-commonjs",
"commonjs",
&[
(
"test/cart.test.js",
"const assert = require(\"node:assert/strict\");\nconst { shipping, label } = require(\"../src/cart.js\");\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => assert.equal(shipping(80), 0));\n it(\"charges small orders\", () => assert.equal(shipping(10), 5));\n it(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n});\n",
),
(
"test/count.test.js",
"const assert = require(\"node:assert/strict\");\nconst { countdown } = require(\"../src/cart.js\");\nit(\"counts down\", () => assert.equal(countdown(3), 0));\n",
),
],
);
assert_cart_verdicts(&commonjs, &["npx", "mocha", "--check-leaks"], "mocha");
let jest = job_runner_project(
"strong-jobs-jest",
"commonjs",
&[
(
"test/cart.test.js",
"const { shipping, label } = require(\"../src/cart.js\");\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n});\n",
),
(
"test/count.test.js",
"const { countdown } = require(\"../src/cart.js\");\ntest(\"counts down\", () => expect(countdown(3)).toBe(0));\n",
),
],
);
assert_cart_verdicts(&jest, &["npx", "jest"], "jest");
let ava = job_runner_project(
"strong-jobs-ava",
"module",
&[
(
"test/cart.test.js",
"import test from \"ava\";\nimport { shipping, label } from \"../src/cart.js\";\ntest(\"ships big orders free\", (t) => t.is(shipping(80), 0));\ntest(\"charges small orders\", (t) => t.is(shipping(10), 5));\ntest(\"labels\", (t) => t.is(label(\" a \"), \"A\"));\n",
),
(
"test/count.test.js",
"import test from \"ava\";\nimport { countdown } from \"../src/cart.js\";\ntest(\"counts down\", (t) => t.is(countdown(3), 0));\n",
),
],
);
assert_cart_verdicts(&ava, &["npx", "ava"], "ava");
}
/// `mutants test` on a Python project under unittest: the run lists mutmut's
/// mutants and records their values (`SUPERCOV_MUTANTS=1`), and the strong
/// pass forks each mutant's tests after collection: a default's mutant, a
/// loop the mutant makes endless, code no test runs, a boundary no test
/// meets, and code a test module's import runs, which a fresh interpreter
/// runs with the mutant on.
#[cfg(unix)]
#[test]
fn mutants_test_runs_python_mutants_under_unittest() {
let project = Project::empty("strong-python-unittest");
project.write(".gitignore", ".supercov\n__pycache__\n");
project.write("shop/__init__.py", "");
project.write(
"shop/cart.py",
"def shipping(total, express=False):\n if total >= 50:\n return 0\n fee = 5\n if express:\n fee += 10\n return fee\n\n\ndef label(name):\n return name.strip().upper()\n\n\ndef countdown(n):\n while n > 0:\n n -= 1\n return n\n\n\ndef refund(total):\n return total * 0.9 if total > 100 else total\n\n\ndef rate():\n return 3\n",
);
project.write("tests/__init__.py", "");
project.write(
"tests/test_cart.py",
"import unittest\nfrom shop.cart import shipping, label, countdown, rate\n\nRATE = rate()\n\n\nclass Cart(unittest.TestCase):\n def test_free(self):\n self.assertEqual(shipping(80), 0)\n\n def test_paid(self):\n self.assertEqual(shipping(10), 5)\n\n def test_label(self):\n self.assertEqual(label(' a '), 'A')\n\n def test_countdown(self):\n self.assertEqual(countdown(3), 0)\n\n def test_rate(self):\n self.assertEqual(RATE, 3)\n",
);
project.git(&["init", "-q"]);
project.commit("cart");
let command = [
"--", "python3", "-m", "unittest", "discover", "-s", "tests", "-t", ".",
];
// `SUPERCOV_MUTANTS=0` is a plain run: no value probe, no list.
project
.supercov_with(&command, &[("SUPERCOV_MUTANTS", "0")])
.succeeds();
let plain = project.latest();
assert!(
!project
.root
.join(format!(".supercov/runs/{plain}/mutants-listed.json"))
.exists()
);
project
.supercov_with(&command, &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let weak = project
.supercov(&["runs", "latest", "mutants", "shop/cart.py:2", "--json"])
.json();
let boundary = weak["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "shop/cart.py:2:14-2:19:EqualityOperator:>")
.cloned()
.unwrap_or_default();
assert_eq!(boundary["status"], "not-infected", "{weak}");
// A command timeout that is no number stops the pass before it runs, and
// leaves no verdict.
let refused = project.supercov_with(
&["runs", "latest", "mutants", "test"],
&[("SUPERCOV_COMMAND_TIMEOUT_MS", "soon")],
);
let said = refused.stderr();
assert_ne!(refused.code(), 0, "{said}");
assert!(said.contains("SUPERCOV_COMMAND_TIMEOUT_MS"), "{said}");
let ran = project.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[("SUPERCOV_STRONG_WORKERS", "2")],
);
let said = ran.stderr();
let reply = ran.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}\n{said}");
assert_eq!(reply["passes"][0]["runner"], "unittest", "{reply}");
let statuses = strong_statuses(&project);
for (id, status) in [
// `express=True`: the default a call that names no `express` gets.
("shop/cart.py:1:29-1:34:BooleanLiteral:True", "killed"),
("shop/cart.py:2:14-2:19:EqualityOperator:>", "survived"),
("shop/cart.py:6:9-6:18:AugmentedAssignment:=", "no-coverage"),
("shop/cart.py:2:17-2:19:NumberLiteral:51", "survived"),
("shop/cart.py:11:12-11:32:MethodExpression:lower", "killed"),
("shop/cart.py:16:9-16:15:AssignmentOperator:+=", "timeout"),
("shop/cart.py:21:12-21:49:IfExpression:true", "no-coverage"),
// Called while the test module loads: run with the mutant on from
// the interpreter's start.
("shop/cart.py:25:12-25:13:NumberLiteral:4", "killed"),
] {
assert_eq!(
statuses.get(id).map(String::as_str),
Some(status),
"{id}: {statuses:?}\n{said}"
);
}
}
/// `mutants test` under bun:test: Bun's runner loads every test file it is
/// given into one process, so each job names its file.
#[cfg(unix)]
#[test]
fn mutants_test_runs_bun_test_mutants_one_job_at_a_time() {
if std::process::Command::new("bun")
.arg("--version")
.output()
.is_err()
{
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BUN").is_none(),
"Bun is required"
);
eprintln!("skipping: Bun is unavailable");
return;
}
let bun = job_runner_project(
"strong-jobs-bun",
"module",
&[
(
"test/cart.test.js",
"import { expect, test } from \"bun:test\";\nimport { shipping, label } from \"../src/cart.js\";\ntest(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\ntest(\"charges small orders\", () => expect(shipping(10)).toBe(5));\ntest(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n",
),
(
"test/count.test.js",
"import { expect, test } from \"bun:test\";\nimport { countdown } from \"../src/cart.js\";\ntest(\"counts down\", () => expect(countdown(3)).toBe(0));\n",
),
],
);
assert_cart_verdicts(&bun, &["bun", "test"], "bun:test");
}
/// `mutants test` under node-tap, installed from the registry as the
/// failure-output check installs it: each test file is a process of tap's,
/// and a file that asserts at its top level is a test of its own.
#[cfg(unix)]
#[test]
fn mutants_test_runs_tap_mutants_one_job_at_a_time() {
let tap = Project::empty("strong-jobs-tap");
tap.write("package.json", r#"{ "name": "cart", "type": "module" }"#);
let installed = std::process::Command::new("npm")
.args(["install", "--no-audit", "--no-fund", "--silent", "tap@21"])
.current_dir(&tap.root)
.output()
.is_ok_and(|output| output.status.success());
if !installed {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_TAP").is_none(),
"tap could not be installed"
);
eprintln!("skipping: tap could not be installed");
return;
}
let project = job_runner_project(
"strong-jobs-tap-cart",
"module",
&[
(
"test/cart.test.js",
"import t from \"tap\";\nimport { shipping, label } from \"../src/cart.js\";\nt.test(\"ships big orders free\", async (t) => t.equal(shipping(80), 0));\nt.test(\"charges small orders\", async (t) => t.equal(shipping(10), 5));\nt.test(\"labels\", async (t) => t.equal(label(\" a \"), \"A\"));\n",
),
(
"test/count.test.js",
"import t from \"tap\";\nimport { countdown } from \"../src/cart.js\";\nt.equal(countdown(3), 0);\n",
),
],
);
// tap's own packages beside the repository's.
std::fs::remove_file(project.root.join("node_modules")).unwrap();
std::os::unix::fs::symlink(
tap.root.join("node_modules"),
project.root.join("node_modules"),
)
.unwrap();
assert_cart_verdicts(&project, &["npx", "tap", "--disable-coverage"], "tap");
}
/// `mutants test` under Vitest's Browser Mode: the job's mutant is switched
/// on in the page, before the test file loads, and the browser's tests are
/// planned under `vitest-browser`.
#[cfg(unix)]
#[test]
fn mutants_test_runs_vitest_browser_mode_mutants_one_job_at_a_time() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let available = std::process::Command::new("node")
.args(["--input-type=module", "-e", "import { chromium } from '@playwright/test'; import { existsSync } from 'node:fs'; process.exit(existsSync(chromium.executablePath()) ? 0 : 1)"])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright and Chromium are required"
);
eprintln!("skipping: Playwright or Chromium is unavailable");
return;
}
let browser = job_runner_project(
"strong-jobs-vitest-browser",
"module",
&[
(
"vitest.config.js",
"import { defineConfig } from \"vitest/config\";\nimport { playwright } from \"@vitest/browser-playwright\";\nexport default defineConfig({ test: { browser: { enabled: true, provider: playwright(), headless: true, instances: [{ browser: \"chromium\" }] } } });\n",
),
(
"test/cart.test.js",
"import { expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\nit(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\nit(\"charges small orders\", () => expect(shipping(10)).toBe(5));\nit(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n",
),
(
"test/count.test.js",
"import { expect, it } from \"vitest\";\nimport { countdown } from \"../src/cart.js\";\nit(\"counts down\", () => expect(countdown(3)).toBe(0));\n",
),
],
);
let plan = {
browser
.supercov_with(
&["--", "npx", "vitest", "run"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
browser
.supercov(&["runs", "latest", "mutants", "test", "--plan", "--json"])
.json()
};
assert!(
plan["tests"]
.as_array()
.unwrap()
.iter()
.all(|test| test["runner"] == "vitest-browser"),
"{plan}"
);
assert_cart_verdicts(&browser, &["npx", "vitest", "run"], "vitest-browser");
// A run of node tests and browser tests: its node tests run as jobs
// beside the browser's.
let mixed = job_runner_project(
"strong-jobs-vitest-mixed",
"module",
&[
(
"vitest.config.js",
"import { defineConfig } from \"vitest/config\";\nimport { playwright } from \"@vitest/browser-playwright\";\nexport default defineConfig({ test: { projects: [\n { test: { name: \"node\", include: [\"test/cart.test.js\"] } },\n { test: { name: \"browser\", include: [\"test/count.test.js\"], browser: { enabled: true, provider: playwright(), headless: true, instances: [{ browser: \"chromium\" }] } } },\n] } });\n",
),
(
"test/cart.test.js",
"import { expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\nit(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\nit(\"charges small orders\", () => expect(shipping(10)).toBe(5));\nit(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n",
),
(
"test/count.test.js",
"import { expect, it } from \"vitest\";\nimport { countdown } from \"../src/cart.js\";\nit(\"counts down\", () => expect(countdown(3)).toBe(0));\n",
),
],
);
assert_cart_verdicts(&mixed, &["npx", "vitest", "run"], "vitest node and browser");
}
/// Rust compiled to wasm that node:test loads: the Rust run beside the
/// JavaScript one lists the crate's mutants, and `mutants test` runs them
/// under the JavaScript tests, the copy's crate built with them switched in
/// and each wasm instance handed the active mutant. Needs wasm-bindgen and
/// the wasm32 target; a job that installed them sets
/// `SUPERCOV_REQUIRE_RUST_WASM=1`.
#[cfg(unix)]
#[test]
fn rust_compiled_to_wasm_under_node_tests_runs_its_mutants() {
let tools = std::process::Command::new("wasm-bindgen")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success())
&& std::process::Command::new("rustup")
.args(["target", "list", "--installed"])
.output()
.is_ok_and(|output| {
String::from_utf8_lossy(&output.stdout).contains("wasm32-unknown-unknown")
});
if !tools {
assert!(
std::env::var("SUPERCOV_REQUIRE_RUST_WASM").as_deref() != Ok("1"),
"wasm-bindgen or the wasm32 target is missing where the job installed them"
);
eprintln!("skipping: needs wasm-bindgen and the wasm32-unknown-unknown target");
return;
}
let project = Project::empty("wasm-node-mutants");
project.write(
"rust/Cargo.toml",
"[workspace]\n\n[package]\nname = \"grades\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n\n[dependencies]\nwasm-bindgen = \"=0.2.129\"\n",
);
project.write(
"rust/src/lib.rs",
"use wasm_bindgen::prelude::*;\n\n#[wasm_bindgen]\npub fn grade(score: u32, curved: bool) -> String {\n if score >= 90 || (curved && score >= 85) {\n \"A\".into()\n } else if score >= 50 {\n \"pass\".into()\n } else {\n \"fail\".into()\n }\n}\n",
);
project.write(
"build.sh",
"set -e\ncd rust\ncargo build -q --target wasm32-unknown-unknown --release\nwasm-bindgen --target nodejs --out-dir ../pkg target/wasm32-unknown-unknown/release/grades.wasm\n",
);
project.write(
"package.json",
r#"{ "name": "grades", "private": true, "scripts": { "test": "sh build.sh && node --test" } }"#,
);
project.write(
"test/grades.test.mjs",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { createRequire } from \"node:module\";\nconst { grade } = createRequire(import.meta.url)(\"../pkg/grades.js\");\n\ntest(\"a curved score is an A\", () => {\n assert.equal(grade(87, true), \"A\");\n});\n\ntest(\"a low score fails\", () => {\n assert.equal(grade(10, false), \"fail\");\n});\n",
);
project.write(".gitignore", "pkg\nrust/target\n.supercov\n");
let locked = std::process::Command::new("cargo")
.args(["generate-lockfile", "-q"])
.current_dir(project.root.join("rust"))
.status()
.unwrap();
assert!(locked.success());
project.git(&["init", "-q"]);
project.commit("grades");
project.supercov(&["--", "npm", "test"]).succeeds();
let runs = project.supercov(&["runs", "--json"]).json();
let rust = runs["data"]["runs"]
.as_array()
.unwrap()
.iter()
.filter_map(|run| run["id"].as_str())
.find(|id| {
project
.supercov(&["runs", id, "decision", "rust/src/lib.rs:5"])
.code()
== 0
})
.expect("a Rust run beside the JavaScript one")
.to_owned();
let reply = project
.supercov(&["runs", &rust, "mutants", "test", "--json"])
.json();
// `&&` to `||` in `(curved && score >= 85)` changes neither test's
// outcome; every other mutant fails one.
assert_eq!(reply["summary"]["killed"], 6, "{reply}");
assert_eq!(reply["summary"]["survived"], 1, "{reply}");
assert_eq!(reply["summary"]["error"], 0, "{reply}");
// A pass that cannot switch the crate's mutants in ends, saying why.
let source = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../supercov-engine/src/rust_strong.rs"),
)
.unwrap();
let line = source
.lines()
.position(|line| line.contains("crate::fault_fs::read(plan_path)"))
.unwrap()
+ 1;
std::fs::remove_file(
project
.root
.join(".supercov/runs")
.join(&rust)
.join("strong-mutation.json"),
)
.unwrap();
let failed = project.supercov_with(
&["runs", &rust, "mutants", "test"],
&[(
"SUPERCOV_TEST_FAULT",
&format!("fs.read#rust_strong.rs:{line}"),
)],
);
assert_ne!(failed.code(), 0, "{}", failed.stderr());
assert!(failed.stderr().contains("plan.json"), "{}", failed.stderr());
}
/// Two inline snapshots in one file, and a test that fakes the clock: the
/// measured run passes as the suite does alone (the snapshots keep their own
/// places; a duration is read from the real clock), and the strong pass runs.
#[cfg(unix)]
#[test]
fn inline_snapshots_and_faked_clocks_measure_and_mutate_as_the_suite_runs() {
let project = vitest_mutants_project("strong-inline-snapshots");
project.write(
"test/snapshots.test.js",
"import { expect, it, vi } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\nit(\"snapshots shipping\", () => {\n expect(shipping(80)).toMatchInlineSnapshot(`0`);\n expect(shipping(10)).toMatchInlineSnapshot(`5`);\n});\nit(\"labels under a faked clock\", () => {\n vi.useFakeTimers();\n vi.setSystemTime(0);\n expect(label(\" b \")).toMatchInlineSnapshot(`\"B\"`);\n vi.useRealTimers();\n});\n",
);
project.commit("snapshots");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
assert!(reply["summary"]["killed"].as_u64().unwrap() >= 8, "{reply}");
}
/// A server Playwright starts from its config's folder, which is not the
/// project's root, and which imports `@playwright/test` itself (a mock
/// server that drives a browser): it is given the same Playwright the tests
/// are, found from the project's root, so it starts and the tests are
/// recorded.
#[cfg(unix)]
#[test]
fn a_web_server_started_in_the_config_s_folder_can_import_playwright() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let available = std::process::Command::new("node")
.args([
"--input-type=module",
"-e",
"await import('@playwright/test')",
])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright is required"
);
eprintln!("skipping: Playwright is unavailable");
return;
}
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("playwright-server-in-config-folder");
project.write(
"package.json",
r#"{ "name": "server-in-config-folder", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/greeting.js",
"export function greeting(name) {\n return name ? `hello ${name}` : \"hello\";\n}\n",
);
// Started with the config's folder as its working directory.
project.write(
"tests/e2e/mocks/server.mjs",
"import http from \"node:http\";\nimport { chromium } from \"@playwright/test\";\nimport { greeting } from \"../../../src/greeting.js\";\nif (typeof chromium.launch !== \"function\") throw new Error(\"no chromium\");\nhttp.createServer((request, response) => {\n const url = new URL(request.url, \"http://local\");\n response.end(greeting(url.searchParams.get(\"name\")));\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"tests/e2e/playwright.config.js",
&format!(
"export default {{\n testDir: \"specs\",\n workers: 1,\n reporter: \"line\",\n use: {{ baseURL: \"http://127.0.0.1:{port}\" }},\n webServer: {{ command: \"node mocks/server.mjs\", url: \"http://127.0.0.1:{port}/\", reuseExistingServer: false, timeout: 20000, env: {{ PORT: \"{port}\" }} }},\n}};\n"
),
);
project.write(
"tests/e2e/specs/greeting.spec.js",
"import { test, expect } from \"@playwright/test\";\ntest(\"greets\", async ({ request }) => {\n expect(await (await request.get(\"/?name=ada\")).text()).toBe(\"hello ada\");\n});\n",
);
project.git(&["init", "-q"]);
project.commit("server in the config's folder");
let measured = project.supercov(&[
"--",
"npx",
"playwright",
"test",
"-c",
"tests/e2e/playwright.config.js",
]);
assert!(
!measured.stderr().contains("was not able to start"),
"{}",
measured.stderr()
);
measured.succeeds();
let summary = project.supercov(&["runs", "latest"]).succeeds();
contains_all(&summary, &["Total 1", "Passed 1"]);
}
/// `mutants test` over a Playwright run against a Node server: the workers
/// of one Playwright invocation each test their own mutant against one
/// server, the mutant carried with each attempt's requests and switched on
/// in its pages; a mutant of the server's top level runs alone, with the
/// server started with it switched on; the controls, runs with no mutant
/// after a kill, pass; and the pass says as it goes what it does.
#[cfg(unix)]
#[test]
fn mutants_test_runs_playwright_mutants_per_request_and_per_server_start() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let available = std::process::Command::new("node")
.args(["--input-type=module", "-e", "import { chromium } from '@playwright/test'; import { existsSync } from 'node:fs'; process.exit(existsSync(chromium.executablePath()) ? 0 : 1)"])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright and Chromium are required"
);
eprintln!("skipping: Playwright or Chromium is unavailable");
return;
}
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("strong-playwright");
project.write(
"package.json",
r#"{ "name": "strong-playwright", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
// The server: its routes and files in support/, which is not measured,
// and the code under test in server/. It notes what it served, outside
// the project: its process, and the worker and mutant each request's
// attempt named.
let served = project.root.with_extension("served.jsonl");
project.write(
"support/server.js",
"import http from \"node:http\";\nimport { appendFileSync, readFileSync } from \"node:fs\";\nimport { answer } from \"../server/app.js\";\nconst files = { \"/\": \"../public/index.html\", \"/page.js\": \"../public/page.js\" };\n// One fault switch for the whole server, as a harness's per-slot fault\n// rules: a test that turns it on must not run beside another test.\nlet fault = false;\nhttp.createServer((request, response) => {\n const cookie = /(?:^|;\\s*)__supercov_scope=([^;]*)/.exec(request.headers.cookie ?? \"\");\n const scope = new URLSearchParams(request.headers[\"x-supercov-scope\"] ?? (cookie ? decodeURIComponent(cookie[1]) : \"\"));\n appendFileSync(process.env.SERVED_LOG, JSON.stringify({ pid: process.pid, worker: scope.get(\"w\"), mutant: scope.get(\"m\"), path: request.url }) + \"\\n\");\n const url = new URL(request.url, \"http://local\");\n if (url.pathname === \"/fault\") {\n fault = url.searchParams.get(\"on\") === \"1\";\n return response.end();\n }\n if (url.pathname === \"/source\")\n return response.end(readFileSync(new URL(\"../server/app.js\", import.meta.url)));\n if (fault && url.pathname === \"/total\") {\n response.statusCode = 503;\n return response.end(\"faulted\");\n }\n try {\n response.end(files[url.pathname] ? readFileSync(new URL(files[url.pathname], import.meta.url)) : answer(url));\n } catch (error) {\n response.statusCode = 500;\n response.end(String(error));\n }\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"server/app.js",
"const GREETING = \"hello\";\n\nexport function total(quantity) {\n console.log(`served ${quantity}`);\n return quantity >= 3 ? quantity * 9 : quantity * 10;\n}\n\nexport function answer(url) {\n return url.pathname === \"/greeting\" ? GREETING : String(total(Number(url.searchParams.get(\"q\"))));\n}\n\nexport const dynamic = \"force-dynamic\";\n",
);
// Reached by no test: the strong pass leaves it as written.
project.write("server/unused.js", "export const unused = (a) => a + 1;\n");
project.write(
"public/index.html",
"<!doctype html><p id=\"out\"></p><script src=\"/page.js\"></script>\n",
);
project.write(
"public/page.js",
"function shout(text) {\n return text.toUpperCase();\n}\ndocument.getElementById(\"out\").textContent = shout(\"hi\");\n",
);
project.write(
"playwright.config.js",
&format!(
"export default {{\n testDir: \"tests\",\n workers: 4,\n reporter: \"line\",\n use: {{ baseURL: \"http://127.0.0.1:{port}\" }},\n webServer: {{ command: \"node support/server.js\", url: \"http://127.0.0.1:{port}/greeting\", reuseExistingServer: false, timeout: 20000, env: {{ PORT: \"{port}\", SERVED_LOG: {:?} }} }},\n}};\n",
served.display().to_string()
),
);
project.write(
"tests/api.spec.js",
"import { test, expect } from \"@playwright/test\";\ntest(\"totals\", async ({ request }) => {\n expect(await (await request.get(\"/total?q=5\")).text()).toBe(\"45\");\n expect(await (await request.get(\"/total?q=1\")).text()).toBe(\"10\");\n});\ntest(\"greets\", async ({ request }) => {\n expect(await (await request.get(\"/greeting\")).text()).toBe(\"hello\");\n});\ntest(\"refuses while faulted @fault\", async ({ request }) => {\n expect(await (await request.get(\"/total?q=2\")).text()).toBe(\"20\");\n await request.get(\"/fault?on=1\");\n await new Promise((done) => setTimeout(done, 400));\n expect((await request.get(\"/total?q=1\")).status()).toBe(503);\n await request.get(\"/fault?on=0\");\n});\ntest(\"keeps its segment config a literal\", async ({ request }) => {\n expect(await (await request.get(\"/source\")).text()).toContain('export const dynamic = \"force-dynamic\";');\n});\n",
);
project.write(
"tests/page.spec.js",
"import { test, expect } from \"@playwright/test\";\ntest(\"shouts\", async ({ page }) => {\n await page.goto(\"/\");\n await expect(page.locator(\"#out\")).toHaveText(\"HI\", { timeout: 12000 });\n});\n",
);
project.git(&["init", "-q"]);
project.commit("strong playwright");
let roots = [("SUPERCOV_SOURCE_ROOTS", "server,public")];
// Measured with the mutants' probes: their values decide some mutants
// without running them.
project
.supercov_with(
&["--", "npx", "playwright", "test"],
&[roots[0], ("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let _ = std::fs::remove_file(&served);
let ran = project.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[roots[0], ("SUPERCOV_PROGRESS_INTERVAL_MS", "300")],
);
let said = ran.stderr();
let reply = ran.json();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let shown = mutants
.iter()
.map(|mutant| format!("{} {} {}", mutant["id"], mutant["status"], mutant["strong"]))
.collect::<Vec<_>>()
.join("\n");
// What each pass wrote and each attempt claimed, for a failure to show.
let mut passes = String::new();
for work in std::fs::read_dir(project.root.join(".supercov/strong"))
.into_iter()
.flatten()
.flatten()
{
passes.push_str(
&std::fs::read_to_string(work.path().join("results.jsonl")).unwrap_or_default(),
);
for pass in std::fs::read_dir(work.path().join("playwright"))
.into_iter()
.flatten()
.flatten()
{
for attempt in std::fs::read_dir(pass.path().join("attempts"))
.into_iter()
.flatten()
.flatten()
{
passes.push_str(&format!(
"{} {}\n",
pass.file_name().to_string_lossy(),
std::fs::read_to_string(attempt.path()).unwrap_or_default()
));
}
}
}
let context = format!("{reply}\n{shown}\n{said}\n{passes}");
// Each pass's time, for whoever weighs the cost of confirming kills.
eprintln!("strong passes: {}", reply["passes"]);
// The one mutant on a line, by its file, line, mutator and descriptor.
let strong = |file: &str, line: u32, ending: &str| {
let found = mutants
.iter()
.filter(|mutant| {
let id = mutant["id"].as_str().unwrap();
id.starts_with(&format!("{file}:{line}:")) && id.ends_with(ending)
})
.collect::<Vec<_>>();
assert_eq!(found.len(), 1, "{file}:{line} {ending}\n{context}");
found[0]["strong"].clone()
};
// The one error: the segment config's value stays a literal Next.js
// can read, and its mutant has no switch.
assert_eq!(reply["summary"]["error"], 1, "{context}");
let segment = strong("server/app.js", 12, ":StringLiteral:empty");
assert_eq!(segment["status"], "error", "{context}");
assert!(
segment["reason"]
.as_str()
.is_some_and(|reason| reason.contains("next-segment-config")),
"{context}"
);
// Only the files with mutants to run get switches.
assert!(
said.contains("switches in 2 of 3 source file(s)"),
"{context}"
);
// A server-side mutant, killed by its own requests, with why.
let always = strong("server/app.js", 5, ":ConditionalExpression:true");
assert_eq!(always["status"], "killed", "{context}");
assert!(
always["reason"]
.as_str()
.is_some_and(|reason| reason.contains("Expected")),
"{context}"
);
// Killed by the first test that took it: its other candidates never ran.
let route = strong("server/app.js", 9, ":EqualityOperator:!==");
assert_eq!(route["status"], "killed", "{context}");
assert_eq!(route["tests"], 1, "{context}");
// A page-side mutant the page shows: its assertion would wait 12 s, its
// own timeout, but the attempt's limit (1.5 x its baseline + 5 s) ends
// it first, a timeout.
let lower = strong("public/page.js", 2, ":MethodExpression:toLowerCase");
assert_eq!(lower["status"], "timeout", "{context}");
assert!(lower["killedBy"].as_str().is_some(), "{lower}\n{context}");
assert!(
lower["reason"]
.as_str()
.is_some_and(|reason| reason.starts_with("ran past its time limit of ")),
"{context}"
);
assert!(lower["durationMs"].as_u64() < Some(12_000), "{context}");
// Run, and no test tells: the log line. Its tests share the server's
// fault switch with the @fault test, which the measured run never ran
// beside them; neither does the strong pass, so nothing kills it.
let logged = strong("server/app.js", 4, ":StringLiteral:empty");
assert_eq!(logged["status"], "survived", "{context}");
assert!(logged["tests"].as_u64() > Some(0), "{context}");
// No request gives `total` 3: decided without running.
let boundary = strong("server/app.js", 5, ":EqualityOperator:>");
assert_eq!(boundary["status"], "survived", "{context}");
assert_eq!(boundary["tests"], 0, "{context}");
// The server's top level: run alone, the server started with it.
let greeting = strong("server/app.js", 1, ":StringLiteral:empty");
assert_eq!(greeting["status"], "killed", "{context}");
assert!(
greeting["reason"]
.as_str()
.is_some_and(|reason| reason.contains("ran alone")),
"{context}"
);
// Controls ran after the kills, and none failed.
let main = reply["passes"]
.as_array()
.unwrap()
.iter()
.find(|pass| pass["pass"] == "main")
.unwrap_or_else(|| panic!("no main pass\n{context}"))
.clone();
assert!(
main["controls"]["ran"].as_u64() > Some(0),
"{main}\n{context}"
);
assert_eq!(
main["controls"]["failed"],
serde_json::json!([]),
"{context}"
);
// The pass said what it did as it went: the round, its attempts and
// what ran.
assert!(
said.contains("[supercov] main round, 1 invocation(s): ")
&& said.contains(" mutant attempt(s), "),
"{context}"
);
// The files the measured run ran one test at a time run so here too.
assert_eq!(main["serialFiles"], 2, "{main}\n{context}");
// One server process served two workers' attempts, each with a mutant
// of its own.
let log = std::fs::read_to_string(&served).unwrap_or_default();
let requests = log
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.filter(|request| {
request["mutant"]
.as_str()
.is_some_and(|mutant| mutant != "-")
})
.collect::<Vec<_>>();
let shared = requests.iter().any(|one| {
requests.iter().any(|other| {
one["pid"] == other["pid"]
&& one["worker"] != other["worker"]
&& one["mutant"] != other["mutant"]
})
});
let _ = std::fs::remove_file(&served);
assert!(shared, "{log}\n{context}");
}
/// A Playwright mutant attempt is stopped at its time limit, its test's
/// baseline x 1.5 + 5 s: a mutant that keeps an element from appearing ends
/// there as a `timeout`, though its test clicks with no timeout of its own
/// and asks for 90 s; a slow test's limit grows with its baseline, so its
/// survivor lives and its timeout waits longer; and the summary and the
/// progress lines say so.
#[cfg(unix)]
#[test]
fn a_playwright_attempt_ends_at_its_baseline_s_time_limit() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let available = std::process::Command::new("node")
.args(["--input-type=module", "-e", "import { chromium } from '@playwright/test'; import { existsSync } from 'node:fs'; process.exit(existsSync(chromium.executablePath()) ? 0 : 1)"])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright and Chromium are required"
);
eprintln!("skipping: Playwright or Chromium is unavailable");
return;
}
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("strong-playwright-limit");
project.write(
"package.json",
r#"{ "name": "strong-playwright-limit", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"support/server.js",
"import http from \"node:http\";\nimport { readFileSync } from \"node:fs\";\nhttp.createServer((request, response) => {\n const path = new URL(request.url, \"http://local\").pathname;\n if (path === \"/health\") return response.end(\"ok\");\n const file = path === \"/\" ? \"index.html\" : path.slice(1);\n response.setHeader(\"content-type\", file.endsWith(\".js\") ? \"text/javascript\" : \"text/html\");\n response.end(readFileSync(new URL(`../public/${file}`, import.meta.url)));\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"public/index.html",
"<!doctype html><body><script src=\"/ready.js\"></script></body>\n",
);
project.write(
"public/ready.js",
"function ready(flag) {\n return flag === \"go\";\n}\nif (ready(\"go\")) {\n const button = document.createElement(\"button\");\n button.id = \"ready\";\n document.body.append(button);\n}\n",
);
project.write(
"public/slow.html",
"<!doctype html><body><p id=\"slow\"></p><script src=\"/slow.js\"></script></body>\n",
);
project.write(
"public/slow.js",
"const box = document.getElementById(\"slow\");\nsetTimeout(() => {\n box.textContent = \"Done\";\n console.log(\"shown\");\n}, 3000);\n",
);
project.write(
"playwright.config.js",
&format!(
"export default {{\n testDir: \"tests\",\n workers: 2,\n reporter: \"line\",\n use: {{ baseURL: \"http://127.0.0.1:{port}\" }},\n webServer: {{ command: \"node support/server.js\", url: \"http://127.0.0.1:{port}/health\", reuseExistingServer: false, timeout: 20000, env: {{ PORT: \"{port}\" }} }},\n}};\n"
),
);
project.write(
"tests/ready.spec.js",
"import { test } from \"@playwright/test\";\ntest(\"clicks when ready\", async ({ page }) => {\n test.setTimeout(90_000);\n await page.goto(\"/\");\n await page.locator(\"#ready\").click();\n});\n",
);
project.write(
"tests/slow.spec.js",
"import { test, expect } from \"@playwright/test\";\ntest(\"waits for the slow text\", async ({ page }) => {\n await page.goto(\"/slow.html\");\n await expect(page.locator(\"#slow\")).toHaveText(\"Done\", { timeout: 60_000 });\n});\n",
);
project.git(&["init", "-q"]);
project.commit("strong playwright limit");
let roots = [("SUPERCOV_SOURCE_ROOTS", "public")];
project
.supercov_with(
&["--", "npx", "playwright", "test"],
&[roots[0], ("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let ran = project.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[roots[0], ("SUPERCOV_PROGRESS_INTERVAL_MS", "300")],
);
let said = ran.stderr();
let reply = ran.json();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let context = format!(
"{reply}\n{}\n{said}",
mutants
.iter()
.map(|mutant| format!("{} {}", mutant["id"], mutant["strong"]))
.collect::<Vec<_>>()
.join("\n")
);
let strong = |file: &str, line: u32, ending: &str| {
let found = mutants
.iter()
.filter(|mutant| {
let id = mutant["id"].as_str().unwrap();
id.starts_with(&format!("{file}:{line}:")) && id.ends_with(ending)
})
.collect::<Vec<_>>();
assert_eq!(found.len(), 1, "{file}:{line} {ending}\n{context}");
found[0]["strong"].clone()
};
let duration = |verdict: &serde_json::Value| verdict["durationMs"].as_u64().unwrap_or(0);
// The button never appears: the click waits until the limit, about
// 1.5 x a baseline of a second or two + 5 s, not the 90 s the test asked
// for nor Playwright's 30 s.
let never = strong("public/ready.js", 2, ":EqualityOperator:!==");
assert_eq!(never["status"], "timeout", "{context}");
assert!(
never["reason"]
.as_str()
.is_some_and(|reason| reason.starts_with("ran past its time limit of ")
&& reason.contains("1.5 × its ")),
"{context}"
);
assert!(
(6_000..20_000).contains(&duration(&never)),
"{never}\n{context}"
);
// The slow test's baseline is over 3 s: its limit is longer, and the
// mutant that keeps its text from showing waits that long.
let blank = strong("public/slow.js", 3, ":StringLiteral:empty");
assert_eq!(blank["status"], "timeout", "{context}");
assert!(
(9_000..25_000).contains(&duration(&blank)),
"{blank}\n{context}"
);
// Slow but passing: no timeout.
let logged = strong("public/slow.js", 4, ":StringLiteral:empty");
assert_eq!(logged["status"], "survived", "{context}");
// The answer counts the timeouts at the limit and says the limit.
assert_eq!(reply["timeLimit"]["factor"], 1.5, "{context}");
assert!(
reply["timeLimit"]["timedOut"].as_u64() >= Some(2),
"{context}"
);
// While an attempt waits near its limit, the progress lines say so.
assert!(said.contains(", near its time limit: "), "{context}");
// The factor is the pass's to set: a factor no number is refused.
let refused = project.supercov_with(
&["runs", "latest", "mutants", "test"],
&[roots[0], ("SUPERCOV_STRONG_TIMEOUT_FACTOR", "slow")],
);
assert!(
refused
.stderr()
.contains("SUPERCOV_STRONG_TIMEOUT_FACTOR takes a number above 0, not slow"),
"{}",
refused.stderr()
);
}
/// A Playwright mutant tries its cheap candidates before its slow one: a
/// test that polls for seconds until the page says it is active is declared
/// first in its file, beside three fast tests that each read one text. The
/// mutants a fast test kills are decided by it, in under a second each, and
/// the slow test never runs them; it runs only the mutants every fast test
/// let live, and a survivor runs all four of its candidates. While it runs,
/// the progress lines name the slow test as the costliest left and say the
/// time its round has left.
#[cfg(unix)]
#[test]
fn a_playwright_mutant_tries_its_cheap_candidates_before_its_slow_one() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let available = std::process::Command::new("node")
.args(["--input-type=module", "-e", "import { chromium } from '@playwright/test'; import { existsSync } from 'node:fs'; process.exit(existsSync(chromium.executablePath()) ? 0 : 1)"])
.current_dir(modules.parent().unwrap())
.output()
.is_ok_and(|output| output.status.success());
if !available {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_BROWSER").is_none(),
"Playwright and Chromium are required"
);
eprintln!("skipping: Playwright or Chromium is unavailable");
return;
}
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("strong-playwright-order");
project.write(
"package.json",
r#"{ "name": "strong-playwright-order", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"support/server.js",
"import http from \"node:http\";\nimport { readFileSync } from \"node:fs\";\nhttp.createServer((request, response) => {\n const path = new URL(request.url, \"http://local\").pathname;\n if (path === \"/health\") return response.end(\"ok\");\n const file = path === \"/\" ? \"index.html\" : path.slice(1);\n response.setHeader(\"content-type\", file.endsWith(\".js\") ? \"text/javascript\" : \"text/html\");\n response.end(readFileSync(new URL(`../public/${file}`, import.meta.url)));\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"public/index.html",
"<!doctype html><body><p id=\"first\"></p><p id=\"second\"></p><p id=\"third\"></p><p id=\"state\"></p><script src=\"/app.js\"></script></body>\n",
);
project.write(
"public/app.js",
"function show(id, text) {\n document.getElementById(id).textContent = text;\n}\nshow(\"first\", \"First\");\nshow(\"second\", \"Second\");\nshow(\"third\", \"Third\");\nconsole.log(\"loaded\");\nsetTimeout(() => show(\"state\", \"Active\"), 3000);\n",
);
project.write(
"playwright.config.js",
&format!(
"export default {{\n testDir: \"tests\",\n workers: 1,\n reporter: \"line\",\n use: {{ baseURL: \"http://127.0.0.1:{port}\" }},\n webServer: {{ command: \"node support/server.js\", url: \"http://127.0.0.1:{port}/health\", reuseExistingServer: false, timeout: 20000, env: {{ PORT: \"{port}\" }} }},\n}};\n"
),
);
// The slow test first: a pass that ran a file's tests in their order,
// each test all its mutants, would run every mutant with it first.
project.write(
"tests/app.spec.js",
"import { test, expect } from \"@playwright/test\";\ntest(\"waits until it is active\", async ({ page }) => {\n await page.goto(\"/\");\n await expect(page.locator(\"#state\")).toHaveText(\"Active\", { timeout: 60_000 });\n});\nfor (const [id, text] of [[\"first\", \"First\"], [\"second\", \"Second\"], [\"third\", \"Third\"]]) {\n test(`shows the ${id}`, async ({ page }) => {\n await page.goto(\"/\");\n expect(await page.locator(`#${id}`).textContent()).toBe(text);\n });\n}\n",
);
project.git(&["init", "-q"]);
project.commit("strong playwright order");
let roots = ("SUPERCOV_SOURCE_ROOTS", "public");
project
.supercov_with(
&["--", "npx", "playwright", "test"],
&[roots, ("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let plan = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--plan", "--json"],
&[roots],
)
.json();
let tests = plan["tests"].as_array().unwrap();
let slow = tests
.iter()
.find(|test| test["title"] == "waits until it is active")
.unwrap_or_else(|| panic!("no slow test in {plan}"))["id"]
.as_str()
.unwrap()
.to_owned();
// The command's output, with each attempt's line: SUPERCOV_VERBOSE.
let ran = project.supercov_with(
&["runs", "latest", "mutants", "test"],
&[
roots,
("SUPERCOV_PROGRESS_INTERVAL_MS", "300"),
("SUPERCOV_VERBOSE", "1"),
],
);
let said = format!("{}\n{}", ran.stdout(), ran.stderr());
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let context = format!(
"{}\n{}\n{said}",
mutants
.iter()
.map(|mutant| format!("{} {}", mutant["id"], mutant["strong"]))
.collect::<Vec<_>>()
.join("\n"),
serde_json::json!({ "tests": plan["tests"], "mutants": plan["mutants"] })
);
let on_line = |line: u32| {
mutants
.iter()
.filter(|mutant| {
mutant["id"]
.as_str()
.unwrap()
.starts_with(&format!("public/app.js:{line}:"))
})
.collect::<Vec<_>>()
};
// Each mutant of `show` and of the three texts breaks what a fast test
// reads: a fast test kills it, at once.
let mut fast_kills = Vec::new();
for line in 1..=6 {
for mutant in on_line(line) {
let strong = &mutant["strong"];
assert_eq!(strong["status"], "killed", "{mutant}\n{context}");
assert_ne!(strong["killedBy"], slow.as_str(), "{mutant}\n{context}");
assert!(
strong["durationMs"].as_u64() < Some(3_000),
"{mutant}\n{context}"
);
fast_kills.push(mutant["id"].as_str().unwrap().to_owned());
}
}
assert!(fast_kills.len() >= 4, "{context}");
// The slow test ran none of them: each attempt's line names its mutant
// and its test.
let slow_ran = said
.lines()
.filter(|line| line.contains(": \"waits until it is active\" "))
.filter_map(|line| line.split("[supercov] ").nth(1))
.filter_map(|line| line.split(": \"").next())
.collect::<Vec<_>>();
assert!(!slow_ran.is_empty(), "{context}");
for id in &slow_ran {
assert!(!fast_kills.iter().any(|fast| fast == id), "{id}\n{context}");
}
// Nothing a fast test reads: every fast test lets it live, then the
// slow one, all four candidates run.
let loaded = on_line(7);
assert_eq!(loaded.len(), 1, "{context}");
assert_eq!(loaded[0]["strong"]["status"], "survived", "{context}");
assert_eq!(loaded[0]["strong"]["tests"], 4, "{context}");
// What only the slow test reads (the state it waits for): it runs out
// of its time limit there, once the fast tests let it live.
let detected_by_slow = on_line(8)
.into_iter()
.filter(|mutant| mutant["strong"]["status"] == "timeout")
.inspect(|mutant| {
assert_eq!(
mutant["strong"]["killedBy"],
slow.as_str(),
"{mutant}\n{context}"
)
})
.count();
assert!(detected_by_slow >= 1, "{context}");
// The progress lines name the costliest test left and the round's time.
assert!(
said.contains("costliest test left: \"waits until it is active\", "),
"{context}"
);
assert!(said.contains(" left in this round"), "{context}");
}
/// A measured Playwright run's plan carries each test's span, from the
/// fixture's record of the attempt (the reporter's record of the same
/// attempt has none), and a file whose tests ran side by side in a
/// `fullyParallel` project runs its strong attempts side by side too.
#[cfg(unix)]
#[test]
fn a_playwright_plan_has_spans_and_overlapping_tests_stay_parallel() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let project = Project::empty("strong-playwright-spans");
project.write(
"package.json",
r#"{ "name": "strong-playwright-spans", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"support/server.js",
"import http from \"node:http\";\nimport { double } from \"../server/app.js\";\nhttp.createServer((request, response) => {\n const url = new URL(request.url, \"http://local\");\n response.end(String(double(Number(url.searchParams.get(\"n\")))));\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"server/app.js",
"export function double(n) {\n return n * 2;\n}\n",
);
project.write(
"playwright.config.js",
&format!(
"export default {{\n testDir: \"tests\",\n fullyParallel: true,\n workers: 2,\n reporter: \"line\",\n use: {{ baseURL: \"http://127.0.0.1:{port}\" }},\n webServer: {{ command: \"node support/server.js\", url: \"http://127.0.0.1:{port}/?n=1\", reuseExistingServer: false, timeout: 20000, env: {{ PORT: \"{port}\" }} }},\n}};\n"
),
);
// Each holds its worker a while: the two run at once.
project.write(
"tests/double.spec.js",
"import { test, expect } from \"@playwright/test\";\nfor (const n of [2, 3]) {\n test(`doubles ${n}`, async ({ request }) => {\n await new Promise((done) => setTimeout(done, 1500));\n expect(await (await request.get(`/?n=${n}`)).text()).toBe(String(n * 2));\n });\n}\n",
);
project.git(&["init", "-q"]);
project.commit("spans");
let roots = [("SUPERCOV_SOURCE_ROOTS", "server")];
project
.supercov_with(&["--", "npx", "playwright", "test"], &roots)
.succeeds();
let plan = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--plan", "--json"],
&roots,
)
.json();
let spans = plan["tests"]
.as_array()
.unwrap()
.iter()
.map(|test| {
let span = &test["span"];
(
span[0]
.as_i64()
.unwrap_or_else(|| panic!("no span: {plan}")),
span[1].as_i64().unwrap(),
)
})
.collect::<Vec<_>>();
assert_eq!(spans.len(), 2, "{plan}");
assert!(
spans[0].0 < spans[1].1 && spans[1].0 < spans[0].1,
"the two tests ran at once: {spans:?}"
);
let ran = project.supercov_with(&["runs", "latest", "mutants", "test", "--json"], &roots);
let reply = ran.json();
let main = reply["passes"]
.as_array()
.unwrap()
.iter()
.find(|pass| pass["pass"] == "main")
.unwrap_or_else(|| panic!("no main pass\n{reply}\n{}", ran.stderr()))
.clone();
assert_eq!(main["serialFiles"], 0, "{main}\n{reply}");
assert_eq!(reply["summary"]["error"], 0, "{reply}");
}
/// A Playwright plan of thousands of mutants, each with every test a
/// candidate, run under a 256 MB heap by a harness that lists the tests
/// first (`playwright test --list --reporter=json`) and then runs a
/// Playwright process a spec file at once, each with a server of its own,
/// started a second apart. The list reads no plan and lists each test once;
/// the main pass holds only as many copies of the tests as an invocation
/// may, and the mutants past them run in further invocations; each process
/// runs its first test within seconds, none undoes another's work, and each
/// mutant gets one verdict from whichever process ran it. Before, the list
/// and the runner each made every repetition of every test, as many as the
/// busiest file had mutants, and ran out of heap; and each process cleared
/// the pass's files as it started, so the others waited on baselines that
/// were gone. A process that does run out of heap is named.
#[cfg(unix)]
#[test]
fn a_large_playwright_plan_runs_in_a_small_heap() {
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
let listeners = (0..3)
.map(|_| std::net::TcpListener::bind("127.0.0.1:0").unwrap())
.collect::<Vec<_>>();
let ports = listeners
.iter()
.map(|listener| listener.local_addr().unwrap().port().to_string())
.collect::<Vec<_>>();
drop(listeners);
let project = Project::empty("strong-playwright-heap");
project.write(
"package.json",
r#"{ "name": "strong-playwright-heap", "private": true, "type": "module" }"#,
);
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
project.write(".gitignore", "node_modules\n.supercov\n");
// About ten thousand mutants, every one reached by every test.
const FUNCTIONS: usize = 1500;
let mut app = String::new();
for index in 0..FUNCTIONS {
app.push_str(&format!(
"function f{index}(n) {{\n return n > {index} ? n + {index} : n - 1;\n}}\n"
));
}
app.push_str(&format!(
"const all = [{}];\nexport function total(n) {{\n let sum = 0;\n for (const f of all) sum += f(n);\n return sum;\n}}\n",
(0..FUNCTIONS)
.map(|index| format!("f{index}"))
.collect::<Vec<_>>()
.join(", ")
));
project.write("server/app.js", &app);
project.write(
"support/server.js",
"import http from \"node:http\";\nimport { total } from \"../server/app.js\";\nhttp.createServer((request, response) => {\n const url = new URL(request.url, \"http://local\");\n response.end(String(total(Number(url.searchParams.get(\"n\")))));\n}).listen(Number(process.env.PORT));\n",
);
project.write(
"playwright.config.js",
&format!(
"const port = process.env.SLOT_PORT ?? \"{}\";\nexport default {{\n testDir: \"tests\",\n workers: 4,\n reporter: \"line\",\n use: {{ baseURL: `http://127.0.0.1:${{port}}` }},\n webServer: {{ command: \"node support/server.js\", url: `http://127.0.0.1:${{port}}/?n=1`, reuseExistingServer: false, timeout: 20000, env: {{ PORT: port }} }},\n}};\n",
ports[0]
),
);
// Three files of ten tests, each asking for a total of its own.
for file in 0..3 {
project.write(
&format!("tests/total{file}.spec.js"),
&format!(
"import {{ test, expect }} from \"@playwright/test\";\nconst expected = (n) => {{\n let sum = 0;\n for (let i = 0; i < {FUNCTIONS}; i++) sum += n > i ? n + i : n - 1;\n return sum;\n}};\nfor (const n of [{}]) {{\n test(`totals ${{n}}`, async ({{ request }}) => {{\n expect(await (await request.get(`/?n=${{n}}`)).text()).toBe(String(expected(n)));\n }});\n}}\n",
(0..10)
.map(|test| (file * 10 + test) * 53 % FUNCTIONS)
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(", ")
),
);
}
// The harness: Playwright's list of the tests, then a process a file,
// each with its own server, started a second apart, as a harness that
// copies a build for each slot starts them. It notes when it listed.
let listed = project.root.with_extension("listed.txt");
project.write(
"e2e.mjs",
&format!(
"import {{ execFileSync, spawn }} from \"node:child_process\";\nimport {{ appendFileSync }} from \"node:fs\";\nconst listed = JSON.parse(execFileSync(\"npx\", [\"playwright\", \"test\", \"--list\", \"--reporter=json\"], {{ maxBuffer: 1 << 30 }}).toString());\nlet count = 0;\nconst visit = (suite) => {{\n for (const spec of suite.specs ?? []) count += spec.tests.length;\n (suite.suites ?? []).forEach(visit);\n}};\nlisted.suites.forEach(visit);\nappendFileSync(process.env.LISTED, `${{count}} ${{Date.now()}}\\n`);\nconst ports = {ports:?};\nconst codes = await Promise.all(ports.map((port, slot) => new Promise((done) => setTimeout(() => {{\n const child = spawn(\"npx\", [\"playwright\", \"test\", `tests/total${{slot}}.spec.js`], {{ stdio: \"inherit\", env: {{ ...process.env, SLOT_PORT: port }} }});\n child.on(\"close\", done);\n}}, slot * 1000))));\nprocess.exit(codes.every((code) => code === 0) ? 0 : 1);\n"
),
);
// A process that runs out of heap however large its heap.
project.write(
"support/hog.js",
"const kept = [];\nfor (;;) kept.push({ at: kept.length });\n",
);
project.git(&["init", "-q"]);
project.commit("a large plan");
let listed_env = listed.display().to_string();
let roots = [
("SUPERCOV_SOURCE_ROOTS", "server"),
("LISTED", listed_env.as_str()),
];
project
.supercov_with(&["--", "node", "e2e.mjs"], &roots)
.succeeds();
let _ = std::fs::remove_file(&listed);
let planning = std::time::Instant::now();
let plan = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--plan", "--json"],
&roots,
)
.json();
let planning = planning.elapsed().as_secs();
let planned = plan["mutants"]
.as_array()
.unwrap()
.iter()
.filter(|mutant| mutant["decided"].is_null())
.count();
assert!(planned > 5_000, "{planned} mutants to run");
// Every process of the pass in a 256 MB heap; sixty copies of the tests
// an invocation (about seven mutants), so that a minute sees several
// even on a slow runner: with six hundred an ARM runner's first
// invocation used the whole minute, and with a hundred and twenty a
// macOS runner's. The budget counts planning too, which takes a slow
// runner most of a minute here: the pass gets its minute after it.
let budget = (60 + 2 * planning).to_string();
let ran = project.supercov_with(
&[
"runs", "latest", "mutants", "test", "--json", "--budget", &budget,
],
&[
roots[0],
roots[1],
("NODE_OPTIONS", "--max-old-space-size=256"),
("SUPERCOV_PLAYWRIGHT_COPIES", "60"),
// Its attempts, kept to time them.
("SUPERCOV_STRONG_KEEP", "1"),
],
);
let said = ran.stderr();
let reply = ran.json();
let context = format!("{reply}\n{said}");
assert!(!said.contains("ran out of memory"), "{context}");
assert!(!said.contains("heap out of memory"), "{context}");
// The list saw the project's thirty tests, once each, every time.
let counts = std::fs::read_to_string(&listed).unwrap_or_default();
let _ = std::fs::remove_file(&listed);
let listings = counts
.lines()
.map(|line| line.split_once(' ').unwrap())
.collect::<Vec<_>>();
assert!(listings.len() >= 2, "{counts}\n{context}");
assert!(
listings.iter().all(|(count, _)| *count == "30"),
"{counts}\n{context}"
);
// The main pass's three processes each began its tests within seconds
// of being started (a second apart, after the list), whatever the
// plan's size: each runner's status says when (one whose tests' mutants
// were all decided by then runs none of them).
let listed_at = listings[0].1.parse::<i64>().unwrap();
let status = std::fs::read_dir(project.root.join(".supercov/strong"))
.unwrap()
.flatten()
.map(|work| work.path().join("playwright/status"))
.find(|status| status.is_dir())
.unwrap_or_else(|| panic!("no status kept\n{context}"));
let mut began = std::collections::BTreeMap::new();
for runner in std::fs::read_dir(&status).unwrap().flatten() {
let runner: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(runner.path()).unwrap()).unwrap();
if runner["round"] == "main" {
began.insert(
runner["pid"].to_string(),
runner["startedAt"].as_i64().unwrap(),
);
}
}
assert_eq!(began.len(), 3, "{began:?}\n{context}");
let waits = began
.values()
.map(|started| started - listed_at)
.collect::<Vec<_>>();
eprintln!("first test of each process, ms after the list: {waits:?}");
assert!(
waits.iter().all(|wait| *wait < 20_000),
"{waits:?}\n{context}"
);
// One verdict a mutant, and none an error: no baseline went missing.
assert_eq!(reply["summary"]["error"], 0, "{context}");
// The main pass went on in further invocations, and killed mutants in
// them.
let mains = reply["passes"]
.as_array()
.unwrap()
.iter()
.filter(|pass| pass["kind"] == "main")
.count();
assert!(mains >= 2, "{context}");
assert!(
said.contains("main (more copies than one invocation holds)"),
"{context}"
);
assert!(reply["summary"]["killed"].as_u64() > Some(5), "{context}");
// A command that runs out of heap: the process is named, and so is
// why each mutant has no verdict.
let ran = project.supercov_with(
&[
"runs",
"latest",
"mutants",
"test",
"--json",
"--",
"node",
"--max-old-space-size=64",
"support/hog.js",
],
&roots,
);
let said = ran.stderr();
let reply = ran.json();
let context = format!("{reply}\n{said}");
assert!(
said.contains("[supercov] a Node process ran out of memory at its")
&& said.contains("support/hog.js (pid "),
"{context}"
);
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let reasons = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.filter_map(|mutant| mutant["strong"]["reason"].as_str())
.filter(|reason| {
reason.contains("before this mutant's verdict: a Node process ran out of memory")
})
.collect::<Vec<_>>();
assert!(
!reasons.is_empty()
&& reasons
.iter()
.all(|reason| reason.contains("support/hog.js")),
"{reasons:?}\n{context}"
);
}
/// A test that passes only after an earlier test of its file ran: its file
/// runs whole for the mutants it can kill, so the mutant it kills is killed,
/// as StrykerJS (which runs the file's tests in order) kills it.
#[cfg(unix)]
#[test]
fn a_test_that_leans_on_an_earlier_one_still_kills_its_mutants() {
let project = vitest_mutants_project("strong-ordered-tests");
project.write(
"src/registry.js",
"let built = false;\nexport function build() {\n built = true;\n}\nexport function add() {\n if (built) {\n throw new Error(\"already built\");\n }\n return 1;\n}\n",
);
project.write(
"test/registry.test.js",
"import { expect, it } from \"vitest\";\nimport { add, build } from \"../src/registry.js\";\nit(\"adds before the build\", () => expect(add()).toBe(1));\nit(\"builds\", () => build());\nit(\"refuses to add after the build\", () => expect(() => add()).toThrow(\"already built\"));\n",
);
project.commit("registry");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/registry.js",
"--json",
"--limit",
"0",
])
.json();
let throw = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
// `if (built)` to `if (false)`: only the last test, after the second
// built, can tell.
.find(|mutant| mutant["id"] == "src/registry.js:6:7-6:12:ConditionalExpression:false")
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(throw["strong"]["status"], "killed", "{throw}");
}
/// A mutant only a later test reaches, where that test leans on an earlier
/// one the mutant's copy leaves out: the later test fails alone with or
/// without the mutant, so that failure is no kill. The file runs whole for
/// the mutant, where the test passes: the mutant survives, as it does in a
/// run of the whole suite.
#[cfg(unix)]
#[test]
fn a_test_that_fails_without_its_predecessor_kills_no_mutant() {
let project = vitest_mutants_project("strong-subset-false-kill");
// `if (item)` gives the first test mutants of its own, so the file's
// baseline runs both tests and the second passes there.
project.write(
"src/items.js",
"const items = [];\nexport function register(item) {\n if (item) items.push(item);\n}\nexport function count() {\n return items.length > 0 ? items.length : 0;\n}\n",
);
project.write(
"test/items.test.js",
"import { expect, it } from \"vitest\";\nimport { count, register } from \"../src/items.js\";\nit(\"registers\", () => register(\"a\"));\nit(\"counts what was registered\", () => expect(count()).toBe(1));\n",
);
project.commit("items");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
let pass = &reply["passes"][0];
assert!(pass["overturned"].as_u64().unwrap_or(0) > 0, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/items.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
// `items.length > 0` to `items.length >= 0`: the count is the same.
let equal = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/items.js:6:") && id.contains(":EqualityOperator:")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(equal["strong"]["status"], "survived", "{equal}");
// `items.length > 0 ? ... : 0` to `... false ...`: the count is 0, and
// the test fails with its predecessor run too.
let never = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/items.js:6:") && id.ends_with(":ConditionalExpression:false")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(never["strong"]["status"], "killed", "{never}");
}
/// The same, where no mutant of module-level code has the file run whole
/// already: a kill a test left out caused is overturned, and the mutant runs
/// the file whole once its whole baseline, run for it, is known.
#[cfg(unix)]
#[test]
fn an_overturned_kill_runs_its_file_whole_after_its_whole_baseline() {
let project = vitest_mutants_project("strong-overturn-whole");
project.write(
"src/items.js",
"const state = {};\nexport function register(item) {\n if (item) (state.items ??= []).push(item);\n}\nexport function count() {\n const items = state.items ?? [];\n return items.length > 0 ? items.length : 0;\n}\n",
);
project.write(
"test/items.test.js",
"import { expect, it } from \"vitest\";\nimport { count, register } from \"../src/items.js\";\nit(\"registers\", () => register(\"a\"));\nit(\"counts what was registered\", () => expect(count()).toBe(1));\n",
);
project.commit("items");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
assert!(
reply["passes"][0]["overturned"].as_u64().unwrap_or(0) > 0,
"{reply}"
);
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/items.js",
"--json",
"--limit",
"0",
])
.json();
let equal = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/items.js:7:") && id.contains(":EqualityOperator:")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(equal["strong"]["status"], "survived", "{equal}");
}
/// A mutant that makes work a test left running loop forever (a timer that
/// fires after the test passed): its evaluations pass the limit outside any
/// test, and the mutant is a timeout, not a survivor.
#[cfg(unix)]
#[test]
fn a_mutant_that_loops_forever_after_its_test_passed_is_a_timeout() {
let project = vitest_mutants_project("strong-outside-tests");
project.write(
"src/poll.js",
"export function poll(items) {\n setTimeout(() => {\n let i = 0;\n while (i < items.length) {\n i++;\n }\n }, 1);\n return items.length;\n}\n",
);
project.write(
"test/poll.test.js",
"import { expect, it } from \"vitest\";\nimport { poll } from \"../src/poll.js\";\nit(\"polls\", async () => {\n expect(poll([1, 2])).toBe(2);\n await new Promise((resolve) => setTimeout(resolve, 20));\n});\nit(\"waits\", async () => {\n await new Promise((resolve) => setTimeout(resolve, 50));\n});\n",
);
project.commit("poll");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/poll.js",
"--json",
"--limit",
"0",
])
.json();
let endless = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "src/poll.js:5:7-5:10:UpdateOperator:--")
.unwrap_or_else(|| panic!("{listed}"));
assert!(
matches!(
endless["strong"]["status"].as_str(),
Some("timeout" | "killed")
),
"{endless}"
);
}
/// A mutant that leaves a module's top-level `await` waiting forever: its
/// test file never loads, so no test's limit can end it. Once its copy is
/// past its limit (three times its file's baseline, and ten seconds), the
/// copy's worker is stopped and the mutant is a timeout, in the same pass:
/// the stage goes on, no deadline to wait out, no second pass.
#[cfg(unix)]
#[test]
fn a_mutant_that_leaves_an_import_waiting_forever_is_a_timeout_in_the_same_pass() {
let project = vitest_mutants_project("strong-import-waits");
project.write(
"src/ready.js",
"export const ready = await new Promise((resolve) => {\n if (globalThis.Date) resolve(true);\n});\n\nexport function double(n) {\n return n * 2;\n}\n",
);
project.write(
"test/ready.test.js",
"import { expect, it } from \"vitest\";\nimport { double, ready } from \"../src/ready.js\";\nit(\"is ready\", () => expect(ready).toBe(true));\nit(\"doubles\", () => expect(double(2)).toBe(4));\n",
);
project.commit("ready");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let passes = reply["passes"].as_array().unwrap();
assert_eq!(passes.len(), 1, "{reply}");
assert_eq!(passes[0]["stalled"], false, "{reply}");
assert!(
passes[0]["profile"]["hungCopies"].as_u64().unwrap_or(0) >= 1,
"{reply}"
);
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/ready.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let never = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/ready.js:2:") && id.ends_with(":ConditionalExpression:false")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(never["strong"]["status"], "timeout", "{never}");
// The stage went on past the stopped copy: every mutant of the file
// has a verdict of its own.
let doubled = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/ready.js:6:") && id.contains(":ArithmeticOperator:")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(doubled["strong"]["status"], "killed", "{doubled}");
}
/// A pass says how far it got while it runs (here every 100 ms): before any
/// verdict, how many mutants it has to run; once there are verdicts, how
/// they stand and the time left at this pace. `inc`'s mutants survive the
/// quick file, which runs first, and run again in the slow one in a later
/// stage, after `dbl`'s verdicts.
#[cfg(unix)]
#[test]
fn a_running_pass_says_how_far_it_got() {
let project = vitest_mutants_project("strong-progress");
project.write(
"src/steps.js",
"export function inc(n) {\n return n + 1;\n}\n\nexport function dbl(n) {\n return n * 2;\n}\n",
);
project.write(
"test/quick.test.js",
"import { expect, it } from \"vitest\";\nimport { dbl, inc } from \"../src/steps.js\";\nit(\"runs inc\", () => {\n inc(1);\n});\nit(\"doubles\", () => expect(dbl(2)).toBe(4));\n",
);
project.write(
"test/slow.test.js",
"import { expect, it } from \"vitest\";\nimport { inc } from \"../src/steps.js\";\nit(\"increments\", async () => {\n await new Promise((resolve) => setTimeout(resolve, 400));\n expect(inc(1)).toBe(2);\n});\n",
);
project.commit("steps");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let ran = project.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[("SUPERCOV_PROGRESS_INTERVAL_MS", "100")],
);
let reply = ran.json();
let said = ran.stderr();
let lines = said
.lines()
.filter(|line| line.starts_with("[supercov] strong pass: ") && line.contains(" mutants ("))
.collect::<Vec<_>>();
let to_run = reply["summary"]["ran"].as_u64().unwrap();
assert!(
lines.iter().any(|line| line.starts_with(&format!(
"[supercov] strong pass: 0 of {to_run} mutants (0 killed, 0 timed out, 0 survived, 0 errors), "
)) && !line.contains(" left")),
"{said}"
);
assert!(
lines.iter().any(|line| !line.contains(": 0 of ")
&& line.contains("; about ")
&& line.ends_with(" left")),
"{said}"
);
}
/// A pass runs in stages, each one run of all it holds: every mutant's
/// cheapest file beside that file's baseline, and each mutant's next batch
/// of other files, the likeliest killer first (nothing learned yet: the
/// cheapest), held back after them until the mutant's copy before has ended.
/// `inc`'s mutants survive `a`, which only calls it; the next batch is one
/// file, the quick `c`, which kills each of them, so the slow `b` never runs:
/// two copies each (the fixture's `cart.js` mutants have one test file, and
/// one copy each). A held-back copy whose mutant was killed first ends with
/// no process.
#[cfg(unix)]
#[test]
fn a_mutant_runs_its_later_files_in_batches_likeliest_killer_first() {
let project = vitest_mutants_project("strong-skip");
project.write(
"vitest.config.js",
"export default { test: { maxWorkers: 1 } };\n",
);
project.write(
"src/steps.js",
"export function inc(n) {\n return n + 1;\n}\n",
);
project.write(
"test/a.test.js",
"import { it } from \"vitest\";\nimport { inc } from \"../src/steps.js\";\nit(\"runs inc\", () => {\n inc(1);\n});\n",
);
project.write(
"test/b.test.js",
"import { expect, it } from \"vitest\";\nimport { inc } from \"../src/steps.js\";\nit(\"increments slowly\", async () => {\n await new Promise((resolve) => setTimeout(resolve, 600));\n expect(inc(1)).toBe(2);\n});\n",
);
project.write(
"test/c.test.js",
"import { expect, it } from \"vitest\";\nimport { inc } from \"../src/steps.js\";\nit(\"increments\", async () => {\n await new Promise((resolve) => setTimeout(resolve, 50));\n expect(inc(1)).toBe(2);\n});\n",
);
project.commit("steps");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let passes = reply["passes"].as_array().unwrap();
assert_eq!(passes.len(), 1, "{reply}");
let ran = reply["summary"]["ran"].as_u64().unwrap();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/steps.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let killed = mutants
.iter()
.filter(|mutant| mutant["strong"]["status"] == "killed")
.count() as u64;
assert!(killed >= 2, "{listed}");
assert!(
mutants
.iter()
.all(|mutant| mutant["strong"]["status"] != "survived"),
"{listed}"
);
// One more copy for each kill a confirmation overturned (the mutant
// runs its file whole), and each a worker took beside its mutant's
// running copy, no other mutant waiting: the cheapest run first, so
// `inc`'s chains come last, with the one worker otherwise idle.
assert!(
passes[0]["profile"]["mutantCopies"].as_u64().unwrap_or(0)
<= ran
+ killed
+ passes[0]["overturned"].as_u64().unwrap_or(0)
+ passes[0]["profile"]["besideCopies"].as_u64().unwrap_or(0),
"{reply}"
);
assert!(
passes[0]["profile"]["skippedCopies"].as_u64().unwrap_or(0) <= killed,
"{reply}"
);
assert!(passes[0]["stages"].as_u64().unwrap_or(0) <= 2, "{reply}");
}
/// A mutant that makes a module throw while it loads: its copy's test file
/// never loads, and its worker ends without the copy's end. That is a kill
/// as soon as the worker is gone (the test file did not finish), not a copy
/// that stopped reporting: no worker is stopped and none counts as hung.
#[cfg(unix)]
#[test]
fn a_mutant_that_breaks_its_test_file_s_load_is_killed_once_its_worker_ends() {
let project = vitest_mutants_project("strong-load-throws");
project.write(
"src/config.js",
"const settings = { strict: true };\nif (!settings.strict) throw new Error(\"not strict\");\nexport const strict = settings.strict;\n",
);
project.write(
"test/config.test.js",
"import { expect, it } from \"vitest\";\nimport { strict } from \"../src/config.js\";\nit(\"is strict\", () => expect(strict).toBe(true));\n",
);
project.commit("config");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let passes = reply["passes"].as_array().unwrap();
assert_eq!(passes.len(), 1, "{reply}");
assert_eq!(passes[0]["profile"]["killedCopies"], 0, "{reply}");
assert_eq!(passes[0]["profile"]["hungCopies"], 0, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/config.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let throws = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/config.js:2:") && id.ends_with(":ConditionalExpression:true")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(throws["strong"]["status"], "killed", "{throws}");
assert_eq!(
throws["strong"]["reason"], "the test file did not finish",
"{throws}"
);
}
/// Vitest 4 and later fork the strong pass's workers through Supercov's
/// spawner, a small process of its own, not from Vitest's (which a fork
/// copies, a gigabyte on a large suite); `SUPERCOV_STRONG_DIRECT_FORK=1`
/// forks them from Vitest's. Either way each mutant gets the same verdict.
#[cfg(unix)]
#[test]
fn a_strong_pass_forks_its_workers_through_a_spawner_with_the_same_verdicts() {
let project = vitest_mutants_project("strong-spawner");
let verdicts = |direct: bool| {
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let env: &[(&str, &str)] = if direct {
&[("SUPERCOV_STRONG_DIRECT_FORK", "1")]
} else {
&[]
};
let reply = project
.supercov_with(&["runs", "latest", "mutants", "test", "--json"], env)
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--json",
"--limit",
"0",
])
.json();
let statuses = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["id"].as_str().unwrap().to_owned(),
mutant["strong"]["status"].to_string(),
)
})
.collect::<std::collections::BTreeMap<_, _>>();
(
reply["passes"][0]["profile"]["spawnedWorkers"].as_u64(),
statuses,
)
};
let (spawned, through) = verdicts(false);
assert!(spawned.unwrap_or(0) > 0, "{spawned:?}");
let (none, direct) = verdicts(true);
assert_eq!(none, Some(0));
assert!(!through.is_empty());
assert_eq!(through, direct);
}
/// The spawner keeps workers started ahead of Vitest's requests, and a copy
/// that gets one sees the process a fresh worker is: Vitest's worker entry
/// as its script, nothing of Supercov's in its environment (a test file that
/// sees otherwise fails to load, and kills what survives). Started ahead or
/// not (`SUPERCOV_STRONG_WORKERS_AHEAD=0`), each mutant gets the same verdict.
#[cfg(unix)]
#[test]
fn a_copy_in_a_worker_started_ahead_gets_the_verdict_a_fresh_worker_gives() {
let project = vitest_mutants_project("strong-ahead");
project.write(
"test/cart.test.js",
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\nif (!/[\\\\/]workers[\\\\/]forks\\.js$/.test(process.argv[1] ?? \"\")) throw new Error(`not Vitest's worker: ${process.argv[1]}`);\nif (\"SUPERCOV_STRONG_WORKER\" in process.env) throw new Error(\"Supercov's worker variable is set\");\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n});\n",
);
project.commit("worker checks");
let verdicts = |ahead: &str| {
// One worker: its copies run one after another, so most get a
// worker started while the one before ran.
project
.supercov(&["--", "npx", "vitest", "run", "--maxWorkers=1"])
.succeeds();
let reply = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[("SUPERCOV_STRONG_WORKERS_AHEAD", ahead)],
)
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--json",
"--limit",
"0",
])
.json();
let statuses = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["id"].as_str().unwrap().to_owned(),
mutant["strong"]["status"].to_string(),
)
})
.collect::<std::collections::BTreeMap<_, _>>();
(
reply["passes"][0]["profile"]["usedAhead"].as_u64(),
statuses,
)
};
let (used, ahead) = verdicts("4");
assert!(used.unwrap_or(0) > 0, "{used:?}");
let (none, fresh) = verdicts("0");
assert_eq!(none.unwrap_or(0), 0);
assert!(ahead.values().any(|status| status == "\"killed\""));
assert!(ahead.values().any(|status| status == "\"survived\""));
assert_eq!(ahead, fresh);
}
/// A mutant that makes a worker drop its channel to Vitest (here it
/// disconnects): Vitest cannot hear the file finish, so it did not, and the
/// mutant is killed whatever the copy wrote. Nothing reports a closed
/// channel as an error of the run, and the pass runs once.
#[cfg(unix)]
#[test]
fn a_worker_that_drops_its_channel_fails_its_file_and_the_pass_runs_once() {
let project = vitest_mutants_project("strong-channel-closed");
project.write(
"src/bye.js",
"export function bye(flag) {\n if (flag) process.disconnect?.();\n return 1;\n}\n",
);
project.write(
"test/bye.test.js",
"import { expect, it } from \"vitest\";\nimport { bye } from \"../src/bye.js\";\nit(\"stays\", () => expect(bye(false)).toBe(1));\n",
);
project.commit("bye");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
assert!(!said.contains("Channel closed"), "{said}");
assert!(!said.contains("Unhandled"), "{said}");
assert_eq!(reply["passes"].as_array().map(Vec::len), Some(1), "{reply}");
assert_eq!(
said.matches("strong pass: switches in").count(),
1,
"{said}"
);
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/bye.js",
"--json",
"--limit",
"0",
])
.json();
let disconnects = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/bye.js:2:") && id.ends_with(":ConditionalExpression:true")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(disconnects["strong"]["status"], "killed", "{disconnects}");
}
/// Under Vitest 3 the workers are tinypool's processes. A worker that loses
/// its channel (one the pass stops once a failed test decided its copy, or
/// one a mutant disconnects or ends) made tinypool 1.1's next write to it
/// fail with "Channel closed", which ended Vitest 3.2's run and left most
/// mutants errors in every pass. Its exit tells tinypool it is gone: the pass
/// runs once, with no error, and those mutants are killed.
#[cfg(unix)]
#[test]
fn a_vitest_3_worker_that_loses_its_channel_ends_no_pass() {
let project = Project::empty("strong-vitest-3-channel");
project.write(
"package.json",
r#"{ "name": "mutants", "type": "module", "scripts": { "test": "vitest run" } }"#,
);
let installed = std::process::Command::new("npm")
.args([
"install",
"--no-audit",
"--no-fund",
"--silent",
"vitest@3.2.4",
])
.current_dir(&project.root)
.output()
.is_ok_and(|output| output.status.success());
if !installed {
assert!(
std::env::var_os("SUPERCOV_REQUIRE_VITEST_3").is_none(),
"Vitest 3 could not be installed"
);
eprintln!("skipping: Vitest 3 could not be installed");
return;
}
project.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/cart.js",
"export function shipping(sum) {\n if (sum >= 50) {\n return 0;\n }\n return 5;\n}\n\nexport function label(name) {\n return name.trim().toUpperCase();\n}\n\nexport function bye(flag) {\n if (flag) process.disconnect?.();\n return 1;\n}\n\nexport function quit(flag) {\n if (flag) process.exit(3);\n return 2;\n}\n",
);
project.write(
"test/cart.test.js",
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label, bye, quit } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n it(\"stays\", () => expect(bye(false)).toBe(1));\n it(\"keeps going\", () => expect(quit(false)).toBe(2));\n for (let i = 0; i < 20; i++) it(`waits ${i}`, async () => { await new Promise((done) => setTimeout(done, 20)); expect(shipping(10)).toBe(5); });\n});\n",
);
project.git(&["init", "-q"]);
project.commit("mutants");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
assert!(!said.contains("Unhandled"), "{said}");
assert_eq!(reply["passes"].as_array().map(Vec::len), Some(1), "{reply}");
assert_eq!(reply["summary"]["error"], 0, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
for line in ["src/cart.js:13:", "src/cart.js:18:"] {
let dropping = mutants
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with(line) && id.ends_with(":ConditionalExpression:true")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(dropping["strong"]["status"], "killed", "{dropping}");
}
assert!(
mutants
.iter()
.filter(|mutant| mutant["strong"]["status"] == "killed")
.count()
> 4,
"{listed}"
);
}
/// A continuous pass gives each Vitest run a bounded number of slots (Vitest
/// reads every slot's file as the run starts): a pass that needs more runs
/// again, in the same pass, with the verdicts one run gives.
#[cfg(unix)]
#[test]
fn a_pass_with_more_copies_than_a_run_has_slots_runs_again_with_the_same_verdicts() {
let project = vitest_mutants_project("strong-run-slots");
project.write(
"test/refund.test.js",
"import { expect, it } from \"vitest\";\nimport { refund } from \"../src/cart.js\";\nit(\"refunds big orders less\", () => expect(refund(200)).toBe(180));\nit(\"refunds small orders whole\", () => expect(refund(50)).toBe(50));\n",
);
project.commit("refunds");
let verdicts = |slots: &str| {
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[("SUPERCOV_STRONG_RUN_SLOTS", slots)],
)
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--json",
"--limit",
"0",
])
.json();
let statuses = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["id"].as_str().unwrap_or_default().to_owned(),
mutant["strong"]["status"].clone(),
)
})
.collect::<std::collections::BTreeMap<_, _>>();
(reply, statuses)
};
let (one_run, expected) = verdicts("");
let (runs, statuses) = verdicts("1");
assert_eq!(
one_run["passes"][0]["profile"]["continuousRuns"], 1,
"{one_run}"
);
assert!(
runs["passes"][0]["profile"]["continuousRuns"]
.as_u64()
.unwrap_or(0)
> 1,
"{runs}"
);
assert_eq!(runs["passes"].as_array().map(Vec::len), Some(1), "{runs}");
assert_eq!(runs["summary"]["error"], 0, "{runs}");
assert!(
expected.values().any(|status| status == "killed"),
"{expected:?}"
);
assert_eq!(statuses, expected);
}
/// A copy that runs none, or only some, of the tests it was to run proves
/// nothing: here `labels` exists in the measured run only, so the copies of
/// `label`'s mutants run no test. They are errors that say so, never
/// survivors, with the stages and without.
#[cfg(unix)]
#[test]
fn a_copy_that_runs_none_of_its_tests_makes_its_mutant_an_error() {
let project = vitest_mutants_project("strong-ran-none");
project.write(
"test/cart.test.js",
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n if (!process.env.SUPERCOV_STRONG) it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n});\n",
);
project.commit("labels in the measured run only");
for stages in ["", "1"] {
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--json"],
&[("SUPERCOV_STRONG_STAGES", stages)],
)
.json();
assert!(
reply["summary"]["error"].as_u64().unwrap_or(0) > 0,
"{reply}"
);
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
let of_label = mutants
.iter()
.filter(|mutant| {
mutant["id"]
.as_str()
.unwrap_or_default()
.starts_with("src/cart.js:9:")
})
.collect::<Vec<_>>();
assert!(!of_label.is_empty(), "{listed}");
for mutant in of_label {
if mutant["strong"].is_null() {
continue;
}
assert_ne!(mutant["strong"]["status"], "survived", "{mutant}");
if mutant["strong"]["status"] == "error" {
assert!(
mutant["strong"]["reason"]
.as_str()
.unwrap_or_default()
.contains("ran none of the tests it was to run"),
"{mutant}"
);
}
}
assert!(
mutants
.iter()
.any(|mutant| mutant["strong"]["status"] == "killed"),
"{listed}"
);
}
}
/// A test file that does not finish without a mutant (here it throws while
/// it loads, in the strong pass only) cannot test the mutants it alone
/// covers: they are errors, not survivors.
#[cfg(unix)]
#[test]
fn mutants_only_an_unfinished_test_file_covers_are_errors() {
let project = vitest_mutants_project("strong-baseline-unfinished");
project.write(
"test/cart.test.js",
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label } from \"../src/cart.js\";\nif (process.env.SUPERCOV_STRONG) throw new Error(\"not in a strong pass\");\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => expect(shipping(80)).toBe(0));\n it(\"charges small orders\", () => expect(shipping(10)).toBe(5));\n it(\"labels\", () => expect(label(\" a \")).toBe(\"A\"));\n});\n",
);
project.commit("unfinished");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert!(reply["summary"]["ran"].as_u64().unwrap_or(0) > 0, "{reply}");
assert_eq!(
reply["summary"]["error"], reply["summary"]["ran"],
"{reply}"
);
assert_eq!(reply["summary"]["killed"], 0, "{reply}");
}
/// A mutant that leaves work re-arming itself after the tests (a ticker that
/// should stop after three ticks and never does): no single evaluation runs
/// away, but the mutant keeps running after the tests ended, as a run
/// waiting on its worker would never end. It is a timeout.
#[cfg(unix)]
#[test]
fn a_mutant_whose_work_keeps_rearming_after_the_tests_is_a_timeout() {
let project = vitest_mutants_project("strong-left-running");
project.write(
"src/ticker.js",
"export function tick(done) {\n let n = 0;\n const step = () => {\n n++;\n if (n < 3) {\n setImmediate(step);\n } else {\n done(n);\n }\n };\n setImmediate(step);\n}\n",
);
project.write(
"test/ticker.test.js",
"import { expect, it } from \"vitest\";\nimport { tick } from \"../src/ticker.js\";\nit(\"ticks\", async () => {\n const seen = [];\n tick((n) => seen.push(n));\n await new Promise((resolve) => setTimeout(resolve, 20));\n expect(seen.length).toBeLessThan(2);\n});\n",
);
project.commit("ticker");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/ticker.js",
"--json",
"--limit",
"0",
])
.json();
let endless = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "src/ticker.js:5:9-5:14:ConditionalExpression:true")
.unwrap_or_else(|| panic!("{listed}"));
assert!(
matches!(
endless["strong"]["status"].as_str(),
Some("timeout" | "killed")
),
"{endless}"
);
}
/// Code under test that catches every error (a stream turning a failure into
/// a frame) also catches the hit limit's: the loop the mutant made endless
/// ends, the test passes, and the mutant is a timeout all the same.
#[cfg(unix)]
#[test]
fn a_mutant_whose_endless_loop_is_caught_by_the_code_is_a_timeout() {
let project = vitest_mutants_project("strong-swallowed-limit");
project.write(
"src/drain.js",
"export async function drain(source) {\n const out = [];\n try {\n for (;;) {\n const r = await source.next();\n if (r.done) break;\n out.push(r.value);\n }\n } catch {\n return out;\n }\n return out;\n}\n",
);
project.write(
"test/drain.test.js",
"import { expect, it } from \"vitest\";\nimport { drain } from \"../src/drain.js\";\nasync function* two() {\n yield 1;\n yield 2;\n}\nit(\"drains\", async () => {\n const out = await drain(two());\n expect(out).toContain(2);\n});\n",
);
project.commit("drain");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/drain.js",
"--json",
"--limit",
"0",
])
.json();
let endless = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/drain.js:6:") && id.ends_with(":ConditionalExpression:false")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(endless["strong"]["status"], "timeout", "{endless}");
}
/// `supercov mutants` with no run measures one first and tests its mutants;
/// a plain run before it lists none and says nothing of mutants; after a
/// source changes, it measures again rather than read a run of other code.
#[cfg(unix)]
#[test]
fn supercov_mutants_measures_when_it_must_and_plain_runs_know_no_mutants() {
let project = vitest_mutants_project("supercov-mutants-command");
project.write(
"src/double.js",
"export function double(n) {\n return n * 2;\n}\n",
);
project.write(
"test/double.test.js",
"import { expect, it } from \"vitest\";\nimport { double } from \"../src/double.js\";\nit(\"doubles\", () => expect(double(3)).toBe(6));\n",
);
project.commit("double");
// No run yet: it measures first, with the command given.
let first = project.supercov(&["mutants", "--json", "--", "npx", "vitest", "run"]);
assert!(
first.stderr().contains("measuring first (no run yet)"),
"{}",
first.stderr()
);
let reply = first.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
assert!(
reply["summary"]["killed"].as_u64().unwrap_or(0) > 0,
"{reply}"
);
// Its run is current and has its mutants' values: read as it is.
let again = project.supercov(&["mutants", "--json"]);
assert!(
!again.stderr().contains("measuring first"),
"{}",
again.stderr()
);
assert!(again.json()["summary"]["killed"].as_u64().unwrap_or(0) > 0);
// A plain run lists no mutants and its summary says nothing of them;
// `supercov mutants` after it measures with the mutants' probes.
let plain = project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
assert!(!plain.contains("Mutants "), "{plain}");
let valued = project.supercov(&["mutants", "--json"]);
assert!(
valued
.stderr()
.contains("measuring first (the latest run recorded no values for its mutants)"),
"{}",
valued.stderr()
);
// A changed source is measured again, with the latest run's command.
project.write(
"src/double.js",
"export function double(n) {\n return n + n;\n}\n",
);
let changed = project.supercov(&["mutants", "--json"]);
assert!(
changed
.stderr()
.contains("measuring first (the checkout changed since the latest run)"),
"{}",
changed.stderr()
);
let reply = changed.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/double.js",
"--json",
"--limit",
"0",
])
.json();
let mutants = listed["data"]["mutants"].as_array().unwrap();
assert!(
mutants.iter().any(|mutant| mutant["original"] == "n + n"),
"{reply} {listed}"
);
}
/// A test file that fakes the clock and leaves it faked: the look for work
/// left running after the tests waits on the real clock, so the file still
/// finishes and a mutant its test cannot tell apart survives.
#[cfg(unix)]
#[test]
fn a_test_file_that_leaves_the_clock_faked_still_finishes_under_a_mutant() {
let project = vitest_mutants_project("strong-faked-clock-left");
project.write(
"src/double.js",
"export function double(n) {\n return n * 2;\n}\n",
);
project.write(
"test/double.test.js",
"import { expect, it, vi } from \"vitest\";\nimport { double } from \"../src/double.js\";\nit(\"doubles zero\", () => {\n vi.useFakeTimers();\n expect(double(0)).toBe(0);\n});\n",
);
project.commit("double");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/double.js",
"--json",
"--limit",
"0",
])
.json();
let division = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| {
let id = mutant["id"].as_str().unwrap_or_default();
id.starts_with("src/double.js:2:") && id.contains(":ArithmeticOperator:")
})
.unwrap_or_else(|| panic!("{listed}"));
assert_eq!(division["strong"]["status"], "survived", "{division}");
}
/// `mutants test` reads its options before anything else: each mistake is
/// named, with the usage on the terminal and as a JSON error with --json,
/// and a run it cannot find or a store it cannot list is said to be so.
/// `supercov mutants` explains itself, and with no run and no command has
/// nothing to measure.
#[test]
fn mutants_test_names_each_mistake_in_its_options_before_it_reads_a_run() {
let project = Project::cart("mutants-test-options");
for (arguments, said) in [
(&["--file"][..], "--file needs a path"),
(&["--file", ""], "--file needs a path"),
(&["--diff"], "--diff needs a base revision"),
(&["--fail-on"], "--fail-on needs statuses"),
(
&["--fail-on", "survived,,killed"],
"--fail-on takes survived, timeout, no-coverage, error, not killed",
),
(&["--shard"], "--shard needs k/n"),
(
&["--shard", "2"],
"--shard takes k/n with 1 <= k <= n, not 2",
),
(&["--shard", "x/2"], "not x/2"),
(&["--shard", "1/y"], "not 1/y"),
(&["--shard", "1/0"], "not 1/0"),
(&["--shard", "3/2"], "not 3/2"),
(&["--critical"], "--critical needs a glob"),
(&["--critical", ""], "--critical needs a glob"),
(&["--plan", "--"], "-- needs a command after it"),
(&["--sideways"], "Unknown option: --sideways"),
] {
let mut command = vec!["runs", "latest", "mutants", "test"];
command.extend(arguments);
let human = project.supercov(&command).exits(2);
contains_all(
&human,
&[said, "Usage: supercov runs <run-id> mutants test"],
);
command.insert(4, "--json");
let json = project.supercov(&command);
assert_eq!(json.code(), 2, "{arguments:?}");
let json = json.json();
assert!(
json["error"]["message"].as_str().unwrap().contains(said),
"{arguments:?}: {json}"
);
}
for help in [
&["runs", "latest", "mutants", "test", "--help"][..],
&["runs", "latest", "mutants", "test", "-h"],
] {
contains_all(
&project.supercov(help).succeeds(),
&[
"Usage: supercov runs <run-id> mutants test",
"--shard <k>/<n>",
],
);
}
for help in [
&["mutants", "--help"][..],
&["mutants", "-h"],
&["help", "mutants"],
] {
contains_all(
&project.supercov(help).succeeds(),
&[
"Usage: supercov mutants [options] [-- <test command>]",
// Every language with mutants is named, with its tool, and
// the ones in preview say so.
"StrykerJS",
"in preview",
"mutmut",
"cargo-mutants",
"Gremlins",
"mutant for Ruby",
],
);
}
// The run's own command is an option, listed with the others.
let test_help = project
.supercov(&["runs", "latest", "mutants", "test", "--help"])
.succeeds();
let options = test_help
.split("Options:")
.nth(1)
.and_then(|rest| rest.split("\n\n").next())
.unwrap_or_default();
assert!(options.contains("-- <command>"), "{test_help}");
let weak_help = project
.supercov(&["runs", "latest", "mutants", "--help"])
.succeeds();
contains_all(
&weak_help,
&["in preview", "cargo-mutants", "Gremlins", "mutant for Ruby"],
);
let overview = project.supercov(&["--help"]).succeeds();
assert!(
overview.contains(
"Test the tests with mutants (JavaScript, TypeScript; Python, Rust, Go and Ruby in preview)"
),
"{overview}"
);
// Options that parse, and no run to read: said on the standard error
// with exit 1, or as a JSON error with --json.
let options = [
"--shard",
"1/2",
"--critical",
"src/**",
"--fail-on",
",",
"--",
"npx",
"vitest",
"run",
];
let mut command = vec!["runs", "nope", "mutants", "test"];
command.extend(options);
let unknown = project.supercov(&command).exits(1);
assert!(unknown.contains("[supercov] "), "{unknown}");
assert!(!unknown.contains("Usage:"), "{unknown}");
command.insert(4, "--json");
let unknown = project.supercov(&command);
assert_eq!(unknown.code(), 2, "{}", unknown.stderr());
assert_eq!(unknown.json()["ok"], false);
// A store that cannot be listed.
project.measure(&[]);
let unlisted = project
.supercov_with(
&["runs", "latest", "mutants", "test", "--plan"],
&[("SUPERCOV_TEST_FAULT", "fs.read_dir#run_store.rs:695")],
)
.exits(1);
assert!(unlisted.contains("run_store.rs:695"), "{unlisted}");
// A run whose evidence is cut short after its header, its size as
// recorded, has no plan. Where the cut lands (a section's header or its
// compressed body) depends on the run's sizes, so the reason may be either.
let run = project.latest();
let directory = project.root.join(format!(".supercov/runs/{run}"));
let metadata: serde_json::Value =
serde_json::from_slice(&std::fs::read(directory.join("run.json")).unwrap()).unwrap();
let evidence = directory.join(metadata["rawEvidence"]["file"].as_str().unwrap());
let mut bytes = std::fs::read(&evidence).unwrap();
let half = bytes.len() / 2;
bytes[half..].fill(b'x');
std::fs::write(&evidence, bytes).unwrap();
let unread = project
.supercov(&["runs", "latest", "mutants", "test", "--plan"])
.exits(1);
assert!(unread.starts_with("[supercov] InvalidArchive("), "{unread}");
// No run, and no command to measure one with.
let empty = Project::empty("mutants-no-run");
let nothing = empty.supercov(&["mutants", "--json"]).exits(2);
assert!(
nothing.contains(
"No run to read mutants from: give the test command, supercov mutants -- <test command>"
),
"{nothing}"
);
}
/// `mutants test` narrowed: to a file, to the lines a change touched since
/// a base (a file git does not track yet is new whole), and to an even share
/// of what runs (the mutants decided unrun with the first). Its gate fails
/// on an asked mutant whose verdict `--fail-on` names, or on any survivor
/// in a `--critical` file, unless supercov.accepted.json accepts it, and
/// names the accepted ones since killed. What stops a pass is said: a
/// working directory or plan it cannot write, verdicts it cannot save, a
/// command it cannot run or the run did not record.
#[cfg(unix)]
#[test]
fn mutants_test_narrows_shares_and_gates_what_it_asks_about() {
let project = vitest_mutants_project("strong-narrow-gate");
// On the base and unchanged since.
project.write(
"src/tax.js",
"export function tax(sum) {\n return sum >= 10 ? sum * 0.2 : 0;\n}\n",
);
project.write(
"test/tax.test.js",
"import { expect, it } from \"vitest\";\nimport { tax } from \"../src/tax.js\";\nit(\"taxes\", () => expect(tax(20)).toBe(4));\n",
);
project.commit("tax");
project.git(&["branch", "base"]);
project.edit("src/cart.js", "return 5;", "return 6;");
project.edit("test/cart.test.js", "toBe(5)", "toBe(6)");
project.commit("dearer");
// Not tracked yet: the run measures the working tree. `n > 0` to
// `n >= 0` is equivalent: `n &&` already left 0 out.
project.write(
"src/extra.js",
"export function positive(a, b) {\n const n = a - b;\n return Boolean(n && n > 0);\n}\n",
);
project.write(
"test/extra.test.js",
"import { expect, it } from \"vitest\";\nimport { positive } from \"../src/extra.js\";\nit(\"is positive\", () => expect(positive(3, 1)).toBe(true));\n",
);
// A command that writes its own verdicts: one record no verdict can be
// read from for the first mutant, a kill for each other, and lines
// that are no verdict at all.
project.write(
"fake-strong.mjs",
"import { appendFileSync, readFileSync } from \"node:fs\";\nconst plan = JSON.parse(readFileSync(process.env.SUPERCOV_STRONG_PLAN, \"utf8\"));\nconst lines = [\"not json\", JSON.stringify({ summary: true, driver: \"fake\" }), JSON.stringify({ note: \"no id\" })];\nplan.mutants.forEach((mutant, index) => {\n lines.push(JSON.stringify(index === 0 ? { id: mutant.id, status: 7 } : { id: mutant.id, status: \"killed\", tests: 1 }));\n});\nappendFileSync(process.env.SUPERCOV_STRONG_RESULTS, lines.join(\"\\n\") + \"\\n\");\n",
);
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let run = project.latest();
let ids = |reply: &serde_json::Value| {
reply["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| mutant["id"].as_str().unwrap().to_owned())
.collect::<Vec<_>>()
};
let plan = |arguments: &[&str]| {
let mut command = vec!["runs", "latest", "mutants", "test", "--plan", "--json"];
command.extend(arguments);
project.supercov(&command).json()
};
let all = plan(&[]);
assert!(
all["summary"]["decided"]["equivalent"].as_u64() >= Some(1),
"{all}"
);
let human = project
.supercov(&["runs", "latest", "mutants", "test", "--plan"])
.succeeds();
contains_all(
&human,
&[
&format!("Strong mutation plan for {run}: "),
" to run ",
" equivalent ",
],
);
// A file's mutants.
let tax = ids(&plan(&["--file", "src/tax.js"]));
assert!(!tax.is_empty());
assert!(
tax.iter().all(|id| id.starts_with("src/tax.js:")),
"{tax:?}"
);
// A change's: the new file whole, cart.js's changed line, not tax.js.
let changed = ids(&plan(&["--diff", "base"]));
assert!(
changed.iter().any(|id| id.starts_with("src/extra.js:")),
"{changed:?}"
);
assert!(
changed.iter().any(|id| id.starts_with("src/cart.js:")),
"{changed:?}"
);
assert!(
changed
.iter()
.all(|id| !id.starts_with("src/tax.js:") && !id.starts_with("src/cart.js:9:")),
"{changed:?}"
);
let unknown = project
.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--plan",
"--diff",
"no-such-base",
])
.exits(1);
assert!(
unknown.contains("git knows no commit by that name"),
"{unknown}"
);
// Two shares: what runs split between them, the decided in the first.
let first = plan(&["--shard", "1/2"]);
let second = plan(&["--shard", "2/2"]);
assert_eq!(second["summary"]["decided"]["survived"], 0, "{second}");
assert_eq!(second["summary"]["decided"]["noCoverage"], 0, "{second}");
assert_eq!(first["summary"]["decided"], all["summary"]["decided"]);
assert_eq!(
first["summary"]["toRun"].as_u64().unwrap() + second["summary"]["toRun"].as_u64().unwrap(),
all["summary"]["toRun"].as_u64().unwrap()
);
// What stops a pass, before any of tax.js's mutants has a verdict.
let tax_pass = ["runs", "latest", "mutants", "test", "--file", "src/tax.js"];
project.write(".supercov/strong", "");
let unmade = project.supercov(&tax_pass).exits(1);
assert!(unmade.contains(".supercov/strong"), "{unmade}");
std::fs::remove_file(project.root.join(".supercov/strong")).unwrap();
let unwritten = project.supercov_with(
&tax_pass,
&[(
"SUPERCOV_TEST_FAULT",
"fs.write#mutants_test_command.rs:1789",
)],
);
assert_eq!(unwritten.code(), 1, "{}", unwritten.stderr());
assert!(
fired_at(&unwritten.stderr(), "mutants_test_command.rs:1789"),
"{}",
unwritten.stderr()
);
// The store's ignore file, written as the pass takes its hold on the
// store, cannot be: the pass does not start.
std::fs::remove_file(project.root.join(".supercov/.gitignore")).unwrap();
let unstarted = project.supercov_with(&tax_pass, &[("SUPERCOV_TEST_FAULT", "store-ignore")]);
assert_eq!(unstarted.code(), 1, "{}", unstarted.stderr());
assert!(
fired_at(&unstarted.stderr(), "store-ignore"),
"{}",
unstarted.stderr()
);
let saved = project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json"));
// What the stopped passes above decided is saved; a directory in its
// place cannot be written.
let _ = std::fs::remove_file(&saved);
std::fs::create_dir(&saved).unwrap();
let mut faked = tax_pass.to_vec();
faked.extend(["--", "node", "fake-strong.mjs"]);
let unsaved = project.supercov(&faked).exits(1);
assert!(unsaved.contains("strong-mutation.json"), "{unsaved}");
// Nothing to run, and still nowhere to save.
let unsaved = project
.supercov(&["runs", "latest", "mutants", "test", "--file", "src/none.js"])
.exits(1);
assert!(unsaved.contains("strong-mutation.json"), "{unsaved}");
std::fs::remove_dir(&saved).unwrap();
// Nothing asked: nothing runs, and nothing fails.
project
.supercov(&["runs", "latest", "mutants", "test", "--file", "src/none.js"])
.succeeds();
// A run that recorded no command, and none given.
let metadata_path = project.root.join(format!(".supercov/runs/{run}/run.json"));
let metadata = std::fs::read_to_string(&metadata_path).unwrap();
let mut commandless: serde_json::Value = serde_json::from_str(&metadata).unwrap();
commandless["command"] = serde_json::json!([]);
std::fs::write(&metadata_path, commandless.to_string()).unwrap();
let commandless = project.supercov(&tax_pass).exits(1);
assert!(
commandless.contains("the run recorded no command: give one after --"),
"{commandless}"
);
std::fs::write(&metadata_path, metadata).unwrap();
// A command that writes no verdict: each mutant it ran is an error.
let mut silent = tax_pass.to_vec();
silent.extend(["--json", "--", "node", "-e", "0"]);
let silent = project.supercov(&silent).json();
assert!(silent["summary"]["ran"].as_u64() > Some(0), "{silent}");
assert_eq!(
silent["summary"]["error"], silent["summary"]["ran"],
"{silent}"
);
let errors = silent["summary"]["error"].as_u64().unwrap();
// The command's own verdicts: a record no verdict is read from leaves
// its mutant to the next pass, and a pass that decides nothing more
// ends them; the mutant is then an error.
let extra = plan(&["--file", "src/extra.js"]);
let unread = extra["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["decided"].is_null())
.unwrap()["id"]
.as_str()
.unwrap()
.to_owned();
let reply = project
.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/extra.js",
"--json",
"--",
"node",
"fake-strong.mjs",
])
.json();
// The summary counts extra.js's mutants alone, the ones asked about:
// tax.js's errors above are not among them.
assert_eq!(reply["summary"]["error"], 1, "{reply}");
assert!(errors > 0);
assert!(reply["summary"]["killed"].as_u64() > Some(0), "{reply}");
assert!(reply["summary"]["equivalent"].as_u64() > Some(0), "{reply}");
assert_eq!(reply["passes"][0]["driver"], "fake", "{reply}");
assert_eq!(reply["passes"].as_array().unwrap().len(), 2, "{reply}");
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/extra.js",
"--json",
"--limit",
"0",
])
.json();
let errored = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == unread.as_str())
.unwrap_or_else(|| panic!("{listed}"))["strong"]
.clone();
assert_eq!(errored["status"], "error", "{errored}");
assert_eq!(
errored["reason"],
"the command ended (exit 0) before this mutant's verdict"
);
// cart.js's mutants, half first: the gate passes over those with no
// verdict yet.
let half = project
.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/cart.js",
"--shard",
"2/2",
])
.succeeds();
contains_all(
&half,
&[
// The mutants asked about are named, and counted alone.
&format!("Strong mutation for {run} ("),
" mutants, in src/cart.js): mutation score ",
" killed ",
],
);
let cart = ["runs", "latest", "mutants", "test", "--file", "src/cart.js"];
let gated = |arguments: &[&str]| {
let mut command = cart.to_vec();
command.extend(arguments);
project.supercov(&command)
};
gated(&[]).succeeds();
let survivor = "src/cart.js:2:7-2:16:EqualityOperator:>";
let failed = gated(&["--fail-on", "survived"]).exits(1);
assert!(
failed.contains(&format!(" survived {survivor}\n")),
"{failed}"
);
let critical = gated(&["--critical", "src/cart.j?"]).exits(1);
assert!(
critical.contains(&format!(" survived {survivor} (critical)\n")),
"{critical}"
);
// `?` is no `/`, and `*` stops at the end of the name.
gated(&[
"--critical",
"src?cart.js",
"--critical",
"src/*z",
"--fail-on",
"timeout",
])
.succeeds();
// Accepted: the survivor passes; an accepted mutant since killed is
// named for removal.
let killed = "src/cart.js:9:10-9:21:MethodExpression:removed";
project.write(
"supercov.accepted.json",
&serde_json::json!([
{"id": survivor, "reason": "no order costs exactly 50"},
{"id": killed, "reason": "once thought equivalent"},
])
.to_string(),
);
let accepted = gated(&["--fail-on", "survived"]).succeeds();
assert!(
accepted.contains(
" 1 accepted mutant(s) in supercov.accepted.json are killed or gone: remove them"
),
"{accepted}"
);
let accepted = gated(&["--fail-on", "survived", "--json"]).json();
assert_eq!(accepted["gate"]["failed"], false, "{accepted}");
assert_eq!(
accepted["gate"]["accepted"][0]["id"], survivor,
"{accepted}"
);
assert_eq!(
accepted["gate"]["staleAccepted"],
serde_json::json!([killed])
);
for (contents, said) in [
("[{\"reason\": \"why\"}]", "an entry has no id"),
(
"[{\"id\": \"a\", \"reason\": \" \"}]",
"a is accepted without a reason",
),
("{", "supercov.accepted.json: "),
] {
project.write("supercov.accepted.json", contents);
let refused = gated(&[]).exits(1);
assert!(refused.contains(said), "{contents}: {refused}");
let refused = gated(&["--json"]);
assert_eq!(refused.code(), 2, "{contents}");
assert!(
refused.json()["error"]["message"]
.as_str()
.unwrap()
.contains(said),
"{contents}"
);
}
// An empty list accepts nothing.
project.write("supercov.accepted.json", "[]");
gated(&[]).succeeds();
std::fs::remove_file(project.root.join("supercov.accepted.json")).unwrap();
// A source changed since a run whose mutants were never listed: its
// mutants are left out, and said so.
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let run = project.latest();
project.edit("src/tax.js", "sum * 0.2", "sum / 5");
let stale = project.supercov(&["runs", "latest", "mutants", "test", "--plan", "--json"]);
assert!(
stale.stderr().contains(&format!(
"1 file(s) changed since run {run}; their mutants are left out"
)),
"{}",
stale.stderr()
);
assert!(
ids(&stale.json())
.iter()
.all(|id| !id.starts_with("src/tax.js:")),
"{}",
stale.stdout()
);
// `supercov mutants` measures that checkout first, and says when it
// cannot start the measurement.
let unmeasured = project
.supercov_with(
&["mutants", "--json"],
&[("SUPERCOV_TEST_FAULT", "spawn#mutants_test_command.rs:395")],
)
.exits(2);
assert!(
unmeasured.contains("[supercov] could not measure: "),
"{unmeasured}"
);
}
/// A run whose one source holds no code (a comment alone) has no mutants
/// to test, and `mutants test` says so. `supercov mutants`, finding no
/// values for mutants in it, measures it again, and that run lists none:
/// nothing runs, and there is no score.
#[test]
fn a_run_whose_source_holds_no_code_has_no_mutants_to_test() {
let project = Project::empty("mutants-no-source");
project.write(
"package.json",
r#"{ "name": "sourceless", "private": true, "type": "module", "scripts": { "test": "node --test" } }"#,
);
project.write(
"test/math.test.js",
"import test from \"node:test\";\nimport assert from \"node:assert/strict\";\ntest(\"adds\", () => assert.equal(1 + 1, 2));\n",
);
project.write("src/later.js", "// Nothing here yet.\n");
project.write(".gitignore", ".supercov\n");
project.git(&["init", "-q"]);
project.commit("tests alone");
let run = project.measure(&[]);
let none = project
.supercov(&["runs", "latest", "mutants", "test", "--plan"])
.exits(1);
assert!(
none.contains(&format!(
"run {run} listed no mutants and measured no source to list them from"
)),
"{none}"
);
// Measured with the mutants' probes, the run lists its mutants: none,
// and no score.
let measured = project.supercov(&["mutants"]);
assert!(
measured.stderr().contains(
"measuring first (the latest run recorded no values for its mutants): node --test"
),
"{}",
measured.stderr()
);
contains_all(
&measured.succeeds(),
&["mutation score -\n", " ran 0 mutant(s) in "],
);
let plan = project
.supercov(&["runs", "latest", "mutants", "test", "--plan", "--json"])
.json();
assert_eq!(plan["summary"]["mutants"], 0, "{plan}");
// The report shows no mutants for it.
project
.supercov(&["report", "--no-open", "--output", "report.html"])
.succeeds();
let report = report_data(&project.read("report.html"));
assert!(report["runs"][0]["mutants"].is_null(), "{report}");
}
/// The mutants commands started in a directory deleted under the shell
/// have no project to work in, and say so.
#[cfg(target_os = "linux")]
#[test]
fn the_mutants_commands_in_a_removed_directory_say_so() {
let parent = std::env::temp_dir().join(format!("supercov-mutants-gone-{}", std::process::id()));
std::fs::create_dir_all(&parent).unwrap();
for (arguments, code, said) in [
(&["mutants"][..], 2, "[supercov] "),
(&["runs", "latest", "mutants", "test"], 1, "[supercov] "),
(
&["runs", "latest", "mutants", "--format", "jsonl"],
2,
"could not resolve the current directory",
),
(
&["runs", "latest", "mutants", "--stryker", "mutation.json"],
2,
"Could not resolve the current directory",
),
] {
let gone = parent.join("gone");
std::fs::create_dir_all(&gone).unwrap();
let output = std::process::Command::new("sh")
.arg("-c")
.arg(r#"cd "$1" && rmdir "$1" && shift && exec "$@""#)
.arg("sh")
.arg(&gone)
.arg(env!("CARGO_BIN_EXE_supercov"))
.args(arguments)
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(code), "{arguments:?}: {stderr}");
assert!(stderr.contains(said), "{arguments:?}: {stderr}");
assert!(
stderr.contains("No such file or directory"),
"{arguments:?}: {stderr}"
);
}
std::fs::remove_dir_all(parent).unwrap();
}
/// A mocha project kept below the top of its repository, its tests run
/// with uncommitted changes on top of a `base` branch: mutants at a clock
/// boundary, a change too long to show whole, a source with no mutants, a
/// source no test loads, and a file of thirty guards nothing calls.
#[cfg(unix)]
fn mutant_views_project(label: &str) -> (Project, Project) {
let repository = Project::empty(label);
let project = Project {
root: repository.root.join("app"),
};
project.write(
"package.json",
r#"{ "name": "views", "type": "module", "scripts": { "test": "mocha" } }"#,
);
let modules = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
std::os::unix::fs::symlink(
modules.canonicalize().unwrap(),
project.root.join("node_modules"),
)
.unwrap();
repository.write(".gitignore", "node_modules\n.supercov\n");
project.write(
"src/cart.js",
"export function shipping(sum) {\n if (sum >= 50) {\n return 0;\n }\n return 5;\n}\n\nexport function label(name) {\n return name.trim().toUpperCase();\n}\n\nexport function refund(sum) {\n return sum > 100 ? sum * 0.9 : sum;\n}\n",
);
project.write(
"src/clock.js",
"export function expired(deadline) {\n return Date.now() > deadline;\n}\n\nexport function fresh(at) {\n return Date.now() - at < 1000;\n}\n\nexport function shout(name) {\n return `HEY ${name}`;\n}\n",
);
project.write(
"src/greet.js",
"export function greet(name) {\n return \"Hello there, \" + name + \", and welcome back to the little store we have built for all of you\";\n}\n\nexport function full(order) {\n return order.items.length + order.extras.length >= order.limit;\n}\n",
);
project.write("src/consts.js", "export const FREE_FROM = 50;\n");
let mut guards = String::from("export function band(n) {\n");
for bound in 0..30 {
guards.push_str(&format!(" if (n > {bound}) return {bound};\n"));
}
guards.push_str(" return -1;\n}\n");
project.write("src/unused.js", &guards);
project.write(
"test/cart.test.js",
"import assert from \"node:assert/strict\";\nimport { shipping, label } from \"../src/cart.js\";\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", () => assert.equal(shipping(80), 0));\n it(\"charges small orders\", () => assert.equal(shipping(10), 5));\n it(\"labels\", () => assert.equal(label(\" a \"), \"A\"));\n});\n",
);
project.write(
"test/more.test.js",
"import assert from \"node:assert/strict\";\nimport { expired } from \"../src/clock.js\";\nimport { greet } from \"../src/greet.js\";\nimport { FREE_FROM } from \"../src/consts.js\";\ndescribe(\"more\", () => {\n it(\"expires\", () => assert.equal(expired(0), true));\n it(\"greets\", () => assert.ok(greet(\"Ann\").startsWith(\"Hello\")));\n it(\"frees from fifty\", () => assert.equal(FREE_FROM, 50));\n});\n",
);
repository.git(&["init", "-q"]);
repository.commit("views");
repository.git(&["branch", "base"]);
// Uncommitted: dearer small orders, and a smaller refund.
project.edit("src/cart.js", "return 5;", "return 6;");
project.edit("src/cart.js", "sum * 0.9", "sum * 0.8");
project.edit("test/cart.test.js", "shipping(10), 5", "shipping(10), 6");
(repository, project)
}
/// Every view of a run's mutants as a reader sees it: the summary's count
/// of mutants at a clock boundary; the table of files, with the one no
/// test ran, a filter's label and its pages; a file's and a line's
/// mutants, cut where too long, with their boundary, StrykerJS's status
/// and the gate; a change's (the run's working tree) with its pages; and
/// a source with no mutants, which notes so.
#[cfg(unix)]
#[test]
fn every_mutants_view_shows_what_the_run_says_of_them() {
let (_repository, project) = mutant_views_project("mutant-views");
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let view = |arguments: &[&str]| {
let mut command = vec!["runs", "latest", "mutants"];
command.extend(arguments);
project.supercov(&command).succeeds()
};
contains_all(
&project.supercov(&["runs", "latest"]).succeeds(),
&["(1 at a clock or random boundary)"],
);
// Read against the working tree while git sees no new file: only the
// changed lines count.
assert!(
view(&["src/clock.js", "--diff", "base"])
.contains("No mutant is on a line this change added or changed.")
);
// A report whose run's mutants cannot be read from its index says so.
let unread = project.supercov_with(
&["report", "--no-open", "--output", "report.html"],
&[(
"SUPERCOV_TEST_FAULT",
"coverage-index-read#mutants_query.rs:717",
)],
);
let said = format!("{}{}", unread.stdout(), unread.stderr());
assert_ne!(unread.code(), 0, "{said}");
assert!(said.contains("could not read mutants for run "), "{said}");
assert!(fired_at(&said, "mutants_query.rs:717"), "{said}");
// The table of files.
contains_all(
&view(&[]),
&[
"1 file no test ran, with ",
" is listed last",
"list the mutants no test infects: ",
],
);
assert!(view(&["--limit", "1"]).contains("next page: "));
let past = view(&["--offset", "100"]);
assert!(!past.contains("inspect a file: "), "{past}");
// One test's view: what it does not infect, none; what it never ran.
let labels = view(&["--title", "labels"]);
contains_all(
&labels,
&[
"title containing \"labels\"",
" files no test ran, with ",
" are listed last",
],
);
assert!(
!labels.contains("list the mutants no test infects"),
"{labels}"
);
// A file's mutants: the clock boundary named where no test infected
// the mutant, not where none reached it.
let clock = view(&["src/clock.js"]);
assert!(clock.contains("(clock boundary)"), "{clock}");
assert!(
clock
.lines()
.filter(|line| line.starts_with("6:"))
.all(|line| !line.contains("boundary")),
"{clock}"
);
assert!(
view(&["src/clock.js:2"]).contains(" untestable in practice: "),
"clock line"
);
let greet = view(&["src/greet.js"]);
assert!(greet.contains('…'), "{greet}");
let full = view(&["src/greet.js:6"]);
assert!(full.contains("\n in: order.items.length"), "{full}");
assert!(view(&["src/cart.js", "--limit", "2"]).contains("next page: "));
assert!(view(&["src/cart.js", "--status", "equivalent"]).contains("No mutants match."));
// Only infected mutants: none left alive to explain line by line.
let infected = view(&["src/cart.js", "--status", "infected"]);
assert!(
!infected.contains("one line's mutants and why"),
"{infected}"
);
let beyond = view(&["src/cart.js", "--offset", "100"]);
assert!(!beyond.contains("No mutants match."), "{beyond}");
assert!(
view(&["src/cart.js", "--mutator", "EqualityOperator"])
.contains("--mutator 'EqualityOperator'"),
"mutator"
);
let gate = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/cart.js",
"--fail-on",
"not-infected",
])
.exits(1);
assert!(
gate.contains("FAILED --fail-on not-infected: 1 mutant (exit 1)"),
"{gate}"
);
// A source with no mutants says so, with StrykerJS's block or alone.
let consts = view(&["src/consts.js"]);
assert!(
consts.contains("src/consts.js has no mutants in this run."),
"{consts}"
);
assert!(!consts.contains("StrykerJS"), "{consts}");
// StrykerJS's report: a survivor it agrees on, no violation.
let source = project.read("src/cart.js");
let report = |file: &str| {
serde_json::json!({
"schemaVersion": "1",
"thresholds": {"high": 80, "low": 60},
"files": {file: {"language": "javascript", "source": source, "mutants": [{
"id": "1",
"mutatorName": "ConditionalExpression",
"replacement": "true",
"location": {"start": {"line": 13, "column": 10}, "end": {"line": 13, "column": 19}},
"status": "Survived",
}]}},
})
.to_string()
};
project.write("reports/clean.json", &report("src/cart.js"));
project.write("reports/nested/clean.json", &report("../../src/cart.js"));
for number in 0..4 {
project.write(
&format!("reports/many/r{number}.json"),
&report("src/cart.js"),
);
}
let joined = view(&["src/cart.js", "--stryker", "reports/clean.json"]);
contains_all(
&joined,
&[
" stryker: Survived",
" Soundness violations 0",
" Only in StrykerJS 0\n",
],
);
let rooted = view(&[
"src/cart.js",
"--stryker",
"reports/nested/clean.json",
"--stryker-root",
"reports/nested",
"--limit",
"1",
]);
assert!(
rooted.contains("--stryker-root 'reports/nested'"),
"{rooted}"
);
// Four reports on a line's view: no command shown stands for them.
let many = view(&[
"src/cart.js:13",
"--stryker",
"reports/many/r0.json",
"reports/many/r1.json",
"reports/many/r2.json",
"reports/many/r3.json",
]);
assert!(many.contains("StrykerJS (4 reports)"), "{many}");
assert!(!many.contains("in these commands"), "{many}");
// A directory after a report is read with it.
let both = view(&[
"src/cart.js:13",
"--stryker",
"reports/clean.json",
"reports/many",
]);
assert!(
both.contains("StrykerJS (5 reports in reports/clean.json, reports/many)"),
"{both}"
);
let consts = view(&["src/consts.js", "--stryker", "reports/clean.json"]);
contains_all(
&consts,
&[
"src/consts.js has no mutants in this run.",
"StrykerJS (reports/clean.json)",
],
);
// More violations than are listed one by one.
let unused = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/unused.js",
"--json",
"--limit",
"0",
])
.json();
let killed = unused["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.filter(|mutant| mutant["mutator"] == "ConditionalExpression")
.map(|mutant| {
let id = mutant["id"].as_str().unwrap();
let parts = id.split(':').collect::<Vec<_>>();
let (start_column, end_line) = parts[2].split_once('-').unwrap();
serde_json::json!({
"id": id,
"mutatorName": "ConditionalExpression",
"replacement": parts[5],
"location": {
"start": {"line": parts[1].parse::<u32>().unwrap(), "column": start_column.parse::<u32>().unwrap()},
"end": {"line": end_line.parse::<u32>().unwrap(), "column": parts[3].parse::<u32>().unwrap()},
},
"status": "Killed",
})
})
.collect::<Vec<_>>();
assert_eq!(killed.len(), 60, "{unused}");
project.write(
"reports/violations.json",
&serde_json::json!({
"schemaVersion": "1",
"thresholds": {"high": 80, "low": 60},
"files": {"src/unused.js": {"language": "javascript", "source": project.read("src/unused.js"), "mutants": killed}},
})
.to_string(),
);
let violated = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/unused.js",
"--stryker",
"reports/violations.json",
])
.exits(1);
contains_all(
&violated,
&[
"SOUNDNESS VIOLATIONS 60",
" … and 10 more (--json lists them by mutant",
],
);
// A change's mutants, read against the working tree the run measured.
let change = view(&["--diff", "base"]);
contains_all(
&change,
&[
"to the working tree: the run was measured with uncommitted changes, or records no commit",
"Not reached",
"src/cart.js:13:",
],
);
assert!(
view(&["--diff", "base", "--stryker", "reports/clean.json"])
.contains(" stryker: Survived")
);
assert!(view(&["--diff", "base", "--limit", "1"]).contains("next page: "));
assert!(view(&["--diff", "base", "--limit", "1", "--offset", "1"]).contains("showing 2-2 of "));
// The last page, from the second mutant on.
let rest = view(&["--diff", "base", "--offset", "1"]);
assert!(rest.contains("showing 2-"), "{rest}");
assert!(!rest.contains("next page: "), "{rest}");
assert!(
view(&["--diff", "base", "--status", "not-infected"])
.contains("No mutant on this change is left that way.")
);
assert!(
view(&["src/clock.js", "--diff", "base"])
.contains("No mutant is on a line this change added or changed.")
);
let every = view(&[
"--diff",
"base",
"--status",
"not-infected,not-reached,infected,unknown,equivalent",
]);
assert!(!every.contains("Not listed: "), "{every}");
// Each of git's asks failing in turn.
let mut said = std::collections::BTreeSet::new();
for nth in 1..=10 {
let ran = project.supercov_with(
&["runs", "latest", "mutants", "--diff", "base"],
&[("SUPERCOV_TEST_FAULT", &format!("git@{nth}"))],
);
if ran.code() == 0 {
continue;
}
let stderr = ran.stderr();
for message in [
"--diff needs git: could not run git",
"Could not find where this change left base",
"could not run git: injected fault at git",
] {
if stderr.contains(message) {
said.insert(message);
}
}
}
assert_eq!(said.len(), 3, "{said:?}");
}
/// A run's mutants written out: one JSON object per line, or a markdown
/// table for a pull request, to standard output or a file; mistakes and a
/// file or output that cannot be written are said, with exit 2.
#[cfg(unix)]
#[test]
fn mutants_export_as_lines_or_a_table_and_says_what_it_cannot_write() {
let (_repository, project) = mutant_views_project("mutants-export");
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let export = |arguments: &[&str]| {
let mut command = vec!["runs", "latest", "mutants"];
command.extend(arguments);
project.supercov(&command)
};
let bogus = export(&["--format", "jsonl", "--status", "bogus"]).exits(2);
assert!(bogus.contains("--status bogus is not a status"), "{bogus}");
let missing = export(&["src/nothing.js", "--format", "jsonl"]).exits(2);
assert!(missing.contains("src/nothing.js"), "{missing}");
// No mutants: no lines, and the note why.
let none = export(&[
"src/consts.js",
"--format",
"jsonl",
"--json",
"--limit",
"5",
"--offset",
"0",
]);
assert_eq!(none.succeeds(), "");
assert!(
none.stderr()
.contains("src/consts.js has no mutants in this run."),
"{}",
none.stderr()
);
let unwritten = export(&["--format", "jsonl", "--output", "missing/mutants.jsonl"]).exits(2);
assert!(unwritten.contains("missing/mutants.jsonl: "), "{unwritten}");
let written = export(&["--format", "markdown", "--output", "mutants.md"]);
assert!(
written
.stderr()
.contains("wrote the mutants' table to mutants.md"),
"{}",
written.stderr()
);
assert!(project.read("mutants.md").starts_with("### Mutants\n\n**"));
let reached = export(&[
"src/cart.js",
"--format",
"markdown",
"--status",
"not-reached",
])
.succeeds();
assert!(reached.contains(" | not reached | "), "{reached}");
assert!(!reached.contains(" | not infected | "), "{reached}");
let empty = export(&["src/consts.js", "--format", "markdown"]).succeeds();
contains_all(
&empty,
&[
"**0 mutants**: weak score **—**\n",
"No mutant is left alive: none is not infected or not reached.",
],
);
let clock = export(&["src/clock.js", "--format", "markdown"]).succeeds();
contains_all(&clock, &["not infected (clock boundary)", "HEY"]);
// A change with no mutant on its lines in the file asked about.
let unchanged = export(&["src/clock.js", "--diff", "base", "--format", "markdown"]).succeeds();
contains_all(
&unchanged,
&[
"### Mutants on this change",
"**0 mutants** on 0 of ",
"weak score **—**\n",
],
);
// StrykerJS joined with no violation: the export passes.
project.write(
"reports/empty.json",
r#"{"schemaVersion": "1", "thresholds": {"high": 80, "low": 60}, "files": {}}"#,
);
export(&[
"src/cart.js",
"--format",
"jsonl",
"--stryker",
"reports/empty.json",
])
.succeeds();
let one = export(&["src/greet.js:1", "--format", "markdown"]).succeeds();
assert!(one.contains("**1 mutant**"), "{one}");
// A standard output with no room left.
#[cfg(target_os = "linux")]
{
let full = std::fs::OpenOptions::new()
.write(true)
.open("/dev/full")
.unwrap();
let output = project
.supercov_command(&["runs", "latest", "mutants", "--format", "jsonl"])
.stdout(full)
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains("could not write the mutants to standard output"),
"{stderr}"
);
}
}
/// Every mutation report of one run, as its levels and languages grow: weak
/// mutation alone, then a change's mutants (`--diff`), then a second
/// language's mutants and a partial strong pass, in the HTML report's data,
/// the markdown table, StrykerJS's `mutation.json` and PIT's
/// `mutations.xml`.
#[cfg(unix)]
#[test]
fn mutation_reports_show_weak_strong_mixed_languages_and_a_change() {
let (repository, project) = mutant_views_project("mutation-reports");
let report = |name: &str, extra: &[&str]| {
let mut command = vec!["report", "--no-open", "--output", name];
command.extend(extra);
project.supercov(&command).succeeds();
report_data(&project.read(name))["runs"][0]["mutants"].clone()
};
let export = |arguments: &[&str]| {
let mut command = vec!["runs", "latest", "mutants"];
command.extend(arguments);
project.supercov(&command)
};
// A plain run: its mutants are listed the first time they are asked for.
project.supercov(&["--", "npx", "mocha"]).succeeds();
let run = project.latest();
export(&["--limit", "1"]).succeeds();
// Weak mutation alone: every mutant pending, the survivors those no test
// infects or reaches, one language.
let weak = report("weak.html", &[]);
assert_eq!(weak["strong"], false, "{weak}");
assert_eq!(
weak["languages"]
.as_object()
.unwrap()
.keys()
.collect::<Vec<_>>(),
["javascript"]
);
assert_eq!(weak["tally"]["mutants"], weak["summary"]["mutants"]);
assert!(weak.get("diff").is_none());
let alive = weak["mutants"]
.as_array()
.unwrap()
.iter()
.filter(|mutant| mutant["alive"] == true)
.count();
assert!(alive > 0);
assert_eq!(weak["tally"]["survivors"], alive);
assert!(
weak["mutants"]
.as_array()
.unwrap()
.iter()
.all(|mutant| mutant["outcome"] == "pending")
);
let stryker = export(&["--format", "stryker"]).succeeds();
let stryker: serde_json::Value = serde_json::from_str(&stryker).unwrap();
assert_eq!(stryker["schemaVersion"], "2");
assert_eq!(stryker["framework"]["name"], "Supercov");
assert_eq!(
stryker["files"]["src/cart.js"]["source"],
project.read("src/cart.js")
);
for mutant in stryker["files"]["src/cart.js"]["mutants"]
.as_array()
.unwrap()
{
assert!(
["NoCoverage", "Survived", "Pending", "Ignored"]
.contains(&mutant["status"].as_str().unwrap()),
"{mutant}"
);
}
// A change: only its lines' mutants, and what it was narrowed to.
let change = report("change.html", &["--diff", "base"]);
assert_eq!(change["diff"]["base"], "base", "{change}");
let lines = change["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| {
(
mutant["file"].as_str().unwrap().to_owned(),
mutant["line"].as_u64().unwrap()..=mutant["endLine"].as_u64().unwrap(),
)
})
.collect::<Vec<_>>();
assert!(!lines.is_empty(), "{change}");
for (file, span) in &lines {
assert_eq!(file, "src/cart.js");
assert!(span.contains(&5) || span.contains(&13), "{span:?}");
}
assert!(change["tally"]["mutants"].as_u64() < weak["tally"]["mutants"].as_u64());
let refused = project.supercov(&[
"report",
"--no-open",
"--output",
"x.html",
"--diff",
"nowhere",
]);
assert_ne!(refused.code(), 0);
let missing = project.supercov(&["report", "--diff"]);
assert_ne!(missing.code(), 0);
assert!(
missing.stderr().contains("--diff requires a base"),
"{}",
missing.stderr()
);
// A second language, listed beside the run, and a partial strong pass,
// saved the way `mutants test` saves one.
project.write("src/tax.py", "def tax(total):\n return total * 2\n");
let listed_path = format!(".supercov/runs/{run}/mutants-listed.json");
let mut listed: serde_json::Value = serde_json::from_str(&project.read(&listed_path)).unwrap();
listed["mutantSets"] =
serde_json::json!({"javascript": listed["mutantSet"], "python": "mutmut@3.8.1"});
listed["languages"] = serde_json::json!({"src/cart.js": "javascript", "src/tax.py": "python"});
listed["files"]["src/tax.py"] = serde_json::json!([{"mutator": "ArithmeticOperator",
"replacement": "total / 2", "start": [2, 12], "end": [2, 21], "original": "total * 2"}]);
project.write(&listed_path, &listed.to_string());
let ids = weak["mutants"]
.as_array()
.unwrap()
.iter()
.filter(|mutant| mutant["file"] == "src/cart.js")
.map(|mutant| mutant["id"].as_str().unwrap().to_owned())
.collect::<Vec<_>>();
let python = "src/tax.py:2:12-2:21:ArithmeticOperator:total / 2";
project.write(
&format!(".supercov/runs/{run}/strong-mutation.json"),
&serde_json::json!({"schemaVersion": 1, "run": run, "mutantSet": "stryker-js@10.1.1", "mutants": {
&ids[0]: {"status": "killed", "killedBy": "cart ships big orders free", "tests": 1, "durationMs": 5},
&ids[1]: {"status": "survived", "tests": 2, "durationMs": 9},
&ids[2]: {"status": "timeout", "tests": 1, "durationMs": 2000},
python: {"status": "error", "tests": 0, "durationMs": 0, "reason": "no strong mutation driver for python yet"},
}})
.to_string(),
);
let strong = report("strong.html", &[]);
assert_eq!(strong["strong"], true, "{strong}");
assert_eq!(
strong["languages"]
.as_object()
.unwrap()
.keys()
.collect::<Vec<_>>(),
["javascript", "python"]
);
assert_eq!(strong["tally"]["strong"]["killed"], 1);
assert_eq!(strong["tally"]["strong"]["survived"], 1);
assert_eq!(strong["tally"]["strong"]["timeout"], 1);
assert_eq!(strong["tally"]["strong"]["notRun"], 1);
assert!(strong["tally"]["strong"]["pending"].as_u64() > Some(0));
assert_eq!(strong["tally"]["mutationScore"], 0.6667);
assert_eq!(strong["languages"]["python"]["mutants"], 1);
let by_id = |id: &str| {
strong["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == id)
.unwrap()
.clone()
};
assert_eq!(by_id(&ids[0])["killedBy"], "cart ships big orders free");
assert_eq!(by_id(&ids[1])["alive"], true);
assert_eq!(by_id(python)["outcome"], "not-run");
assert_eq!(by_id(python)["why"], "not run: no driver for python yet");
// The static page shows the same mutation testing, and a change's.
let page = |extra: &[&str]| {
let mut command = vec!["runs", "latest", "report", "--format", "html", "--force"];
command.extend(extra);
project.supercov(&command).succeeds()
};
contains_all(
&page(&[]),
&[
"<h2>Mutation testing</h2>",
"javascript, python",
"Strong mutation: 66.7%",
"not run: no driver for python",
"data-key=\"mutants\"",
"<h3>Left alive: ",
],
);
let changed = page(&["--diff", "base"]);
assert!(
changed.contains("<strong>This change only:</strong>"),
"{changed}"
);
let unknown = project
.supercov(&[
"runs", "latest", "report", "--format", "html", "--diff", "nowhere",
])
.exits(2);
assert!(unknown.contains("nowhere"), "{unknown}");
// Mutants the run's index cannot give: the page is refused, and why said.
let unread = project
.supercov_with(
&["runs", "latest", "report", "--format", "html"],
&[("SUPERCOV_TEST_FAULT", "coverage-index@2")],
)
.exits(2);
assert!(unread.contains("could not read run "), "{unread}");
// A run whose index cannot be built again: refused the same way.
for entry in std::fs::read_dir(project.root.join(format!(".supercov/runs/{run}"))).unwrap() {
let path = entry.unwrap().path();
if path
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("query-index")
{
std::fs::remove_file(path).unwrap();
}
}
let unopened = project
.supercov_with(
&["runs", "latest", "report", "--format", "html"],
&[("SUPERCOV_TEST_FAULT", "fs.rename@1")],
)
.exits(2);
assert!(unopened.contains("could not open run "), "{unopened}");
let other = project
.supercov(&[
"runs", "latest", "report", "--format", "lcov", "--diff", "base",
])
.exits(2);
assert!(other.contains("give it with --format html"), "{other}");
let markdown = export(&["--format", "markdown"]).succeeds();
contains_all(
&markdown,
&[
"Mutation score **66.7%** (of 3 of ",
" mutants) · 1 killed · 1 timed out · 1 survived · 1 not run (no driver)",
"| Where | Mutant | Weak | Strong | Why |",
" | survived | every test that reached it passed with it in place (2 tests ran) |",
],
);
let stryker: serde_json::Value =
serde_json::from_str(&export(&["--format", "stryker"]).succeeds()).unwrap();
assert_eq!(stryker["files"]["src/tax.py"]["language"], "python");
let statuses = stryker["files"]["src/cart.js"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| mutant["status"].as_str().unwrap().to_owned())
.collect::<std::collections::BTreeSet<_>>();
for status in ["Killed", "Survived", "Timeout"] {
assert!(statuses.contains(status), "{statuses:?}");
}
let pit = export(&["--format", "pit", "--output", "mutations.xml"]);
assert!(
pit.stderr().contains("as a pit report to mutations.xml"),
"{}",
pit.stderr()
);
contains_all(
&project.read("mutations.xml"),
&[
"<mutations partial=\"false\">",
"status=\"KILLED\"",
"status=\"TIMED_OUT\"",
"<killingTest>cart ships big orders free</killingTest>",
"<sourceFile>tax.py</sourceFile><mutatedClass>src.tax</mutatedClass>",
],
);
// A file the checkout no longer holds: left out of StrykerJS's report,
// which needs every file's source, and said so.
std::fs::remove_file(project.root.join("src/tax.py")).unwrap();
let written = export(&["--format", "stryker", "--output", "mutation.json"]);
assert!(
written
.stderr()
.contains("src/tax.py could not be read: its mutants are left out of the report"),
"{}",
written.stderr()
);
let kept: serde_json::Value = serde_json::from_str(&project.read("mutation.json")).unwrap();
assert!(kept["files"].get("src/tax.py").is_none());
let bogus = export(&["--format", "bogus"]).exits(2);
assert!(bogus.contains("jsonl, markdown, stryker or pit"), "{bogus}");
// A file with no mutants: a report with no file.
let empty: serde_json::Value =
serde_json::from_str(&export(&["src/consts.js", "--format", "stryker"]).succeeds())
.unwrap();
assert_eq!(empty["files"], serde_json::json!({}));
// Piped, the static HTML export is printed, as every format is.
assert!(
project
.supercov(&["runs", "latest", "report", "--format", "html"])
.succeeds()
.starts_with("<!doctype html>")
);
// The static HTML export is not printed into a terminal: it is written
// beside the store's reports, again each time, and the path said.
for _ in 0..2 {
let mut terminal =
common::OnTerminal::start(&project, &["runs", "latest", "report", "--format", "html"]);
terminal.wait_for("coverage-report.html (html)");
let (code, seen) = terminal.finish();
assert_eq!(code, 0, "{seen}");
assert!(!seen.contains("<!doctype"), "{seen}");
}
assert!(
project
.read(".supercov/reports/coverage-report.html")
.starts_with("<!doctype html>")
);
// A change with no mutant on its lines still says what it was narrowed to.
repository.commit("everything");
let unchanged = report("unchanged.html", &["--diff", "HEAD"]);
assert_eq!(unchanged["tally"]["mutants"], 0, "{unchanged}");
assert_eq!(unchanged["diff"]["base"], "HEAD", "{unchanged}");
}
/// `--stryker` and the other mutants options each name what they need, and
/// a report or directory of reports that cannot be read is said to be so.
#[cfg(unix)]
#[test]
fn mutants_options_and_stryker_reports_that_cannot_be_read_are_refused() {
let (_repository, project) = mutant_views_project("mutants-stryker-refusals");
project.supercov(&["--", "npx", "mocha"]).succeeds();
// A source changed since a run whose mutants were never listed: its
// mutants are not listed, and that is said.
project.edit("src/greet.js", "Hello there", "Hi there");
let changed = project.supercov(&["runs", "latest", "mutants"]);
let said = format!("{}{}", changed.succeeds(), changed.stderr());
assert!(said.contains("1 file(s) changed since run"), "{said}");
for (flag, said) in [
("--status", "--status requires statuses"),
("--mutator", "--mutator requires a StrykerJS mutator"),
(
"--stryker",
"--stryker requires a StrykerJS mutation.json report",
),
("--diff", "--diff requires a git ref"),
("--fail-on", "--fail-on requires statuses"),
("--stryker-root", "--stryker-root requires a directory"),
] {
let refused = project
.supercov(&["runs", "latest", "mutants", flag])
.exits(2);
assert!(refused.contains(said), "{flag}: {refused}");
}
// No status named: every mutant, as with no --status.
project
.supercov(&["runs", "latest", "mutants", "--status", ","])
.succeeds();
std::fs::create_dir_all(project.root.join("reports/void/deeper")).unwrap();
let void = project
.supercov(&["runs", "latest", "mutants", "--stryker", "reports/void"])
.exits(2);
assert!(
void.contains("reports/void holds no .json report"),
"{void}"
);
project.write("reports/broken.json", "not json");
let broken = project
.supercov(&[
"runs",
"latest",
"mutants",
"--stryker",
"reports/broken.json",
])
.exits(2);
assert!(
broken.contains("Could not read reports/broken.json as a StrykerJS report"),
"{broken}"
);
for fault in [
"fs.read_dir#public_query.rs:962",
"fs.read_dir entry#public_query.rs:962",
] {
let unlisted = project
.supercov_with(
&["runs", "latest", "mutants", "--stryker", "reports"],
&[("SUPERCOV_TEST_FAULT", fault)],
)
.exits(2);
assert!(
unlisted.contains("Could not read reports: "),
"{fault}: {unlisted}"
);
assert!(
fired_at(&unlisted, "public_query.rs:962"),
"{fault}: {unlisted}"
);
}
// A report that is not UTF-8, and a directory's `.json.gz` file read as
// the mutant gem's session results, which these bytes are not.
std::fs::write(project.root.join("reports/bytes.json"), [0xff, 0xfe]).unwrap();
let bytes = project
.supercov(&[
"runs",
"latest",
"mutants",
"--stryker",
"reports/bytes.json",
])
.exits(2);
assert!(
bytes.contains("Could not read reports/bytes.json: "),
"{bytes}"
);
std::fs::create_dir_all(project.root.join("reports/ruby")).unwrap();
std::fs::write(
project.root.join("reports/ruby/session.json.gz"),
[0x1f, 0x8b, 0],
)
.unwrap();
let session = project
.supercov(&["runs", "latest", "mutants", "--stryker", "reports/ruby"])
.exits(2);
assert!(
session.contains("Could not read reports/ruby/session.json.gz as mutant's session results"),
"{session}"
);
}
/// A Ruby method's mutants are the mutant gem's, listed from a plain run,
/// and the strong pass runs them in forks of the loaded Minitest suite: a
/// boundary the test checks is killed, a literal it cannot tell from 0
/// survives, and a method no test calls is no coverage.
#[cfg(unix)]
/// A Ruby process a test starts with `--disable-gems` (test-unit's
/// `assert_separately`) loads Supercov's runtime through RUBYOPT without
/// RubyGems, which loaded `rbconfig` for it: the runtime disabled itself
/// and said so on the child's error output, which such tests read.
#[test]
fn ruby_children_without_rubygems_keep_their_error_output_clean() {
let Some(ruby) = ruby() else {
return;
};
let project = Project::empty("ruby-disable-gems");
project.write("lib/noop.rb", "def noop\n 1\nend\n");
project.write(
"test/child_test.rb",
"require 'minitest/autorun'\nrequire 'open3'\nrequire 'noop'\n\nclass ChildTest < Minitest::Test\n def test_child\n noop\n out, err, = Open3.capture3(RbConfig.ruby, '--disable-gems', '-e', 'print 1')\n assert_equal ['1', ''], [out, err]\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov(&["--", ruby.as_str(), "-Ilib", "test/child_test.rb"])
.succeeds();
}
/// A Ruby run measured for mutants records, per test, whether each mutant
/// a value probe computes would have given the original's value: a call's
/// other method, its receiver alone, a condition's truth.
#[cfg(unix)]
#[test]
fn ruby_value_probes_tell_which_mutants_no_test_infects() {
let Some(ruby) = ruby() else {
return;
};
let project = Project::empty("ruby-values");
project.write(
"lib/label.rb",
"class Label\n def tidy(s)\n s.strip\n end\n\n def pick(flag)\n flag ? :on : :off\n end\n\n def small?(n)\n n < 10\n end\nend\n",
);
project.write(
"test/label_test.rb",
"require 'minitest/autorun'\nrequire 'label'\n\nclass LabelTest < Minitest::Test\n def test_tidy\n assert_equal 'a', Label.new.tidy('a')\n end\n\n def test_pick\n assert_equal :on, Label.new.pick(true)\n end\n\n def test_small\n assert Label.new.small?(3)\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov_with(
&["--", ruby.as_str(), "-Ilib", "test/label_test.rb"],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let status = |id: &str| {
listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == id)
.map(|mutant| mutant["status"].as_str().unwrap_or_default().to_owned())
.unwrap_or_else(|| format!("missing: {listed}"))
};
for (id, expected) in [
// `"a".lstrip` and `"a"` are `"a".strip`; `nil` is not.
("lib/label.rb:3:5-3:12:Send:s.lstrip", "not-infected"),
("lib/label.rb:3:5-3:12:Send:s", "not-infected"),
("lib/label.rb:3:5-3:12:Send:nil", "infected"),
// The flag was only ever true.
("lib/label.rb:7:5-7:9:NamedValue:true", "not-infected"),
("lib/label.rb:7:5-7:9:NamedValue:false", "infected"),
// `3 < 10` is true; `3 == 10`, `10` and `nil` are not.
("lib/label.rb:11:5-11:11:Send:n == 10", "infected"),
("lib/label.rb:11:5-11:11:Send:10", "infected"),
("lib/label.rb:11:5-11:11:Send:nil", "infected"),
] {
assert_eq!(status(id), expected, "{id}");
}
}
#[cfg(unix)]
#[test]
fn ruby_mutants_are_mutant_gems_and_the_strong_pass_runs_them_in_minitest() {
let Some(ruby) = ruby() else {
return;
};
let project = Project::empty("ruby-strong");
project.write(
"lib/calc.rb",
"class Calc\n def add(a, b)\n a + b\n end\n\n def big?(n)\n n > 10\n end\n\n def unused(x)\n x * 2\n end\nend\n",
);
project.write(
"test/calc_test.rb",
"require 'minitest/autorun'\nrequire 'calc'\n\nclass CalcTest < Minitest::Test\n def test_adds\n assert_equal 3, Calc.new.add(1, 2)\n end\n\n def test_big\n assert Calc.new.big?(20)\n refute Calc.new.big?(3)\n end\nend\n",
);
project.git(&["init", "-q"]);
project.commit("fixture");
project
.supercov(&["--", ruby.as_str(), "-Ilib", "test/calc_test.rb"])
.succeeds();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "500"])
.json();
assert_eq!(listed["data"]["mutantSet"], "mutant@0.17.1", "{listed}");
let ids = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.map(|mutant| mutant["id"].as_str().unwrap().to_owned())
.collect::<Vec<_>>();
for id in [
"lib/calc.rb:7:5-7:11:Send:n == 10",
"lib/calc.rb:7:9-7:11:Integer:0",
"lib/calc.rb:3:5-3:10:Send:a - b",
"lib/calc.rb:11:5-11:10:Send:x / 2",
] {
assert!(ids.iter().any(|each| each == id), "{id} in {ids:?}");
}
let ran = project.supercov(&["runs", "latest", "mutants", "test", "--json"]);
let said = ran.stderr();
let reply = ran.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}\n{said}");
let strong = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "500"])
.json();
let status = |id: &str| {
strong["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == id)
.map(|mutant| {
mutant["strong"]["status"]
.as_str()
.unwrap_or_default()
.to_owned()
})
.unwrap_or_default()
};
assert_eq!(
status("lib/calc.rb:7:5-7:11:Send:n == 10"),
"killed",
"{strong}\n{said}"
);
assert_eq!(
status("lib/calc.rb:3:5-3:10:Send:a - b"),
"killed",
"{strong}"
);
assert_eq!(
status("lib/calc.rb:7:9-7:11:Integer:11"),
"survived",
"{strong}"
);
assert_eq!(
status("lib/calc.rb:11:5-11:10:Send:x / 2"),
"no-coverage",
"{strong}"
);
}
/// Go's strong pass: every Gremlins mutant of a module, run in test
/// binaries built once, each mutant against the tests that ran its code.
/// A mutant that does not compile is `unviable`; a constant Go needs as a
/// constant is built alone; a loop made endless is a `timeout`; code no
/// test runs is `no-coverage`.
#[cfg(unix)]
#[test]
fn go_mutants_are_killed_kept_or_found_not_to_compile() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-strong");
// A module older than Go 1.21: each file with a value probe is built
// as 1.21.
project.write("go.mod", "module example.com/calc\n\ngo 1.20\n");
project.write(
"calc.go",
"package calc\n\nconst Limit = 2 + 3\n\nfunc Clamp(n int) int {\n\tif n > Limit {\n\t\treturn Limit\n\t}\n\treturn n\n}\n\nfunc Sum(n int) int {\n\ttotal := 0\n\tfor i := 0; i < n; i++ {\n\t\ttotal += i\n\t}\n\treturn total\n}\n\nfunc Join(a, b string) string { return a + b }\n\nfunc Half(n int) int { return n / 2 }\n\nfunc Unused(n int) int { return n - 1 }\n",
);
project.write(
"calc_test.go",
"package calc\n\nimport \"testing\"\n\nfunc TestClamp(t *testing.T) {\n\tif Clamp(5) != 5 || Clamp(6) != 5 || Clamp(1) != 1 {\n\t\tt.Fatal(\"clamp\")\n\t}\n}\n\nfunc TestSum(t *testing.T) {\n\tif Sum(4) != 6 {\n\t\tt.Fatal(\"sum\")\n\t}\n}\n\nfunc TestJoinAndHalf(t *testing.T) {\n\tif Join(\"a\", \"b\") != \"ab\" || Half(0) != 0 {\n\t\tt.Fatal(\"join\")\n\t}\n}\n",
);
project
.supercov_with(
&["mutants", "--json", "--", go, "test", "./..."],
&[("SUPERCOV_MUTANT_HIT_LIMIT", "100000")],
)
.succeeds();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let status = |id: &str| {
listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == id)
.unwrap_or_else(|| panic!("no {id} in {listed}"))["strong"]["status"]
.clone()
};
assert_eq!(listed["data"]["mutantSet"], "gremlins@0.6.0", "{listed}");
// Built alone: a constant declaration has no place for a switch.
assert_eq!(status("calc.go:3:17-3:18:ArithmeticOperator:-"), "killed");
// At 5, `n > 5` and `n >= 5` both return 5: no test can tell them.
assert_eq!(status("calc.go:6:7-6:8:EqualityOperator:>="), "survived");
assert_eq!(status("calc.go:6:7-6:8:EqualityOperator:<="), "killed");
// `i--` never ends the loop.
assert_eq!(status("calc.go:14:22-14:24:UpdateOperator:--"), "timeout");
// Strings have no `-`.
assert_eq!(
status("calc.go:20:42-20:43:ArithmeticOperator:-"),
"unviable"
);
// `0 * 2` is `0 / 2`: no test tells them apart.
assert_eq!(
status("calc.go:22:33-22:34:ArithmeticOperator:*"),
"survived"
);
assert_eq!(
status("calc.go:24:35-24:36:ArithmeticOperator:+"),
"no-coverage"
);
}
/// A Go suite behind `make test`: the strong pass builds its test binaries
/// with the flags the Makefile gives `go test`, as the measured run recorded
/// them. Without the tag, the file behind it would not be built at all, and
/// its mutant could not be killed.
#[cfg(unix)]
#[test]
fn go_mutants_of_a_wrapped_command_are_built_with_its_flags() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-strong-make");
project.write("go.mod", "module example.com/tagged\n\ngo 1.22\n");
project.write(
"double.go",
"//go:build tagged\n\npackage tagged\n\nfunc Double(n int) int { return n * 2 }\n",
);
project.write(
"double_test.go",
"//go:build tagged\n\npackage tagged\n\nimport \"testing\"\n\nfunc TestDouble(t *testing.T) {\n\tif Double(3) != 6 {\n\t\tt.Fatal(\"double\")\n\t}\n}\n",
);
let directory = std::path::Path::new(go)
.parent()
.map(|dir| dir.display().to_string())
.unwrap_or_default();
project.write(
"Makefile",
&format!("test:\n\tPATH=\"$$PATH:{directory}\" go test -tags tagged ./...\n"),
);
project
.supercov(&["mutants", "--json", "--", "make", "test"])
.succeeds();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let mutant = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == "double.go:5:35-5:36:ArithmeticOperator:/")
.unwrap_or_else(|| panic!("{listed}"))
.clone();
assert_eq!(mutant["strong"]["status"], "killed", "{mutant}");
}
/// Ctrl-C during a JavaScript strong pass, sent to Supercov's process group
/// as a terminal sends it: the resident runners and what their jobs started
/// stop, though each runs in a process group of its own, Supercov exits as
/// the signal does, and what the pass decided is saved.
#[cfg(unix)]
#[test]
fn an_interrupted_javascript_pass_leaves_no_process_running() {
use std::os::unix::process::CommandExt;
let project = mutants_project("js-strong-interrupted");
// A function only this test runs: under a mutant (its value is not 4),
// the test starts a process and waits, its pid and the runner's to the
// marker.
project.write("src/twice.js", "export const twice = (n) => n * 2;\n");
project.write(
"test/slow.test.js",
"import assert from \"node:assert/strict\";\nimport { spawn } from \"node:child_process\";\nimport { renameSync, writeFileSync } from \"node:fs\";\nimport { twice } from \"../src/twice.js\";\ndescribe(\"slow\", () => {\n it(\"waits under a mutant\", async function () {\n this.timeout(0);\n if (twice(2) === 4) return;\n const sleeper = spawn(\"sleep\", [\"120\"], { stdio: \"ignore\" });\n const marker = process.env.SUPERCOV_TEST_MARKER;\n writeFileSync(`${marker}.tmp`, `${process.pid} ${sleeper.pid}`);\n renameSync(`${marker}.tmp`, marker);\n await new Promise((done) => setTimeout(done, 120000));\n });\n});\n",
);
project.commit("slow");
project
.supercov_with(&["--", "npx", "mocha"], &[("SUPERCOV_MUTANTS", "1")])
.succeeds();
let run = project.latest();
let marker = project.root.with_extension("marker");
let _ = std::fs::remove_file(&marker);
let mut supercov = project
.supercov_command(&["runs", "latest", "mutants", "test"])
.env("SUPERCOV_TEST_MARKER", &marker)
.process_group(0)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let started = std::time::Instant::now();
while !marker.exists() {
assert!(
started.elapsed() < std::time::Duration::from_secs(120),
"the strong pass never started its tests"
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
let pids = std::fs::read_to_string(&marker)
.unwrap()
.split_whitespace()
.map(|pid| pid.parse::<i32>().unwrap())
.collect::<Vec<_>>();
// SAFETY: a signal to the process group this test started.
unsafe { libc::kill(-(supercov.id() as i32), libc::SIGINT) };
let status = supercov.wait().unwrap();
let running = |pid: i32| {
// SAFETY: signal 0 only asks whether the process is there.
unsafe { libc::kill(pid, 0) == 0 }
};
let gone = (0..50).any(|_| {
std::thread::sleep(std::time::Duration::from_millis(100));
!pids.iter().any(|pid| running(*pid))
});
let _ = std::fs::remove_file(&marker);
for pid in &pids {
if running(*pid) {
// SAFETY: cleaning up a process this test's run left.
unsafe { libc::kill(*pid, libc::SIGKILL) };
}
}
assert!(gone, "{pids:?} outlived the interrupted pass");
assert_eq!(status.code(), Some(130), "{status:?}");
assert!(
project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json"))
.is_file()
);
}
/// A Vitest project for passes cut short: `src/cart.js`'s mutants are
/// decided at once, while each of `src/slow.js`'s holds its test for five
/// minutes, past its limit, the test's process id written to
/// `SUPERCOV_TEST_MARKER` first.
#[cfg(unix)]
fn vitest_slow_project(label: &str) -> Project {
vitest_slow_project_waiting(label, 0)
}
/// `vitest_slow_project`, its slow test also taking `unmutated_ms` without
/// a mutant: a mutant's test is given three times its measured time and
/// 10 s more, so the longer it takes, the later slow.js's mutants are
/// judged timeouts.
#[cfg(unix)]
fn vitest_slow_project_waiting(label: &str, unmutated_ms: u64) -> Project {
let project = vitest_mutants_project(label);
project.write("src/slow.js", "export const twice = (n) => n * 2;\n");
let unmutated = if unmutated_ms > 0 {
format!(
" else {{\n await new Promise((done) => setTimeout(done, {unmutated_ms}));\n }}"
)
} else {
String::new()
};
project.write(
"test/slow.test.js",
&format!(
"import {{ renameSync, writeFileSync }} from \"node:fs\";\nimport {{ expect, it }} from \"vitest\";\nimport {{ twice }} from \"../src/slow.js\";\nit(\"doubles\", async () => {{\n if (twice(2) !== 4) {{\n const marker = process.env.SUPERCOV_TEST_MARKER;\n if (marker) {{\n writeFileSync(`${{marker}}.tmp`, String(process.pid));\n renameSync(`${{marker}}.tmp`, marker);\n }}\n await new Promise((done) => setTimeout(done, 300000));\n }}{unmutated}\n expect(twice(2)).toBe(4);\n}}, 300000);\n"
),
);
project.commit("slow");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
project
}
/// The saved verdicts of `project`'s latest run, by mutant id.
#[cfg(unix)]
fn saved_statuses(project: &Project) -> std::collections::BTreeMap<String, String> {
let run = project.latest();
std::fs::read(
project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json")),
)
.ok()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
.and_then(|saved| saved["mutants"].as_object().cloned())
.unwrap_or_default()
.into_iter()
.map(|(id, verdict)| (id, verdict["status"].as_str().unwrap_or("").to_owned()))
.collect()
}
/// A Vitest pass sent a signal -- only Supercov, as `timeout` signals the
/// command it runs, the tests' processes being in a group of their own --
/// stops its workers and ends within seconds, as the signal ends it, with
/// the verdicts it reached saved. A pass that does not end once told to
/// (a test makes one linger) is ended `STOP_PATIENCE` (8 s) after the
/// signal, what it decided saved first.
#[cfg(unix)]
#[test]
fn a_vitest_pass_sent_a_signal_ends_in_seconds_with_what_it_decided_saved() {
let project = vitest_slow_project("strong-signalled");
let run = project.latest();
let marker = project.root.with_extension("marker");
let stop = |signal: i32, faults: &str| {
let _ = std::fs::remove_file(
project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json")),
);
let _ = std::fs::remove_file(&marker);
let mut supercov = project
.supercov_command(&["runs", "latest", "mutants", "test"])
.env("SUPERCOV_TEST_MARKER", &marker)
.env("SUPERCOV_TEST_FAULT", faults)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
// The slow copy is running, and cart.js's mutants are decided.
let started = std::time::Instant::now();
while !marker.exists()
|| saved_statuses(&project)
.values()
.all(|status| status != "killed")
{
assert!(
started.elapsed() < std::time::Duration::from_secs(120),
"the pass never got under way"
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
let test = std::fs::read_to_string(&marker)
.unwrap()
.trim()
.parse::<i32>()
.unwrap();
// SAFETY: a signal to the process this test started.
unsafe { libc::kill(supercov.id() as i32, signal) };
let told = std::time::Instant::now();
let mut said = String::new();
std::io::Read::read_to_string(supercov.stderr.as_mut().unwrap(), &mut said).unwrap();
let status = supercov.wait().unwrap();
let took = told.elapsed();
// SAFETY: signal 0 only asks whether the process is there.
let gone = (0..50).any(|_| {
std::thread::sleep(std::time::Duration::from_millis(100));
unsafe { libc::kill(test, 0) != 0 }
});
if !gone {
// SAFETY: cleaning up a process this test's pass left.
unsafe { libc::kill(test, libc::SIGKILL) };
}
assert!(gone, "the slow copy's worker outlived the pass\n{said}");
let killed = saved_statuses(&project)
.values()
.filter(|status| *status == "killed")
.count();
assert!(killed > 0, "{said}");
(status.code(), took, said)
};
let (code, took, said) = stop(libc::SIGTERM, "");
assert_eq!(code, Some(143), "{said}");
assert!(took < std::time::Duration::from_secs(8), "{took:?}\n{said}");
assert!(
said.contains(
"[supercov] interrupted: the verdicts the pass reached are saved into the run"
),
"{said}"
);
let (code, took, said) = stop(libc::SIGINT, "strong-pass-lingers");
assert_eq!(code, Some(130), "{said}");
assert!(
took >= std::time::Duration::from_secs(8) && took < std::time::Duration::from_secs(14),
"{took:?}\n{said}"
);
assert!(
said.contains("[supercov] the strong pass did not end within 8 s of being told to stop (sent SIGINT), so it is ended: the verdicts it reached are saved into the run"),
"{said}"
);
}
/// `--budget <seconds>`: once it is spent the pass stops and ends as one
/// that finished, the verdicts it reached saved, the mutants left without
/// one for the next pass -- not errors, and not a pass that ran nothing.
/// A pass that does not end once its budget is spent is ended in time. The
/// budget is the whole command's: what `supercov mutants` spent measuring
/// is not the pass's, and a budget measuring spent runs nothing.
#[cfg(unix)]
#[test]
fn a_budget_ends_the_pass_and_leaves_the_rest_for_the_next() {
// Ten seconds without a mutant: slow.js's mutants are judged timeouts
// 40 s into their copies, well past the budget below. Given 13 s, the
// limit of a test that takes no time, they were judged before a slow
// runner's budget was spent.
let project = vitest_slow_project_waiting("strong-budget", 10_000);
let slow_ids = || {
saved_statuses(&project)
.into_iter()
.filter(|(id, _)| id.starts_with("src/slow.js:"))
.collect::<Vec<_>>()
};
// Spent before any slow mutant could end.
let first = project.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/slow.js",
"--budget",
"1",
"--json",
]);
let reply = first.json();
assert_eq!(first.code(), 0, "{reply}\n{}", first.stderr());
let left = reply["budget"]["left"].as_u64().unwrap();
assert!(left > 0, "{reply}");
assert_eq!(reply["budget"]["seconds"], 1, "{reply}");
assert_eq!(reply["summary"]["error"], 0, "{reply}");
assert!(reply["result"].is_null(), "{reply}");
assert!(slow_ids().is_empty(), "{:?}", slow_ids());
// Long enough for cart.js's mutants, not for slow.js's, whose test waits
// five minutes and is judged a timeout 40 s in. What cart.js's take is
// this machine's: a fixed twelve seconds decided only some of them on a
// busy macOS runner. Timed by a pass of their own, whose verdicts are
// then forgotten.
let timed = project.supercov(&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/cart.js",
"--json",
]);
let reply = timed.json();
assert_eq!(timed.code(), 0, "{reply}\n{}", timed.stderr());
assert_eq!(reply["summary"]["error"], 0, "{reply}");
let cart_ms = reply["summary"]["durationMs"].as_u64().unwrap();
let run = project.latest();
std::fs::remove_file(
project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json")),
)
.unwrap();
// Three times that beside slow.js's copies, and short of their 40 s.
let budget = (cart_ms * 3 / 1000 + 10).min(30).to_string();
let second = project.supercov(&[
"runs", "latest", "mutants", "test", "--budget", &budget, "--json",
]);
let reply = second.json();
assert_eq!(second.code(), 0, "{reply}\n{}", second.stderr());
assert!(reply["summary"]["killed"].as_u64() > Some(0), "{reply}");
assert_eq!(reply["budget"]["left"].as_u64(), Some(left), "{reply}");
assert!(slow_ids().is_empty(), "{:?}", slow_ids());
// A pass that lingers once its budget is spent.
let lingering = project.supercov_with(
&["runs", "latest", "mutants", "test", "--budget", "1"],
&[("SUPERCOV_TEST_FAULT", "strong-pass-lingers")],
);
let said = lingering.stderr();
assert_eq!(lingering.code(), 143, "{said}");
assert!(
said.contains(
"did not end within 8 s of being told to stop (its budget spent), so it is ended"
),
"{said}"
);
// Measured first, as the latest run recorded no values for its
// mutants: measuring, which takes two seconds here, spends the budget,
// and the pass runs nothing.
let started = std::time::Instant::now();
let measured = project.supercov(&[
"mutants",
"--file",
"src/slow.js",
"--budget",
"1",
"--",
"sh",
"-c",
"sleep 2 && npx vitest run",
]);
let (out, said) = (measured.stdout(), measured.stderr());
assert_eq!(measured.code(), 0, "{out}\n{said}");
assert!(said.contains("measuring first"), "{said}");
assert!(
out.contains(" budget of 1 s spent: 2 mutant(s) left without a verdict")
&& out.contains(" s of the 1 s budget, which leaves the pass 0 s\n"),
"{out}"
);
// Ended once measuring did: no pass began.
assert!(
!said.contains("strong pass:") && started.elapsed() < std::time::Duration::from_secs(60),
"{said}"
);
}
/// Copies run within the project's own worker limit, each with a pool id
/// Vitest gave it (1 to `maxWorkers`) that no copy running beside it has: a
/// setup file that gives each worker its own database by `VITEST_POOL_ID`,
/// and throws where the id is past the databases it made or another
/// copy's still in use, lets every copy run, and every mutant gets a
/// verdict.
#[cfg(unix)]
#[test]
fn copies_keep_to_the_project_s_workers_and_their_pool_ids() {
let project = vitest_mutants_project("strong-pool-ids");
project.write(
"vitest.config.js",
"export default { test: { maxWorkers: 2, setupFiles: [\"./test/database.js\"] } };\n",
);
project.write(
"test/database.js",
"import { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { afterAll } from \"vitest\";\nconst worker = Number(process.env.VITEST_POOL_ID);\nif (!(worker >= 1 && worker <= 2)) throw new Error(`Worker ${worker} has no database: 2 were made`);\nconst locks = new URL(\"../.databases/\", import.meta.url);\nmkdirSync(locks, { recursive: true });\nconst lock = new URL(String(worker), locks);\nlet holder;\ntry { holder = Number(readFileSync(lock, \"utf8\")); } catch {}\nif (holder && holder !== process.pid) {\n let running = true;\n try { process.kill(holder, 0); } catch { running = false; }\n if (running) throw new Error(`Worker ${worker}'s database is in use by process ${holder}`);\n}\nwriteFileSync(lock, String(process.pid));\nafterAll(() => rmSync(lock, { force: true }));\n",
);
for file in ["a", "b", "c"] {
project.write(
&format!("test/{file}.test.js"),
"import { describe, expect, it } from \"vitest\";\nimport { shipping, label, refund } from \"../src/cart.js\";\nconst nap = () => new Promise((done) => setTimeout(done, 50));\ndescribe(\"cart\", () => {\n it(\"ships big orders free\", async () => { await nap(); expect(shipping(80)).toBe(0); });\n it(\"charges small orders\", async () => { await nap(); expect(shipping(10)).toBe(5); });\n it(\"labels\", async () => { await nap(); expect(label(\" a \")).toBe(\"A\"); });\n it(\"refunds\", async () => { await nap(); expect(refund(200)).toBe(180); });\n});\n",
);
}
project.write(".gitignore", "node_modules\n.supercov\n.databases\n");
project.commit("a database per worker");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let reply = project
.supercov(&["runs", "latest", "mutants", "test", "--json"])
.json();
assert_eq!(reply["summary"]["error"], 0, "{reply}");
assert!(reply["summary"]["killed"].as_u64() >= Some(5), "{reply}");
assert_eq!(
reply["passes"][0]["profile"]["unevaluatedReruns"], 0,
"{reply}"
);
}
/// A mutant that makes a hook fail (a `beforeAll` seeding through a schema
/// the mutant broke) is killed: Vitest skips the hook's tests and fails the
/// run, and the reason is the hook's error. A copy whose file does not load
/// or set up before its mutant ran runs again; where that repeats, the
/// mutant is an error that says the file's error. A copy that ran none of
/// its tests says why. The staged pass judges a hook alike.
#[cfg(unix)]
#[test]
fn a_hook_or_a_load_that_fails_says_its_error() {
let project = vitest_mutants_project("strong-hooks");
// One worker: the file's baseline copy, listed first, loads first, and
// the mutant's copies after it. With a worker per processor the two
// started side by side, and on an arm64 runner the mutant's copy loaded
// first some of the time: the load meant to fail was the baseline's.
project.write(
"vitest.config.js",
"export default { test: { maxWorkers: 1, setupFiles: [\"./test/setup.js\"] } };\n",
);
// Fails where `SETUP_FAILS_COUNTER` names a directory: the first load
// after the first, or (`always`) every load after the first. Each load
// takes the next number by creating its file, so that two loads can
// never both take the same one.
project.write(
"test/setup.js",
"import { closeSync, mkdirSync, openSync } from \"node:fs\";\nconst counter = process.env.SETUP_FAILS_COUNTER;\nif (counter) {\n mkdirSync(counter, { recursive: true });\n let count = 0;\n for (;; count++) {\n try { closeSync(openSync(`${counter}/${count}`, \"wx\")); break; } catch (error) { if (error.code !== \"EEXIST\") throw error; }\n }\n if (count === 1 || (count > 1 && process.env.SETUP_FAILS === \"always\")) throw new Error(\"the test database is gone\");\n}\n",
);
project.write(
"src/schema.js",
"export const users = { name: \"users\" };\n",
);
project.write(
"src/store.js",
"const tables = new Map([[\"users\", []]]);\nexport function insert(table, row) {\n const rows = tables.get(table.name);\n if (!rows) throw new Error(`relation \"${table.name}\" does not exist`);\n rows.push(row);\n return rows.length;\n}\n",
);
project.write(
"test/store.test.js",
"import { beforeAll, describe, expect, it } from \"vitest\";\nimport { users } from \"../src/schema.js\";\nimport { insert } from \"../src/store.js\";\ndescribe(\"store\", () => {\n beforeAll(() => {\n if (process.env.HOOK_FAILS) throw new Error(\"the seed did not load\");\n insert(users, { id: 1 });\n });\n it(\"inserts\", () => expect(insert(users, { id: 2 })).toBe(2));\n});\n",
);
project.commit("hooks");
project.supercov(&["--", "npx", "vitest", "run"]).succeeds();
let schema = "src/schema.js:1:30-1:37:StringLiteral:empty";
let counter = project.root.with_extension("counter");
let counter_path = counter.to_str().unwrap();
let pass = |env: &[(&str, &str)]| {
let _ = std::fs::remove_dir_all(&counter);
let run = project.latest();
let _ = std::fs::remove_file(
project
.root
.join(format!(".supercov/runs/{run}/strong-mutation.json")),
);
let reply = project
.supercov_with(
&[
"runs",
"latest",
"mutants",
"test",
"--file",
"src/schema.js",
"--json",
],
env,
)
.json();
let listed = project
.supercov(&[
"runs",
"latest",
"mutants",
"src/schema.js",
"--json",
"--limit",
"0",
])
.json();
let mutant = listed["data"]["mutants"]
.as_array()
.unwrap()
.iter()
.find(|mutant| mutant["id"] == schema)
.unwrap_or_else(|| panic!("{listed}"))
.clone();
(reply, mutant["strong"].clone())
};
for stages in ["", "1"] {
let (_, strong) = pass(&[("SUPERCOV_STRONG_STAGES", stages)]);
assert_eq!(strong["status"], "killed", "{strong}");
assert_eq!(
strong["reason"], "a hook failed: relation \"\" does not exist",
"{strong}"
);
assert_eq!(strong["killedBy"], "test/store.test.js", "{strong}");
}
// Fails once: the copy runs again, and the mutant is killed.
let (reply, strong) = pass(&[("SETUP_FAILS_COUNTER", counter_path)]);
assert_eq!(strong["status"], "killed", "{strong}");
assert!(
reply["passes"][0]["profile"]["unevaluatedReruns"].as_u64() >= Some(1),
"{reply}"
);
// Fails every time: an error with the file's own.
let (_, strong) = pass(&[
("SETUP_FAILS_COUNTER", counter_path),
("SETUP_FAILS", "always"),
]);
assert_eq!(strong["status"], "error", "{strong}");
assert_eq!(
strong["reason"],
"its copy of test/store.test.js did not load before the mutant ran, twice: the test database is gone",
"{strong}"
);
// The hook fails without the mutant too: the copy ran none of its tests,
// and says why.
let (_, strong) = pass(&[("HOOK_FAILS", "1")]);
assert_eq!(strong["status"], "error", "{strong}");
assert_eq!(
strong["reason"],
"its copy of test/store.test.js ran none of the tests it was to run: the seed did not load",
"{strong}"
);
}
/// A file the command builds only with a tag (`go test -tags tagged`) gets
/// value probes as any other: the type checker is asked with the tag.
#[test]
fn a_go_file_behind_a_build_tag_gets_value_probes() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-probes-tagged");
project.write("go.mod", "module example.com/tagged\n\ngo 1.22\n");
project.write(
"double.go",
"//go:build tagged\n\npackage tagged\n\nfunc Double(n int) int { return n * 2 }\n",
);
project.write(
"double_test.go",
"//go:build tagged\n\npackage tagged\n\nimport \"testing\"\n\nfunc TestDouble(t *testing.T) {\n\tif Double(3) != 6 {\n\t\tt.Fatal(\"double\")\n\t}\n}\n",
);
project
.supercov_with(
&["--", go, "test", "-tags", "tagged", "./..."],
&[("SUPERCOV_MUTANTS", "1")],
)
.succeeds();
let listed = project
.supercov(&["runs", "latest", "mutants", "--json", "--limit", "0"])
.json();
let mutant = &listed["data"]["mutants"][0];
assert_eq!(
mutant["id"], "double.go:5:35-5:36:ArithmeticOperator:/",
"{listed}"
);
// `3 * 2` and `3 / 2` differ, and the probe saw it.
assert_eq!(mutant["status"], "infected", "{listed}");
}
/// Ctrl-C during a Go strong pass, sent to Supercov's process group as a
/// terminal sends it, stops every test binary the pass started and what
/// they started, though each runs in a process group of its own.
#[cfg(unix)]
#[test]
fn an_interrupted_go_pass_leaves_no_process_running() {
use std::os::unix::process::CommandExt;
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-strong-interrupted");
project.write("go.mod", "module example.com/slow\n\ngo 1.22\n");
project.write(
"slow.go",
"package slow\n\nfunc Big(n int) bool { return n > 9 }\n",
);
// In the strong pass (its binaries are given an active mutant), the
// test starts a process and waits: its pid and its own go to the marker.
project.write(
"slow_test.go",
"package slow\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestBig(t *testing.T) {\n\tif !Big(10) {\n\t\tt.Fatal(\"big\")\n\t}\n\tif os.Getenv(\"SUPERCOV_ACTIVE_MUTANT\") == \"\" {\n\t\treturn\n\t}\n\tsleeper := exec.Command(\"sleep\", \"120\")\n\tif err := sleeper.Start(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmarker := os.Getenv(\"SUPERCOV_TEST_MARKER\")\n\tos.WriteFile(marker+\".tmp\", []byte(fmt.Sprintf(\"%d %d\", os.Getpid(), sleeper.Process.Pid)), 0o644)\n\tos.Rename(marker+\".tmp\", marker)\n\ttime.Sleep(120 * time.Second)\n}\n",
);
let marker = project.root.with_extension("marker");
let _ = std::fs::remove_file(&marker);
let mut supercov = project
.supercov_command(&["mutants", "--", go, "test", "./..."])
.env("SUPERCOV_TEST_MARKER", &marker)
.process_group(0)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let started = std::time::Instant::now();
while !marker.exists() {
assert!(
started.elapsed() < std::time::Duration::from_secs(240),
"the strong pass never started its tests"
);
std::thread::sleep(std::time::Duration::from_millis(100));
}
let pids = std::fs::read_to_string(&marker)
.unwrap()
.split_whitespace()
.map(|pid| pid.parse::<i32>().unwrap())
.collect::<Vec<_>>();
// SAFETY: a signal to the process group this test started.
unsafe { libc::kill(-(supercov.id() as i32), libc::SIGINT) };
supercov.wait().unwrap();
let running = |pid: i32| {
// SAFETY: signal 0 only asks whether the process is there.
unsafe { libc::kill(pid, 0) == 0 }
};
let gone = (0..50).any(|_| {
std::thread::sleep(std::time::Duration::from_millis(100));
!pids.iter().any(|pid| running(*pid))
});
let _ = std::fs::remove_file(&marker);
for pid in &pids {
if running(*pid) {
// SAFETY: cleaning up a process this test's run left.
unsafe { libc::kill(*pid, libc::SIGKILL) };
}
}
assert!(gone, "{pids:?} outlived the interrupted pass");
}
/// A mutant `go vet` rejects fails `go test` before any test runs, as one
/// that does not compile does: the strong pass calls it unviable, with
/// vet's finding.
#[cfg(unix)]
#[test]
fn a_go_mutant_vet_rejects_is_unviable() {
let Some(go) = go() else {
eprintln!("skipping: no Go toolchain found");
return;
};
let project = Project::empty("go-strong-vet");
project.write("go.mod", "module example.com/vet\n\ngo 1.22\n");
project.write(
"odd.go",
"package vet\n\nfunc Middle(x int) bool { return x != 1 && x != 2 }\n\nfunc Big(x int) bool { return x > 9 }\n",
);
project.write(
"odd_test.go",
"package vet\n\nimport \"testing\"\n\nfunc TestMiddle(t *testing.T) {\n\tif !Middle(3) || Middle(1) || !Big(10) {\n\t\tt.Fatal(\"middle\")\n\t}\n}\n",
);
let text = project
.supercov(&["mutants", "--", go, "test", "./..."])
.succeeds();
assert!(text.contains(" unviable 1\n"), "{text}");
let saved = std::fs::read_dir(project.root.join(".supercov/runs"))
.unwrap()
.filter_map(|entry| std::fs::read(entry.unwrap().path().join("strong-mutation.json")).ok())
.next()
.expect("verdicts saved");
let saved: serde_json::Value = serde_json::from_slice(&saved).unwrap();
let verdict = &saved["mutants"]["odd.go:3:41-3:43:LogicalOperator:||"];
assert_eq!(verdict["status"], "unviable", "{saved}");
assert!(
verdict["reason"]
.as_str()
.unwrap()
.ends_with("odd.go:3:34: suspect or: x != 1 || x != 2"),
"{verdict}"
);
}