requirements.references.coverage.tests
Requirements index · View definition
Requirement
Every Rust function carrying a test attribute,
#[test]or an attribute whose path ends intestsuch as#[tokio::test], including those in Cargo integration-test targets, MUST carry a{test}reference to a requirement or named example under, in a comment attached to it or within its body. A test function without one MUST be a validation error naming its file, line, and name.
Rationale
The reviewed tests cover each obligation in requirements.references.coverage.tests.
Which functions count as tests
src/rust_coverage.rs#mod[tests]/fn[test_functions_need_a_test_reference]feedsuntested_testsa source with several function kinds.#[test]and#[tokio::test]functions, including#[tokio::test(flavor = ...)], are flagged when they lack a reference.#[cfg(test)]and#[rstest]functions are not flagged, which matches reading “path ends intest” as the last path segment beingtest.- A
#[test]insidemod testsis flagged.
tests/coverage.rs#fn[a_test_without_a_test_reference_fails_validation_even_in_mod_tests]covers#[test]inmod tests. Thecoverage.test_moduleexample requires this.
Where the reference may sit and which role counts
- The same unit test checks a
{test}reference in a comment above the function and one inside the body. Both are accepted. - The same test checks that a
{cite}-only function (only_cited) is still flagged. Only{test}satisfies the requirement.
Which references are valid
src/rust_coverage.rs#mod[tests]/fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement]shows that a{test}reference to a requirement-backed example (requirements.case) counts. It also shows that a reference to an example with no requirement (requirements.orphan) is flagged. This agrees withrequirements.references.rust_item_coverage, which says an example MUST reference a requirement. The assertions check both the flagged names and themissing_function_referencesresult.
Integration-test targets and the error message
src/rust_coverage.rs#mod[tests]/fn[a_test_without_a_test_reference_is_an_error_not_a_coverage_warning]writestests/foo.rsand runsvalidate_rust_functions. It asserts exactly one error, containingtests/foo.rs:2: test function bare. That gives the file, line and name, and covers a Cargo integration-test target. A plain helper function gets only a coverage warning, not an error.- The
tests/coverage.rstest asserts the exact end-to-end error text,src/lib.rs:7: test function checks has no {test} reference .... It also asserts that thefixturehelper produces no error.
Not tested, and why it is not a gap
- No test uses the fenced
:::{test}form on a test function. It is the same edge as the inline form underrequirements.references.roles, andcoverage.testsdoes not treat it as a separate mode. - No test uses a
{test}reference to an undefined name. The subject text does not name that case.
No gaps found.
Inputs
Implementation
Input 9: outline src/rust_coverage.rs fn[untested_tests]
- File:
src/rust_coverage.rs - Selector:
fn[untested_tests] - Kind:
fn src/rust_coverage.rs:255–300
/// Test functions of a Rust source without a valid `{test}` reference, as
/// `(node, line, name)`.
// {impl}`requirements.references.coverage.tests`
pub(crate) fn untested_tests(
source: &str,
outline: &outline::Outline,
definitions: &BTreeMap<String, Declaration>,
) -> Vec<(usize, usize, String)> {
// The same rule as item coverage, restricted to `{test}`.
let counts = |kind: crate::ReferenceKind, name: &str| {
kind == crate::ReferenceKind::Test && covering_reference(kind, name, definitions)
};
let mut tested = vec![false; outline.nodes.len()];
for comment in &outline.comments {
if reference_roles(&source[comment.byte_start..comment.byte_end], false)
.iter()
.any(|role| counts(role.kind, role.name))
{
tested[comment.owner] = true;
}
}
for fence in crate::fenced::comment_fences(source, outline) {
if let Some(owner) = fence.owner
&& fence.closed
&& counts(fence.kind, &fence.name)
{
tested[owner] = true;
}
}
let lines: Vec<&str> = source.lines().collect();
outline
.nodes
.iter()
.enumerate()
.filter(|(index, node)| node.kind == "fn" && !tested[*index])
.filter(|(_, node)| {
// Attributes are attached before the declaration line.
let start = node.line_start.saturating_sub(1);
let end = node.declaration_line.min(lines.len());
lines
.get(start..end)
.is_some_and(|attached| TEST_ATTRIBUTE.is_match(&attached.join("\n")))
})
.filter_map(|(index, node)| Some((index, node.declaration_line, node.display_name()?)))
.collect()
}
Input 10: outline src/rust_coverage.rs fn[validate_rust_functions]
- File:
src/rust_coverage.rs - Selector:
fn[validate_rust_functions] - Kind:
fn src/rust_coverage.rs:475–554
// {impl}`requirements.ci.errors`
// {impl}`requirements.references.procedure`
pub(crate) fn validate_rust_functions(
root: &Path,
sources: &[PathBuf],
definitions: &BTreeMap<String, Declaration>,
reads: &EvidenceReads,
errors: &mut Vec<String>,
discovery_errors: &mut Vec<String>,
progress: &mut impl FnMut(InspectionProgress),
) -> Vec<UncoveredItem> {
let mut uncovered = Vec::new();
progress(InspectionProgress {
stage: RUST_COVERAGE_STAGE,
completed: 0,
total: None,
});
let files = rust_files(root, sources);
let total = files.len();
for (completed, file) in files.into_iter().enumerate() {
progress(InspectionProgress {
stage: RUST_COVERAGE_STAGE,
completed,
total: Some(total),
});
let label = display_path(root, &file);
let source = match fs::read_to_string(&file) {
Ok(source) => source,
Err(error) => {
let error = format!("{label}: cannot read Rust source: {error}");
discovery_errors.push(error.clone());
errors.push(error);
continue;
}
};
match unreferenced_items(&source, definitions) {
Ok((outline, missing)) => {
// Only a test without `{test}` fails validation; other items
// without coverage are reported, not errors.
// {impl}`requirements.references.coverage.tests`
let untested = untested_tests(&source, &outline, definitions);
for (_, line, name) in &untested {
errors.push(format!(
"{label}:{line}: test function {name} has no {{test}} reference to a requirement or example"
));
}
for (index, line, kind, name) in missing {
// A test without `{test}` is already a validation error,
// so it is not also a coverage warning.
if reads.covers(&label, &outline, index)
|| untested.iter().any(|(node, _, _)| *node == index)
{
continue;
}
uncovered.push(UncoveredItem {
file: label.clone(),
selectors: crate::coverage_history::enclosing_selectors(&outline, index),
error: uncovered_error(&label, line, kind, &name),
in_tests: crate::coverage_history::in_tests_module(&outline, index)
|| crate::coverage_history::in_tests_file(Path::new(&label)),
});
}
}
Err(error) => {
let error = format!(
"{label}:{}: cannot parse Rust source: {}",
error.line, error.message
);
discovery_errors.push(error.clone());
errors.push(error);
}
}
}
progress(InspectionProgress {
stage: RUST_COVERAGE_STAGE,
completed: total,
total: Some(total),
});
uncovered
}
Tests
Input 3: requirements selection requirements.references.coverage.test_module
requirements.references.coverage.test_module:md/requirements/references.md:323–329
:::{example} coverage.test_module
A helper function inside `mod tests` has no reference and is read by no record.
`habeas status --coverage` does not warn about it. A `#[test]` function in the
same module without a `{test}` reference is still a validation error.
{test}`requirements.references.coverage.report`
{test}`requirements.references.coverage.tests`
:::
Input 4: outline src/rust_coverage.rs mod[tests]/fn[test_functions_need_a_test_reference]
- File:
src/rust_coverage.rs - Selector:
mod[tests]/fn[test_functions_need_a_test_reference] - Kind:
fn src/rust_coverage.rs:710–738
// {test}`requirements.references.coverage.tests`
// {test}`requirements.references.procedure`
#[test]
fn test_functions_need_a_test_reference() {
let source = concat!(
"// {test}`requirements.example`\n#[test]\nfn tested() {}\n\n",
"#[test]\nfn tested_in_body() {\n // {test}`requirements.example`\n}\n\n",
"#[test]\nfn untested() {}\n\n",
"// {cite}`requirements.example`\n#[tokio::test]\nasync fn only_cited() {}\n\n",
"#[tokio::test(flavor = \"multi_thread\")]\nasync fn untested_async() {}\n\n",
"#[cfg(test)]\nfn not_a_test() {}\n\n",
"#[rstest]\nfn other_attribute() {}\n\n",
"mod tests {\n #[test]\n fn nested_untested() {}\n}\n",
);
let outline = crate::outline::parse_with(&crate::outline::RUST_PROFILE, source).unwrap();
let names: Vec<String> = super::untested_tests(source, &outline, &definitions())
.into_iter()
.map(|(_, _, name)| name)
.collect();
assert_eq!(
names,
[
"untested",
"only_cited",
"untested_async",
"nested_untested"
]
);
}
Input 5: outline src/rust_coverage.rs mod[tests]/fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement]
- File:
src/rust_coverage.rs - Selector:
mod[tests]/fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement] - Kind:
fn src/rust_coverage.rs:740–765
// {test}`requirements.references.coverage.tests`
// {test}`requirements.references.rust_item_coverage`
#[test]
fn a_test_reference_to_an_example_counts_only_when_it_references_a_requirement() {
let mut definitions = definitions();
definitions.insert(
"requirements.orphan".to_owned(),
Declaration {
kind: DefinitionKind::Example,
text: "No requirement.".to_owned(),
..definitions["requirements.case"].clone()
},
);
let source = concat!(
"// {test}`requirements.case`\n#[test]\nfn traced() {}\n\n",
"// {test}`requirements.orphan`\n#[test]\nfn orphan() {}\n",
);
let outline = crate::outline::parse_with(&crate::outline::RUST_PROFILE, source).unwrap();
let names: Vec<String> = super::untested_tests(source, &outline, &definitions)
.into_iter()
.map(|(_, _, name)| name)
.collect();
assert_eq!(names, ["orphan"]);
let missing = missing_function_references(source, &definitions).unwrap();
assert_eq!(missing, [(7, "function", "orphan".to_owned())]);
}
Input 6: outline src/rust_coverage.rs mod[tests]/fn[a_test_without_a_test_reference_is_an_error_not_a_coverage_warning]
- File:
src/rust_coverage.rs - Selector:
mod[tests]/fn[a_test_without_a_test_reference_is_an_error_not_a_coverage_warning] - Kind:
fn src/rust_coverage.rs:767–796
// {test}`requirements.references.coverage.tests`
// {test}`requirements.references.coverage.report`
#[test]
fn a_test_without_a_test_reference_is_an_error_not_a_coverage_warning() {
let project = TempDir::new().unwrap();
fs::create_dir_all(project.path().join("tests")).unwrap();
fs::write(
project.path().join("tests/foo.rs"),
"#[test]\nfn bare() {}\n\nfn helper() {}\n",
)
.unwrap();
let mut errors = Vec::new();
let uncovered = validate_rust_functions(
project.path(),
&crate::evidence::discovered_files(project.path(), &mut Vec::new()),
&definitions(),
&super::EvidenceReads::default(),
&mut errors,
&mut Vec::new(),
&mut |_| {},
);
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(
errors[0].contains("tests/foo.rs:2: test function bare"),
"{errors:?}"
);
let warned: Vec<&str> = uncovered.iter().map(|item| item.error.as_str()).collect();
assert_eq!(warned.len(), 1, "{warned:?}");
assert!(warned[0].contains("function helper"), "{warned:?}");
}
Input 7: outline tests/coverage.rs fn[a_test_without_a_test_reference_fails_validation_even_in_mod_tests]
- File:
tests/coverage.rs - Selector:
fn[a_test_without_a_test_reference_fails_validation_even_in_mod_tests] - Kind:
fn tests/coverage.rs:296–321
// {test}`requirements.references.coverage.tests`
// {test}`requirements.references.coverage.test_module`
// {test}`requirements.references.procedure`
#[test]
fn a_test_without_a_test_reference_fails_validation_even_in_mod_tests() {
let temp = project();
let root = temp.path();
fs::write(
root.join("src/lib.rs"),
"fn parse() {}\n\nmod tests {\n fn fixture() {}\n\n #[test]\n fn checks() {}\n}\n",
)
.unwrap();
commit(root, "first");
let errors = habeas::validate_repository(root).unwrap().errors;
assert!(
errors.iter().any(|error| error
== "src/lib.rs:7: test function checks has no {test} reference to a requirement or example"),
"{errors:#?}"
);
// The helper in `mod tests` is neither an error nor a warning.
assert!(
!errors.iter().any(|error| error.contains("fixture")),
"{errors:#?}"
);
assert_eq!(warned(root), ["parse"]);
}
Referenced definitions
Input 2: requirements selection requirements.references.roles
requirements.references.roles:md/requirements/references.md:3–49
:::{req} roles
Project text files MAY use the `{impl}`, `{cite}`, and `{test}` roles with a backtick-delimited full requirement or example name, or with a built-in name under {cite}`requirements.references.builtin_definitions`, and MAY use the `{fixme}` role in fenced form. A reference MAY instead be written in fenced form, `:::{role} name` on one line, a body, and a closing fence, following the fence rules of {cite}`requirements.ci.span` and {cite}`requirements.ci.fence_lengths`; the fenced form is the same edge with attached commentary, and the inline form carries none. In a source comment, fence lines MUST be recognized after removing each line's comment delimiters within one comment run under {cite}`requirements.references.outline_comments`, and a fence that does not close within its comment run MUST be a validation error. Each reference is a directed edge between its source and the named definition. A source is a project source item or a requirement or example declaration. The roles MUST mean:
- `{cite}`: the source relies on, supports, or refers to the definition. It is an
edge from the source to the definition.
- `{impl}`: the source implements part of the definition: it makes a decision,
performs a check, produces an output, or handles a case that the definition
specifies. A requirement MAY implement part of another requirement by refining
one of its obligations. Calling code that implements a definition, or
producing a result a caller uses to meet it, MUST NOT by itself count as
implementing it. A check MUST count only if the definition states it, or the
source could not meet one of the definition's obligations without it; source
that checks it is consistent with a definition, such as recognizing a form the
definition specifies in order to decide whether to run other behavior, relies
on that definition and calls for `{cite}`. A requirement stating a convention
for every output of a kind, such as every validation error, is implemented by
the source that carries out the convention as a whole, such as the step that
collects and reports those outputs.
- `{test}`: the source is designed to verify behavior the definition specifies:
a test through its scenario and the assertions about that scenario's outcome,
or a named example through the concrete case it describes.
- `{fixme}`: the source acknowledges a known gap in fulfilling the definition. It
MUST use the fenced form, and its body MUST describe the gap. The body MAY
begin with option lines naming issues that track the gap, one per line, in the
form `:github: <owner>/<repo>#<number>`, such as
`:github: rust-lang/rust#123`. `github` MUST be the only recognized option.
A named `{fixme}` MAY appear only in sources outside the book. Validation MUST report
any other option line, a `:github:` value not in that form, an inline
`{fixme}`, a `{fixme}` in a requirement or example declaration, and a
`{fixme}` whose body, without option lines and comment delimiters, is empty.
An unnamed `{fixme}`, a fence of `:::{fixme}` with no name, MAY appear in any
project text, including a requirement or example body, to tie that place to
the issues it names. It MUST have at least one `:github:` option line and MAY
have a description; it is not a reference edge, acknowledges no gap, needs no
coverage, and does not count as a reference for Rust item coverage. Its
issues are checked under {cite}`requirements.cli.fixme_issues`.
`{impl}`, `{test}`, and `{fixme}` are edges from the definition to the source.
Only requirements and examples are assessed; code is reviewed as part of the
definitions it implements or tests.
```text
{impl}`requirements.references.roles`
{cite}`requirements.references.roles`
{test}`requirements.references.roles`
```
:::
Other sources
Input 1: requirements selection requirements.references.coverage.tests
requirements.references.coverage.tests:md/requirements/references.md:228–235
:::{req} coverage.tests
Every Rust function carrying a test attribute, `#[test]` or an attribute whose
path ends in `test` such as `#[tokio::test]`, including those in Cargo
integration-test targets, MUST carry a `{test}` reference to a requirement or
named example under {cite}`requirements.references.roles`, in a comment
attached to it or within its body. A test function without one MUST be a
validation error naming its file, line, and name.
:::
Input 8: requirements selection requirements.references.rust_item_coverage
requirements.references.rust_item_coverage:md/requirements/references.md:224–226
:::{req} rust_item_coverage
During repository validation, Habeas MUST parse every first-party Rust source file: every `.rs` file among the sources reference discovery considers under {cite}`requirements.references.discovery`, except those under the project-root `vendor` directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid `{impl}`, `{cite}`, or `{test}` reference to a defined requirement or named example, or a valid citation of the built-in `habeas:util` under {cite}`requirements.references.util`, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under {cite}`requirements.authoring.finish_search.inputs` MUST count alongside mandatory inputs and additional reads. Comments belong to items under {cite}`requirements.references.outline_comments`; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under {cite}`requirements.examples.definition`. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only {cite}`requirements.references.coverage.tests` and {cite}`requirements.references.coverage.examples` make an uncovered item a validation error; other items without recent coverage are warned about under {cite}`requirements.references.coverage.report`.
:::