requirements.test-coverage.storage.provenance
Requirements index · View definition
Requirement
Each coverage record MUST identify its instrumented build configuration and capture enough source-input identity to determine whether its coverage remains compatible with the project’s current source. Source identity MUST account for uncommitted content changes rather than rely only on the Git revision.
Source identity MUST include the paths and contents of the workspace’s first-party Rust sources and the recorded source and build inputs that affect the instrumented program, including manifests and the dependency lockfile when present. Adding, removing, or changing an included input MUST invalidate the workspace’s collected coverage for the combined view. Freshness checking MUST NOT require rebuilding the project.
Rationale
The reviewed tests adequately cover each obligation of requirements.test-coverage.storage.provenance. I did not read the implementation.
- Build configuration identity. In
tests/execution_coverage.rs#fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns], the storedconfiguration_inputsare checked for rustc (it must contain “LLVM version:”), a non-empty target, cargo-profile “test” and the-C instrument-coverageinstrumentation. Theconfigurationvalue is compared across runs. It is equal for a scheduling-only nextest profile and different when--features alpha -Fbetais used. - Source identity with uncommitted changes.
tests/execution_coverage.rs#fn[no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata]checks that a dirty working tree recordsdirty: trueand the revision. After the file is restored, it checksdirty: false.src/execution_coverage.rs#mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content]keeps therevisionunchanged and setsdirty: Some(true). It then changescode.rscontent and assertsfreshis false. Content changes alone therefore invalidate the record, not the revision.
- Paths and contents of first-party Rust sources, manifests and lockfile. The same unit test checks that these changes make
freshfalse, and that restoring the original state makes it true again:- a changed Rust file;
- an added Rust file;
- a removed Rust file;
- a changed
Cargo.lock; - a changed root
Cargo.toml; - an added member manifest;
- an added
rust-toolchain.toml; - a removed
Cargo.toml; - a removed
Cargo.lock. The real-build test confirms the recorded inputs includeCargo.lock,build.rs, aninclude_str!file and arerun-if-changedfile.
- Recorded source and build inputs. The unit test covers watched directories with a new file, a nested file and a path that is created later. The real-build test covers two kinds of input:
- Changing the include file or the build-script input makes the combined view show “1 stale test attempts”.
- Changing the compiler environment variable or the build environment variable also makes it show that.
- Environment inputs.
src/execution_coverage/book.rs#mod[tests]/fn[cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does]shows that package-specific Cargo variables don’t invalidate coverage. It also shows thatCC,RUSTFLAGS, the Cargo profile and linker variables, and a fixture build input each invalidate it, with the combined view showing “stale coverage; recollect”. - Failure to read build inputs.
tests/execution_coverage.rs#fn[unreadable_build_inputs_fail_preparation_before_any_tests_start]checks that an unreadable build input fails the run during preparation. - No rebuild during freshness checking. The unit test calls
freshdirectly on a bare temp directory with no buildable project, so it checks freshness without a build. The real-build test asserts thatretained_files(&storage)is identical before and after the freshness renders. This is not a strict proof that no rebuild happens. Together the two checks are adequate for the stated obligation.
I found no unaddressed obligation or gap.
Inputs
Tests
Input 2: outline src/execution_coverage/book.rs mod[tests]/fn[cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does]
- File:
src/execution_coverage/book.rs - Selector:
mod[tests]/fn[cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does] - Kind:
fn src/execution_coverage/book.rs:1720–1777
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.index.freshness`
#[test]
fn cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does() {
let (temp, book) = fixture();
let root = temp.path();
let attempt = record(root, "one", 1, "build-a", &[(1, 1), (2, 0)]);
let path = attempt.parent().unwrap().parent().unwrap().join("run.json");
let mut run: Run = load(&path).unwrap();
// An older report captured package-specific compiler values. Reading
// through `cargo run` supplies values for Habeas instead of this package.
for name in [
"CARGO_MANIFEST_DIR",
"CARGO_PKG_VERSION",
"CARGO_CFG_TARGET_OS",
"CARGO_FEATURE_ALPHA",
"CARGO_BIN_EXE_fixture",
"OUT_DIR",
] {
run.environment_inputs
.insert(name.into(), Some("different compiled package".into()));
}
save(&path, &run).unwrap();
let mut rendered = book.clone();
populate(&mut rendered, root).unwrap();
assert!(
rendered
.chapters()
.next()
.unwrap()
.content
.contains("1/2 (50.0%)")
);
for name in [
"CC",
"RUSTFLAGS",
"CARGO_PROFILE_TEST_DEBUG",
"CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER",
"HABEAS_FIXTURE_BUILD_INPUT",
] {
let changed = format!("changed-{}", uuid::Uuid::new_v4());
assert_ne!(std::env::var(name).ok().as_deref(), Some(changed.as_str()));
run.environment_inputs.insert(name.into(), Some(changed));
save(&path, &run).unwrap();
let mut rendered = book.clone();
populate(&mut rendered, root).unwrap();
assert!(
rendered
.chapters()
.next()
.unwrap()
.content
.contains("stale coverage; recollect"),
"{name}"
);
run.environment_inputs.remove(name);
}
}
Input 3: outline src/execution_coverage.rs mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content]
- File:
src/execution_coverage.rs - Selector:
mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content] - Kind:
fn src/execution_coverage.rs:357–435
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.index.freshness`
#[test]
fn source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let target = root.join("target");
fs::write(root.join("Cargo.toml"), "[workspace]\n").unwrap();
fs::write(root.join("Cargo.lock"), "lock content").unwrap();
fs::write(root.join("code.rs"), "fn original() {}\n").unwrap();
fs::create_dir(root.join("generated-inputs")).unwrap();
fs::create_dir(root.join("generated-inputs/node_modules")).unwrap();
fs::write(root.join("generated-inputs/data"), "initial").unwrap();
let mut inputs = input_hashes(&workspace_inputs(root, &target).unwrap()).unwrap();
for path in [root.join("generated-inputs"), root.join("not-created-yet")] {
inputs.insert(
path.to_string_lossy().into_owned(),
input_digest(&path, Some(&target)).unwrap(),
);
}
let run = Run {
schema: 1,
id: "fixture".into(),
started: 1,
command: vec![],
selection: vec![],
configuration: "config".into(),
configuration_inputs: BTreeMap::new(),
sources: BTreeMap::new(),
inputs,
environment_inputs: BTreeMap::new(),
revision: Some("unchanged revision".into()),
dirty: Some(true),
outcome: "success".into(),
diagnostics: vec![],
};
assert!(fresh(&run, root, &target).unwrap());
for (path, content) in [
("code.rs", "fn dirty() {}\n"),
("added.rs", "fn added() {}\n"),
("Cargo.lock", "different lock"),
(
"Cargo.toml",
"[workspace]\n[workspace.package]\nversion = '2.0.0'\n",
),
(
"member/Cargo.toml",
"[package]\nname = 'other'\nversion = '1.0.0'\n",
),
("rust-toolchain.toml", "[toolchain]\nchannel = 'stable'\n"),
("generated-inputs/new", "new watched input"),
(
"generated-inputs/node_modules/data",
"watched non-Rust input",
),
("not-created-yet", "now created"),
] {
let path = root.join(path);
let previous = fs::read(&path).ok();
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, content).unwrap();
assert!(!fresh(&run, root, &target).unwrap(), "{}", path.display());
match previous {
Some(previous) => fs::write(path, previous).unwrap(),
None => fs::remove_file(path).unwrap(),
}
assert!(fresh(&run, root, &target).unwrap());
}
for name in ["Cargo.toml", "Cargo.lock"] {
let path = root.join(name);
let original = fs::read(&path).unwrap();
fs::remove_file(&path).unwrap();
assert!(!fresh(&run, root, &target).unwrap(), "{name}");
fs::write(path, original).unwrap();
assert!(fresh(&run, root, &target).unwrap());
}
fs::remove_file(root.join("code.rs")).unwrap();
assert!(!fresh(&run, root, &target).unwrap());
}
Input 4: outline tests/execution_coverage.rs fn[real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks]
- File:
tests/execution_coverage.rs - Selector:
fn[real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks] - Kind:
fn tests/execution_coverage.rs:615–739
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.index.freshness`
#[test]
fn real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks() {
use mdbook_preprocessor::book::{Book, Chapter};
use std::io::Write;
use std::process::Stdio;
let temp = fixture();
let root = temp.path();
fs::write(root.join("included data.txt"), "included").unwrap();
fs::write(root.join("build-input.data"), "build input").unwrap();
fs::write(
root.join("build.rs"),
"fn main() {\nprintln!(\"cargo:rerun-if-changed=build-input.data\");\nprintln!(\"cargo:rerun-if-env-changed=HABEAS_FIXTURE_BUILD_ENV\");\n}\n",
)
.unwrap();
let source = root.join("src/lib.rs");
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"fn second() {",
"fn second() { assert_eq!(include_str!(\"../included data.txt\"), \"included\"); assert_eq!(env!(\"HABEAS_FIXTURE_RUST_ENV\"), \"compiler-value\");",
),
)
.unwrap();
assert_success(
&Command::new(env!("CARGO_BIN_EXE_habeas"))
.args(["coverage", "--", "-E", "test(second)"])
.current_dir(root)
.env("HABEAS_FIXTURE_RUST_ENV", "compiler-value")
.env("HABEAS_FIXTURE_BUILD_ENV", "build-value")
.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(),
);
let saved = runs(root);
assert_eq!(saved.len(), 1);
let recorded_inputs = saved[0].1["inputs"].as_object().unwrap();
for file in [
"included data.txt",
"build-input.data",
"build.rs",
"Cargo.lock",
] {
assert!(
recorded_inputs.keys().any(|path| {
fs::canonicalize(path).ok() == Some(fs::canonicalize(root.join(file)).unwrap())
}),
"capture omitted {file}: {:?}",
recorded_inputs.keys().collect::<Vec<_>>()
);
}
assert_eq!(
saved[0].1["environment_inputs"]["HABEAS_FIXTURE_RUST_ENV"],
"compiler-value"
);
assert_eq!(
saved[0].1["environment_inputs"]["HABEAS_FIXTURE_BUILD_ENV"],
"build-value"
);
let render = |compiler: &str, build: &str| {
let mut book = Book::new();
book.push_item(Chapter::new(
"Coverage",
":::{coverage-index}\n:::\n".into(),
"coverage.md",
vec![],
));
let input = serde_json::json!([{
"root": root, "config": {"book":{"src":"md"}}, "renderer":"html", "mdbook_version":"0.5.3"
}, book]);
let mut child = Command::new(env!("CARGO_BIN_EXE_habeas"))
.arg("mdbook")
.current_dir(root)
.env("HABEAS_FIXTURE_RUST_ENV", compiler)
.env("HABEAS_FIXTURE_BUILD_ENV", build)
.env("CARGO_NET_OFFLINE", "true")
.env_remove("CARGO_TARGET_DIR")
.env_remove("CARGO_BUILD_TARGET_DIR")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(input.to_string().as_bytes())
.unwrap();
let output = child.wait_with_output().unwrap();
assert_success(&output);
serde_json::from_slice::<Book>(&output.stdout)
.unwrap()
.chapters()
.find(|chapter| chapter.name == "Coverage gaps")
.unwrap()
.content
.clone()
};
let storage = root.join("target/habeas/coverage");
let before = retained_files(&storage);
assert!(!render("compiler-value", "build-value").contains("stale test attempts"));
for file in ["included data.txt", "build-input.data"] {
let path = root.join(file);
let original = fs::read(&path).unwrap();
fs::write(&path, "changed").unwrap();
assert!(
render("compiler-value", "build-value").contains("1 stale test attempts"),
"{file}"
);
fs::write(path, original).unwrap();
assert!(!render("compiler-value", "build-value").contains("stale test attempts"));
}
for (compiler, build) in [("changed", "build-value"), ("compiler-value", "changed")] {
assert!(render(compiler, build).contains("1 stale test attempts"));
}
assert_eq!(retained_files(&storage), before);
}
Input 5: 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 6: 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);
}
Input 7: outline tests/execution_coverage.rs fn[unreadable_build_inputs_fail_preparation_before_any_tests_start]
- File:
tests/execution_coverage.rs - Selector:
fn[unreadable_build_inputs_fail_preparation_before_any_tests_start] - Kind:
fn tests/execution_coverage.rs:1352–1381
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.failures`
#[cfg(unix)]
#[test]
fn unreadable_build_inputs_fail_preparation_before_any_tests_start() {
use std::os::unix::fs::PermissionsExt;
let temp = fixture();
let root = temp.path();
fs::write(
root.join("build.rs"),
"fn main() { println!(\"cargo::rerun-if-changed=input.data\"); }\n",
)
.unwrap();
fs::write(root.join("input.data"), "private build input").unwrap();
fs::set_permissions(root.join("input.data"), fs::Permissions::from_mode(0o000)).unwrap();
let output = coverage(root, &["-E", "test(second)"]);
fs::set_permissions(root.join("input.data"), fs::Permissions::from_mode(0o600)).unwrap();
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr).contains("Coverage preparation failed"));
let saved = runs(root);
assert_eq!(saved[0].1["outcome"], "failed");
assert!(attempts(&saved[0].0).is_empty());
assert!(
saved[0].1["diagnostics"][0]
.as_str()
.unwrap()
.contains("before test startup")
);
}
Other sources
Input 1: requirements selection requirements.test-coverage.storage.provenance
requirements.test-coverage.storage.provenance:md/requirements/test-coverage.md:115–127
:::{req} storage.provenance
Each coverage record MUST identify its instrumented build configuration and
capture enough source-input identity to determine whether its coverage remains
compatible with the project's current source. Source identity MUST account for
uncommitted content changes rather than rely only on the Git revision.
Source identity MUST include the paths and contents of the workspace's
first-party Rust sources and the recorded source and build inputs that affect
the instrumented program, including manifests and the dependency lockfile when
present. Adding, removing, or changing an included input MUST invalidate the
workspace's collected coverage for the combined view. Freshness checking MUST
NOT require rebuilding the project.
:::
Input 8: outline tests/execution_coverage.rs fn[retained_files]
- File:
tests/execution_coverage.rs - Selector:
fn[retained_files] - Kind:
fn tests/execution_coverage.rs:463–481
// {cite}`habeas:util`
fn retained_files(root: &Path) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {
let mut files = std::collections::BTreeMap::new();
let mut pending = vec![root.to_owned()];
while let Some(dir) = pending.pop() {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
pending.push(path);
} else {
files.insert(
path.strip_prefix(root).unwrap().to_owned(),
fs::read(path).unwrap(),
);
}
}
}
files
}