1use std::collections::{BTreeMap, BTreeSet};
19use std::ffi::OsString;
20use std::path::{Path, PathBuf};
21use std::process::{Command, Output};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use anyhow::{bail, Context, Result};
25use serde::Deserialize;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Survivor {
30 pub file: String,
32 pub line: u32,
34 pub description: String,
36}
37
38pub type MutatedLines = BTreeSet<(String, u32)>;
42
43#[derive(Debug, Clone, Deserialize)]
46pub struct MutantsReport {
47 pub outcomes: Vec<MutantOutcome>,
48}
49
50#[derive(Debug, Clone, Deserialize)]
54pub struct MutantOutcome {
55 pub summary: String,
56 pub scenario: Scenario,
57}
58
59#[derive(Debug, Clone, Deserialize)]
62pub enum Scenario {
63 Baseline,
64 Mutant(MutantInfo),
65}
66
67#[derive(Debug, Clone, Deserialize)]
71pub struct MutantInfo {
72 pub file: String,
73 pub span: Span,
74 pub name: String,
75}
76
77#[derive(Debug, Clone, Deserialize)]
79pub struct Span {
80 pub start: LineCol,
81}
82
83#[derive(Debug, Clone, Deserialize)]
85pub struct LineCol {
86 pub line: u32,
87}
88
89pub fn parse_mutants_report(json: &str) -> Result<MutantsReport> {
91 serde_json::from_str(json).context("parsing cargo-mutants outcomes.json")
92}
93
94pub fn unexplained_survivors(report: &MutantsReport, exempt: &[String]) -> Vec<Survivor> {
103 evaluate(cargo_mutants_survivors(report), exempt)
104}
105
106fn cargo_mutants_survivors(report: &MutantsReport) -> Vec<Survivor> {
110 report
111 .outcomes
112 .iter()
113 .filter_map(|outcome| {
114 if outcome.summary != "MissedMutant" {
115 return None;
116 }
117 let Scenario::Mutant(mutant) = &outcome.scenario else {
118 return None;
119 };
120 Some(Survivor {
121 file: mutant.file.clone(),
122 line: mutant.span.start.line,
123 description: mutant.name.clone(),
124 })
125 })
126 .collect()
127}
128
129pub fn mutated_lines(report: &MutantsReport) -> MutatedLines {
135 report
136 .outcomes
137 .iter()
138 .filter_map(|outcome| {
139 if outcome.summary != "CaughtMutant" && outcome.summary != "MissedMutant" {
140 return None;
141 }
142 let Scenario::Mutant(mutant) = &outcome.scenario else {
143 return None;
144 };
145 Some((mutant.file.clone(), mutant.span.start.line))
146 })
147 .collect()
148}
149
150pub fn evaluate(survivors: Vec<Survivor>, exempt: &[String]) -> Vec<Survivor> {
155 survivors
156 .into_iter()
157 .filter(|survivor| !exempt.iter().any(|path| path == &survivor.file))
158 .collect()
159}
160
161pub fn evaluate_scoped(
173 survivors: Vec<Survivor>,
174 mutated: &MutatedLines,
175 whole_file: &[String],
176 line_scoped: &BTreeMap<String, BTreeSet<u32>>,
177) -> Result<Vec<Survivor>> {
178 let mut over: Vec<String> = Vec::new();
179 for (file, lines) in line_scoped {
180 for &line in lines {
181 let has_survivor = survivors
182 .iter()
183 .any(|survivor| survivor.file == *file && survivor.line == line);
184 if has_survivor {
185 continue;
186 }
187 if mutated.contains(&(file.clone(), line)) {
188 over.push(format!("\n {file}:{line}"));
189 }
190 }
191 }
192 if !over.is_empty() {
193 bail!(
194 "a line-scoped mutation exemption may only list a line with a surviving mutant, but \
195 these had mutants that were all caught:{}",
196 over.concat()
197 );
198 }
199 Ok(survivors
200 .into_iter()
201 .filter(|survivor| {
202 let whole = whole_file.iter().any(|path| path == &survivor.file);
203 let line = line_scoped
204 .get(&survivor.file)
205 .is_some_and(|lines| lines.contains(&survivor.line));
206 !(whole || line)
207 })
208 .collect())
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
217#[serde(rename_all = "snake_case")]
218pub enum MutantStatus {
219 Survived,
221 Killed,
223 NoCoverage,
225 Timeout,
227 CompileError,
229 RuntimeError,
231}
232
233impl MutantStatus {
234 fn is_survivor(self) -> bool {
237 matches!(self, MutantStatus::Survived | MutantStatus::NoCoverage)
238 }
239
240 fn is_viable(self) -> bool {
245 matches!(
246 self,
247 MutantStatus::Survived
248 | MutantStatus::Killed
249 | MutantStatus::NoCoverage
250 | MutantStatus::Timeout
251 )
252 }
253}
254
255#[derive(Debug, Clone, Deserialize)]
258pub struct NormalizedMutant {
259 pub file: String,
261 pub line: u32,
263 pub status: MutantStatus,
265 pub mutator: String,
267 #[serde(default)]
269 pub replacement: Option<String>,
270}
271
272pub fn parse_normalized_results(json: &str) -> Result<Vec<NormalizedMutant>> {
275 serde_json::from_str(json).context("parsing normalized mutation results")
276}
277
278pub fn evaluate_normalized(
286 mutants: &[NormalizedMutant],
287 whole_file: &[String],
288 line_scoped: &BTreeMap<String, BTreeSet<u32>>,
289) -> Result<Vec<Survivor>> {
290 evaluate_scoped(
291 normalized_survivors(mutants),
292 &normalized_mutated_lines(mutants),
293 whole_file,
294 line_scoped,
295 )
296}
297
298fn normalized_survivors(mutants: &[NormalizedMutant]) -> Vec<Survivor> {
300 mutants
301 .iter()
302 .filter(|mutant| mutant.status.is_survivor())
303 .map(|mutant| Survivor {
304 file: mutant.file.clone(),
305 line: mutant.line,
306 description: describe_normalized(mutant),
307 })
308 .collect()
309}
310
311fn normalized_mutated_lines(mutants: &[NormalizedMutant]) -> MutatedLines {
314 mutants
315 .iter()
316 .filter(|mutant| mutant.status.is_viable())
317 .map(|mutant| (mutant.file.clone(), mutant.line))
318 .collect()
319}
320
321fn describe_normalized(mutant: &NormalizedMutant) -> String {
324 match &mutant.replacement {
325 Some(replacement) => format!("{} (-> {})", mutant.mutator, one_line(replacement)),
326 None => mutant.mutator.clone(),
327 }
328}
329
330pub fn measure_rust(
338 root: &Path,
339 exempt: &[String],
340 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
341 base: Option<&str>,
342 features: &[String],
343) -> Result<Vec<Survivor>> {
344 let out = MutantsOut::new();
345 let diff = match base {
346 Some(base) => match write_base_diff(root, base, &out)? {
349 None => return Ok(Vec::new()),
350 Some(path) => Some(path),
351 },
352 None => None,
353 };
354 let engine = ensure_cargo_mutants()?;
355 run_cargo_mutants(&engine, root, &out.0, diff.as_deref(), features)?;
356 let outcomes = out.0.join("mutants.out").join("outcomes.json");
357 let json = match std::fs::read_to_string(&outcomes) {
361 Ok(json) => json,
362 Err(_) => return Ok(Vec::new()),
363 };
364 let report = parse_mutants_report(&json)?;
365 evaluate_scoped(
366 cargo_mutants_survivors(&report),
367 &mutated_lines(&report),
368 exempt,
369 exempt_lines,
370 )
371}
372
373fn one_line(replacement: &str) -> String {
376 let flat = replacement.split_whitespace().collect::<Vec<_>>().join(" ");
377 const MAX: usize = 60;
378 if flat.chars().count() > MAX {
379 format!("{}…", flat.chars().take(MAX).collect::<String>())
380 } else {
381 flat
382 }
383}
384
385pub fn measure_typescript(
404 root: &Path,
405 exempt: &[String],
406 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
407 base: Option<&str>,
408 adapter: &Path,
409) -> Result<Vec<Survivor>> {
410 let mutate = match base {
411 Some(base) => {
412 let ranges = mutate_ranges(root, base)?;
413 if ranges.is_empty() {
415 return Ok(Vec::new());
416 }
417 Some(ranges)
418 }
419 None => None,
420 };
421 let json = run_ts_adapter(root, adapter, mutate.as_deref())?;
422 let mutants = parse_normalized_results(&json)?;
423 evaluate_normalized(&mutants, exempt, exempt_lines)
424}
425
426fn run_ts_adapter(root: &Path, adapter: &Path, mutate: Option<&[String]>) -> Result<String> {
437 let out = AdapterOut::new();
438 std::fs::create_dir_all(&out.0).context("creating the mutation adapter output dir")?;
439 let results = out.0.join("results.json");
440
441 let mut command = Command::new("node");
442 command
443 .current_dir(root)
444 .arg(adapter)
445 .arg("--out")
446 .arg(&results);
447 if let Some(specs) = mutate {
448 command.arg("--mutate").arg(specs.join(","));
449 }
450 let output = command
451 .output()
452 .context("running the TypeScript mutation adapter (is `node` installed?)")?;
453 if !output.status.success() {
454 bail!(
455 "the TypeScript mutation adapter failed in `{}`:\n{}{}",
456 root.display(),
457 String::from_utf8_lossy(&output.stdout),
458 String::from_utf8_lossy(&output.stderr),
459 );
460 }
461 std::fs::read_to_string(&results).with_context(|| {
462 format!(
463 "reading the TypeScript mutation adapter's results from `{}`",
464 results.display()
465 )
466 })
467}
468
469struct AdapterOut(PathBuf);
472
473impl AdapterOut {
474 fn new() -> Self {
475 static COUNTER: AtomicU64 = AtomicU64::new(0);
476 let name = format!(
477 "testing-conventions-ts-adapter-{}-{}",
478 std::process::id(),
479 COUNTER.fetch_add(1, Ordering::Relaxed),
480 );
481 AdapterOut(std::env::temp_dir().join(name))
482 }
483}
484
485impl Drop for AdapterOut {
486 fn drop(&mut self) {
487 let _ = std::fs::remove_dir_all(&self.0);
488 }
489}
490
491fn mutate_ranges(root: &Path, base: &str) -> Result<Vec<String>> {
497 let changed = crate::patch_coverage::changed_lines(root, base)?;
498 let mut specs = Vec::new();
499 for (file, lines) in changed {
500 if !is_mutatable_ts(&file) {
501 continue;
502 }
503 for (start, end) in contiguous_runs(&lines) {
504 specs.push(format!("{file}:{start}-{end}"));
505 }
506 }
507 Ok(specs)
508}
509
510fn is_mutatable_ts(file: &str) -> bool {
514 let is_source = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
515 .iter()
516 .any(|ext| file.ends_with(ext));
517 let is_decl = file.ends_with(".d.ts");
518 let is_test = file.contains(".test.") || file.contains(".spec.");
519 is_source && !is_decl && !is_test
520}
521
522fn contiguous_runs(lines: &BTreeSet<u64>) -> Vec<(u64, u64)> {
524 let mut runs: Vec<(u64, u64)> = Vec::new();
525 for &line in lines {
526 match runs.last_mut() {
527 Some(run) if run.1 + 1 == line => run.1 = line,
528 _ => runs.push((line, line)),
529 }
530 }
531 runs
532}
533
534pub fn measure_python(
552 root: &Path,
553 exempt: &[String],
554 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
555 base: Option<&str>,
556) -> Result<Vec<Survivor>> {
557 let changed = match base {
558 Some(base) => Some(crate::patch_coverage::changed_lines(root, base)?),
559 None => None,
560 };
561 let modules: Vec<String> = match &changed {
562 None => Vec::new(),
563 Some(changed) => {
564 let modules: Vec<String> = changed
565 .keys()
566 .filter(|file| is_mutatable_py(file))
567 .cloned()
568 .collect();
569 if modules.is_empty() {
571 return Ok(Vec::new());
572 }
573 modules
574 }
575 };
576 let json = run_py_adapter(root, &modules)?;
577 let mut mutants = parse_normalized_results(&json)?;
578 if let Some(changed) = &changed {
579 mutants.retain(|mutant| {
581 changed
582 .get(&mutant.file)
583 .is_some_and(|lines| lines.contains(&u64::from(mutant.line)))
584 });
585 }
586 evaluate_normalized(&mutants, exempt, exempt_lines)
587}
588
589fn run_py_adapter(root: &Path, modules: &[String]) -> Result<String> {
597 let out = AdapterOut::new();
598 std::fs::create_dir_all(&out.0).context("creating the mutation adapter output dir")?;
599 let results = out.0.join("results.json");
600
601 let mut command = Command::new("python3");
602 command
603 .current_dir(root)
604 .args(["-m", "testing_conventions.mutation.main", "--out"])
605 .arg(&results)
606 .env("PYTHONDONTWRITEBYTECODE", "1");
607 for module in modules {
608 command.arg("--module").arg(module);
609 }
610 let output = command
611 .output()
612 .context("running the Python mutation adapter (is `python3` installed?)")?;
613 if !output.status.success() {
614 bail!(
615 "the Python mutation adapter failed in `{}`:\n{}{}",
616 root.display(),
617 String::from_utf8_lossy(&output.stdout),
618 String::from_utf8_lossy(&output.stderr),
619 );
620 }
621 std::fs::read_to_string(&results).with_context(|| {
622 format!(
623 "reading the Python mutation adapter's results from `{}`",
624 results.display()
625 )
626 })
627}
628
629fn is_mutatable_py(file: &str) -> bool {
632 if !file.ends_with(".py") {
633 return false;
634 }
635 let base = file.rsplit('/').next().unwrap_or(file);
636 !(base.ends_with("_test.py") || base.starts_with("test_") || base == "conftest.py")
637}
638
639struct MutantsOut(PathBuf);
642
643impl MutantsOut {
644 fn new() -> Self {
645 static COUNTER: AtomicU64 = AtomicU64::new(0);
646 let name = format!(
647 "testing-conventions-mutants-{}-{}",
648 std::process::id(),
649 COUNTER.fetch_add(1, Ordering::Relaxed),
650 );
651 MutantsOut(std::env::temp_dir().join(name))
652 }
653}
654
655impl Drop for MutantsOut {
656 fn drop(&mut self) {
657 let _ = std::fs::remove_dir_all(&self.0);
658 }
659}
660
661fn write_base_diff(root: &Path, base: &str, out: &MutantsOut) -> Result<Option<PathBuf>> {
670 let range = format!("{base}...HEAD");
671 let output = Command::new("git")
672 .current_dir(root)
673 .args(["diff", "--relative", &range])
674 .output()
675 .context("running `git diff` for `--base` (is git installed?)")?;
676 if !output.status.success() {
677 bail!(
678 "git diff {range} failed: {}",
679 String::from_utf8_lossy(&output.stderr)
680 );
681 }
682 if output.stdout.is_empty() {
683 return Ok(None);
684 }
685 std::fs::create_dir_all(&out.0).context("creating the mutants output dir")?;
686 let path = out.0.join("base.diff");
687 std::fs::write(&path, &output.stdout).context("writing the base diff")?;
688 Ok(Some(path))
689}
690
691const CARGO_MUTANTS_VERSION: &str = "27.1.0";
694
695fn ensure_cargo_mutants() -> Result<PathBuf> {
705 let root = cargo_mutants_cache_root();
706 let bin = root.join("bin").join(cargo_mutants_bin_name());
707 let lock_path = root.join(".install.lock");
708 provision(&bin, &lock_path, || {
709 run_install(&root, |command| command.output())
710 })
711}
712
713fn cargo_mutants_bin_name() -> &'static str {
716 if cfg!(windows) {
717 "cargo-mutants.exe"
718 } else {
719 "cargo-mutants"
720 }
721}
722
723fn cargo_mutants_cache_root() -> PathBuf {
727 cache_base()
728 .join("testing-conventions")
729 .join(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}"))
730}
731
732fn cache_base() -> PathBuf {
735 resolve_cache_base(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))
736}
737
738fn resolve_cache_base(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
741 if let Some(dir) = xdg.filter(|value| !value.is_empty()) {
742 return PathBuf::from(dir);
743 }
744 if let Some(dir) = home.filter(|value| !value.is_empty()) {
745 return PathBuf::from(dir).join(".cache");
746 }
747 std::env::temp_dir()
748}
749
750fn provision(
765 bin: &Path,
766 lock_path: &Path,
767 install: impl FnOnce() -> Result<()>,
768) -> Result<PathBuf> {
769 if bin.exists() {
770 return Ok(bin.to_path_buf());
771 }
772 if let Some(parent) = lock_path.parent() {
773 std::fs::create_dir_all(parent).context("creating the provisioning lock's parent dir")?;
774 }
775 let lock_file = std::fs::OpenOptions::new()
776 .create(true)
777 .truncate(false)
778 .write(true)
779 .open(lock_path)
780 .context("opening the provisioning lock file")?;
781 lock_file
782 .lock()
783 .context("acquiring the provisioning lock")?;
784 if bin.exists() {
786 return Ok(bin.to_path_buf());
787 }
788 install()?;
789 if !bin.exists() {
790 bail!(
791 "provisioning reported success but cargo-mutants is not at `{}`",
792 bin.display()
793 );
794 }
795 Ok(bin.to_path_buf())
796}
797
798fn install_argv(root: &Path) -> Vec<OsString> {
802 vec![
803 OsString::from("install"),
804 OsString::from("cargo-mutants"),
805 OsString::from("--locked"),
806 OsString::from("--version"),
807 OsString::from(CARGO_MUTANTS_VERSION),
808 OsString::from("--root"),
809 root.as_os_str().to_os_string(),
810 ]
811}
812
813fn run_install(
818 root: &Path,
819 run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
820) -> Result<()> {
821 let mut command = Command::new("cargo");
822 command.args(install_argv(root));
823 strip_llvm_cov_env(&mut command);
824 let output = run(&mut command)
825 .context("provisioning cargo-mutants via `cargo install` (is cargo installed?)")?;
826 if !output.status.success() {
827 bail!(
828 "failed to provision cargo-mutants {CARGO_MUTANTS_VERSION}:\n{}{}",
829 String::from_utf8_lossy(&output.stdout),
830 String::from_utf8_lossy(&output.stderr),
831 );
832 }
833 Ok(())
834}
835
836fn strip_llvm_cov_env(command: &mut Command) {
840 for var in [
841 "RUSTFLAGS",
842 "CARGO_ENCODED_RUSTFLAGS",
843 "RUSTDOCFLAGS",
844 "CARGO_ENCODED_RUSTDOCFLAGS",
845 "LLVM_PROFILE_FILE",
846 "CARGO_LLVM_COV",
847 "CARGO_LLVM_COV_SHOW_ENV",
848 "CARGO_LLVM_COV_TARGET_DIR",
849 "CARGO_LLVM_COV_BUILD_DIR",
850 "RUSTC_WRAPPER",
851 "RUSTC_WORKSPACE_WRAPPER",
852 "__CARGO_LLVM_COV_RUSTC_WRAPPER",
853 "__CARGO_LLVM_COV_RUSTC_WRAPPER_RUSTFLAGS",
854 "__CARGO_LLVM_COV_RUSTC_WRAPPER_CRATE_NAMES",
855 ] {
856 command.env_remove(var);
857 }
858}
859
860fn run_cargo_mutants(
872 engine: &Path,
873 root: &Path,
874 out: &Path,
875 in_diff: Option<&Path>,
876 features: &[String],
877) -> Result<()> {
878 let mut command = Command::new(engine);
879 command
880 .current_dir(root)
881 .arg("mutants")
882 .arg("--output")
883 .arg(out);
884 if let Some(diff) = in_diff {
885 command.arg("--in-diff").arg(diff);
886 }
887 if !features.is_empty() {
888 command.args(["--", "--features"]).arg(features.join(","));
889 }
890 strip_llvm_cov_env(&mut command);
891 let output = command.output().context("running cargo-mutants")?;
892 match output.status.code() {
893 Some(0) | Some(2) => Ok(()),
895 _ => bail!(
896 "cargo-mutants did not run cleanly in `{}` (baseline build/test failure?):\n{}{}",
897 root.display(),
898 String::from_utf8_lossy(&output.stdout),
899 String::from_utf8_lossy(&output.stderr),
900 ),
901 }
902}
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907
908 const NORMALIZED: &str = r#"[
912 {"file": "src/a.ts", "line": 2, "status": "survived",
913 "mutator": "ConditionalExpression", "replacement": "true", "id": "ignored"},
914 {"file": "src/a.ts", "line": 5, "status": "no_coverage", "mutator": "ArithmeticOperator"},
915 {"file": "src/a.ts", "line": 9, "status": "killed",
916 "mutator": "BooleanLiteral", "replacement": "false"},
917 {"file": "src/a.ts", "line": 12, "status": "timeout", "mutator": "BlockStatement"},
918 {"file": "src/a.ts", "line": 15, "status": "compile_error", "mutator": "OptionalChaining"},
919 {"file": "src/a.ts", "line": 18, "status": "runtime_error", "mutator": "StringLiteral"}
920 ]"#;
921
922 #[test]
923 fn parses_the_normalized_schema() {
924 let mutants = parse_normalized_results(NORMALIZED).expect("valid normalized results");
925 assert_eq!(mutants.len(), 6);
926 assert_eq!(mutants[0].status, MutantStatus::Survived);
927 assert_eq!(mutants[1].status, MutantStatus::NoCoverage);
928 assert_eq!(mutants[0].replacement.as_deref(), Some("true"));
929 assert_eq!(mutants[1].replacement, None);
930 }
931
932 #[test]
933 fn normalized_survivors_are_survived_and_nocoverage_only() {
934 let mutants = parse_normalized_results(NORMALIZED).unwrap();
935 let survivors = normalized_survivors(&mutants);
936 assert_eq!(survivors.len(), 2);
938 assert_eq!((survivors[0].line, survivors[1].line), (2, 5));
939 assert!(survivors[0].description.contains("ConditionalExpression"));
941 assert!(survivors[0].description.contains("-> true"));
942 assert_eq!(survivors[1].description, "ArithmeticOperator");
943 }
944
945 #[test]
946 fn normalized_mutated_lines_collects_only_viable_mutants() {
947 let mutants = parse_normalized_results(NORMALIZED).unwrap();
948 assert_eq!(
951 normalized_mutated_lines(&mutants),
952 [2u32, 5, 9, 12]
953 .into_iter()
954 .map(|line| ("src/a.ts".to_string(), line))
955 .collect()
956 );
957 }
958
959 #[test]
960 fn evaluate_normalized_reports_unexempted_survivors() {
961 let mutants = parse_normalized_results(NORMALIZED).unwrap();
962 let kept = evaluate_normalized(&mutants, &[], &BTreeMap::new()).unwrap();
963 assert_eq!(kept.len(), 2, "both survivors stand with no exemptions");
964 }
965
966 #[test]
967 fn evaluate_normalized_drops_a_whole_file_exemption() {
968 let mutants = parse_normalized_results(NORMALIZED).unwrap();
969 let kept =
970 evaluate_normalized(&mutants, &["src/a.ts".to_string()], &BTreeMap::new()).unwrap();
971 assert!(
972 kept.is_empty(),
973 "the whole-file exemption lifts both survivors"
974 );
975 }
976
977 #[test]
978 fn evaluate_normalized_drops_a_line_scoped_exemption() {
979 let mutants = parse_normalized_results(NORMALIZED).unwrap();
980 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([2u32]))]);
981 let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
982 assert_eq!(kept.len(), 1);
984 assert_eq!(kept[0].line, 5);
985 }
986
987 #[test]
988 fn evaluate_normalized_rejects_exempting_a_caught_line() {
989 let mutants = parse_normalized_results(NORMALIZED).unwrap();
992 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([9u32]))]);
993 let err = evaluate_normalized(&mutants, &[], &line_scoped).unwrap_err();
994 assert!(
995 err.to_string().contains("all caught") && err.to_string().contains("src/a.ts:9"),
996 "got: {err}"
997 );
998 }
999
1000 #[test]
1001 fn evaluate_normalized_leaves_an_unviable_listed_line_alone() {
1002 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1005 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([15u32]))]);
1006 let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
1007 assert_eq!(kept.len(), 2);
1008 }
1009
1010 const SAMPLE: &str = r#"{
1013 "outcomes": [
1014 {"scenario": "Baseline", "summary": "Success",
1015 "phase_results": []},
1016 {"scenario": {"Mutant": {"file": "src/lib.rs", "package": "p", "genre": "FnValue",
1017 "replacement": "true", "name": "src/lib.rs:7:7: replace > with == in is_positive",
1018 "function": {"function_name": "is_positive"},
1019 "span": {"start": {"line": 7, "column": 7}, "end": {"line": 7, "column": 8}}}},
1020 "summary": "MissedMutant"},
1021 {"scenario": {"Mutant": {"file": "src/other.rs", "package": "p", "genre": "FnValue",
1022 "replacement": "0", "name": "src/other.rs:3:5: replace add -> i32 with 0",
1023 "span": {"start": {"line": 3, "column": 5}, "end": {"line": 3, "column": 9}}}},
1024 "summary": "CaughtMutant"}
1025 ],
1026 "total_mutants": 2
1027 }"#;
1028
1029 #[test]
1030 fn parses_the_outcomes_export() {
1031 let report = parse_mutants_report(SAMPLE).expect("valid outcomes.json");
1032 assert_eq!(report.outcomes.len(), 3);
1033 assert!(matches!(report.outcomes[0].scenario, Scenario::Baseline));
1034 }
1035
1036 #[test]
1037 fn collects_only_missed_mutants_as_survivors() {
1038 let report = parse_mutants_report(SAMPLE).unwrap();
1039 let survivors = unexplained_survivors(&report, &[]);
1040 assert_eq!(survivors.len(), 1);
1042 assert_eq!(survivors[0].file, "src/lib.rs");
1043 assert_eq!(survivors[0].line, 7);
1044 assert!(survivors[0].description.contains("replace > with =="));
1045 }
1046
1047 #[test]
1048 fn an_exemption_drops_a_survivor_in_that_file() {
1049 let report = parse_mutants_report(SAMPLE).unwrap();
1050 let exempt = vec!["src/lib.rs".to_string()];
1051 assert!(unexplained_survivors(&report, &exempt).is_empty());
1052 }
1053
1054 #[test]
1055 fn an_exemption_on_another_file_leaves_the_survivor() {
1056 let report = parse_mutants_report(SAMPLE).unwrap();
1057 let exempt = vec!["src/elsewhere.rs".to_string()];
1058 assert_eq!(unexplained_survivors(&report, &exempt).len(), 1);
1059 }
1060
1061 #[test]
1062 fn is_mutatable_ts_keeps_sources_and_drops_tests_and_decls() {
1063 assert!(is_mutatable_ts("src/index.ts"));
1064 assert!(is_mutatable_ts("src/util.tsx"));
1065 assert!(is_mutatable_ts("src/util.js"));
1066 assert!(!is_mutatable_ts("src/index.test.ts"));
1067 assert!(!is_mutatable_ts("src/index.spec.ts"));
1068 assert!(!is_mutatable_ts("src/types.d.ts"));
1069 assert!(!is_mutatable_ts("README.md"));
1070 }
1071
1072 #[test]
1073 fn contiguous_runs_collapses_adjacent_lines() {
1074 let lines: BTreeSet<u64> = [2u64, 3, 4, 7, 9, 10].into_iter().collect();
1075 assert_eq!(contiguous_runs(&lines), vec![(2, 4), (7, 7), (9, 10)]);
1076 assert!(contiguous_runs(&BTreeSet::new()).is_empty());
1077 }
1078
1079 #[test]
1080 fn one_line_flattens_and_caps() {
1081 assert_eq!(one_line("a -\n b"), "a - b");
1082 let long = "x".repeat(80);
1083 let capped = one_line(&long);
1084 assert!(capped.chars().count() <= 61 && capped.ends_with('…'));
1085 }
1086
1087 #[test]
1088 fn is_mutatable_py_keeps_sources_and_drops_tests() {
1089 assert!(is_mutatable_py("calc.py"));
1090 assert!(is_mutatable_py("pkg/util.py"));
1091 assert!(!is_mutatable_py("calc_test.py"));
1092 assert!(!is_mutatable_py("test_calc.py"));
1093 assert!(!is_mutatable_py("pkg/conftest.py"));
1094 assert!(!is_mutatable_py("README.md"));
1095 }
1096
1097 #[test]
1098 fn mutated_lines_collects_caught_and_missed() {
1099 let report = parse_mutants_report(SAMPLE).unwrap();
1102 assert_eq!(
1103 mutated_lines(&report),
1104 [
1105 ("src/lib.rs".to_string(), 7),
1106 ("src/other.rs".to_string(), 3)
1107 ]
1108 .into_iter()
1109 .collect()
1110 );
1111 }
1112
1113 #[test]
1114 fn evaluate_scoped_drops_a_survivor_on_an_exempt_line() {
1115 let report = parse_mutants_report(SAMPLE).unwrap();
1116 let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([7u32]))]);
1117 let kept = evaluate_scoped(
1118 cargo_mutants_survivors(&report),
1119 &mutated_lines(&report),
1120 &[],
1121 &line_scoped,
1122 )
1123 .unwrap();
1124 assert!(
1125 kept.is_empty(),
1126 "the src/lib.rs:7 survivor should be lifted"
1127 );
1128 }
1129
1130 #[test]
1131 fn evaluate_scoped_rejects_exempting_a_caught_line() {
1132 let report = parse_mutants_report(SAMPLE).unwrap();
1134 let line_scoped = BTreeMap::from([("src/other.rs".to_string(), BTreeSet::from([3u32]))]);
1135 let err = evaluate_scoped(
1136 cargo_mutants_survivors(&report),
1137 &mutated_lines(&report),
1138 &[],
1139 &line_scoped,
1140 )
1141 .unwrap_err();
1142 assert!(
1143 err.to_string().contains("all caught") && err.to_string().contains("src/other.rs:3"),
1144 "got: {err}"
1145 );
1146 }
1147
1148 #[test]
1149 fn evaluate_scoped_leaves_an_unmutated_listed_line_alone() {
1150 let report = parse_mutants_report(SAMPLE).unwrap();
1153 let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([99u32]))]);
1154 let kept = evaluate_scoped(
1155 cargo_mutants_survivors(&report),
1156 &mutated_lines(&report),
1157 &[],
1158 &line_scoped,
1159 )
1160 .unwrap();
1161 assert_eq!(kept.len(), 1);
1162 assert_eq!(kept[0].line, 7);
1163 }
1164
1165 #[test]
1166 fn evaluate_scoped_still_honors_a_whole_file_exemption() {
1167 let report = parse_mutants_report(SAMPLE).unwrap();
1168 let kept = evaluate_scoped(
1169 cargo_mutants_survivors(&report),
1170 &mutated_lines(&report),
1171 &["src/lib.rs".to_string()],
1172 &BTreeMap::new(),
1173 )
1174 .unwrap();
1175 assert!(kept.is_empty());
1176 }
1177
1178 fn unique_tmp() -> PathBuf {
1179 static COUNTER: AtomicU64 = AtomicU64::new(0);
1180 let dir = std::env::temp_dir().join(format!(
1181 "tc-provision-test-{}-{}",
1182 std::process::id(),
1183 COUNTER.fetch_add(1, Ordering::Relaxed)
1184 ));
1185 std::fs::create_dir_all(&dir).unwrap();
1186 dir
1187 }
1188
1189 #[test]
1190 fn provision_returns_an_existing_binary_without_installing() {
1191 let tmp = unique_tmp();
1192 let bin = tmp.join("bin").join("cargo-mutants");
1193 let lock = tmp.join(".install.lock");
1194 std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
1195 std::fs::write(&bin, b"binary").unwrap();
1196 let mut installed = false;
1197 let got = provision(&bin, &lock, || {
1198 installed = true;
1199 Ok(())
1200 })
1201 .unwrap();
1202 assert_eq!(got, bin);
1203 assert!(!installed, "a present binary must not be reinstalled");
1204 std::fs::remove_dir_all(&tmp).unwrap();
1205 }
1206
1207 #[test]
1208 fn provision_installs_when_the_binary_is_absent() {
1209 let tmp = unique_tmp();
1210 let bin = tmp.join("bin").join("cargo-mutants");
1211 let lock = tmp.join(".install.lock");
1212 let mut installed = false;
1213 let got = provision(&bin, &lock, || {
1214 installed = true;
1215 std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
1216 std::fs::write(&bin, b"binary").unwrap();
1217 Ok(())
1218 })
1219 .unwrap();
1220 assert!(installed, "an absent binary must be installed");
1221 assert_eq!(got, bin);
1222 std::fs::remove_dir_all(&tmp).unwrap();
1223 }
1224
1225 #[test]
1226 fn provision_errors_when_install_produces_no_binary() {
1227 let tmp = unique_tmp();
1228 let bin = tmp.join("bin").join("cargo-mutants");
1229 let lock = tmp.join(".install.lock");
1230 let err = provision(&bin, &lock, || Ok(())).unwrap_err();
1231 assert!(
1232 err.to_string().contains("cargo-mutants is not at"),
1233 "got: {err}"
1234 );
1235 std::fs::remove_dir_all(&tmp).unwrap();
1236 }
1237
1238 #[test]
1239 fn provision_propagates_an_install_failure() {
1240 let tmp = unique_tmp();
1241 let bin = tmp.join("bin").join("cargo-mutants");
1242 let lock = tmp.join(".install.lock");
1243 let err = provision(&bin, &lock, || bail!("install blew up")).unwrap_err();
1244 assert!(err.to_string().contains("install blew up"), "got: {err}");
1245 std::fs::remove_dir_all(&tmp).unwrap();
1246 }
1247
1248 #[test]
1249 fn provision_does_not_duplicate_the_install_under_concurrent_callers() {
1250 use std::sync::{Arc, Barrier};
1257 use std::thread;
1258 use std::time::Duration;
1259
1260 let tmp = unique_tmp();
1261 let bin = tmp.join("bin").join("cargo-mutants");
1262 let lock = tmp.join(".install.lock");
1263 let install_count = Arc::new(AtomicU64::new(0));
1264 let barrier = Arc::new(Barrier::new(2));
1265
1266 let handles: Vec<_> = (0..2)
1267 .map(|_| {
1268 let bin = bin.clone();
1269 let lock = lock.clone();
1270 let install_count = Arc::clone(&install_count);
1271 let barrier = Arc::clone(&barrier);
1272 thread::spawn(move || {
1273 barrier.wait();
1274 provision(&bin, &lock, || {
1275 install_count.fetch_add(1, Ordering::SeqCst);
1276 thread::sleep(Duration::from_millis(50));
1277 std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
1278 std::fs::write(&bin, b"binary").unwrap();
1279 Ok(())
1280 })
1281 })
1282 })
1283 .collect();
1284
1285 for h in handles {
1286 h.join()
1287 .expect("provisioning thread must not panic")
1288 .unwrap();
1289 }
1290
1291 assert_eq!(
1292 install_count.load(Ordering::SeqCst),
1293 1,
1294 "two concurrent callers on a cold cache must share one install, not each run their own"
1295 );
1296 std::fs::remove_dir_all(&tmp).unwrap();
1297 }
1298
1299 #[test]
1300 fn resolve_cache_base_prefers_xdg_then_home_then_temp() {
1301 let xdg = |s: &str| Some(OsString::from(s));
1302 assert_eq!(
1304 resolve_cache_base(xdg("/xdg"), xdg("/home")),
1305 PathBuf::from("/xdg")
1306 );
1307 assert_eq!(
1309 resolve_cache_base(xdg(""), xdg("/home")),
1310 PathBuf::from("/home/.cache")
1311 );
1312 assert_eq!(
1314 resolve_cache_base(None, xdg("/home")),
1315 PathBuf::from("/home/.cache")
1316 );
1317 assert_eq!(resolve_cache_base(None, None), std::env::temp_dir());
1319 assert_eq!(
1320 resolve_cache_base(xdg(""), Some(OsString::new())),
1321 std::env::temp_dir()
1322 );
1323 }
1324
1325 #[test]
1326 fn cache_root_is_absolute_and_version_scoped() {
1327 let root = cargo_mutants_cache_root();
1328 assert!(
1329 root.ends_with(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}")),
1330 "version-scoped; got {root:?}"
1331 );
1332 assert!(
1333 root.to_string_lossy().contains("testing-conventions"),
1334 "tool-namespaced; got {root:?}"
1335 );
1336 assert!(
1338 root.is_absolute(),
1339 "expected an absolute path; got {root:?}"
1340 );
1341 }
1342
1343 #[test]
1344 fn install_argv_pins_the_version_and_isolates_the_root() {
1345 let argv: Vec<String> = install_argv(Path::new("/cache/cargo-mutants-27"))
1346 .iter()
1347 .map(|arg| arg.to_string_lossy().into_owned())
1348 .collect();
1349 assert_eq!(
1350 argv,
1351 vec![
1352 "install",
1353 "cargo-mutants",
1354 "--locked",
1355 "--version",
1356 CARGO_MUTANTS_VERSION,
1357 "--root",
1358 "/cache/cargo-mutants-27",
1359 ]
1360 );
1361 }
1362
1363 #[cfg(unix)]
1364 fn fake_output(code: i32, stderr: &str) -> Output {
1365 use std::os::unix::process::ExitStatusExt;
1366 Output {
1367 status: std::process::ExitStatus::from_raw(code << 8),
1368 stdout: Vec::new(),
1369 stderr: stderr.as_bytes().to_vec(),
1370 }
1371 }
1372
1373 #[cfg(unix)]
1374 #[test]
1375 fn run_install_succeeds_on_a_zero_exit() {
1376 let mut ran = false;
1377 run_install(Path::new("/cache/root"), |command| {
1378 ran = true;
1379 let argv: Vec<String> = command
1381 .get_args()
1382 .map(|arg| arg.to_string_lossy().into_owned())
1383 .collect();
1384 assert!(argv.contains(&CARGO_MUTANTS_VERSION.to_string()));
1385 Ok(fake_output(0, ""))
1386 })
1387 .unwrap();
1388 assert!(ran);
1389 }
1390
1391 #[cfg(unix)]
1392 #[test]
1393 fn run_install_reports_a_nonzero_exit_with_the_engine_output() {
1394 let err = run_install(Path::new("/cache/root"), |_| {
1395 Ok(fake_output(1, "error: could not compile cargo-mutants"))
1396 })
1397 .unwrap_err();
1398 assert!(
1399 err.to_string()
1400 .contains("failed to provision cargo-mutants")
1401 && err.to_string().contains("could not compile"),
1402 "got: {err}"
1403 );
1404 }
1405
1406 #[cfg(unix)]
1407 #[test]
1408 fn run_install_propagates_a_spawn_failure() {
1409 let err = run_install(Path::new("/cache/root"), |_| {
1410 Err(std::io::Error::new(
1411 std::io::ErrorKind::NotFound,
1412 "no cargo",
1413 ))
1414 })
1415 .unwrap_err();
1416 assert!(
1417 err.to_string().contains("is cargo installed?"),
1418 "got: {err}"
1419 );
1420 }
1421
1422 #[test]
1423 fn cargo_mutants_bin_name_matches_the_platform() {
1424 let name = cargo_mutants_bin_name();
1425 if cfg!(windows) {
1426 assert_eq!(name, "cargo-mutants.exe");
1427 } else {
1428 assert_eq!(name, "cargo-mutants");
1429 }
1430 }
1431}