Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.test-coverage.storage

Requirements index · View definition

evidence Valid

Requirement

Coverage runs MUST be stored as disposable build artifacts under habeas/coverage/ in the project’s Cargo target directory (target/habeas/coverage/ with default Cargo settings), retaining earlier runs until those artifacts are removed. Each run record MUST identify the run, capture time, command, and test selection, and, when available, the source revision and whether the source had uncommitted changes.

Rationale

The two marked tests in tests/execution_coverage.rs cover every obligation in requirements.test-coverage.storage.

  • Default storage location. fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns] reads runs through the runs helper, which lists target/habeas/coverage under the project root. This is the default Cargo target directory.
  • Configured target directory. fn[no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata] sets build.target-dir = 'custom-target' in .cargo/config.toml. It asserts that custom-target/habeas/coverage holds the run and that target/habeas/coverage does not exist.
  • Retention of earlier runs. The first test runs coverage repeatedly. It asserts that two run directories exist after the second run and that the first run’s attempts still hold 6 records after later runs. It also asserts that the first run’s profile files still exist after a later failed build.
  • Run record fields.
    • id: run.json["id"] equals the run directory name.
    • capture time: started is greater than 0.
    • command: command[0] equals "cargo nextest run".
    • selection: the selection contains --workspace. A filtered rerun gives ["-E","test(second)"] exactly. The no-argument run gives ["--workspace"].
  • Source revision and dirty flag when available. The second test builds a git repository. It asserts that revision equals the commit id and that dirty is true with modified source, then false after the source is restored.
  • Source revision and dirty flag when unavailable. In the first test the fixture is not a git repository, and the test asserts that both revision and dirty are null.
  • Disposable build artifacts. The storage lives under the target directory, as the location assertions above show. No separate behavior needs testing for this.

I found no unaddressed obligation, and no acknowledgments apply.

Inputs

Tests

Input 2: outline tests/execution_coverage.rs fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]
// {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 3: outline tests/execution_coverage.rs fn[no_arguments_selects_all_workspace_members_with_configured_parallelism_and_git_metadata]
// {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.storage
:::{req} storage
Coverage runs MUST be stored as disposable build artifacts under
`habeas/coverage/` in the project's Cargo target directory
(`target/habeas/coverage/` with default Cargo settings), retaining earlier runs
until those artifacts are removed. Each run record MUST identify the run,
capture time, command, and test selection, and, when available, the source
revision and whether the source had uncommitted changes.
:::
Input 4: outline tests/execution_coverage.rs fn[coverage]
// {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()
}
Input 5: outline tests/execution_coverage.rs fn[runs]
// {cite}`habeas:util`
fn runs(root: &Path) -> Vec<(std::path::PathBuf, Value)> {
    let mut runs = fs::read_dir(root.join("target/habeas/coverage"))
        .unwrap()
        .map(|entry| {
            let path = entry.unwrap().path();
            let value: Value =
                serde_json::from_slice(&fs::read(path.join("run.json")).unwrap()).unwrap();
            (path, value)
        })
        .collect::<Vec<_>>();
    runs.sort_by_key(|(_, value)| value["started"].as_u64().unwrap());
    runs
}
Input 6: outline tests/execution_coverage.rs fn[attempts]
// {cite}`habeas:util`
fn attempts(run: &Path) -> Vec<Value> {
    fs::read_dir(run.join("attempts"))
        .unwrap()
        .map(|entry| {
            serde_json::from_slice(&fs::read(entry.unwrap().path().join("attempt.json")).unwrap())
                .unwrap()
        })
        .collect()
}