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

Requirements index · View definition

evidence Valid

Requirement

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.

Rationale

Scope. requirements.test-coverage.check is an umbrella requirement. Its own obligations are:

  • habeas coverage-check checks saved coverage against the threshold and function rules.
  • It returns success only when every applicable obligation is satisfied or has accepted exception evidence.
  • It never builds, executes tests, collects coverage, or invokes an assessment model.

The detailed threshold, function and exception rules belong to check.threshold, check.functions and check.exceptions. Those are cited context, so I did not reassess their tests.

Mapping to the marked tests (both in tests/execution_coverage.rs):

  • fn[full_test_flow_checks_real_function_counters_after_all_tests]
    • Success case. It runs a real full flow on a fixture. The standalone saved_check (which runs coverage-check) succeeds and prints “Coverage check passed”.
    • Failure case. It then adds an unexecuted nested hidden function. The flow and the standalone saved_check both exit non-zero and print “Coverage check failed”. The output contains #fn[outer]/fn[hidden]: zero execution and not #fn[outer]: zero execution. The test run itself is recorded as success, so the policy alone caused the failure.
    • No model. model_tripwire stands up a server, and the test asserts it received zero requests after both coverage-check runs.
    • Read-only. The evidence directory is byte-identical before and after.
  • fn[book_rendering_preserves_retained_coverage_and_never_launches_tests]
    • Standalone coverage-check. It runs with a cargo shim on PATH that records every call and exits 99 for anything other than metadata. The test asserts the following:
      • The forbidden-command marker file is never created.
      • The test-executed sentinel file is never created.
      • The retained coverage files are unchanged.
      • The command fails and reports “File execution coverage” for a filtered, partly unmeasured run, so it does check saved data and fails when obligations are unmet.

These cover the “success only when satisfied” outcome in both directions, and every “MUST NOT” (build, execute tests, collect coverage, invoke a model).

Exceptions. The “or has accepted exception evidence” path is tested at the report level in src/execution_coverage/check.rs#mod[tests], for example fn[accepted_file_and_function_explanations_remain_separate_from_execution] and fn[missing_and_stale_explanations_fail_the_report]. Those tests carry {test} references to the sub-requirements check.exceptions, check.threshold and check.functions. That behavior is delegated to those requirements and needs no separate test here.

I found no plausible requirement-violating behavior of the command-level obligations that these two tests would accept. For example, a coverage-check that rebuilt, ran tests, called a model, or passed with an unexecuted function would fail them.

Inputs

Tests

Input 5: 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 6: outline tests/execution_coverage.rs fn[book_rendering_preserves_retained_coverage_and_never_launches_tests]
// {test}`requirements.test-coverage.index.render_only`
// {test}`requirements.test-coverage.index.selection`
// {test}`requirements.test-coverage.check`
#[cfg(unix)]
#[test]
fn book_rendering_preserves_retained_coverage_and_never_launches_tests() {
    use mdbook_preprocessor::book::{Book, Chapter};
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;
    use std::process::Stdio;
    let temp = fixture();
    let root = temp.path();
    let marker = root.join("test-executed");
    let source = root.join("src/lib.rs");
    fs::write(
        &source,
        fs::read_to_string(&source).unwrap().replace(
            "fn second() {",
            &format!("fn second() {{ std::fs::write({marker:?}, b\"executed\").unwrap();"),
        ),
    )
    .unwrap();
    assert_success(&coverage(root, &["-E", "test(second)"]));
    assert!(
        marker.exists(),
        "the captured test must exercise the execution sentinel"
    );
    fs::remove_file(&marker).unwrap();
    let storage = root.join("target/habeas/coverage");
    let before = retained_files(&storage);
    let bin = root.join("read-only-tools");
    fs::create_dir(&bin).unwrap();
    let forbidden = root.join("forbidden-command");
    let calls = root.join("metadata-calls");
    fs::write(&calls, "").unwrap();
    let cargo = bin.join("cargo");
    fs::write(&cargo, "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$HABEAS_CARGO_CALL_LOG\"\nif [ \"$1\" != metadata ]; then\n  printf '%s\\n' \"$*\" >> \"$HABEAS_FORBIDDEN_COMMAND\"\n  exit 99\nfi\nexec \"$HABEAS_REAL_CARGO\" \"$@\"\n").unwrap();
    fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).unwrap();
    let mut paths = vec![bin];
    paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
    let tool_path = std::env::join_paths(&paths).unwrap();
    let checked = Command::new(env!("CARGO_BIN_EXE_habeas"))
        .arg("coverage-check")
        .current_dir(root)
        .env("PATH", &tool_path)
        .env("HABEAS_REAL_CARGO", env!("CARGO"))
        .env("HABEAS_CARGO_CALL_LOG", &calls)
        .env("HABEAS_FORBIDDEN_COMMAND", &forbidden)
        .env("CARGO_NET_OFFLINE", "true")
        .env_remove("CARGO_TARGET_DIR")
        .env_remove("CARGO_BUILD_TARGET_DIR")
        .output()
        .unwrap();
    assert!(
        !checked.status.success(),
        "filtered coverage leaves unmeasured functions"
    );
    assert!(
        String::from_utf8_lossy(&checked.stdout).contains("File execution coverage"),
        "{}",
        String::from_utf8_lossy(&checked.stderr)
    );
    assert!(!marker.exists(), "standalone coverage-check ran a test");
    assert!(
        !forbidden.exists(),
        "standalone coverage-check launched compilation or collection"
    );
    assert_eq!(
        retained_files(&storage),
        before,
        "standalone coverage-check modified captured data"
    );
    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("PATH", &tool_path)
        .env("HABEAS_REAL_CARGO", env!("CARGO"))
        .env("HABEAS_CARGO_CALL_LOG", &calls)
        .env("HABEAS_FORBIDDEN_COMMAND", &forbidden)
        .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);
    let rendered: Book = serde_json::from_slice(&output.stdout).unwrap();
    assert!(
        rendered
            .chapters()
            .find(|chapter| chapter.name == "Coverage gaps")
            .unwrap()
            .content
            .contains("Unresolved coverage gaps")
    );
    assert!(
        fs::read_to_string(calls)
            .unwrap()
            .lines()
            .all(|line| line.starts_with("metadata "))
    );
    assert!(
        !forbidden.exists(),
        "rendering invoked a test or coverage command"
    );
    assert!(!marker.exists(), "rendering ran a captured test binary");
    assert_eq!(
        retained_files(&storage),
        before,
        "rendering modified collected coverage"
    );
}

Referenced definitions

Input 2: requirements selection requirements.test-coverage.check.threshold
:::{req} check.threshold
Each first-party Rust file under
{cite}`requirements.references.rust_item_coverage` MUST have at least 80%
execution coverage of its instrumented lines, or current accepted exception
evidence explaining why the file falls below that target under
{cite}`requirements.test-coverage.check.exceptions`. Counts MUST use the
file-and-line union rule of {cite}`requirements.test-coverage.index.summary`;
a line counts as executed when any eligible test process or its associated
child processes has a positive execution count for it.

The check MUST use the combined selection and freshness rules of
{cite}`requirements.test-coverage.index.selection` and
{cite}`requirements.test-coverage.index.freshness`, restricted to the active
build configuration. It MUST compare exact counts rather than rounded displayed
percentages, average file percentages, or impose an 80% target within each
function. A file whose executable code is not measured MUST require exception
evidence rather than pass with a fabricated percentage. A file established to
contain no executable coverage obligations MUST be reported as such and MUST
NOT require a threshold exception.
Absence of recorded instrumented lines alone MUST NOT establish that a file
contains no executable coverage obligations.
:::
Input 3: requirements selection requirements.test-coverage.check.functions
:::{req} check.functions
Every function under {cite}`requirements.test-coverage.check.scope` without
recorded execution attributable to it MUST have current accepted exception
evidence under {cite}`requirements.test-coverage.check.exceptions`, even when
its containing file meets the target of
{cite}`requirements.test-coverage.check.threshold`.

Execution attributable only to another function, including a nested function
or closure, MUST NOT establish coverage of the enclosing function merely
because their source locations overlap. Having no recorded lines alone MUST
NOT establish that a function has no executable coverage obligations.
:::
Input 4: requirements selection requirements.test-coverage.check.exceptions
:::{req} check.exceptions
An unmet file threshold or an unexecuted or not-measured function MAY satisfy
the coverage policy only
through current, accepted, independently assessed evidence explaining why its
coverage is incomplete. An exception MUST be attached to the source file or
function whose incomplete coverage it justifies. A file-threshold exception
MUST NOT automatically excuse untested functions.
An exception MUST NOT excuse another source item's incomplete coverage.
Changes to the source item, justification, or other inputs
of its citation review MUST invalidate the affected exception under
{cite}`requirements.references.citation_review`.

A source comment or unassessed justification alone MUST NOT count as accepted
exception evidence. Function and gap identities MUST remain portable between
equivalent local and CI checkouts rather than depend on checkout paths,
run identifiers, timestamps, or process identifiers.
:::

Other sources

Input 1: 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.
:::