requirements.test-coverage.run
Requirements index · View definition
Requirement
habeas coverage [-- <nextest arguments>]MUST run LLVM-instrumented Rust tests throughcargo nextest run, forwarding the supplied arguments and preserving nextest’s configured test concurrency, filtering, and retries. With no supplied arguments it MUST select the workspace.
Rationale
The reviewed tests cover each obligation in requirements.test-coverage.run. They run the real habeas binary through the helper coverage in tests/execution_coverage.rs, which invokes habeas coverage -- <args>.
- Runs instrumented tests through
cargo nextest run.real_parallel_processes_retries_child_profiles_and_filtered_rerunsasserts that the saved command iscargo nextest run.- The same test asserts that the recorded rustc configuration contains
-C instrument-coverageand that profile files exist for every attempt. compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_featureschecks the compiler wrapper. It checks that-C instrument-coverageis appended to compile invocations but not to compiler queries. It also checks that arguments, the exit status, and a prior wrapper are preserved.
- Forwards supplied arguments.
real_parallel_processes_retries_child_profiles_and_filtered_rerunscovers--workspace,--retries,-j,-E,--profile,--features,-F,--config,--no-runand--no-fail-fast. It asserts the recorded selection and the observable effects.configured_retries_filters_profiles_and_libtest_arguments_are_preservedforwards libtest arguments after--(--exact second) and asserts that exactly one test,second, runs.
- Preserves concurrency.
no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadatasetstest-threads = 2in the nextest config. It uses two tests that rendezvous with each other and fail after a timeout unless they run in parallel. The-j 2case is in the real-parallel test. - Preserves filtering.
configured_retries_filters_profiles_and_libtest_arguments_are_preservedsets a profiledefault-filterand asserts that onlyretriesruns. It also checks that a different profile’s filter selects onlysecond.real_parallel_processes_retries_child_profiles_and_filtered_rerunschecks-Efilters.
- Preserves retries.
- The real-parallel test uses
--retries 1and asserts two attempts forretries, with outcomes failed/1 and success/2. configured_retries_filters_profiles_and_libtest_arguments_are_preservedchecks retries configured in the nextest config, with no CLI flag.- The real-parallel test also checks
--retries 0, which gives a failed outcome.
- The real-parallel test uses
- No arguments selects the workspace.
no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadataruns with no arguments in a workspace whosedefault-membersis only the root. It asserts that the selection is["--workspace"], that three attempts ran, and that the member’smember_runstest ran.
I found no scenario that the text names that these tests leave unchecked.
Inputs
Tests
Input 2: outline src/execution_coverage/runner.rs mod[tests]/fn[compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features]
- File:
src/execution_coverage/runner.rs - Selector:
mod[tests]/fn[compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features] - Kind:
fn src/execution_coverage/runner.rs:1481–1635
// {test}`requirements.test-coverage.run`
// {test}`requirements.test-coverage.storage.configuration`
#[cfg(unix)]
#[test]
fn compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features() {
use std::os::unix::fs::PermissionsExt;
const TEST_NAME: &str = "execution_coverage::runner::tests::compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features";
if let Ok(arguments) = std::env::var("HABEAS_COMPILER_TEST_ARGUMENTS") {
let arguments: Vec<String> = serde_json::from_str(&arguments).unwrap();
let arguments = arguments
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>();
assert_eq!(
compile_process(&arguments).unwrap(),
std::env::var("HABEAS_COMPILER_TEST_STATUS")
.unwrap()
.parse::<i32>()
.unwrap()
);
return;
}
assert_eq!(
compile_process(&[]).unwrap_err().to_string(),
"missing rustc invocation"
);
let root = tempfile::tempdir().unwrap();
let compiler = root.path().join("fixture rustc");
let wrapper = root.path().join("prior wrapper");
fs::write(
&compiler,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$HABEAS_COMPILER_TEST_CAPTURE\"\nif [ \"${LLVM_PROFILE_FILE+x}\" = x ]; then exit 99; fi\nexit \"$HABEAS_COMPILER_TEST_STATUS\"\n",
)
.unwrap();
fs::write(
&wrapper,
"#!/bin/sh\nprintf '%s\\n' \"$1\" > \"$HABEAS_COMPILER_TEST_WRAPPER_CAPTURE\"\nexec \"$@\"\n",
)
.unwrap();
for path in [&compiler, &wrapper] {
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
for (name, wrapped, args, status, expected_features) in [
("query", false, vec!["--print", "sysroot"], 0, None),
(
"compile",
false,
vec![
"--crate-name",
"fixture",
"--cfg",
"feature=\"zeta\"",
"--cfg",
"feature=\"alpha\"",
"--cfg",
"feature=\"zeta\"",
"--cfg",
"test",
"--target",
"fixture-target",
"source with spaces.rs",
],
0,
Some(vec!["alpha", "zeta"]),
),
(
"wrapped",
true,
vec!["--crate-name", "fixture", "-C", "opt-level=2"],
17,
Some(vec![]),
),
] {
let capture = root.path().join(format!("{name}.args"));
let wrapper_capture = root.path().join(format!("{name}.wrapper"));
let ledger = root.path().join(format!("{name}.ledger"));
let mut arguments = vec![compiler.to_string_lossy().into_owned()];
arguments.extend(args.iter().map(|arg| (*arg).to_owned()));
let mut child = Command::new(std::env::current_exe().unwrap());
child
.args(["--exact", TEST_NAME])
.env(
"HABEAS_COMPILER_TEST_ARGUMENTS",
serde_json::to_string(&arguments).unwrap(),
)
.env("HABEAS_COMPILER_TEST_STATUS", status.to_string())
.env("HABEAS_COMPILER_TEST_CAPTURE", &capture)
.env("HABEAS_COMPILER_TEST_WRAPPER_CAPTURE", &wrapper_capture)
.env("HABEAS_COVERAGE_FEATURE_LEDGER", &ledger)
.env("CARGO_MANIFEST_DIR", root.path())
.env_remove("HABEAS_PREVIOUS_WORKSPACE_WRAPPER");
if wrapped {
child.env("HABEAS_PREVIOUS_WORKSPACE_WRAPPER", &wrapper);
}
let result = child.output().unwrap();
assert!(
result.status.success(),
"{name}: {}\n{}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed"));
let mut expected = args.iter().map(|arg| (*arg).to_owned()).collect::<Vec<_>>();
if let Some(features) = expected_features {
expected.extend(["-C".into(), "instrument-coverage".into()]);
let records = fs::read_dir(&ledger)
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!(
records.len(),
1,
"one feature record per package and target"
);
let record: (String, Vec<String>) = load(&records[0].path()).unwrap();
let target = if name == "compile" {
"fixture-target"
} else {
"host"
};
assert_eq!(record.0, format!("{} [{target}]", root.path().display()));
assert_eq!(
record.1, features,
"features are unique, sorted, and omit non-feature cfgs"
);
} else {
assert!(
!ledger.exists(),
"compiler queries create no feature records"
);
}
assert_eq!(
fs::read_to_string(capture)
.unwrap()
.lines()
.collect::<Vec<_>>(),
expected
);
if wrapped {
assert_eq!(
fs::read_to_string(wrapper_capture).unwrap().trim(),
compiler.to_str().unwrap()
);
} else {
assert!(!wrapper_capture.exists());
}
}
assert_eq!(
compile_process(&[root.path().join("missing-rustc").into_os_string()])
.unwrap_err()
.kind(),
io::ErrorKind::NotFound
);
}
Input 3: outline tests/execution_coverage.rs fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]
- File:
tests/execution_coverage.rs - Selector:
fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns] - Kind:
fn tests/execution_coverage.rs:741–1018
// {test}`requirements.test-coverage.run`
// {test}`requirements.test-coverage.processes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.storage`
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.storage.configuration`
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.failures`
#[test]
fn real_parallel_processes_retries_child_profiles_and_filtered_reruns() {
let temp = fixture();
let root = temp.path();
assert_success(&coverage(
root,
&["--workspace", "--retries", "1", "-j", "2", "--no-fail-fast"],
));
let saved = runs(root);
assert_eq!(saved.len(), 1);
let first = &saved[0].0;
assert_eq!(
saved[0].1["id"],
first.file_name().unwrap().to_str().unwrap()
);
assert!(saved[0].1["started"].as_u64().unwrap() > 0);
assert_eq!(saved[0].1["command"][0], "cargo nextest run");
assert!(
saved[0].1["selection"]
.as_array()
.unwrap()
.iter()
.any(|arg| arg == "--workspace")
);
assert!(saved[0].1["revision"].is_null());
assert!(saved[0].1["dirty"].is_null());
assert!(
saved[0].1["inputs"]
.get(root.join("src/lib.rs").to_str().unwrap())
.is_some()
);
let records = attempts(first);
assert_eq!(records.len(), 6); // five tests, one retried
let retry = records
.iter()
.filter(|record| record["test"] == "retries")
.collect::<Vec<_>>();
assert_eq!(retry.len(), 2);
assert!(
retry
.iter()
.any(|record| record["outcome"] == "failed" && record["attempt"] == "1")
);
assert!(
retry
.iter()
.any(|record| record["outcome"] == "success" && record["attempt"] == "2")
);
let child = records
.iter()
.find(|record| record["test"] == "child_process")
.unwrap();
assert_eq!(child["processes"].as_array().unwrap().len(), 2);
assert!(
child["processes"]
.as_array()
.unwrap()
.iter()
.all(|process| process["diagnostic"].is_null()
&& !process["lines"].as_object().unwrap().is_empty())
);
assert!(
records
.iter()
.all(|record| !record["processes"].as_array().unwrap().is_empty())
);
assert_eq!(
records
.iter()
.filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
.count(),
2
);
let same_named = records
.iter()
.filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
.collect::<Vec<_>>();
let binaries = same_named
.iter()
.map(|record| record["binary"].as_str().unwrap())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
binaries,
std::collections::BTreeSet::from(["coverage-fixture", "coverage-fixture::processes"])
);
let identities = records
.iter()
.map(|record| record["id"].as_str().unwrap())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(identities.len(), records.len());
for record in &records {
for process in record["processes"].as_array().unwrap() {
for profile in process["profiles"].as_array().unwrap() {
assert!(
first
.join("attempts")
.join(record["id"].as_str().unwrap())
.join(profile.as_str().unwrap())
.is_file()
);
}
}
}
let configuration = &saved[0].1["configuration_inputs"];
assert!(
configuration["rustc"]
.as_str()
.unwrap()
.contains("LLVM version:")
);
assert!(!configuration["target"].as_str().unwrap().is_empty());
assert_eq!(configuration["cargo-profile"], "test");
assert!(
configuration["instrumentation"]
.as_str()
.unwrap()
.contains("-C instrument-coverage")
);
assert!(first.join("maps.json").is_file());
assert!(
saved[0].1["sources"]["src/lib.rs"]
.as_str()
.unwrap()
.contains("pub fn value")
);
assert_success(&coverage(root, &["-E", "test(second)"]));
let saved = runs(root);
assert_eq!(saved.len(), 2);
assert_eq!(attempts(&saved[1].0).len(), 1);
assert_eq!(saved[0].1["configuration"], saved[1].1["configuration"]);
assert_eq!(
saved[1].1["selection"],
serde_json::json!(["-E", "test(second)"])
);
// A scheduling profile doesn't split build compatibility.
let config = root.join(".config/nextest.toml");
let mut source = fs::read_to_string(&config).unwrap();
source.push_str("\n[profile.focused]\ntest-threads = 1\n");
fs::write(config, source).unwrap();
assert_success(&coverage(
root,
&["--profile", "focused", "-E", "test(second)"],
));
let saved = runs(root);
assert_eq!(saved[0].1["configuration"], saved[2].1["configuration"]);
assert_eq!(attempts(&saved[0].0).len(), 6); // historical profiles were retained
// Collection must preserve failure, including a retry's attempt outcome.
let failed = coverage(root, &["-E", "test(retries)", "--retries", "0"]);
assert!(!failed.status.success());
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert_eq!(attempts(&newest.0)[0]["outcome"], "failed");
// Empty selection has nextest's own exit result and a visible run diagnostic.
let empty = coverage(
root,
&["-E", "test(definitely_missing)", "--no-tests", "pass"],
);
assert_success(&empty);
let saved = runs(root);
assert!(attempts(&saved.last().unwrap().0).is_empty());
assert!(
saved.last().unwrap().1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty test selection")
);
let empty_failure = coverage(root, &["-E", "test(definitely_missing)"]);
assert_eq!(
empty_failure.status.code(),
Some(4),
"{}",
String::from_utf8_lossy(&empty_failure.stderr)
);
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty test selection")
);
assert_success(&coverage(
root,
&["--features", "alpha", "-Fbeta", "-E", "test(second)"],
));
let saved = runs(root);
let newest = saved.last().unwrap();
assert_ne!(newest.1["configuration"], saved[0].1["configuration"]);
let enabled: Value = serde_json::from_str(
newest.1["configuration_inputs"]["enabled-features"]
.as_str()
.unwrap(),
)
.unwrap();
assert!(enabled.as_object().unwrap().values().any(|features| {
features
.as_array()
.unwrap()
.contains(&Value::String("alpha".into()))
&& features
.as_array()
.unwrap()
.contains(&Value::String("beta".into()))
}));
assert_success(&coverage(
root,
&[
"--config",
"build.build-dir='custom-build'",
"-E",
"test(second)",
],
));
let saved = runs(root);
assert_eq!(attempts(&saved.last().unwrap().0).len(), 1);
assert!(!root.join("custom-build").exists());
assert_success(&coverage(root, &["--no-run", "-E", "test(second)"]));
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "success");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Compilation-only")
);
assert!(
!newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty")
);
// Compilation failures also retain run identity and all earlier process data.
fs::write(
root.join("src/lib.rs"),
"compile_error!(\"deliberate build failure\");\n",
)
.unwrap();
let failed_build = coverage(root, &["-E", "test(second)"]);
assert!(!failed_build.status.success());
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Instrumented compilation")
);
assert_eq!(attempts(first).len(), 6);
for record in &records {
for process in record["processes"].as_array().unwrap() {
for profile in process["profiles"].as_array().unwrap() {
assert!(
first
.join("attempts")
.join(record["id"].as_str().unwrap())
.join(profile.as_str().unwrap())
.is_file()
);
}
}
}
}
Input 4: outline tests/execution_coverage.rs fn[configured_retries_filters_profiles_and_libtest_arguments_are_preserved]
- File:
tests/execution_coverage.rs - Selector:
fn[configured_retries_filters_profiles_and_libtest_arguments_are_preserved] - Kind:
fn tests/execution_coverage.rs:1020–1055
// {test}`requirements.test-coverage.run`
#[test]
fn configured_retries_filters_profiles_and_libtest_arguments_are_preserved() {
let temp = fixture();
let root = temp.path();
let path = root.join(".config/nextest.toml");
let mut config: toml_edit::DocumentMut = fs::read_to_string(&path).unwrap().parse().unwrap();
config["profile"]["default"]["retries"] = toml_edit::value(1);
config["profile"]["default"]["default-filter"] = toml_edit::value("test(retries)");
config["profile"]["focused"]["default-filter"] = toml_edit::value("test(second)");
fs::write(path, config.to_string()).unwrap();
assert_success(&coverage(root, &[]));
let saved = runs(root);
let records = attempts(&saved[0].0);
assert_eq!(records.len(), 2, "{records:?}");
assert!(records.iter().all(|attempt| attempt["test"] == "retries"));
assert!(records.iter().any(|attempt| attempt["outcome"] == "failed"));
assert!(
records
.iter()
.any(|attempt| attempt["outcome"] == "success")
);
assert_success(&coverage(
root,
&["--profile", "focused", "--", "--exact", "second"],
));
let saved = runs(root);
let records = attempts(&saved.last().unwrap().0);
assert_eq!(records.len(), 1);
assert_eq!(records[0]["test"], "second");
assert_eq!(
saved.last().unwrap().1["selection"],
serde_json::json!(["--profile", "focused", "--", "--exact", "second"])
);
assert_eq!(saved[0].1["configuration"], saved[1].1["configuration"]);
}
Input 5: outline tests/execution_coverage.rs fn[no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata]
- File:
tests/execution_coverage.rs - Selector:
fn[no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata] - Kind:
fn tests/execution_coverage.rs:1112–1226
// {test}`requirements.test-coverage.run`
// {test}`requirements.test-coverage.storage`
// {test}`requirements.test-coverage.storage.provenance`
#[test]
fn no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata() {
let temp = fixture();
let root = temp.path();
let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
fs::write(
root.join("Cargo.toml"),
format!("{manifest}\n[workspace]\nmembers = ['member']\ndefault-members = ['.']\n"),
)
.unwrap();
fs::create_dir_all(root.join("member/src")).unwrap();
fs::write(
root.join("member/Cargo.toml"),
"[package]\nname = 'workspace-member'\nversion = '0.1.0'\nedition = '2024'\n",
)
.unwrap();
fs::write(
root.join("member/src/lib.rs"),
"#[test] fn member_runs() {}\n",
)
.unwrap();
fs::write(root.join("tests/processes.rs"), "").unwrap();
fs::write(
root.join("src/lib.rs"),
r#"
fn rendezvous(own: &str, other: &str) {
std::fs::write(own, "started").unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !std::path::Path::new(other).exists() {
assert!(std::time::Instant::now() < deadline, "tests did not run in parallel");
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test] fn parallel_a() { rendezvous("a.started", "b.started"); }
#[test] fn parallel_b() { rendezvous("b.started", "a.started"); }
"#,
)
.unwrap();
let config = root.join(".config/nextest.toml");
let mut source: toml_edit::DocumentMut = fs::read_to_string(&config).unwrap().parse().unwrap();
source["profile"]["default"]["test-threads"] = toml_edit::value(2);
fs::write(config, source.to_string()).unwrap();
// Cargo's configured target is also where retained coverage must live.
fs::create_dir_all(root.join(".cargo")).unwrap();
fs::write(
root.join(".cargo/config.toml"),
"[build]\ntarget-dir = 'custom-target'\n",
)
.unwrap();
fs::write(
root.join(".gitignore"),
"custom-target/\n*.started\nCargo.lock\n",
)
.unwrap();
let repo = git2::Repository::init(root).unwrap();
let mut index = repo.index().unwrap();
index
.add_all(["*"], git2::IndexAddOption::DEFAULT, None)
.unwrap();
index.write().unwrap();
let tree_id = index.write_tree().unwrap();
let tree = repo.find_tree(tree_id).unwrap();
let signature = git2::Signature::now("Coverage fixture", "fixture@example.test").unwrap();
let revision = repo
.commit(Some("HEAD"), &signature, &signature, "Fixture", &tree, &[])
.unwrap();
let source = fs::read_to_string(root.join("src/lib.rs")).unwrap();
fs::write(
root.join("src/lib.rs"),
format!("{source}\n// dirty source bytes\n"),
)
.unwrap();
assert_success(&coverage(root, &[]));
assert!(!root.join("target/habeas/coverage").exists());
let storage = root.join("custom-target/habeas/coverage");
let run_path = fs::read_dir(&storage)
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
let run: Value = serde_json::from_slice(&fs::read(run_path.join("run.json")).unwrap()).unwrap();
assert_eq!(run["revision"], revision.to_string());
assert_eq!(run["dirty"], true);
assert_eq!(run["selection"], serde_json::json!(["--workspace"]));
let records = attempts(&run_path);
assert_eq!(records.len(), 3);
assert!(
records
.iter()
.any(|attempt| attempt["test"] == "member_runs")
);
assert!(
records
.iter()
.all(|attempt| attempt["outcome"] == "success")
);
fs::write(root.join("src/lib.rs"), source).unwrap();
assert_success(&coverage(root, &["--workspace", "-E", "test(member_runs)"]));
let clean_run = fs::read_dir(&storage)
.unwrap()
.map(|entry| {
serde_json::from_slice::<Value>(
&fs::read(entry.unwrap().path().join("run.json")).unwrap(),
)
.unwrap()
})
.max_by_key(|run| run["started"].as_u64().unwrap())
.unwrap();
assert_eq!(clean_run["revision"], revision.to_string());
assert_eq!(clean_run["dirty"], false);
}
Other sources
Input 1: requirements selection requirements.test-coverage.run
requirements.test-coverage.run:md/requirements/test-coverage.md:33–38
:::{req} run
`habeas coverage [-- <nextest arguments>]` MUST run LLVM-instrumented Rust tests
through `cargo nextest run`, forwarding the supplied arguments and preserving
nextest's configured test concurrency, filtering, and retries. With no supplied
arguments it MUST select the workspace.
:::
Input 6: outline tests/execution_coverage.rs fn[coverage]
- File:
tests/execution_coverage.rs - Selector:
fn[coverage] - Kind:
fn tests/execution_coverage.rs:50–66
// {cite}`habeas:util`
fn coverage(root: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_habeas"))
.arg("coverage")
.arg("--")
.args(args)
.current_dir(root)
.env("CARGO_NET_OFFLINE", "true")
.env_remove("CARGO_TARGET_DIR")
.env_remove("CARGO_BUILD_TARGET_DIR")
.env_remove("RUSTC_WORKSPACE_WRAPPER")
.env_remove("HABEAS_PREVIOUS_WORKSPACE_WRAPPER")
.env_remove("HABEAS_COVERAGE_RUN")
.env_remove("HABEAS_COVERAGE_FEATURE_LEDGER")
.output()
.unwrap()
}