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.test

Requirements index · View definition

evidence Valid

Requirement

habeas test MUST run the full-workspace instrumented nextest workflow of cite requirements.test-coverage.run and, only after that workflow succeeds, run the post-suite check of cite requirements.test-coverage.check. It MUST return a failing exit status if test execution, coverage collection, or the post-suite check fails. It MUST NOT author exception evidence or invoke an assessment model.

Rationale

The tests cover every obligation in requirements.test-coverage.test. The helper full_flow in tests/execution_coverage.rs runs habeas test. saved_check runs coverage-check, and model_tripwire sets up the model server.

  • Runs the instrumented nextest workflow, then the post-suite check. fn[full_test_flow_checks_real_function_counters_after_all_tests] runs habeas test in a fixture workspace. It succeeds, and stdout contains “Coverage check passed”. Exactly one saved run exists, with 4 attempts covering sync unit tests, an async tokio test and an integration target. Every attempt has non-empty function counters. So the full-workspace instrumented run happens and the check follows it. The fixture’s nextest default filter is kind(lib), yet the run still produces 4 attempts, so no-argument habeas test selects the whole workspace.
  • Fails when the post-suite check fails. The same test then changes the sources so a nested function has zero execution. habeas test exits non-zero and stdout contains #fn[outer]/fn[hidden]: zero execution. The saved run’s outcome is still “success”, so the failure comes from the check and not from test execution. A later coverage-check also fails.
  • Fails on test failure and skips the check. fn[failed_suite_stops_full_flow_before_the_coverage_check] uses a panicking test. The exit status is failing, stdout has no “Coverage check” text, and the saved outcome is “failed”. This shows the check runs only after the workflow succeeds, and that test failure fails the command.
  • Fails on coverage collection failure and skips the check. fn[passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports] has tests that pass but write a missing profile or a corrupt profile. habeas test exits non-zero, stderr says partial profiles were retained, and stdout has no “Coverage check” text. The saved outcome is “failed” even though every test attempt succeeded.
  • Does not author exception evidence. The full-flow test snapshots the evidence directory before the run. It asserts the contents are unchanged after both the passing and the failing habeas test runs, and after coverage-check.
  • Does not invoke an assessment model. model_tripwire configures a local HTTP server as the authoring backend. The test asserts the request count is 0 after both the passing and the failing flows.

All three tests carry {test} references to requirements.test-coverage.test. I found no unmarked relevant tests and no untested obligation. The cited run and check requirements are context and I did not reassess them.

Inputs

Tests

Input 4: outline tests/execution_coverage.rs fn[full_test_flow_checks_real_function_counters_after_all_tests]
// {test}`requirements.test-coverage.test`
// {test}`requirements.test-coverage.check`
// {test}`requirements.test-coverage.check.functions`
// {test}`requirements.test-coverage.check.guidance`
#[test]
fn full_test_flow_checks_real_function_counters_after_all_tests() {
    let temp = fixture();
    let root = temp.path();
    let (requests, stop, server) = model_tripwire(root);
    fs::create_dir(root.join("evidence")).unwrap();
    fs::write(root.join("evidence/sentinel.txt"), "existing evidence").unwrap();
    let original_evidence = retained_files(&root.join("evidence"));
    let nextest = root.join(".config/nextest.toml");
    let mut configuration = fs::read_to_string(&nextest)
        .unwrap()
        .parse::<toml_edit::DocumentMut>()
        .unwrap();
    configuration["profile"]["default"]["default-filter"] = toml_edit::value("kind(lib)");
    fs::write(nextest, configuration.to_string()).unwrap();
    let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    fs::write(
        root.join("Cargo.toml"),
        format!("{manifest}\n[dev-dependencies]\ntokio = {{ version = '1', features = ['macros', 'rt'] }}\n"),
    )
    .unwrap();
    fs::write(root.join("src/lib.rs"), "pub fn value(flag: bool) -> u32 {\n if flag { 10 } else { 20 }\n}\n#[cfg(test)] #[test] fn a() { assert_eq!(value(true), 10); }\n#[cfg(test)] #[test] fn b() { assert_eq!(value(false), 20); }\n#[cfg(test)] #[tokio::test] async fn asynchronous() { assert_eq!(value(true), 10); }\n").unwrap();
    fs::write(
        root.join("tests/processes.rs"),
        "#[test] fn integration() { assert_eq!(coverage_fixture::value(true),10); }\n",
    )
    .unwrap();
    let output = full_flow(root);
    assert_success(&output);
    assert!(String::from_utf8_lossy(&output.stdout).contains("Coverage check passed"));
    let checked = saved_check(root);
    assert_success(&checked);
    assert!(String::from_utf8_lossy(&checked.stdout).contains("Coverage check passed"));
    assert_eq!(retained_files(&root.join("evidence")), original_evidence);
    let saved = runs(root);
    assert_eq!(saved.len(), 1);
    assert_eq!(
        attempts(&saved[0].0).len(),
        4,
        "the full workspace includes sync and async unit tests AND integration targets"
    );
    for attempt in attempts(&saved[0].0) {
        for process in attempt["processes"].as_array().unwrap() {
            assert!(
                process["functions"]
                    .as_array()
                    .is_some_and(|functions| !functions.is_empty())
            );
        }
    }
    fs::write(root.join("src/lib.rs"), "pub fn value(flag: bool) -> u32 { if flag { 10 } else { 20 } }\npub fn outer() { fn hidden() {} let f = || {}; f(); }\n#[cfg(test)] #[test] fn a() { value(true); outer(); }\n#[cfg(test)] #[test] fn b() { value(false); }\n#[cfg(test)] #[tokio::test] async fn asynchronous() { assert_eq!(value(true), 10); }\n").unwrap();
    let output = full_flow(root);
    assert!(!output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("#fn[outer]/fn[hidden]: zero execution"),
        "{stdout}\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!stdout.contains("#fn[outer]: zero execution"), "{stdout}");
    assert_eq!(
        runs(root).last().unwrap().1["outcome"],
        "success",
        "tests succeeded; the policy caused failure"
    );
    let checked = saved_check(root);
    assert!(!checked.status.success());
    assert!(String::from_utf8_lossy(&checked.stdout).contains("Coverage check failed"));
    assert_eq!(retained_files(&root.join("evidence")), original_evidence);
    stop.send(()).unwrap();
    server.join().unwrap();
    assert_eq!(
        requests.load(std::sync::atomic::Ordering::SeqCst),
        0,
        "verification must never call a model"
    );
}
Input 5: outline tests/execution_coverage.rs fn[failed_suite_stops_full_flow_before_the_coverage_check]
// {test}`requirements.test-coverage.test`
#[test]
fn failed_suite_stops_full_flow_before_the_coverage_check() {
    let temp = fixture();
    let root = temp.path();
    fs::write(root.join("src/lib.rs"),"pub fn value(_: bool) -> u32 { 10 }\n#[cfg(test)] #[test] fn failure() { panic!(\"deliberate fixture failure\"); }\n").unwrap();
    fs::write(
        root.join("tests/processes.rs"),
        "#[test] fn integration() { coverage_fixture::value(true); }\n",
    )
    .unwrap();
    let output = full_flow(root);
    assert!(!output.status.success());
    assert!(!String::from_utf8_lossy(&output.stdout).contains("Coverage check"));
    assert_eq!(runs(root).last().unwrap().1["outcome"], "failed");
}
Input 6: outline tests/execution_coverage.rs fn[passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports]
// {test}`requirements.test-coverage.failures`
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.test`
#[cfg(unix)]
#[test]
fn passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports() {
    let temp = fixture();
    let root = temp.path();
    fs::write(root.join("tests/processes.rs"), "").unwrap();
    fs::write(root.join("src/lib.rs"), r#"
#[test] fn good_profile() { assert_eq!(std::hint::black_box(1), 1); }
unsafe extern "C" { fn _exit(status: i32) -> !; }
#[test] fn missing_profile() { unsafe { _exit(0) } }
#[test] fn corrupt_profile() {
    let template = std::path::PathBuf::from(std::env::var("LLVM_PROFILE_FILE").unwrap());
    std::fs::write(template.parent().unwrap().join(format!("{}-corrupt.profraw", std::process::id())), "not an LLVM profile").unwrap();
}
"#).unwrap();
    let output = coverage(root, &["--workspace"]);
    assert!(!output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stderr)
            .contains("partial profiles and reports have been retained")
    );
    let combined = full_flow(root);
    assert!(!combined.status.success());
    assert!(!String::from_utf8_lossy(&combined.stdout).contains("Coverage check"));
    assert!(
        String::from_utf8_lossy(&combined.stderr)
            .contains("partial profiles and reports have been retained")
    );
    let saved = runs(root);
    assert_eq!(saved[0].1["outcome"], "failed");
    let records = attempts(&saved[0].0);
    assert_eq!(records.len(), 3);
    assert!(
        records
            .iter()
            .all(|attempt| attempt["outcome"] == "success"),
        "test execution itself succeeds: {records:?}"
    );
    let missing = records
        .iter()
        .find(|attempt| attempt["test"] == "missing_profile")
        .unwrap();
    assert!(
        missing["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .any(|diagnostic| diagnostic
                .as_str()
                .unwrap()
                .contains("No LLVM profile was written"))
    );
    let corrupt = records
        .iter()
        .find(|attempt| attempt["test"] == "corrupt_profile")
        .unwrap();
    assert!(
        corrupt["processes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|process| !process["diagnostic"].is_null()
                && process["lines"].as_object().unwrap().is_empty())
    );
    let good = records
        .iter()
        .find(|attempt| attempt["test"] == "good_profile")
        .unwrap();
    assert!(
        !good["processes"][0]["lines"]
            .as_object()
            .unwrap()
            .is_empty()
    );
    for attempt in [&good, &corrupt] {
        for profile in attempt["processes"]
            .as_array()
            .unwrap()
            .iter()
            .flat_map(|process| process["profiles"].as_array().unwrap())
        {
            assert!(
                saved[0]
                    .0
                    .join("attempts")
                    .join(attempt["id"].as_str().unwrap())
                    .join(profile.as_str().unwrap())
                    .is_file()
            );
        }
    }
}

Referenced definitions

Input 2: requirements selection requirements.test-coverage.run
:::{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 3: requirements selection requirements.test-coverage.check
:::{req} check
`habeas coverage-check` MUST check saved execution coverage against
{cite}`requirements.test-coverage.check.threshold` and
{cite}`requirements.test-coverage.check.functions`, returning success only when
every applicable obligation is satisfied or has accepted exception evidence
under {cite}`requirements.test-coverage.check.exceptions`. The command MUST NOT
build the project, execute tests, collect coverage, or invoke an assessment model.
:::

Other sources

Input 1: requirements selection requirements.test-coverage.test
:::{req} test
`habeas test` MUST run the full-workspace instrumented nextest workflow of
{cite}`requirements.test-coverage.run` and, only after that workflow succeeds,
run the post-suite check of {cite}`requirements.test-coverage.check`. It MUST
return a failing exit status if test execution, coverage collection, or the
post-suite check fails. It MUST NOT author exception evidence or invoke an
assessment model.
:::
Input 7: outline tests/execution_coverage.rs fn[full_flow]
// {cite}`habeas:util`
fn full_flow(root: &Path) -> Output {
    Command::new(env!("CARGO_BIN_EXE_habeas"))
        .arg("test")
        .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 8: outline tests/execution_coverage.rs fn[saved_check]
// {cite}`habeas:util`
fn saved_check(root: &Path) -> Output {
    Command::new(env!("CARGO_BIN_EXE_habeas"))
        .arg("coverage-check")
        .current_dir(root)
        .env_remove("CARGO_TARGET_DIR")
        .env_remove("CARGO_BUILD_TARGET_DIR")
        .output()
        .unwrap()
}
Input 9: outline tests/execution_coverage.rs fn[model_tripwire]
// {cite}`habeas:util`
fn model_tripwire(
    root: &Path,
) -> (
    std::sync::Arc<std::sync::atomic::AtomicUsize>,
    std::sync::mpsc::Sender<()>,
    std::thread::JoinHandle<()>,
) {
    use std::sync::atomic::{AtomicUsize, Ordering};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    listener.set_nonblocking(true).unwrap();
    fs::write(root.join("habeas.toml"), format!(
        "version = 1\n[authoring]\ndefault = 'trap'\n[authoring.configs.trap]\nbackend = 'ollama'\nmodel = 'must-not-be-invoked'\nendpoint = 'http://{}'\n",
        listener.local_addr().unwrap()
    )).unwrap();
    let count = std::sync::Arc::new(AtomicUsize::new(0));
    let observed = count.clone();
    let (stop, stopped) = std::sync::mpsc::channel();
    let thread = std::thread::spawn(move || {
        loop {
            match listener.accept() {
                Ok((mut stream, _)) => {
                    observed.fetch_add(1, Ordering::SeqCst);
                    let _ = stream.write_all(b"HTTP/1.1 500 Unexpected model request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(error) => panic!("{error}"),
            }
            if !matches!(
                stopped.try_recv(),
                Err(std::sync::mpsc::TryRecvError::Empty)
            ) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
    });
    (count, stop, thread)
}