use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use testing_conventions::patch_coverage::check_rust;
use testing_conventions::run;
struct TempRepo(PathBuf);
impl TempRepo {
fn new(slug: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let root = std::env::temp_dir().join(format!(
"tc-patch-cov-rust-{}-{}-{}",
slug,
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed),
));
std::fs::create_dir_all(&root).unwrap();
git(&root, &["init", "-q"]);
git(&root, &["config", "user.email", "test@example.com"]);
git(&root, &["config", "user.name", "Test"]);
let repo = TempRepo(root);
repo.write("Cargo.toml", CARGO_TOML);
repo
}
fn write(&self, rel: &str, contents: &str) {
let path = self.0.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, contents).unwrap();
}
fn commit(&self, message: &str) {
git(&self.0, &["add", "-A"]);
git(
&self.0,
&["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
);
}
fn head(&self) -> String {
let out = Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(&self.0)
.output()
.expect("git rev-parse should run");
assert!(out.status.success(), "git rev-parse failed");
String::from_utf8(out.stdout).unwrap().trim().to_string()
}
}
impl Drop for TempRepo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn git(dir: &Path, args: &[&str]) {
let status = Command::new("git")
.args(args)
.current_dir(dir)
.status()
.expect("git should run");
assert!(status.success(), "git {args:?} failed");
}
fn uncovered(repo: &TempRepo, base: &str) -> Vec<String> {
check_rust(&repo.0, base, &[])
.expect("checking a readable repo should succeed")
.iter()
.map(|u| format!("{}:{}", u.file, u.line))
.collect()
}
fn run_patch_coverage(repo: &TempRepo, base: &str, config: Option<&str>) -> anyhow::Result<i32> {
let mut argv: Vec<OsString> = vec![
"testing-conventions".into(),
"unit".into(),
"patch-coverage".into(),
repo.0.clone().into_os_string(),
"--language".into(),
"rust".into(),
"--base".into(),
base.into(),
];
if let Some(name) = config {
argv.push("--config".into());
argv.push(repo.0.join(name).into_os_string());
}
run(argv)
}
const CARGO_TOML: &str =
"[package]\nname = \"tc_patch_rust\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n[workspace]\n";
const WIDGET_RS: &str = r#"pub fn widget(n: i64) -> &'static str {
if n > 0 {
"pos"
} else {
"neg"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn covers_both_arms() {
assert_eq!(widget(1), "pos");
assert_eq!(widget(-1), "neg");
}
}
"#;
const WIDGET_RS_UNCOVERED: &str = r#"pub fn widget(n: i64) -> &'static str {
if n > 0 {
"pos"
} else if n == -42 {
"answer"
} else {
"neg"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn covers_both_arms() {
assert_eq!(widget(1), "pos");
assert_eq!(widget(-1), "neg");
}
}
"#;
const WIDGET_RS_COVERED_EDIT: &str = r#"pub fn widget(n: i64) -> &'static str {
if n > 0 {
"positive"
} else {
"neg"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn covers_both_arms() {
assert_eq!(widget(1), "positive");
assert_eq!(widget(-1), "neg");
}
}
"#;
#[test]
fn rust_uncovered_changed_line_is_reported() {
let repo = TempRepo::new("uncovered");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write("src/lib.rs", WIDGET_RS_UNCOVERED);
repo.commit("add an untested arm");
let reported = uncovered(&repo, &base);
assert!(
reported.contains(&"src/lib.rs:5".to_string()),
"the uncovered new line should be reported; got: {reported:?}"
);
}
#[test]
fn rust_covered_change_is_clean() {
let repo = TempRepo::new("covered");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write("src/lib.rs", WIDGET_RS_COVERED_EDIT);
repo.commit("reword a covered line and update its test");
assert!(
uncovered(&repo, &base).is_empty(),
"a change to a covered line is clean"
);
}
#[test]
fn a_change_touching_no_rust_is_clean() {
let repo = TempRepo::new("no-rs");
repo.write("src/lib.rs", WIDGET_RS);
repo.write("README.md", "# project\n");
repo.commit("base");
let base = repo.head();
repo.write("README.md", "# project\n\nnow with docs\n");
repo.commit("docs only");
assert!(
uncovered(&repo, &base).is_empty(),
"a change that touches no Rust source is clean"
);
}
#[test]
fn rust_added_untested_file_changed_lines_are_uncovered() {
let repo = TempRepo::new("added");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write("src/lib.rs", &format!("{WIDGET_RS}pub mod extra;\n"));
repo.write("src/extra.rs", "pub fn extra() -> i64 {\n 41\n}\n");
repo.commit("add a brand-new untested module");
let reported = uncovered(&repo, &base);
assert!(
reported.iter().any(|r| r.starts_with("src/extra.rs:")),
"the added file's uncovered lines should be reported; got: {reported:?}"
);
}
#[test]
fn rust_changed_comment_line_is_not_a_subject() {
let repo = TempRepo::new("comment");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write(
"src/lib.rs",
r#"// classify the sign of n
pub fn widget(n: i64) -> &'static str {
if n > 0 {
"pos"
} else {
"neg"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn covers_both_arms() {
assert_eq!(widget(1), "pos");
assert_eq!(widget(-1), "neg");
}
}
"#,
);
repo.commit("add an explanatory comment");
assert!(
uncovered(&repo, &base).is_empty(),
"a changed comment line has nothing to cover"
);
}
#[test]
fn an_unknown_base_ref_is_an_error() {
let repo = TempRepo::new("bad-base");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
assert!(
check_rust(&repo.0, "no-such-ref", &[]).is_err(),
"an unresolvable base ref must error"
);
}
#[test]
fn rust_subcommand_exits_nonzero_on_an_uncovered_changed_line() {
let repo = TempRepo::new("cli-red");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write("src/lib.rs", WIDGET_RS_UNCOVERED);
repo.commit("add an untested arm");
assert_eq!(run_patch_coverage(&repo, &base, None).unwrap(), 1);
}
#[test]
fn rust_subcommand_exits_zero_when_the_change_is_covered() {
let repo = TempRepo::new("cli-clean");
repo.write("src/lib.rs", WIDGET_RS);
repo.commit("base");
let base = repo.head();
repo.write("src/lib.rs", WIDGET_RS_COVERED_EDIT);
repo.commit("reword a covered line and update its test");
assert_eq!(run_patch_coverage(&repo, &base, None).unwrap(), 0);
}
#[test]
fn rust_a_coverage_exemption_lifts_an_uncovered_changed_line() {
let repo = TempRepo::new("exempt");
repo.write(
"testing-conventions.toml",
"[[rust.exempt]]\npath = \"src/shim.rs\"\nrules = [\"coverage\"]\n\
reason = \"thin launcher; logic lives in tested modules\"\n",
);
repo.write("src/lib.rs", &format!("{WIDGET_RS}pub mod shim;\n"));
repo.write("src/shim.rs", "pub fn shim() -> i64 {\n 0\n}\n");
repo.commit("base");
let base = repo.head();
repo.write("src/shim.rs", "pub fn shim() -> i64 {\n 1\n}\n");
repo.commit("edit the untested launcher");
assert_eq!(run_patch_coverage(&repo, &base, None).unwrap(), 1);
assert_eq!(
run_patch_coverage(&repo, &base, Some("testing-conventions.toml")).unwrap(),
0
);
}