1use std::collections::{BTreeMap, BTreeSet};
6use std::ffi::OsString;
7use std::path::{Path, PathBuf};
8use std::process::{Command, Output};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use anyhow::{bail, Context, Result};
12use serde::Deserialize;
13
14use crate::colocated_test::Language;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Survivor {
19 pub file: String,
22 pub line: u32,
24 pub description: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Measurement {
33 EngineNotRun,
35 Tested {
38 count: usize,
39 survivors: Vec<Survivor>,
40 },
41}
42
43pub type MutatedLines = BTreeSet<(String, u32)>;
47
48fn is_declaration_only(base: &Path, file: &str, language: Language) -> bool {
52 match std::fs::read_to_string(base.join(file)) {
53 Ok(source) => !language.is_subject(&source, Path::new(file)),
54 Err(_) => false,
55 }
56}
57
58fn is_hidden_from_tests(base: &Path, file: &str, line: u32) -> bool {
62 let source = std::fs::read_to_string(base.join(file)).unwrap_or_default();
63 crate::isolation::lines_hidden_from_tests(&source).contains(&line)
64}
65
66fn is_subprocess_seam(base: &Path, mutant: &MutantInfo) -> bool {
70 if mutant.genre != "FnValue" {
71 return false;
72 }
73 let source = std::fs::read_to_string(base.join(&mutant.file)).unwrap_or_default();
74 crate::subprocess_seam::subprocess_seam_lines(&source).contains(&mutant.span.start.line)
75}
76
77fn is_judged(base: &Path, mutant: &MutantInfo) -> bool {
81 !is_declaration_only(base, &mutant.file, Language::Rust)
82 && !is_hidden_from_tests(base, &mutant.file, mutant.span.start.line)
83 && !is_subprocess_seam(base, mutant)
84}
85
86#[derive(Debug, Clone, Deserialize)]
89pub struct MutantsReport {
90 pub outcomes: Vec<MutantOutcome>,
91}
92
93#[derive(Debug, Clone, Deserialize)]
97pub struct MutantOutcome {
98 pub summary: String,
99 pub scenario: Scenario,
100}
101
102#[derive(Debug, Clone, Deserialize)]
105pub enum Scenario {
106 Baseline,
107 Mutant(MutantInfo),
108}
109
110#[derive(Debug, Clone, Deserialize)]
114pub struct MutantInfo {
115 pub file: String,
116 pub span: Span,
117 pub name: String,
118 pub genre: String,
119}
120
121#[derive(Debug, Clone, Deserialize)]
123pub struct Span {
124 pub start: LineCol,
125 pub end: LineCol,
126}
127
128#[derive(Debug, Clone, Deserialize)]
130pub struct LineCol {
131 pub line: u32,
132}
133
134pub fn parse_mutants_report(json: &str) -> Result<MutantsReport> {
136 serde_json::from_str(json).context("parsing cargo-mutants outcomes.json")
137}
138
139fn parse_mutants_list(json: &str) -> Result<Vec<MutantInfo>> {
142 serde_json::from_str(json).context("parsing the cargo-mutants mutant list")
143}
144
145pub fn unexplained_survivors(report: &MutantsReport, exempt: &[String]) -> Vec<Survivor> {
149 evaluate(cargo_mutants_survivors(report), exempt)
150}
151
152fn cargo_mutants_survivors(report: &MutantsReport) -> Vec<Survivor> {
156 report
157 .outcomes
158 .iter()
159 .filter_map(|outcome| {
160 if outcome.summary != "MissedMutant" {
161 return None;
162 }
163 let Scenario::Mutant(mutant) = &outcome.scenario else {
164 return None;
165 };
166 Some(Survivor {
167 file: mutant.file.clone(),
168 line: mutant.span.start.line,
169 description: strip_embedded_location(&mutant.name).to_string(),
170 })
171 })
172 .collect()
173}
174
175fn strip_embedded_location(name: &str) -> &str {
178 let Some((location, description)) = name.split_once(": ") else {
179 return name;
180 };
181 let mut parts = location.rsplitn(3, ':');
182 let numeric = |part: Option<&str>| part.is_some_and(|p| p.parse::<u32>().is_ok());
183 if numeric(parts.next()) && numeric(parts.next()) && parts.next().is_some() {
184 description
185 } else {
186 name
187 }
188}
189
190pub fn mutated_lines(report: &MutantsReport) -> MutatedLines {
194 report
195 .outcomes
196 .iter()
197 .filter_map(|outcome| {
198 if outcome.summary != "CaughtMutant" && outcome.summary != "MissedMutant" {
199 return None;
200 }
201 let Scenario::Mutant(mutant) = &outcome.scenario else {
202 return None;
203 };
204 Some((mutant.file.clone(), mutant.span.start.line))
205 })
206 .collect()
207}
208
209fn conclusive_count(report: &MutantsReport) -> usize {
213 report
214 .outcomes
215 .iter()
216 .filter(|outcome| outcome.summary == "CaughtMutant" || outcome.summary == "MissedMutant")
217 .count()
218}
219
220pub fn evaluate(survivors: Vec<Survivor>, exempt: &[String]) -> Vec<Survivor> {
223 survivors
224 .into_iter()
225 .filter(|survivor| !exempt.iter().any(|path| path == &survivor.file))
226 .collect()
227}
228
229pub fn evaluate_scoped(
233 survivors: Vec<Survivor>,
234 mutated: &MutatedLines,
235 whole_file: &[String],
236 line_scoped: &BTreeMap<String, BTreeSet<u32>>,
237) -> Result<Vec<Survivor>> {
238 let mut over: Vec<String> = Vec::new();
239 for (file, lines) in line_scoped {
240 for &line in lines {
241 let has_survivor = survivors
242 .iter()
243 .any(|survivor| survivor.file == *file && survivor.line == line);
244 if has_survivor {
245 continue;
246 }
247 if mutated.contains(&(file.clone(), line)) {
248 over.push(format!("\n {file}:{line}"));
249 }
250 }
251 }
252 if !over.is_empty() {
253 bail!(
254 "a line-scoped mutation exemption may only list a line with a surviving mutant, but \
255 these had mutants that were all caught:{}",
256 over.concat()
257 );
258 }
259 Ok(survivors
260 .into_iter()
261 .filter(|survivor| {
262 let whole = whole_file.iter().any(|path| path == &survivor.file);
263 let line = line_scoped
264 .get(&survivor.file)
265 .is_some_and(|lines| lines.contains(&survivor.line));
266 !(whole || line)
267 })
268 .collect())
269}
270
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum MutantStatus {
277 Survived,
279 Killed,
281 NoCoverage,
283 Timeout,
285 CompileError,
287 RuntimeError,
289}
290
291impl MutantStatus {
292 fn is_survivor(self) -> bool {
295 matches!(self, MutantStatus::Survived | MutantStatus::NoCoverage)
296 }
297
298 fn is_viable(self) -> bool {
301 matches!(
302 self,
303 MutantStatus::Survived
304 | MutantStatus::Killed
305 | MutantStatus::NoCoverage
306 | MutantStatus::Timeout
307 )
308 }
309
310 fn is_conclusive(self) -> bool {
314 matches!(
315 self,
316 MutantStatus::Survived | MutantStatus::Killed | MutantStatus::NoCoverage
317 )
318 }
319}
320
321#[derive(Debug, Clone, Deserialize)]
324pub struct NormalizedMutant {
325 pub file: String,
327 pub line: u32,
329 pub status: MutantStatus,
331 pub mutator: String,
333 #[serde(default)]
335 pub replacement: Option<String>,
336}
337
338pub fn parse_normalized_results(json: &str) -> Result<Vec<NormalizedMutant>> {
341 serde_json::from_str(json).context("parsing normalized mutation results")
342}
343
344pub fn evaluate_normalized(
348 mutants: &[NormalizedMutant],
349 whole_file: &[String],
350 line_scoped: &BTreeMap<String, BTreeSet<u32>>,
351) -> Result<Vec<Survivor>> {
352 evaluate_scoped(
353 normalized_survivors(mutants),
354 &normalized_mutated_lines(mutants),
355 whole_file,
356 line_scoped,
357 )
358}
359
360fn normalized_survivors(mutants: &[NormalizedMutant]) -> Vec<Survivor> {
362 mutants
363 .iter()
364 .filter(|mutant| mutant.status.is_survivor())
365 .map(|mutant| Survivor {
366 file: mutant.file.clone(),
367 line: mutant.line,
368 description: describe_normalized(mutant),
369 })
370 .collect()
371}
372
373fn normalized_mutated_lines(mutants: &[NormalizedMutant]) -> MutatedLines {
376 mutants
377 .iter()
378 .filter(|mutant| mutant.status.is_viable())
379 .map(|mutant| (mutant.file.clone(), mutant.line))
380 .collect()
381}
382
383fn normalized_conclusive_count(mutants: &[NormalizedMutant]) -> usize {
386 mutants
387 .iter()
388 .filter(|mutant| mutant.status.is_conclusive())
389 .count()
390}
391
392fn describe_normalized(mutant: &NormalizedMutant) -> String {
395 match &mutant.replacement {
396 Some(replacement) => format!("{} (-> {})", mutant.mutator, one_line(replacement)),
397 None => mutant.mutator.clone(),
398 }
399}
400
401pub fn measure_rust(
405 root: &Path,
406 exempt: &[String],
407 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
408 base: Option<&str>,
409 features: &[String],
410) -> Result<Measurement> {
411 let out = MutantsOut::new();
412 let workspace_root = cargo_workspace_root(root)?;
416 let prefix = canonical_scan_prefix(root, &workspace_root);
417 let scope = rust_base_scope(root, &workspace_root, prefix.as_deref(), base, &out)?;
418 let (diff, base_diff) = match &scope {
419 RustScope::NothingToJudge => return Ok(Measurement::EngineNotRun),
420 RustScope::WholeCrate => (None, None),
421 RustScope::Diff(path, parsed) => (Some(path.as_path()), Some(parsed)),
422 };
423
424 let engine = ensure_cargo_mutants()?;
425 let run = run_cargo_mutants(&engine, root, &out.0, diff, features)?;
426 let outcomes = out.0.join("mutants.out").join("outcomes.json");
427 match std::fs::read_to_string(&outcomes) {
430 Ok(json) => rust_measurement(&json, root, prefix.as_deref(), exempt, exempt_lines),
431 Err(_) => {
432 zero_mutant_measurement(&engine, root, &workspace_root, features, base_diff, &run)
433 }
434 }
435}
436
437fn base_diff_command<'a>(
442 root: &'a Path,
443 workspace_root: &'a Path,
444 prefix: Option<&'a str>,
445 range: &'a str,
446) -> (&'a Path, Vec<&'a str>) {
447 match prefix {
448 None => (root, vec!["diff", "--relative", range]),
449 Some(prefix) => (
450 workspace_root,
451 vec!["diff", "--relative", range, "--", prefix],
452 ),
453 }
454}
455
456fn base_diff_exit(output: &std::process::Output, range: &str) -> Result<()> {
459 if !output.status.success() {
460 bail!(
461 "git diff {range} failed: {}",
462 String::from_utf8_lossy(&output.stderr)
463 );
464 }
465 Ok(())
466}
467
468enum RustScope {
470 NothingToJudge,
473 WholeCrate,
475 Diff(PathBuf, BaseDiff),
477}
478
479fn rust_base_scope(
482 root: &Path,
483 workspace_root: &Path,
484 prefix: Option<&str>,
485 base: Option<&str>,
486 out: &MutantsOut,
487) -> Result<RustScope> {
488 let Some(base) = base else {
489 return Ok(RustScope::WholeCrate);
490 };
491 Ok(
492 match rust_diff_scope(root, workspace_root, prefix, base, out)? {
493 None => RustScope::NothingToJudge,
494 Some((path, parsed)) => RustScope::Diff(path, parsed),
495 },
496 )
497}
498
499fn rust_diff_scope(
503 root: &Path,
504 workspace_root: &Path,
505 prefix: Option<&str>,
506 base: &str,
507 out: &MutantsOut,
508) -> Result<Option<(PathBuf, BaseDiff)>> {
509 let written = write_base_diff(root, workspace_root, prefix, base, out)?;
510 let read = written.as_deref().map(read_base_diff).transpose()?;
511 Ok(rust_scope(written, read))
512}
513
514fn rust_scope(path: Option<PathBuf>, diff: Option<String>) -> Option<(PathBuf, BaseDiff)> {
520 let (path, diff) = (path?, diff?);
521 let parsed = parse_base_diff(&diff);
522 if !parsed.files.iter().any(|file| file.ends_with(".rs")) {
523 return None;
524 }
525 Some((path, parsed))
526}
527
528fn rust_measurement(
531 json: &str,
532 root: &Path,
533 prefix: Option<&str>,
534 exempt: &[String],
535 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
536) -> Result<Measurement> {
537 let mut report = rebase_report_paths(parse_mutants_report(json)?, prefix);
538 report.outcomes.retain(|outcome| match &outcome.scenario {
539 Scenario::Baseline => true,
540 Scenario::Mutant(mutant) => is_judged(root, mutant),
541 });
542 let survivors = evaluate_scoped(
543 cargo_mutants_survivors(&report),
544 &mutated_lines(&report),
545 exempt,
546 exempt_lines,
547 )?;
548 Ok(Measurement::Tested {
549 count: conclusive_count(&report),
550 survivors,
551 })
552}
553
554fn zero_mutant_measurement(
558 engine: &Path,
559 root: &Path,
560 workspace_root: &Path,
561 features: &[String],
562 base_diff: Option<&BaseDiff>,
563 run: &Output,
564) -> Result<Measurement> {
565 if let Some(diff) = base_diff {
566 let listed: Vec<MutantInfo> =
567 list_cargo_mutants(engine, root, features, |command| command.output())?
568 .into_iter()
569 .filter(|mutant| is_judged(workspace_root, mutant))
570 .collect();
571 zero_mutant_verdict(&listed, diff, run)?;
572 }
573 Ok(Measurement::Tested {
574 count: 0,
575 survivors: Vec::new(),
576 })
577}
578
579fn one_line(replacement: &str) -> String {
582 let flat = replacement.split_whitespace().collect::<Vec<_>>().join(" ");
583 const MAX: usize = 60;
584 if flat.chars().count() > MAX {
585 format!("{}…", flat.chars().take(MAX).collect::<String>())
586 } else {
587 flat
588 }
589}
590
591pub fn measure_typescript(
595 root: &Path,
596 exempt: &[String],
597 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
598 base: Option<&str>,
599 adapter: &Path,
600) -> Result<Measurement> {
601 let package_root =
602 crate::tiers::package_root(root, "package.json").unwrap_or_else(|| root.to_path_buf());
603 let prefix = scan_prefix(root, &package_root);
604 let mutate = match ts_base_scope(root, base, prefix.as_deref())? {
605 TsScope::NothingToJudge => return Ok(Measurement::EngineNotRun),
606 TsScope::Mutate(specs) => specs,
607 };
608 let test_files = prefix.as_deref().map(scan_scoped_test_file_globs);
609 let json = run_ts_adapter(
610 &package_root,
611 adapter,
612 mutate.as_deref(),
613 test_files.as_deref(),
614 )?;
615 let mutants = to_scan_relative(parse_normalized_results(&json)?, prefix.as_deref());
616 normalized_measurement(&judged_ts_mutants(mutants, root), exempt, exempt_lines)
617}
618
619fn judged_ts_mutants(mutants: Vec<NormalizedMutant>, root: &Path) -> Vec<NormalizedMutant> {
623 let mut mutants = mutants;
624 mutants.retain(|mutant| !is_declaration_only(root, &mutant.file, Language::TypeScript));
625 mutants
626}
627
628fn normalized_measurement(
631 mutants: &[NormalizedMutant],
632 exempt: &[String],
633 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
634) -> Result<Measurement> {
635 Ok(Measurement::Tested {
636 count: normalized_conclusive_count(mutants),
637 survivors: evaluate_normalized(mutants, exempt, exempt_lines)?,
638 })
639}
640
641enum TsScope {
643 NothingToJudge,
645 Mutate(Option<Vec<String>>),
648}
649
650fn ts_base_scope(root: &Path, base: Option<&str>, prefix: Option<&str>) -> Result<TsScope> {
654 let Some(base) = base else {
655 return Ok(TsScope::Mutate(prefix.map(scan_scoped_mutate_globs)));
656 };
657 let ranges = mutate_ranges(root, base)?;
658 if ranges.is_empty() {
659 return Ok(TsScope::NothingToJudge);
660 }
661 Ok(TsScope::Mutate(Some(prefix_mutate_specs(ranges, prefix))))
662}
663
664fn scan_prefix(root: &Path, package_root: &Path) -> Option<String> {
667 let rel = root.strip_prefix(package_root).ok()?;
668 let parts: Vec<String> = rel
669 .components()
670 .map(|part| part.as_os_str().to_string_lossy().into_owned())
671 .collect();
672 if parts.is_empty() {
673 None
674 } else {
675 Some(parts.join("/"))
676 }
677}
678
679fn prefix_mutate_specs(specs: Vec<String>, prefix: Option<&str>) -> Vec<String> {
682 match prefix {
683 None => specs,
684 Some(prefix) => specs
685 .into_iter()
686 .map(|spec| format!("{prefix}/{spec}"))
687 .collect(),
688 }
689}
690
691fn scan_scoped_mutate_globs(prefix: &str) -> Vec<String> {
695 const EXTENSIONS: &str = "+(cjs|mjs|js|ts|mts|cts|jsx|tsx|html|vue|svelte)";
696 vec![
697 format!("{prefix}/**/!(*.+(s|S)pec|*.+(t|T)est).{EXTENSIONS}"),
698 format!("!{prefix}/**/__tests__/**/*.{EXTENSIONS}"),
699 ]
700}
701
702fn scan_scoped_test_file_globs(prefix: &str) -> Vec<String> {
706 vec![format!("{prefix}/**")]
707}
708
709fn to_scan_relative(mutants: Vec<NormalizedMutant>, prefix: Option<&str>) -> Vec<NormalizedMutant> {
713 let Some(prefix) = prefix else {
714 return mutants;
715 };
716 let prefix = format!("{prefix}/");
717 mutants
718 .into_iter()
719 .filter_map(|mut mutant| {
720 mutant.file = mutant.file.strip_prefix(&prefix)?.to_string();
721 Some(mutant)
722 })
723 .collect()
724}
725
726fn adapter_cwd<'a>(root: &'a Path, engine: &str) -> Result<&'a Path> {
730 let cwd = if root.as_os_str().is_empty() {
731 Path::new(".")
732 } else {
733 root
734 };
735 if !cwd.is_dir() {
736 bail!(
737 "the {engine} mutation adapter's working directory `{}` is not a directory",
738 cwd.display()
739 );
740 }
741 Ok(cwd)
742}
743
744fn spawn_context(interpreter: &str, entry: &str, cwd: &Path) -> String {
748 format!(
749 "spawning `{interpreter} {entry}` in `{}` (is `{interpreter}` on PATH?)",
750 cwd.display()
751 )
752}
753
754fn ts_adapter_args(mutate: Option<&[String]>, test_files: Option<&[String]>) -> Vec<String> {
758 let mut args = Vec::new();
759 if let Some(specs) = mutate {
760 args.push("--mutate".to_string());
761 args.push(specs.join(","));
762 }
763 if let Some(globs) = test_files {
764 args.push("--test-files".to_string());
765 args.push(globs.join(","));
766 }
767 args
768}
769
770fn run_ts_adapter(
774 package_root: &Path,
775 adapter: &Path,
776 mutate: Option<&[String]>,
777 test_files: Option<&[String]>,
778) -> Result<String> {
779 let (_out, results) = adapter_results_path()?;
780 let cwd = adapter_cwd(package_root, "TypeScript")?;
781
782 let mut command = Command::new("node");
783 command
784 .current_dir(cwd)
785 .arg(adapter)
786 .arg("--out")
787 .arg(&results)
788 .args(ts_adapter_args(mutate, test_files));
789 let output =
790 command
791 .output()
792 .context(spawn_context("node", &adapter.display().to_string(), cwd))?;
793 adapter_exit(&output, "TypeScript", cwd)?;
794 read_adapter_results(&results, "TypeScript")
795}
796
797fn read_adapter_results(results: &Path, engine: &str) -> Result<String> {
799 std::fs::read_to_string(results).with_context(|| {
800 format!(
801 "reading the {engine} mutation adapter's results from `{}`",
802 results.display()
803 )
804 })
805}
806
807fn adapter_results_path() -> Result<(AdapterOut, PathBuf)> {
813 let out = AdapterOut::new();
814 std::fs::create_dir_all(&out.0).context("creating the mutation adapter output dir")?;
815 let results = out.0.join("results.json");
816 Ok((out, results))
817}
818
819fn adapter_exit(output: &std::process::Output, language: &str, cwd: &Path) -> Result<()> {
823 if !output.status.success() {
824 bail!(
825 "the {language} mutation adapter failed in `{}`:\n{}{}",
826 cwd.display(),
827 String::from_utf8_lossy(&output.stdout),
828 String::from_utf8_lossy(&output.stderr),
829 );
830 }
831 Ok(())
832}
833
834struct AdapterOut(PathBuf);
835
836impl AdapterOut {
837 fn new() -> Self {
838 static COUNTER: AtomicU64 = AtomicU64::new(0);
839 let name = format!(
840 "testing-conventions-ts-adapter-{}-{}",
841 std::process::id(),
842 COUNTER.fetch_add(1, Ordering::Relaxed),
843 );
844 AdapterOut(std::env::temp_dir().join(name))
845 }
846}
847
848impl Drop for AdapterOut {
849 fn drop(&mut self) {
850 let _ = std::fs::remove_dir_all(&self.0);
851 }
852}
853
854fn mutate_ranges(root: &Path, base: &str) -> Result<Vec<String>> {
858 let changed = crate::patch_coverage::changed_lines(root, base)?;
859 let mut specs = Vec::new();
860 for (file, lines) in changed {
861 if !is_mutatable_ts(&file) || is_declaration_only(root, &file, Language::TypeScript) {
862 continue;
863 }
864 for (start, end) in contiguous_runs(&lines) {
865 specs.push(format!("{file}:{start}-{end}"));
866 }
867 }
868 Ok(specs)
869}
870
871fn is_mutatable_ts(file: &str) -> bool {
875 let is_source = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
876 .iter()
877 .any(|ext| file.ends_with(ext));
878 let is_decl = file.ends_with(".d.ts");
879 let is_test = file.contains(".test.") || file.contains(".spec.");
880 is_source && !is_decl && !is_test
881}
882
883fn contiguous_runs(lines: &BTreeSet<u64>) -> Vec<(u64, u64)> {
885 let mut runs: Vec<(u64, u64)> = Vec::new();
886 for &line in lines {
887 match runs.last_mut() {
888 Some(run) if run.1 + 1 == line => run.1 = line,
889 _ => runs.push((line, line)),
890 }
891 }
892 runs
893}
894
895pub fn measure_python(
899 root: &Path,
900 exempt: &[String],
901 exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
902 base: Option<&str>,
903) -> Result<Measurement> {
904 let changed = match base {
905 Some(base) => Some(crate::patch_coverage::changed_lines(root, base)?),
906 None => None,
907 };
908 let modules = match &changed {
909 None => Vec::new(),
910 Some(changed) => {
911 let modules = mutatable_py_modules(changed);
912 if modules.is_empty() {
913 return Ok(Measurement::EngineNotRun);
914 }
915 modules
916 }
917 };
918 let json = run_py_adapter(root, &modules)?;
919 let mutants = judged_py_mutants(parse_normalized_results(&json)?, root, changed.as_ref());
920 normalized_measurement(&mutants, exempt, exempt_lines)
921}
922
923fn mutatable_py_modules(changed: &BTreeMap<String, BTreeSet<u64>>) -> Vec<String> {
926 changed
927 .keys()
928 .filter(|file| is_mutatable_py(file))
929 .cloned()
930 .collect()
931}
932
933fn judged_py_mutants(
936 mutants: Vec<NormalizedMutant>,
937 root: &Path,
938 changed: Option<&BTreeMap<String, BTreeSet<u64>>>,
939) -> Vec<NormalizedMutant> {
940 let mut mutants = mutants;
941 if let Some(changed) = changed {
942 mutants.retain(|mutant| {
943 changed
944 .get(&mutant.file)
945 .is_some_and(|lines| lines.contains(&u64::from(mutant.line)))
946 });
947 }
948 mutants.retain(|mutant| !is_declaration_only(root, &mutant.file, Language::Python));
949 mutants
950}
951
952fn run_py_adapter(root: &Path, modules: &[String]) -> Result<String> {
956 let (_out, results) = adapter_results_path()?;
957 let cwd = adapter_cwd(root, "Python")?;
958
959 const ENTRY: &str = "-m testing_conventions.mutation.main";
960 let mut command = Command::new("python3");
961 command
962 .current_dir(cwd)
963 .args(["-m", "testing_conventions.mutation.main", "--out"])
964 .arg(&results)
965 .env("PYTHONDONTWRITEBYTECODE", "1");
966 for module in modules {
967 command.arg("--module").arg(module);
968 }
969 let output = command
970 .output()
971 .context(spawn_context("python3", ENTRY, cwd))?;
972 adapter_exit(&output, "Python", cwd)?;
973 read_adapter_results(&results, "Python")
974}
975
976fn is_mutatable_py(file: &str) -> bool {
979 if !file.ends_with(".py") {
980 return false;
981 }
982 let base = file.rsplit('/').next().unwrap_or(file);
983 !(base.ends_with("_test.py") || base.starts_with("test_") || base == "conftest.py")
984}
985
986struct MutantsOut(PathBuf);
989
990impl MutantsOut {
991 fn new() -> Self {
992 static COUNTER: AtomicU64 = AtomicU64::new(0);
993 let name = format!(
994 "testing-conventions-mutants-{}-{}",
995 std::process::id(),
996 COUNTER.fetch_add(1, Ordering::Relaxed),
997 );
998 MutantsOut(std::env::temp_dir().join(name))
999 }
1000}
1001
1002impl Drop for MutantsOut {
1003 fn drop(&mut self) {
1004 let _ = std::fs::remove_dir_all(&self.0);
1005 }
1006}
1007
1008fn cargo_workspace_root(root: &Path) -> Result<PathBuf> {
1012 let output = Command::new("cargo")
1013 .current_dir(root)
1014 .args(["locate-project", "--workspace", "--message-format", "plain"])
1015 .output()
1016 .context("running `cargo locate-project` (is cargo installed?)")?;
1017 if !output.status.success() {
1018 bail!(
1019 "cargo locate-project failed in `{}`: {}",
1020 root.display(),
1021 String::from_utf8_lossy(&output.stderr)
1022 );
1023 }
1024 let manifest = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
1025 manifest_dir(&manifest)
1026}
1027
1028fn manifest_dir(manifest: &Path) -> Result<PathBuf> {
1030 manifest.parent().map(Path::to_path_buf).with_context(|| {
1031 format!(
1032 "no parent dir for the workspace manifest `{}`",
1033 manifest.display()
1034 )
1035 })
1036}
1037
1038fn canonical_scan_prefix(root: &Path, workspace_root: &Path) -> Option<String> {
1042 let root = root.canonicalize().ok()?;
1043 let workspace_root = workspace_root.canonicalize().ok()?;
1044 scan_prefix(&root, &workspace_root)
1045}
1046
1047fn write_base_diff(
1051 root: &Path,
1052 workspace_root: &Path,
1053 prefix: Option<&str>,
1054 base: &str,
1055 out: &MutantsOut,
1056) -> Result<Option<PathBuf>> {
1057 let range = format!("{base}...HEAD");
1058 let (dir, args) = base_diff_command(root, workspace_root, prefix, &range);
1059 let output = Command::new("git")
1060 .current_dir(dir)
1061 .args(&args)
1062 .output()
1063 .context("running `git diff` for `--base` (is git installed?)")?;
1064 base_diff_exit(&output, &range)?;
1065 if output.stdout.is_empty() {
1066 return Ok(None);
1067 }
1068 std::fs::create_dir_all(&out.0).context("creating the mutants output dir")?;
1069 let path = out.0.join("base.diff");
1070 std::fs::write(&path, &output.stdout).context("writing the base diff")?;
1071 Ok(Some(path))
1072}
1073
1074fn read_base_diff(path: &Path) -> Result<String> {
1076 std::fs::read_to_string(path)
1077 .with_context(|| format!("reading the written base diff `{}`", path.display()))
1078}
1079
1080struct BaseDiff {
1084 files: Vec<String>,
1085 inserted: BTreeMap<String, BTreeSet<u32>>,
1086}
1087
1088fn parse_base_diff(diff: &str) -> BaseDiff {
1091 let mut files = Vec::new();
1092 let mut inserted: BTreeMap<String, BTreeSet<u32>> = BTreeMap::new();
1093 let mut current: Option<String> = None;
1094 let mut lines = diff.lines();
1095 while let Some(line) = lines.next() {
1096 if let Some(path) = line.strip_prefix("+++ ") {
1097 current = (path != "/dev/null").then(|| {
1098 let path = path.strip_prefix("b/").unwrap_or(path).to_string();
1099 files.push(path.clone());
1100 path
1101 });
1102 } else if let Some(header) = line.strip_prefix("@@ ") {
1103 if let Some(counts) = parse_hunk_header(header) {
1104 consume_hunk(&mut lines, counts, current.as_ref(), &mut inserted);
1105 }
1106 }
1107 }
1108 BaseDiff { files, inserted }
1109}
1110
1111fn consume_hunk(
1115 lines: &mut std::str::Lines<'_>,
1116 (new_start, old_count, new_count): (u32, u32, u32),
1117 file: Option<&String>,
1118 inserted: &mut BTreeMap<String, BTreeSet<u32>>,
1119) {
1120 let mut new_line = new_start;
1121 let (mut old_left, mut new_left) = (old_count, new_count);
1122 while old_left > 0 || new_left > 0 {
1123 let Some(line) = lines.next() else { break };
1124 if line.starts_with('\\') {
1125 } else if line.starts_with('+') {
1128 if let Some(file) = file {
1129 inserted.entry(file.clone()).or_default().insert(new_line);
1130 }
1131 new_line += 1;
1132 new_left = new_left.saturating_sub(1);
1133 } else if line.starts_with('-') {
1134 old_left = old_left.saturating_sub(1);
1135 } else {
1136 new_line += 1;
1137 old_left = old_left.saturating_sub(1);
1138 new_left = new_left.saturating_sub(1);
1139 }
1140 }
1141}
1142
1143fn parse_hunk_header(header: &str) -> Option<(u32, u32, u32)> {
1145 let mut parts = header.split(' ');
1146 let (_, old_count) = parse_range(parts.next()?.strip_prefix('-')?)?;
1147 let (new_start, new_count) = parse_range(parts.next()?.strip_prefix('+')?)?;
1148 Some((new_start, old_count, new_count))
1149}
1150
1151fn parse_range(range: &str) -> Option<(u32, u32)> {
1153 match range.split_once(',') {
1154 Some((start, count)) => Some((start.parse().ok()?, count.parse().ok()?)),
1155 None => Some((range.parse().ok()?, 1)),
1156 }
1157}
1158
1159fn rebase_report_paths(report: MutantsReport, prefix: Option<&str>) -> MutantsReport {
1163 let Some(prefix) = prefix else {
1164 return report;
1165 };
1166 let prefix = format!("{prefix}/");
1167 MutantsReport {
1168 outcomes: report
1169 .outcomes
1170 .into_iter()
1171 .filter_map(|mut outcome| {
1172 if let Scenario::Mutant(mutant) = &mut outcome.scenario {
1173 mutant.file = mutant.file.strip_prefix(&prefix)?.to_string();
1174 }
1175 Some(outcome)
1176 })
1177 .collect(),
1178 }
1179}
1180
1181const CARGO_MUTANTS_VERSION: &str = "27.1.0";
1184
1185fn ensure_cargo_mutants() -> Result<PathBuf> {
1189 provision_pinned(&cargo_mutants_cache_root(), execute)
1190}
1191
1192fn provision_pinned(
1194 root: &Path,
1195 run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1196) -> Result<PathBuf> {
1197 let bin = root.join("bin").join(CARGO_MUTANTS_BIN_NAME);
1198 let lock_path = root.join(".install.lock");
1199 provision(&bin, &lock_path, || run_install(root, run))
1200}
1201
1202fn execute(command: &mut Command) -> std::io::Result<Output> {
1204 command.output()
1205}
1206
1207const CARGO_MUTANTS_BIN_NAME: &str = if cfg!(windows) {
1210 "cargo-mutants.exe"
1211} else {
1212 "cargo-mutants"
1213};
1214
1215fn cargo_mutants_cache_root() -> PathBuf {
1219 cache_base()
1220 .join("testing-conventions")
1221 .join(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}"))
1222}
1223
1224fn cache_base() -> PathBuf {
1227 resolve_cache_base(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))
1228}
1229
1230fn resolve_cache_base(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
1233 if let Some(dir) = xdg.filter(|value| !value.is_empty()) {
1234 return PathBuf::from(dir);
1235 }
1236 if let Some(dir) = home.filter(|value| !value.is_empty()) {
1237 return PathBuf::from(dir).join(".cache");
1238 }
1239 std::env::temp_dir()
1240}
1241
1242fn hold_lock(lock_path: &Path) -> Result<std::fs::File> {
1246 if let Some(parent) = lock_path.parent() {
1247 std::fs::create_dir_all(parent).context("creating the provisioning lock's parent dir")?;
1248 }
1249 let lock_file = std::fs::OpenOptions::new()
1250 .create(true)
1251 .truncate(false)
1252 .write(true)
1253 .open(lock_path)
1254 .context("opening the provisioning lock file")?;
1255 lock_file
1256 .lock()
1257 .context("acquiring the provisioning lock")?;
1258 Ok(lock_file)
1259}
1260
1261fn installed_binary(bin: &Path) -> Result<PathBuf> {
1264 if !bin.exists() {
1265 bail!(
1266 "provisioning reported success but cargo-mutants is not at `{}`",
1267 bin.display()
1268 );
1269 }
1270 Ok(bin.to_path_buf())
1271}
1272
1273fn provision(
1277 bin: &Path,
1278 lock_path: &Path,
1279 install: impl FnOnce() -> Result<()>,
1280) -> Result<PathBuf> {
1281 if bin.exists() {
1282 return Ok(bin.to_path_buf());
1283 }
1284 let _lock = hold_lock(lock_path)?;
1285 if bin.exists() {
1287 return Ok(bin.to_path_buf());
1288 }
1289 install()?;
1290 installed_binary(bin)
1291}
1292
1293fn install_argv(root: &Path) -> Vec<OsString> {
1297 vec![
1298 OsString::from("install"),
1299 OsString::from("cargo-mutants"),
1300 OsString::from("--locked"),
1301 OsString::from("--version"),
1302 OsString::from(CARGO_MUTANTS_VERSION),
1303 OsString::from("--root"),
1304 root.as_os_str().to_os_string(),
1305 ]
1306}
1307
1308fn run_install(
1312 root: &Path,
1313 run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1314) -> Result<()> {
1315 let mut command = Command::new("cargo");
1316 command.args(install_argv(root));
1317 strip_llvm_cov_env(&mut command);
1318 let output = run(&mut command)
1319 .context("provisioning cargo-mutants via `cargo install` (is cargo installed?)")?;
1320 if !output.status.success() {
1321 bail!(
1322 "failed to provision cargo-mutants {CARGO_MUTANTS_VERSION}:\n{}{}",
1323 String::from_utf8_lossy(&output.stdout),
1324 String::from_utf8_lossy(&output.stderr),
1325 );
1326 }
1327 Ok(())
1328}
1329
1330fn strip_llvm_cov_env(command: &mut Command) {
1334 for var in [
1335 "RUSTFLAGS",
1336 "CARGO_ENCODED_RUSTFLAGS",
1337 "RUSTDOCFLAGS",
1338 "CARGO_ENCODED_RUSTDOCFLAGS",
1339 "LLVM_PROFILE_FILE",
1340 "CARGO_LLVM_COV",
1341 "CARGO_LLVM_COV_SHOW_ENV",
1342 "CARGO_LLVM_COV_TARGET_DIR",
1343 "CARGO_LLVM_COV_BUILD_DIR",
1344 "RUSTC_WRAPPER",
1345 "RUSTC_WORKSPACE_WRAPPER",
1346 "__CARGO_LLVM_COV_RUSTC_WRAPPER",
1347 "__CARGO_LLVM_COV_RUSTC_WRAPPER_RUSTFLAGS",
1348 "__CARGO_LLVM_COV_RUSTC_WRAPPER_CRATE_NAMES",
1349 ] {
1350 command.env_remove(var);
1351 }
1352}
1353
1354fn run_cargo_mutants(
1358 engine: &Path,
1359 root: &Path,
1360 out: &Path,
1361 in_diff: Option<&Path>,
1362 features: &[String],
1363) -> Result<Output> {
1364 let mut command = Command::new(engine);
1365 command
1366 .current_dir(root)
1367 .args(mutants_argv(out, in_diff, features));
1368 strip_llvm_cov_env(&mut command);
1369 let output = command.output().context("running cargo-mutants")?;
1370 classify_mutants_exit(root, &output)?;
1371 Ok(output)
1372}
1373
1374fn zero_mutant_verdict(listed: &[MutantInfo], diff: &BaseDiff, run: &Output) -> Result<()> {
1378 let dropped = dropped_mutants(listed, diff);
1379 if dropped.is_empty() {
1380 return Ok(());
1381 }
1382 let sites: Vec<String> = dropped.iter().map(|mutant| mutant_site(mutant)).collect();
1383 bail!(
1384 "cargo-mutants tested no mutants, but {} of the crate's {} mutant site(s) sit on the diff's inserted lines — the changed-line filter dropped real mutants:\n{}\nengine output:\n{}{}",
1385 dropped.len(),
1386 listed.len(),
1387 sites.join("\n"),
1388 String::from_utf8_lossy(&run.stdout),
1389 String::from_utf8_lossy(&run.stderr),
1390 )
1391}
1392
1393fn dropped_mutants<'a>(listed: &'a [MutantInfo], diff: &BaseDiff) -> Vec<&'a MutantInfo> {
1396 listed
1397 .iter()
1398 .filter(|mutant| {
1399 diff.inserted.get(&mutant.file).is_some_and(|lines| {
1400 lines
1401 .range(mutant.span.start.line..=mutant.span.end.line)
1402 .next()
1403 .is_some()
1404 })
1405 })
1406 .collect()
1407}
1408
1409fn mutant_site(mutant: &MutantInfo) -> String {
1411 format!(
1412 " {}:{}: {}",
1413 mutant.file,
1414 mutant.span.start.line,
1415 strip_embedded_location(&mutant.name)
1416 )
1417}
1418
1419fn list_argv(features: &[String]) -> Vec<OsString> {
1423 let mut argv = vec![
1424 OsString::from("mutants"),
1425 OsString::from("--list"),
1426 OsString::from("--json"),
1427 ];
1428 if !features.is_empty() {
1429 argv.push(OsString::from("--features"));
1430 argv.push(OsString::from(features.join(",")));
1431 }
1432 argv
1433}
1434
1435fn list_cargo_mutants(
1439 engine: &Path,
1440 root: &Path,
1441 features: &[String],
1442 run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1443) -> Result<Vec<MutantInfo>> {
1444 let mut command = Command::new(engine);
1445 command.current_dir(root).args(list_argv(features));
1446 strip_llvm_cov_env(&mut command);
1447 let output = run(&mut command).context("listing the crate's mutants with cargo-mutants")?;
1448 if !output.status.success() {
1449 bail!(
1450 "cargo-mutants --list failed in `{}`:\n{}{}",
1451 root.display(),
1452 String::from_utf8_lossy(&output.stdout),
1453 String::from_utf8_lossy(&output.stderr),
1454 );
1455 }
1456 parse_mutants_list(&String::from_utf8_lossy(&output.stdout))
1457}
1458
1459fn mutants_argv(out: &Path, in_diff: Option<&Path>, features: &[String]) -> Vec<OsString> {
1461 let mut argv = vec![
1462 OsString::from("mutants"),
1463 OsString::from("--output"),
1464 out.as_os_str().to_os_string(),
1465 OsString::from("--cargo-test-arg"),
1466 OsString::from("--lib"),
1467 ];
1468 if let Some(diff) = in_diff {
1469 argv.push(OsString::from("--in-diff"));
1470 argv.push(diff.as_os_str().to_os_string());
1471 }
1472 if !features.is_empty() {
1473 argv.push(OsString::from("--features"));
1474 argv.push(OsString::from(features.join(",")));
1475 }
1476 argv
1477}
1478
1479fn classify_mutants_exit(root: &Path, output: &Output) -> Result<()> {
1483 match output.status.code() {
1484 Some(0) | Some(2) | Some(3) => Ok(()),
1485 _ => bail!(
1486 "cargo-mutants did not run cleanly in `{}` (baseline build/test failure?):\n{}{}",
1487 root.display(),
1488 String::from_utf8_lossy(&output.stdout),
1489 String::from_utf8_lossy(&output.stderr),
1490 ),
1491 }
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496 use super::*;
1497
1498 #[test]
1499 fn neither_scope_adds_an_argument() {
1500 assert!(ts_adapter_args(None, None).is_empty());
1501 }
1502
1503 #[test]
1504 fn each_scope_contributes_its_own_flag_and_a_comma_joined_list() {
1505 let mutate = vec!["src/a.ts".to_string(), "src/b.ts".to_string()];
1506 let tests = vec!["src/a.test.ts".to_string()];
1507 assert_eq!(
1508 ts_adapter_args(Some(&mutate), None),
1509 vec!["--mutate", "src/a.ts,src/b.ts"]
1510 );
1511 assert_eq!(
1512 ts_adapter_args(None, Some(&tests)),
1513 vec!["--test-files", "src/a.test.ts"]
1514 );
1515 assert_eq!(
1516 ts_adapter_args(Some(&mutate), Some(&tests)),
1517 vec![
1518 "--mutate",
1519 "src/a.ts,src/b.ts",
1520 "--test-files",
1521 "src/a.test.ts"
1522 ]
1523 );
1524 }
1525
1526 #[test]
1527 fn an_empty_list_still_passes_its_flag() {
1528 assert_eq!(ts_adapter_args(Some(&[]), None), vec!["--mutate", ""]);
1530 }
1531
1532 #[test]
1533 fn with_no_prefix_the_base_diff_runs_unscoped_at_the_scan_path() {
1534 let (dir, args) = base_diff_command(
1535 Path::new("/crate"),
1536 Path::new("/workspace"),
1537 None,
1538 "main...HEAD",
1539 );
1540 assert_eq!(dir, Path::new("/crate"));
1541 assert_eq!(args, vec!["diff", "--relative", "main...HEAD"]);
1542 }
1543
1544 #[test]
1545 fn with_a_prefix_the_base_diff_runs_at_the_workspace_root_scoped_by_it() {
1546 let (dir, args) = base_diff_command(
1549 Path::new("/workspace/crate"),
1550 Path::new("/workspace"),
1551 Some("crate/src"),
1552 "main...HEAD",
1553 );
1554 assert_eq!(dir, Path::new("/workspace"));
1555 assert_eq!(
1556 args,
1557 vec!["diff", "--relative", "main...HEAD", "--", "crate/src"]
1558 );
1559 }
1560
1561 #[test]
1562 fn a_failed_base_diff_names_the_range() {
1563 let output = std::process::Output {
1564 status: std::process::Command::new("false").status().unwrap(),
1565 stdout: Vec::new(),
1566 stderr: b"fatal: bad revision".to_vec(),
1567 };
1568 let err = base_diff_exit(&output, "nope...HEAD").unwrap_err();
1569 assert!(err.to_string().contains("nope...HEAD"), "got: {err}");
1570 }
1571
1572 #[test]
1573 fn an_adapter_failure_surfaces_both_captured_streams() {
1574 let output = std::process::Output {
1575 status: std::process::Command::new("false").status().unwrap(),
1576 stdout: b"stryker said this".to_vec(),
1577 stderr: b"and then this".to_vec(),
1578 };
1579 let err = adapter_exit(&output, "TypeScript", Path::new("/pkg")).unwrap_err();
1580 let text = err.to_string();
1581 assert!(
1582 text.contains("TypeScript mutation adapter failed"),
1583 "got: {text}"
1584 );
1585 assert!(text.contains("/pkg"), "got: {text}");
1586 assert!(text.contains("stryker said this"), "got: {text}");
1587 assert!(text.contains("and then this"), "got: {text}");
1588 }
1589
1590 #[test]
1591 fn an_adapter_that_succeeded_is_not_an_error() {
1592 let output = std::process::Output {
1593 status: std::process::Command::new("true").status().unwrap(),
1594 stdout: Vec::new(),
1595 stderr: Vec::new(),
1596 };
1597 assert!(adapter_exit(&output, "Python", Path::new("/pkg")).is_ok());
1598 }
1599
1600 #[test]
1601 fn an_install_that_produced_no_binary_is_an_error() {
1602 let missing = scratch_dir("installed-binary-absent").join("cargo-mutants");
1603 let err = installed_binary(&missing).unwrap_err();
1604 assert!(
1605 err.to_string().contains("provisioning reported success"),
1606 "got: {err}"
1607 );
1608 }
1609
1610 #[test]
1611 fn an_install_that_produced_the_binary_returns_its_path() {
1612 let dir = scratch_dir("installed-binary-present");
1613 std::fs::create_dir_all(&dir).unwrap();
1614 let bin = dir.join("cargo-mutants");
1615 std::fs::write(&bin, "").unwrap();
1616 assert_eq!(installed_binary(&bin).unwrap(), bin);
1617 }
1618
1619 fn scratch_dir(name: &str) -> PathBuf {
1621 std::env::temp_dir().join(format!("testing-conventions-{name}-{}", std::process::id()))
1622 }
1623
1624 const NORMALIZED: &str = r#"[
1625 {"file": "src/a.ts", "line": 2, "status": "survived",
1626 "mutator": "ConditionalExpression", "replacement": "true", "id": "ignored"},
1627 {"file": "src/a.ts", "line": 5, "status": "no_coverage", "mutator": "ArithmeticOperator"},
1628 {"file": "src/a.ts", "line": 9, "status": "killed",
1629 "mutator": "BooleanLiteral", "replacement": "false"},
1630 {"file": "src/a.ts", "line": 12, "status": "timeout", "mutator": "BlockStatement"},
1631 {"file": "src/a.ts", "line": 15, "status": "compile_error", "mutator": "OptionalChaining"},
1632 {"file": "src/a.ts", "line": 18, "status": "runtime_error", "mutator": "StringLiteral"}
1633 ]"#;
1634
1635 #[test]
1636 fn parses_the_normalized_schema() {
1637 let mutants = parse_normalized_results(NORMALIZED).expect("valid normalized results");
1638 assert_eq!(mutants.len(), 6);
1639 assert_eq!(mutants[0].status, MutantStatus::Survived);
1640 assert_eq!(mutants[1].status, MutantStatus::NoCoverage);
1641 assert_eq!(mutants[0].replacement.as_deref(), Some("true"));
1642 assert_eq!(mutants[1].replacement, None);
1643 }
1644
1645 #[test]
1646 fn normalized_survivors_are_survived_and_nocoverage_only() {
1647 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1648 let survivors = normalized_survivors(&mutants);
1649 assert_eq!(survivors.len(), 2);
1650 assert_eq!((survivors[0].line, survivors[1].line), (2, 5));
1651 assert!(survivors[0].description.contains("ConditionalExpression"));
1652 assert!(survivors[0].description.contains("-> true"));
1653 assert_eq!(survivors[1].description, "ArithmeticOperator");
1654 }
1655
1656 #[test]
1657 fn normalized_mutated_lines_collects_only_viable_mutants() {
1658 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1659 assert_eq!(
1660 normalized_mutated_lines(&mutants),
1661 [2u32, 5, 9, 12]
1662 .into_iter()
1663 .map(|line| ("src/a.ts".to_string(), line))
1664 .collect()
1665 );
1666 }
1667
1668 #[test]
1669 fn normalized_conclusive_count_is_survived_killed_and_nocoverage() {
1670 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1671 assert_eq!(normalized_conclusive_count(&mutants), 3);
1672 assert_eq!(normalized_conclusive_count(&[]), 0);
1673 }
1674
1675 #[test]
1676 fn a_normalized_measurement_reports_the_conclusive_count_and_the_kept_survivors() {
1677 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1678 assert_eq!(
1679 normalized_measurement(&mutants, &[], &BTreeMap::new()).unwrap(),
1680 Measurement::Tested {
1681 count: 3,
1684 survivors: normalized_survivors(&mutants),
1685 }
1686 );
1687
1688 assert_eq!(
1690 normalized_measurement(&mutants, &["src/a.ts".to_string()], &BTreeMap::new()).unwrap(),
1691 Measurement::Tested {
1692 count: 3,
1693 survivors: vec![],
1694 }
1695 );
1696 }
1697
1698 #[test]
1699 fn evaluate_normalized_reports_unexempted_survivors() {
1700 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1701 let kept = evaluate_normalized(&mutants, &[], &BTreeMap::new()).unwrap();
1702 assert_eq!(kept.len(), 2, "both survivors stand with no exemptions");
1703 }
1704
1705 #[test]
1706 fn evaluate_normalized_drops_a_whole_file_exemption() {
1707 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1708 let kept =
1709 evaluate_normalized(&mutants, &["src/a.ts".to_string()], &BTreeMap::new()).unwrap();
1710 assert!(
1711 kept.is_empty(),
1712 "the whole-file exemption lifts both survivors"
1713 );
1714 }
1715
1716 #[test]
1717 fn evaluate_normalized_drops_a_line_scoped_exemption() {
1718 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1719 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([2u32]))]);
1720 let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
1721 assert_eq!(kept.len(), 1);
1722 assert_eq!(kept[0].line, 5);
1723 }
1724
1725 #[test]
1726 fn evaluate_normalized_rejects_exempting_a_caught_line() {
1727 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1728 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([9u32]))]);
1729 let err = evaluate_normalized(&mutants, &[], &line_scoped).unwrap_err();
1730 assert!(
1731 err.to_string().contains("all caught") && err.to_string().contains("src/a.ts:9"),
1732 "got: {err}"
1733 );
1734 }
1735
1736 #[test]
1737 fn evaluate_normalized_leaves_an_unviable_listed_line_alone() {
1738 let mutants = parse_normalized_results(NORMALIZED).unwrap();
1739 let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([15u32]))]);
1740 let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
1741 assert_eq!(kept.len(), 2);
1742 }
1743
1744 const SAMPLE: &str = r#"{
1745 "outcomes": [
1746 {"scenario": "Baseline", "summary": "Success",
1747 "phase_results": []},
1748 {"scenario": {"Mutant": {"file": "src/lib.rs", "package": "p", "genre": "FnValue",
1749 "replacement": "true", "name": "src/lib.rs:7:7: replace > with == in is_positive",
1750 "function": {"function_name": "is_positive"},
1751 "span": {"start": {"line": 7, "column": 7}, "end": {"line": 7, "column": 8}}}},
1752 "summary": "MissedMutant"},
1753 {"scenario": {"Mutant": {"file": "src/other.rs", "package": "p", "genre": "FnValue",
1754 "replacement": "0", "name": "src/other.rs:3:5: replace add -> i32 with 0",
1755 "span": {"start": {"line": 3, "column": 5}, "end": {"line": 3, "column": 9}}}},
1756 "summary": "CaughtMutant"}
1757 ],
1758 "total_mutants": 2
1759 }"#;
1760
1761 #[test]
1762 fn parses_the_outcomes_export() {
1763 let report = parse_mutants_report(SAMPLE).expect("valid outcomes.json");
1764 assert_eq!(report.outcomes.len(), 3);
1765 assert!(matches!(report.outcomes[0].scenario, Scenario::Baseline));
1766 }
1767
1768 #[test]
1769 fn collects_only_missed_mutants_as_survivors() {
1770 let report = parse_mutants_report(SAMPLE).unwrap();
1771 let survivors = unexplained_survivors(&report, &[]);
1772 assert_eq!(survivors.len(), 1);
1773 assert_eq!(survivors[0].file, "src/lib.rs");
1774 assert_eq!(survivors[0].line, 7);
1775 assert!(survivors[0].description.contains("replace > with =="));
1776 }
1777
1778 #[test]
1779 fn a_survivor_description_carries_no_location_prefix() {
1780 let report = parse_mutants_report(SAMPLE).unwrap();
1781 let survivors = unexplained_survivors(&report, &[]);
1782 assert_eq!(
1783 survivors[0].description, "replace > with == in is_positive",
1784 "the name's embedded `file:line:col:` prefix is stripped"
1785 );
1786 }
1787
1788 #[test]
1789 fn strip_embedded_location_removes_a_file_line_col_prefix() {
1790 assert_eq!(
1791 strip_embedded_location("src/lib.rs:7:5: replace > with == in is_positive"),
1792 "replace > with == in is_positive"
1793 );
1794 }
1795
1796 #[test]
1797 fn strip_embedded_location_keeps_a_name_without_one() {
1798 for name in [
1799 "replace add -> 0",
1800 "note: no location segment",
1801 "7:5: no file segment",
1802 "src/lib.rs:7:x: non-numeric column",
1803 "src/lib.rs:x:5: non-numeric line",
1804 ] {
1805 assert_eq!(strip_embedded_location(name), name);
1806 }
1807 }
1808
1809 #[test]
1810 fn conclusive_count_is_caught_plus_missed() {
1811 let report = parse_mutants_report(SAMPLE).unwrap();
1812 assert_eq!(conclusive_count(&report), 2);
1813 assert_eq!(conclusive_count(&MutantsReport { outcomes: vec![] }), 0);
1814 }
1815
1816 #[test]
1817 fn an_exemption_drops_a_survivor_in_that_file() {
1818 let report = parse_mutants_report(SAMPLE).unwrap();
1819 let exempt = vec!["src/lib.rs".to_string()];
1820 assert!(unexplained_survivors(&report, &exempt).is_empty());
1821 }
1822
1823 #[test]
1824 fn an_exemption_on_another_file_leaves_the_survivor() {
1825 let report = parse_mutants_report(SAMPLE).unwrap();
1826 let exempt = vec!["src/elsewhere.rs".to_string()];
1827 assert_eq!(unexplained_survivors(&report, &exempt).len(), 1);
1828 }
1829
1830 const BASELINE_ONLY: &str = r#"{
1831 "outcomes": [
1832 {"scenario": "Baseline", "summary": "MissedMutant", "phase_results": []},
1833 {"scenario": "Baseline", "summary": "CaughtMutant", "phase_results": []}
1834 ],
1835 "total_mutants": 0
1836 }"#;
1837
1838 #[test]
1839 fn a_baseline_outcome_is_never_a_survivor() {
1840 let report = parse_mutants_report(BASELINE_ONLY).unwrap();
1841 assert!(unexplained_survivors(&report, &[]).is_empty());
1842 }
1843
1844 #[test]
1845 fn a_baseline_outcome_is_never_a_mutated_line() {
1846 let report = parse_mutants_report(BASELINE_ONLY).unwrap();
1847 assert!(mutated_lines(&report).is_empty());
1848 }
1849
1850 #[test]
1851 fn parse_base_diff_skips_a_malformed_hunk_header() {
1852 let diff = "\
1853diff --git a/src/lib.rs b/src/lib.rs
1854--- a/src/lib.rs
1855+++ b/src/lib.rs
1856@@ junk @@
1857";
1858 let parsed = parse_base_diff(diff);
1859 assert_eq!(parsed.files, vec!["src/lib.rs"]);
1860 assert!(parsed.inserted.is_empty());
1861 }
1862
1863 #[test]
1864 fn a_missing_base_diff_read_reports_its_path() {
1865 let missing = unique_tmp().join("base.diff");
1866 let err = read_base_diff(&missing).unwrap_err();
1867 let msg = format!("{err:#}");
1868 assert!(msg.contains("reading the written base diff"), "{msg}");
1869 }
1870
1871 #[test]
1872 fn a_missing_adapter_results_read_names_the_engine_and_path() {
1873 let missing = unique_tmp().join("results.json");
1874 let err = read_adapter_results(&missing, "TypeScript").unwrap_err();
1875 let msg = format!("{err:#}");
1876 assert!(
1877 msg.contains("TypeScript mutation adapter's results"),
1878 "{msg}"
1879 );
1880 }
1881
1882 #[test]
1883 fn manifest_dir_is_the_manifest_parent() {
1884 let dir = manifest_dir(Path::new("/w/Cargo.toml")).unwrap();
1885 assert_eq!(dir, Path::new("/w"));
1886 }
1887
1888 #[test]
1889 fn a_rootless_manifest_path_is_an_error() {
1890 let err = manifest_dir(Path::new("/")).unwrap_err();
1891 let msg = format!("{err:#}");
1892 assert!(msg.contains("no parent dir"), "{msg}");
1893 }
1894
1895 #[test]
1896 fn a_directory_outside_any_workspace_fails_locate_project() {
1897 let dir = unique_tmp();
1898 let err = cargo_workspace_root(&dir).unwrap_err();
1899 let msg = format!("{err:#}");
1900 assert!(msg.contains("cargo locate-project failed"), "{msg}");
1901 std::fs::remove_dir_all(&dir).ok();
1902 }
1903
1904 #[test]
1905 fn a_bad_base_ref_fails_the_base_diff() {
1906 let dir = unique_tmp();
1907 let init = Command::new("git")
1908 .current_dir(&dir)
1909 .args(["init", "-q"])
1910 .output()
1911 .unwrap();
1912 assert!(init.status.success());
1913 let out = MutantsOut::new();
1914 let err = write_base_diff(&dir, &dir, None, "tc-no-such-ref", &out).unwrap_err();
1915 let msg = format!("{err:#}");
1916 assert!(msg.contains("git diff"), "{msg}");
1917 std::fs::remove_dir_all(&dir).ok();
1918 }
1919
1920 #[test]
1921 fn a_python_adapter_failure_reports_the_adapter_output() {
1922 let dir = unique_tmp();
1923 let err = run_py_adapter(&dir, &[]).unwrap_err();
1924 let msg = format!("{err:#}");
1925 assert!(msg.contains("the Python mutation adapter failed"), "{msg}");
1926 std::fs::remove_dir_all(&dir).ok();
1927 }
1928
1929 #[test]
1930 fn is_declaration_only_is_true_for_a_const_only_rust_file() {
1931 let dir = unique_tmp();
1932 std::fs::write(
1933 dir.join("settings.rs"),
1934 "pub const TIMEOUT: u64 = 30 * 60;\n",
1935 )
1936 .unwrap();
1937 assert!(is_declaration_only(&dir, "settings.rs", Language::Rust));
1938 std::fs::remove_dir_all(&dir).ok();
1939 }
1940
1941 #[test]
1942 fn is_declaration_only_is_false_for_a_rust_file_with_a_function() {
1943 let dir = unique_tmp();
1944 std::fs::write(dir.join("lib.rs"), "pub fn run() {}\n").unwrap();
1945 assert!(!is_declaration_only(&dir, "lib.rs", Language::Rust));
1946 std::fs::remove_dir_all(&dir).ok();
1947 }
1948
1949 #[test]
1950 fn is_declaration_only_covers_python_and_typescript_too() {
1951 let dir = unique_tmp();
1952 std::fs::write(dir.join("settings.py"), "TIMEOUT = 30 * 60\n").unwrap();
1953 std::fs::write(dir.join("settings.ts"), "export const TIMEOUT = 30 * 60;\n").unwrap();
1954 assert!(is_declaration_only(&dir, "settings.py", Language::Python));
1955 assert!(is_declaration_only(
1956 &dir,
1957 "settings.ts",
1958 Language::TypeScript
1959 ));
1960 std::fs::remove_dir_all(&dir).ok();
1961 }
1962
1963 #[test]
1964 fn is_declaration_only_is_false_for_an_unreadable_file() {
1965 let dir = unique_tmp();
1966 assert!(!is_declaration_only(&dir, "missing.rs", Language::Rust));
1967 std::fs::remove_dir_all(&dir).ok();
1968 }
1969
1970 fn mutant_at(file: &str, line: u32, genre: &str) -> MutantInfo {
1971 MutantInfo {
1972 file: file.to_string(),
1973 span: Span {
1974 start: LineCol { line },
1975 end: LineCol { line },
1976 },
1977 name: format!("a mutant at {file}:{line}"),
1978 genre: genre.to_string(),
1979 }
1980 }
1981
1982 #[test]
1983 fn is_judged_is_true_for_an_ordinary_mutant() {
1984 let dir = unique_tmp();
1985 std::fs::write(
1986 dir.join("add.rs"),
1987 "pub fn add(a: u64) -> u64 {\n a + 1\n}\n",
1988 )
1989 .unwrap();
1990 assert!(is_judged(&dir, &mutant_at("add.rs", 2, "FnValue")));
1991 std::fs::remove_dir_all(&dir).ok();
1992 }
1993
1994 #[test]
1995 fn is_judged_is_false_in_a_declaration_only_module() {
1996 let dir = unique_tmp();
1997 std::fs::write(
1998 dir.join("settings.rs"),
1999 "pub const TIMEOUT: u64 = 30 * 60;\n",
2000 )
2001 .unwrap();
2002 assert!(!is_judged(&dir, &mutant_at("settings.rs", 1, "FnValue")));
2003 std::fs::remove_dir_all(&dir).ok();
2004 }
2005
2006 #[test]
2007 fn is_judged_is_false_inside_an_item_the_test_build_skips() {
2008 let dir = unique_tmp();
2009 std::fs::write(
2010 dir.join("entrypoint.rs"),
2011 "#[cfg(not(test))]\npub fn main() -> u8 {\n 1\n}\n",
2012 )
2013 .unwrap();
2014 assert!(!is_judged(&dir, &mutant_at("entrypoint.rs", 3, "FnValue")));
2015 std::fs::remove_dir_all(&dir).ok();
2016 }
2017
2018 #[test]
2019 fn is_judged_is_false_for_a_whole_body_replacement_in_a_seam() {
2020 let dir = unique_tmp();
2021 std::fs::write(
2022 dir.join("probe.rs"),
2023 "pub fn probe() -> bool {\n Command::new(\"true\").output().is_ok()\n}\n",
2024 )
2025 .unwrap();
2026 assert!(!is_judged(&dir, &mutant_at("probe.rs", 2, "FnValue")));
2027 std::fs::remove_dir_all(&dir).ok();
2028 }
2029
2030 #[test]
2031 fn is_judged_still_judges_an_operator_swap_in_a_seam() {
2032 let dir = unique_tmp();
2033 std::fs::write(
2034 dir.join("probe.rs"),
2035 "pub fn probe() -> bool {\n Command::new(\"true\").output().is_ok()\n}\n",
2036 )
2037 .unwrap();
2038 assert!(is_judged(&dir, &mutant_at("probe.rs", 2, "BinaryOperator")));
2039 std::fs::remove_dir_all(&dir).ok();
2040 }
2041
2042 #[test]
2043 fn rebase_report_paths_strips_the_workspace_prefix() {
2044 let report = parse_mutants_report(SAMPLE).unwrap();
2045 let prefixed = MutantsReport {
2046 outcomes: report
2047 .outcomes
2048 .iter()
2049 .cloned()
2050 .map(|mut outcome| {
2051 if let Scenario::Mutant(mutant) = &mut outcome.scenario {
2052 mutant.file = format!("member/{}", mutant.file);
2053 }
2054 outcome
2055 })
2056 .collect(),
2057 };
2058 let rebased = rebase_report_paths(prefixed, Some("member"));
2059 let survivors = unexplained_survivors(&rebased, &[]);
2060 assert_eq!(survivors.len(), 1);
2061 assert_eq!(survivors[0].file, "src/lib.rs");
2062 assert_eq!(rebased.outcomes.len(), 3);
2063 }
2064
2065 #[test]
2066 fn rebase_report_paths_drops_an_out_of_scope_mutant_and_keeps_none_identity() {
2067 let report = parse_mutants_report(SAMPLE).unwrap();
2068 let rebased = rebase_report_paths(report.clone(), Some("member"));
2069 assert_eq!(
2070 rebased.outcomes.len(),
2071 1,
2072 "only the pathless baseline outcome remains"
2073 );
2074 let unchanged = rebase_report_paths(report, None);
2075 assert_eq!(unchanged.outcomes.len(), 3);
2076 assert_eq!(unexplained_survivors(&unchanged, &[])[0].file, "src/lib.rs");
2077 }
2078
2079 #[test]
2080 fn adapter_cwd_normalises_the_empty_package_root_to_the_current_dir() {
2081 assert_eq!(
2085 adapter_cwd(Path::new(""), "TypeScript").unwrap(),
2086 Path::new(".")
2087 );
2088 assert_eq!(
2089 adapter_cwd(Path::new("src"), "TypeScript").unwrap(),
2090 Path::new("src")
2091 );
2092 }
2093
2094 #[test]
2095 fn adapter_cwd_rejects_a_directory_that_is_not_there() {
2096 let err = adapter_cwd(Path::new("no/such/dir"), "Python")
2099 .expect_err("a directory that is not there is an error");
2100 assert_eq!(
2101 err.to_string(),
2102 "the Python mutation adapter's working directory `no/such/dir` is not a directory"
2103 );
2104 }
2105
2106 #[test]
2107 fn spawn_context_names_the_interpreter_the_entry_and_the_working_directory() {
2108 assert_eq!(
2109 spawn_context("node", "/pkg/dist/mutation/main.js", Path::new("/pkg")),
2110 "spawning `node /pkg/dist/mutation/main.js` in `/pkg` (is `node` on PATH?)"
2111 );
2112 }
2113
2114 #[test]
2115 fn scan_prefix_is_the_scan_path_relative_to_the_package_root() {
2116 assert_eq!(
2117 scan_prefix(Path::new("/repo/pkg/src"), Path::new("/repo/pkg")),
2118 Some("src".to_string())
2119 );
2120 assert_eq!(
2121 scan_prefix(Path::new("/repo/pkg/src/nested"), Path::new("/repo/pkg")),
2122 Some("src/nested".to_string())
2123 );
2124 assert_eq!(
2125 scan_prefix(Path::new("/repo/pkg"), Path::new("/repo/pkg")),
2126 None
2127 );
2128 assert_eq!(
2129 scan_prefix(Path::new("pkg/src"), Path::new("pkg")),
2130 Some("src".to_string())
2131 );
2132 }
2133
2134 #[test]
2135 fn prefix_mutate_specs_rebases_diff_ranges_onto_the_package_root() {
2136 let specs = vec!["index.ts:8-11".to_string(), "a/b.ts:2-2".to_string()];
2137 assert_eq!(
2138 prefix_mutate_specs(specs.clone(), Some("src")),
2139 vec![
2140 "src/index.ts:8-11".to_string(),
2141 "src/a/b.ts:2-2".to_string()
2142 ]
2143 );
2144 assert_eq!(prefix_mutate_specs(specs.clone(), None), specs);
2145 }
2146
2147 #[test]
2148 fn scan_scoped_mutate_globs_mirror_strykers_default_under_the_scan_path() {
2149 assert_eq!(
2150 scan_scoped_mutate_globs("src"),
2151 vec![
2152 "src/**/!(*.+(s|S)pec|*.+(t|T)est).+(cjs|mjs|js|ts|mts|cts|jsx|tsx|html|vue|svelte)"
2153 .to_string(),
2154 "!src/**/__tests__/**/*.+(cjs|mjs|js|ts|mts|cts|jsx|tsx|html|vue|svelte)"
2155 .to_string(),
2156 ]
2157 );
2158 }
2159
2160 #[test]
2161 fn scan_scoped_test_file_globs_narrow_the_run_without_moving_the_runner_root() {
2162 assert_eq!(
2163 scan_scoped_test_file_globs("src"),
2164 vec!["src/**".to_string()]
2165 );
2166 assert_eq!(
2167 scan_scoped_test_file_globs("packages/core/src"),
2168 vec!["packages/core/src/**".to_string()]
2169 );
2170 }
2171
2172 #[test]
2173 fn to_scan_relative_strips_the_prefix_and_drops_out_of_scope_mutants() {
2174 let mutants = parse_normalized_results(
2175 r#"[
2176 {"file": "src/a.ts", "line": 2, "status": "survived", "mutator": "X"},
2177 {"file": "tests/e2e/t.ts", "line": 9, "status": "survived", "mutator": "X"}
2178 ]"#,
2179 )
2180 .unwrap();
2181 let rebased = to_scan_relative(mutants.clone(), Some("src"));
2182 assert_eq!(rebased.len(), 1, "the out-of-scan-path mutant is dropped");
2183 assert_eq!(rebased[0].file, "a.ts");
2184 let unchanged = to_scan_relative(mutants, None);
2185 assert_eq!(unchanged.len(), 2);
2186 assert_eq!(unchanged[0].file, "src/a.ts");
2187 }
2188
2189 #[test]
2190 fn is_mutatable_ts_keeps_sources_and_drops_tests_and_decls() {
2191 assert!(is_mutatable_ts("src/index.ts"));
2192 assert!(is_mutatable_ts("src/util.tsx"));
2193 assert!(is_mutatable_ts("src/util.js"));
2194 assert!(!is_mutatable_ts("src/index.test.ts"));
2195 assert!(!is_mutatable_ts("src/index.spec.ts"));
2196 assert!(!is_mutatable_ts("src/types.d.ts"));
2197 assert!(!is_mutatable_ts("README.md"));
2198 }
2199
2200 #[test]
2201 fn contiguous_runs_collapses_adjacent_lines() {
2202 let lines: BTreeSet<u64> = [2u64, 3, 4, 7, 9, 10].into_iter().collect();
2203 assert_eq!(contiguous_runs(&lines), vec![(2, 4), (7, 7), (9, 10)]);
2204 assert!(contiguous_runs(&BTreeSet::new()).is_empty());
2205 }
2206
2207 #[test]
2208 fn one_line_flattens_and_caps() {
2209 assert_eq!(one_line("a -\n b"), "a - b");
2210 let long = "x".repeat(80);
2211 let capped = one_line(&long);
2212 assert!(capped.chars().count() <= 61 && capped.ends_with('…'));
2213 }
2214
2215 #[test]
2216 fn mutatable_py_modules_keeps_only_the_changed_python_sources() {
2217 let changed = BTreeMap::from([
2218 ("pkg/calc.py".to_string(), BTreeSet::from([3u64])),
2219 ("pkg/calc_test.py".to_string(), BTreeSet::from([4u64])),
2220 ("README.md".to_string(), BTreeSet::from([1u64])),
2221 ("pkg/util.py".to_string(), BTreeSet::from([9u64])),
2222 ]);
2223
2224 assert_eq!(
2225 mutatable_py_modules(&changed),
2226 ["pkg/calc.py", "pkg/util.py"]
2227 );
2228 }
2229
2230 #[test]
2231 fn mutatable_py_modules_is_empty_when_the_diff_touches_no_python_source() {
2232 let changed = BTreeMap::from([("docs/guide.md".to_string(), BTreeSet::from([1u64]))]);
2233
2234 assert!(mutatable_py_modules(&changed).is_empty());
2235 }
2236
2237 #[test]
2238 fn a_diff_scoped_python_run_judges_only_mutants_on_a_changed_line() {
2239 let mutants = vec![py_mutant("pkg/calc.py", 3), py_mutant("pkg/calc.py", 99)];
2240 let changed = BTreeMap::from([("pkg/calc.py".to_string(), BTreeSet::from([3u64]))]);
2241
2242 let judged = judged_py_mutants(mutants, Path::new("/nonexistent-tc-py"), Some(&changed));
2243
2244 assert_eq!(
2245 judged.iter().map(|m| m.line).collect::<Vec<_>>(),
2246 [3],
2247 "a mutant off the diff is not this run's to judge"
2248 );
2249 }
2250
2251 #[test]
2252 fn a_typescript_run_drops_the_mutants_in_a_declaration_only_module() {
2253 let dir = unique_tmp();
2254 std::fs::write(dir.join("types.ts"), "export type Id = string;\n").unwrap();
2255 std::fs::write(dir.join("calc.ts"), "export const add = (a, b) => a + b;\n").unwrap();
2256 let mutants = vec![py_mutant("types.ts", 1), py_mutant("calc.ts", 1)];
2257
2258 let judged = judged_ts_mutants(mutants, &dir);
2259
2260 assert_eq!(
2263 judged.iter().map(|m| m.file.as_str()).collect::<Vec<_>>(),
2264 ["calc.ts"]
2265 );
2266 std::fs::remove_dir_all(&dir).ok();
2267 }
2268
2269 #[test]
2270 fn an_unscoped_python_run_judges_every_mutant() {
2271 let mutants = vec![py_mutant("pkg/calc.py", 3), py_mutant("pkg/calc.py", 99)];
2272
2273 let judged = judged_py_mutants(mutants, Path::new("/nonexistent-tc-py"), None);
2274
2275 assert_eq!(judged.iter().map(|m| m.line).collect::<Vec<_>>(), [3, 99]);
2276 }
2277
2278 fn py_mutant(file: &str, line: u32) -> NormalizedMutant {
2279 NormalizedMutant {
2280 file: file.to_string(),
2281 line,
2282 status: MutantStatus::Survived,
2283 mutator: "ConditionalExpression".to_string(),
2284 replacement: None,
2285 }
2286 }
2287
2288 #[test]
2289 fn is_mutatable_py_keeps_sources_and_drops_tests() {
2290 assert!(is_mutatable_py("calc.py"));
2291 assert!(is_mutatable_py("pkg/util.py"));
2292 assert!(!is_mutatable_py("calc_test.py"));
2293 assert!(!is_mutatable_py("test_calc.py"));
2294 assert!(!is_mutatable_py("pkg/conftest.py"));
2295 assert!(!is_mutatable_py("README.md"));
2296 }
2297
2298 #[test]
2299 fn mutated_lines_collects_caught_and_missed() {
2300 let report = parse_mutants_report(SAMPLE).unwrap();
2301 assert_eq!(
2302 mutated_lines(&report),
2303 [
2304 ("src/lib.rs".to_string(), 7),
2305 ("src/other.rs".to_string(), 3)
2306 ]
2307 .into_iter()
2308 .collect()
2309 );
2310 }
2311
2312 #[test]
2313 fn evaluate_scoped_drops_a_survivor_on_an_exempt_line() {
2314 let report = parse_mutants_report(SAMPLE).unwrap();
2315 let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([7u32]))]);
2316 let kept = evaluate_scoped(
2317 cargo_mutants_survivors(&report),
2318 &mutated_lines(&report),
2319 &[],
2320 &line_scoped,
2321 )
2322 .unwrap();
2323 assert!(
2324 kept.is_empty(),
2325 "the src/lib.rs:7 survivor should be lifted"
2326 );
2327 }
2328
2329 #[test]
2330 fn evaluate_scoped_rejects_exempting_a_caught_line() {
2331 let report = parse_mutants_report(SAMPLE).unwrap();
2332 let line_scoped = BTreeMap::from([("src/other.rs".to_string(), BTreeSet::from([3u32]))]);
2333 let err = evaluate_scoped(
2334 cargo_mutants_survivors(&report),
2335 &mutated_lines(&report),
2336 &[],
2337 &line_scoped,
2338 )
2339 .unwrap_err();
2340 assert!(
2341 err.to_string().contains("all caught") && err.to_string().contains("src/other.rs:3"),
2342 "got: {err}"
2343 );
2344 }
2345
2346 #[test]
2347 fn evaluate_scoped_leaves_an_unmutated_listed_line_alone() {
2348 let report = parse_mutants_report(SAMPLE).unwrap();
2349 let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([99u32]))]);
2350 let kept = evaluate_scoped(
2351 cargo_mutants_survivors(&report),
2352 &mutated_lines(&report),
2353 &[],
2354 &line_scoped,
2355 )
2356 .unwrap();
2357 assert_eq!(kept.len(), 1);
2358 assert_eq!(kept[0].line, 7);
2359 }
2360
2361 #[test]
2362 fn evaluate_scoped_still_honors_a_whole_file_exemption() {
2363 let report = parse_mutants_report(SAMPLE).unwrap();
2364 let kept = evaluate_scoped(
2365 cargo_mutants_survivors(&report),
2366 &mutated_lines(&report),
2367 &["src/lib.rs".to_string()],
2368 &BTreeMap::new(),
2369 )
2370 .unwrap();
2371 assert!(kept.is_empty());
2372 }
2373
2374 fn unique_tmp() -> PathBuf {
2375 static COUNTER: AtomicU64 = AtomicU64::new(0);
2376 let dir = std::env::temp_dir().join(format!(
2377 "tc-provision-test-{}-{}",
2378 std::process::id(),
2379 COUNTER.fetch_add(1, Ordering::Relaxed)
2380 ));
2381 std::fs::create_dir_all(&dir).unwrap();
2382 dir
2383 }
2384
2385 enum Install {
2386 MustNotRun,
2387 WritesNothing,
2388 WritesBin,
2389 Fails,
2390 CountsSleepsAndWritesBin(std::sync::Arc<AtomicU64>),
2391 }
2392
2393 fn write_bin(bin: &Path) {
2394 std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
2395 std::fs::write(bin, b"binary").unwrap();
2396 }
2397
2398 fn drive_provision(bin: &Path, lock: &Path, install: Install) -> Result<PathBuf> {
2399 provision(bin, lock, || match install {
2400 Install::MustNotRun => panic!("must not reinstall"),
2401 Install::WritesNothing => Ok(()),
2402 Install::WritesBin => {
2403 write_bin(bin);
2404 Ok(())
2405 }
2406 Install::Fails => bail!("install blew up"),
2407 Install::CountsSleepsAndWritesBin(count) => {
2408 count.fetch_add(1, Ordering::SeqCst);
2409 std::thread::sleep(std::time::Duration::from_millis(50));
2410 write_bin(bin);
2411 Ok(())
2412 }
2413 })
2414 }
2415
2416 #[test]
2417 fn provision_returns_an_existing_binary_without_installing() {
2418 let tmp = unique_tmp();
2419 let bin = tmp.join("bin").join("cargo-mutants");
2420 let lock = tmp.join(".install.lock");
2421 write_bin(&bin);
2422 let got = drive_provision(&bin, &lock, Install::MustNotRun).unwrap();
2423 assert_eq!(got, bin);
2424 std::fs::remove_dir_all(&tmp).unwrap();
2425 }
2426
2427 #[test]
2428 fn the_must_not_run_sentinel_panics_when_installation_runs() {
2429 let tmp = unique_tmp();
2430 std::fs::create_dir_all(&tmp).unwrap();
2431 let bin = tmp.join("bin").join("cargo-mutants");
2432 let lock = tmp.join(".install.lock");
2433 let panicked =
2434 std::panic::catch_unwind(|| drive_provision(&bin, &lock, Install::MustNotRun)).is_err();
2435 std::fs::remove_dir_all(&tmp).unwrap();
2436 assert!(panicked);
2437 }
2438
2439 #[test]
2440 fn provision_with_a_rootless_lock_path_fails_to_open_the_lock() {
2441 let bin = unique_tmp().join("bin").join("cargo-mutants");
2442 let err = drive_provision(&bin, Path::new("/"), Install::WritesNothing).unwrap_err();
2443 let msg = format!("{err:#}");
2444 assert!(msg.contains("opening the provisioning lock"), "{msg}");
2445 }
2446
2447 #[test]
2448 fn provision_installs_when_the_binary_is_absent() {
2449 let tmp = unique_tmp();
2450 let bin = tmp.join("bin").join("cargo-mutants");
2451 let lock = tmp.join(".install.lock");
2452 let got = drive_provision(&bin, &lock, Install::WritesBin).unwrap();
2453 assert_eq!(got, bin);
2454 assert_eq!(
2455 std::fs::read(&bin).unwrap(),
2456 b"binary",
2457 "an absent binary must be installed"
2458 );
2459 std::fs::remove_dir_all(&tmp).unwrap();
2460 }
2461
2462 #[test]
2463 fn provision_errors_when_install_produces_no_binary() {
2464 let tmp = unique_tmp();
2465 let bin = tmp.join("bin").join("cargo-mutants");
2466 let lock = tmp.join(".install.lock");
2467 let err = drive_provision(&bin, &lock, Install::WritesNothing).unwrap_err();
2468 assert!(
2469 err.to_string().contains("cargo-mutants is not at"),
2470 "got: {err}"
2471 );
2472 std::fs::remove_dir_all(&tmp).unwrap();
2473 }
2474
2475 #[test]
2476 fn provision_propagates_an_install_failure() {
2477 let tmp = unique_tmp();
2478 let bin = tmp.join("bin").join("cargo-mutants");
2479 let lock = tmp.join(".install.lock");
2480 let err = drive_provision(&bin, &lock, Install::Fails).unwrap_err();
2481 assert!(err.to_string().contains("install blew up"), "got: {err}");
2482 std::fs::remove_dir_all(&tmp).unwrap();
2483 }
2484
2485 #[test]
2486 fn provision_does_not_duplicate_the_install_under_concurrent_callers() {
2487 use std::sync::{Arc, Barrier};
2491 use std::thread;
2492
2493 let tmp = unique_tmp();
2494 let bin = tmp.join("bin").join("cargo-mutants");
2495 let lock = tmp.join(".install.lock");
2496 let install_count = Arc::new(AtomicU64::new(0));
2497 let barrier = Arc::new(Barrier::new(2));
2498
2499 let handles: Vec<_> = (0..2)
2500 .map(|_| {
2501 let bin = bin.clone();
2502 let lock = lock.clone();
2503 let install_count = Arc::clone(&install_count);
2504 let barrier = Arc::clone(&barrier);
2505 thread::spawn(move || {
2506 barrier.wait();
2507 drive_provision(
2508 &bin,
2509 &lock,
2510 Install::CountsSleepsAndWritesBin(install_count),
2511 )
2512 })
2513 })
2514 .collect();
2515
2516 for h in handles {
2517 h.join()
2518 .expect("provisioning thread must not panic")
2519 .unwrap();
2520 }
2521
2522 assert_eq!(
2523 install_count.load(Ordering::SeqCst),
2524 1,
2525 "two concurrent callers on a cold cache must share one install, not each run their own"
2526 );
2527 std::fs::remove_dir_all(&tmp).unwrap();
2528 }
2529
2530 #[test]
2531 fn resolve_cache_base_prefers_xdg_then_home_then_temp() {
2532 let xdg = |s: &str| Some(OsString::from(s));
2533 assert_eq!(
2534 resolve_cache_base(xdg("/xdg"), xdg("/home")),
2535 PathBuf::from("/xdg")
2536 );
2537 assert_eq!(
2538 resolve_cache_base(xdg(""), xdg("/home")),
2539 PathBuf::from("/home/.cache")
2540 );
2541 assert_eq!(
2542 resolve_cache_base(None, xdg("/home")),
2543 PathBuf::from("/home/.cache")
2544 );
2545 assert_eq!(resolve_cache_base(None, None), std::env::temp_dir());
2546 assert_eq!(
2547 resolve_cache_base(xdg(""), Some(OsString::new())),
2548 std::env::temp_dir()
2549 );
2550 }
2551
2552 #[test]
2553 fn cache_root_is_absolute_and_version_scoped() {
2554 let root = cargo_mutants_cache_root();
2555 assert!(
2556 root.ends_with(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}")),
2557 "version-scoped; got {root:?}"
2558 );
2559 assert!(
2560 root.to_string_lossy().contains("testing-conventions"),
2561 "tool-namespaced; got {root:?}"
2562 );
2563 assert!(
2564 root.is_absolute(),
2565 "expected an absolute path; got {root:?}"
2566 );
2567 }
2568
2569 #[test]
2570 fn install_argv_pins_the_version_and_isolates_the_root() {
2571 let argv: Vec<String> = install_argv(Path::new("/cache/cargo-mutants-27"))
2572 .iter()
2573 .map(|arg| arg.to_string_lossy().into_owned())
2574 .collect();
2575 assert_eq!(
2576 argv,
2577 vec![
2578 "install",
2579 "cargo-mutants",
2580 "--locked",
2581 "--version",
2582 CARGO_MUTANTS_VERSION,
2583 "--root",
2584 "/cache/cargo-mutants-27",
2585 ]
2586 );
2587 }
2588
2589 #[test]
2590 fn mutants_argv_enables_features_on_the_engine_itself() {
2591 let argv = |diff, features: &[&str]| -> Vec<String> {
2592 mutants_argv(
2593 Path::new("/out"),
2594 diff,
2595 &features.iter().map(|f| f.to_string()).collect::<Vec<_>>(),
2596 )
2597 .iter()
2598 .map(|arg| arg.to_string_lossy().into_owned())
2599 .collect()
2600 };
2601 assert_eq!(
2602 argv(None, &["cli", "boost"]),
2603 vec![
2604 "mutants",
2605 "--output",
2606 "/out",
2607 "--cargo-test-arg",
2608 "--lib",
2609 "--features",
2610 "cli,boost"
2611 ]
2612 );
2613 assert_eq!(
2614 argv(Some(Path::new("/out/base.diff")), &["cli"]),
2615 vec![
2616 "mutants",
2617 "--output",
2618 "/out",
2619 "--cargo-test-arg",
2620 "--lib",
2621 "--in-diff",
2622 "/out/base.diff",
2623 "--features",
2624 "cli",
2625 ]
2626 );
2627 assert_eq!(
2628 argv(None, &[]),
2629 vec!["mutants", "--output", "/out", "--cargo-test-arg", "--lib"]
2630 );
2631 }
2632
2633 #[test]
2634 fn list_argv_mirrors_the_run_feature_selection() {
2635 let argv = |features: &[&str]| -> Vec<String> {
2636 list_argv(&features.iter().map(|f| f.to_string()).collect::<Vec<_>>())
2637 .iter()
2638 .map(|arg| arg.to_string_lossy().into_owned())
2639 .collect()
2640 };
2641 assert_eq!(argv(&[]), vec!["mutants", "--list", "--json"]);
2642 assert_eq!(
2643 argv(&["cli", "boost"]),
2644 vec!["mutants", "--list", "--json", "--features", "cli,boost"]
2645 );
2646 }
2647
2648 #[test]
2649 fn parse_base_diff_maps_inserted_lines_per_hunk() {
2650 let diff = "\
2651diff --git a/src/lib.rs b/src/lib.rs
2652--- a/src/lib.rs
2653+++ b/src/lib.rs
2654@@ -1,4 +1,5 @@
2655 fn a() {}
2656+fn b() {}
2657 fn c() {}
2658-fn d() {}
2659+fn e() {}
2660 fn f() {}
2661@@ -10,2 +11,4 @@
2662 tail
2663+one
2664+two
2665 more
2666";
2667 let parsed = parse_base_diff(diff);
2668 assert_eq!(parsed.files, vec!["src/lib.rs"]);
2669 assert_eq!(
2670 parsed.inserted.get("src/lib.rs"),
2671 Some(&BTreeSet::from([2, 4, 12, 13]))
2672 );
2673 }
2674
2675 #[test]
2676 fn parse_base_diff_leaves_a_deletion_only_file_without_inserted_lines() {
2677 let diff = "\
2678--- a/src/gone.rs
2679+++ b/src/gone.rs
2680@@ -5,2 +4,0 @@
2681-x
2682-y
2683";
2684 let parsed = parse_base_diff(diff);
2685 assert_eq!(parsed.files, vec!["src/gone.rs"]);
2686 assert!(parsed.inserted.is_empty());
2687 }
2688
2689 #[test]
2690 fn parse_base_diff_skips_a_deleted_file() {
2691 let diff = "\
2692--- a/src/dead.rs
2693+++ /dev/null
2694@@ -1,2 +0,0 @@
2695-a
2696-b
2697";
2698 let parsed = parse_base_diff(diff);
2699 assert!(parsed.files.is_empty());
2700 assert!(parsed.inserted.is_empty());
2701 }
2702
2703 #[test]
2704 fn parse_base_diff_consumes_hunk_bodies_by_count_so_content_never_reads_as_a_header() {
2705 let diff = "\
2708+++ b/notes.txt
2709@@ -1,1 +1,2 @@
2710 keep
2711++++ not a header
2712";
2713 let parsed = parse_base_diff(diff);
2714 assert_eq!(parsed.files, vec!["notes.txt"]);
2715 assert_eq!(parsed.inserted.get("notes.txt"), Some(&BTreeSet::from([2])));
2716 }
2717
2718 #[test]
2719 fn parse_base_diff_defaults_an_elided_hunk_count_to_one() {
2720 let diff = "\
2721+++ b/one.txt
2722@@ -1 +1 @@
2723-old
2724+new
2725";
2726 let parsed = parse_base_diff(diff);
2727 assert_eq!(parsed.inserted.get("one.txt"), Some(&BTreeSet::from([1])));
2728 }
2729
2730 #[test]
2731 fn parse_base_diff_skips_no_newline_annotations_mid_hunk() {
2732 let diff = "\
2733+++ b/n.txt
2734@@ -1 +1 @@
2735-old
2736\\ No newline at end of file
2737+new
2738\\ No newline at end of file
2739";
2740 let parsed = parse_base_diff(diff);
2741 assert_eq!(parsed.inserted.get("n.txt"), Some(&BTreeSet::from([1])));
2742 }
2743
2744 #[cfg(unix)]
2745 fn fake_output(code: i32, stderr: &str) -> Output {
2746 use std::os::unix::process::ExitStatusExt;
2747 Output {
2748 status: std::process::ExitStatus::from_raw(code << 8),
2749 stdout: Vec::new(),
2750 stderr: stderr.as_bytes().to_vec(),
2751 }
2752 }
2753
2754 #[cfg(unix)]
2755 enum FakeRun {
2756 AssertsVersionAndSucceeds,
2757 FailsWith(&'static str),
2758 SpawnError,
2759 }
2760
2761 #[cfg(unix)]
2762 fn drive_install(root: &Path, run: FakeRun) -> Result<()> {
2763 run_install(root, |command| match run {
2764 FakeRun::AssertsVersionAndSucceeds => {
2765 let argv: Vec<String> = command
2766 .get_args()
2767 .map(|arg| arg.to_string_lossy().into_owned())
2768 .collect();
2769 assert!(argv.contains(&CARGO_MUTANTS_VERSION.to_string()));
2770 Ok(fake_output(0, ""))
2771 }
2772 FakeRun::FailsWith(stderr) => Ok(fake_output(1, stderr)),
2773 FakeRun::SpawnError => Err(std::io::Error::new(
2774 std::io::ErrorKind::NotFound,
2775 "no cargo",
2776 )),
2777 })
2778 }
2779
2780 #[cfg(unix)]
2781 #[test]
2782 fn run_install_succeeds_on_a_zero_exit() {
2783 drive_install(Path::new("/cache/root"), FakeRun::AssertsVersionAndSucceeds).unwrap();
2784 }
2785
2786 #[cfg(unix)]
2787 #[test]
2788 fn run_install_reports_a_nonzero_exit_with_the_engine_output() {
2789 let err = drive_install(
2790 Path::new("/cache/root"),
2791 FakeRun::FailsWith("error: could not compile cargo-mutants"),
2792 )
2793 .unwrap_err();
2794 assert!(
2795 err.to_string()
2796 .contains("failed to provision cargo-mutants")
2797 && err.to_string().contains("could not compile"),
2798 "got: {err}"
2799 );
2800 }
2801
2802 #[cfg(unix)]
2803 #[test]
2804 fn run_install_propagates_a_spawn_failure() {
2805 let err = drive_install(Path::new("/cache/root"), FakeRun::SpawnError).unwrap_err();
2806 assert!(
2807 err.to_string().contains("is cargo installed?"),
2808 "got: {err}"
2809 );
2810 }
2811
2812 #[cfg(unix)]
2813 #[test]
2814 fn provision_pinned_installs_via_the_injected_runner() {
2815 let root = unique_tmp();
2816 let bin = root.join("bin").join(CARGO_MUTANTS_BIN_NAME);
2817 let expected = bin.clone();
2818 let got = provision_pinned(&root, |_| {
2819 write_bin(&bin);
2820 Ok(fake_output(0, ""))
2821 })
2822 .unwrap();
2823 assert_eq!(got, expected);
2824 std::fs::remove_dir_all(&root).unwrap();
2825 }
2826
2827 #[test]
2828 fn execute_surfaces_a_spawn_failure() {
2829 let err = execute(&mut Command::new("/nonexistent-tc-cargo")).unwrap_err();
2830 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
2831 }
2832
2833 #[cfg(unix)]
2834 fn fake_stdout(code: i32, stdout: &str) -> Output {
2835 use std::os::unix::process::ExitStatusExt;
2836 Output {
2837 status: std::process::ExitStatus::from_raw(code << 8),
2838 stdout: stdout.as_bytes().to_vec(),
2839 stderr: Vec::new(),
2840 }
2841 }
2842
2843 #[cfg(unix)]
2844 enum FakeList {
2845 AssertsArgvAndReturns(&'static str, Vec<&'static str>),
2846 FailsWith(&'static str),
2847 SpawnError,
2848 }
2849
2850 #[cfg(unix)]
2851 fn drive_list(features: &[String], run: FakeList) -> Result<Vec<MutantInfo>> {
2852 list_cargo_mutants(
2853 Path::new("/cache/bin/cargo-mutants"),
2854 Path::new("/crate"),
2855 features,
2856 |command| match run {
2857 FakeList::AssertsArgvAndReturns(json, expected) => {
2858 let argv: Vec<String> = command
2859 .get_args()
2860 .map(|arg| arg.to_string_lossy().into_owned())
2861 .collect();
2862 assert_eq!(argv, expected);
2863 assert_eq!(command.get_current_dir(), Some(Path::new("/crate")));
2864 Ok(fake_stdout(0, json))
2865 }
2866 FakeList::FailsWith(stderr) => Ok(fake_output(1, stderr)),
2867 FakeList::SpawnError => Err(std::io::Error::new(
2868 std::io::ErrorKind::NotFound,
2869 "no engine",
2870 )),
2871 },
2872 )
2873 }
2874
2875 #[cfg(unix)]
2876 #[test]
2877 fn list_cargo_mutants_parses_the_listing_from_a_clean_run() {
2878 let json = r#"[{"file": "src/lib.rs", "name": "replace add -> 0", "genre": "FnValue",
2879 "span": {"start": {"line": 3, "column": 1}, "end": {"line": 5, "column": 2}}}]"#;
2880 let listed = drive_list(
2881 &["cli".to_string()],
2882 FakeList::AssertsArgvAndReturns(
2883 json,
2884 vec!["mutants", "--list", "--json", "--features", "cli"],
2885 ),
2886 )
2887 .unwrap();
2888 assert_eq!(listed.len(), 1);
2889 assert_eq!(listed[0].file, "src/lib.rs");
2890 assert_eq!(listed[0].span.start.line, 3);
2891 assert_eq!(listed[0].span.end.line, 5);
2892 assert_eq!(listed[0].name, "replace add -> 0");
2893 }
2894
2895 #[cfg(unix)]
2896 #[test]
2897 fn list_cargo_mutants_reports_a_nonzero_exit_with_the_engine_output() {
2898 let err = drive_list(&[], FakeList::FailsWith("error: no such option")).unwrap_err();
2899 assert!(
2900 err.to_string().contains("cargo-mutants --list failed")
2901 && err.to_string().contains("no such option"),
2902 "got: {err}"
2903 );
2904 }
2905
2906 #[cfg(unix)]
2907 #[test]
2908 fn list_cargo_mutants_propagates_a_spawn_failure() {
2909 let err = drive_list(&[], FakeList::SpawnError).unwrap_err();
2910 assert!(
2911 err.to_string()
2912 .contains("listing the crate's mutants with cargo-mutants"),
2913 "got: {err}"
2914 );
2915 }
2916
2917 #[cfg(unix)]
2918 #[test]
2919 fn a_dropped_site_renders_indented_with_its_location_stripped_from_the_name() {
2920 let mutant = listed_mutant("src/a.rs", 12, 14, "src/a.rs:12:5: replace foo with bar");
2921
2922 assert_eq!(mutant_site(&mutant), " src/a.rs:12: replace foo with bar");
2923 }
2924
2925 #[cfg(unix)]
2926 fn listed_mutant(file: &str, start: u32, end: u32, name: &str) -> MutantInfo {
2927 MutantInfo {
2928 file: file.to_string(),
2929 span: Span {
2930 start: LineCol { line: start },
2931 end: LineCol { line: end },
2932 },
2933 name: name.to_string(),
2934 genre: "FnValue".to_string(),
2935 }
2936 }
2937
2938 #[cfg(unix)]
2939 fn diff_with_inserted(file: &str, lines: &[u32]) -> BaseDiff {
2940 BaseDiff {
2941 files: vec![file.to_string()],
2942 inserted: BTreeMap::from([(file.to_string(), lines.iter().copied().collect())]),
2943 }
2944 }
2945
2946 #[cfg(unix)]
2947 #[test]
2948 fn zero_mutant_verdict_accepts_a_zero_with_no_mutant_on_the_inserted_lines() {
2949 let run = fake_output(0, "");
2950 zero_mutant_verdict(&[], &diff_with_inserted("src/lib.rs", &[5]), &run).unwrap();
2951 let listed = [listed_mutant("src/lib.rs", 5, 8, "replace add -> 0")];
2952 zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[4, 9]), &run).unwrap();
2953 zero_mutant_verdict(&listed, &diff_with_inserted("src/other.rs", &[6]), &run).unwrap();
2954 }
2955
2956 #[cfg(unix)]
2957 #[test]
2958 fn zero_mutant_verdict_is_fatal_on_a_mutant_at_either_span_boundary() {
2959 let listed = [listed_mutant("src/lib.rs", 5, 8, "replace add -> 0")];
2960 let run = fake_stdout(0, "0 mutants tested");
2961 for line in [5, 8] {
2962 let err =
2963 zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[line]), &run)
2964 .unwrap_err();
2965 let message = err.to_string();
2966 assert!(
2967 message.contains("1 of the crate's 1 mutant site(s)")
2968 && message.contains("src/lib.rs:5: replace add -> 0")
2969 && message.contains("0 mutants tested"),
2970 "got: {message}"
2971 );
2972 }
2973 }
2974
2975 #[cfg(unix)]
2976 #[test]
2977 fn zero_mutant_verdict_names_each_dropped_site_once() {
2978 let listed = [
2979 listed_mutant(
2980 "src/lib.rs",
2981 7,
2982 7,
2983 "src/lib.rs:7:7: replace > with == in is_positive",
2984 ),
2985 listed_mutant("src/lib.rs", 7, 7, "replace add -> 0"),
2986 ];
2987 let run = fake_stdout(0, "0 mutants tested");
2988 let message = zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[7]), &run)
2989 .unwrap_err()
2990 .to_string();
2991 assert!(
2992 message.contains(" src/lib.rs:7: replace > with == in is_positive"),
2993 "the name's embedded `file:line:col:` prefix is stripped; got: {message}"
2994 );
2995 assert!(
2996 !message.contains(": src/lib.rs:7:7:"),
2997 "a dropped site carries one location; got: {message}"
2998 );
2999 assert!(
3000 message.contains(" src/lib.rs:7: replace add -> 0"),
3001 "a name with no embedded location keeps its rendered location; got: {message}"
3002 );
3003 }
3004
3005 #[cfg(unix)]
3006 #[test]
3007 fn classify_mutants_exit_accepts_the_caught_and_survivor_exits() {
3008 classify_mutants_exit(Path::new("/crate"), &fake_output(0, "")).unwrap();
3009 classify_mutants_exit(Path::new("/crate"), &fake_output(2, "")).unwrap();
3010 }
3011
3012 #[cfg(unix)]
3013 #[test]
3014 fn classify_mutants_exit_accepts_a_timeout_exit_3() {
3015 classify_mutants_exit(Path::new("/crate"), &fake_output(3, ""))
3016 .expect("a timeout (exit 3) is inconclusive, not fatal");
3017 }
3018
3019 #[cfg(unix)]
3020 #[test]
3021 fn classify_mutants_exit_is_fatal_on_a_baseline_failure() {
3022 let err = classify_mutants_exit(Path::new("/crate"), &fake_output(4, "baseline broke"))
3023 .unwrap_err();
3024 assert!(
3025 err.to_string().contains("did not run cleanly")
3026 && err.to_string().contains("baseline broke"),
3027 "got: {err}"
3028 );
3029 }
3030
3031 #[test]
3032 fn cargo_mutants_bin_name_matches_the_platform() {
3033 #[cfg(windows)]
3034 assert_eq!(CARGO_MUTANTS_BIN_NAME, "cargo-mutants.exe");
3035 #[cfg(not(windows))]
3036 assert_eq!(CARGO_MUTANTS_BIN_NAME, "cargo-mutants");
3037 }
3038
3039 fn one_file_diff(file: &str) -> String {
3041 format!("diff --git a/{file} b/{file}\n--- a/{file}\n+++ b/{file}\n@@ -1,0 +1,1 @@\n+x\n")
3042 }
3043
3044 #[test]
3045 fn a_diff_touching_rust_source_is_in_scope_with_its_parsed_reading() {
3046 let (path, parsed) = rust_scope(
3047 Some(PathBuf::from("base.diff")),
3048 Some(one_file_diff("src/lib.rs")),
3049 )
3050 .expect("a diff touching a .rs file is in scope");
3051
3052 assert_eq!(path, PathBuf::from("base.diff"));
3053 assert_eq!(parsed.files, vec!["src/lib.rs".to_string()]);
3054 }
3055
3056 #[test]
3057 fn a_diff_touching_no_rust_source_is_out_of_scope() {
3058 assert!(rust_scope(
3059 Some(PathBuf::from("base.diff")),
3060 Some(one_file_diff("docs/readme.md")),
3061 )
3062 .is_none());
3063 }
3064
3065 #[test]
3066 fn a_run_whose_git_diff_wrote_nothing_is_out_of_scope() {
3067 assert!(rust_scope(None, None).is_none());
3068 assert!(rust_scope(Some(PathBuf::from("base.diff")), None).is_none());
3069 }
3070
3071 #[test]
3072 fn a_deletion_only_hunk_still_consumes_the_lines_it_declared() {
3073 let text = "-gone\n--- a/not-a-file.rs\n";
3077 let mut lines = text.lines();
3078 let mut inserted = BTreeMap::new();
3079
3080 consume_hunk(
3081 &mut lines,
3082 (1, 1, 0),
3083 Some(&"src/lib.rs".to_string()),
3084 &mut inserted,
3085 );
3086
3087 assert!(inserted.is_empty(), "a deletion inserts nothing");
3088 assert_eq!(lines.next(), Some("--- a/not-a-file.rs"));
3089 }
3090}