Skip to main content

testing_conventions/
mutation.rs

1//! Mutation testing (`unit mutation`) — the rung above coverage: a test that *runs* a
2//! line still passes if you delete its assertions, and a surviving mutant proves it. Each
3//! language drives its engine through an adapter; this module measures, the CLI layer gates.
4
5use 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/// A surviving mutant — a mutation the unit suite ran but failed to catch.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Survivor {
19    /// The mutated file, scan-path-relative and `/`-separated — cargo-mutants reports
20    /// workspace-root-relative paths, rebased onto the scan path before gating.
21    pub file: String,
22    /// The 1-based line the mutation starts on.
23    pub line: u32,
24    /// cargo-mutants' human description (e.g. `replace > with == in is_positive`).
25    pub description: String,
26}
27
28/// One mutation measurement: whether the engine ran, and what it found. Telling
29/// [`Measurement::EngineNotRun`] from an all-killed [`Measurement::Tested`] keeps a vacuous
30/// pass visible, and a counted pass carries its own evidence.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Measurement {
33    /// The `--base` diff carried no mutatable changed lines; the engine never ran.
34    EngineNotRun,
35    /// The engine ran: `count` viable, conclusive mutants judged (caught or missed),
36    /// `survivors` the un-exempted surviving ones.
37    Tested {
38        count: usize,
39        survivors: Vec<Survivor>,
40    },
41}
42
43/// The `(file, line)` locations an engine produced a viable mutant for — the input the
44/// line-scoped guard reads to tell an over-exemption (a listed line whose mutants
45/// were all caught) from an out-of-scope line (no mutant there).
46pub type MutatedLines = BTreeSet<(String, u32)>;
47
48/// `true` when `file` (resolved against `base`) is a declaration-only module, per the same
49/// [`Language::is_subject`] predicate `colocated-test` uses. An unreadable file is never
50/// dropped, so it stays a survivor rather than vanishing silently.
51fn 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
58/// `true` when the mutant at `line` of `file` (resolved against `base`) sits inside an item a
59/// test build never compiles. An unreadable file is never dropped, so it stays a survivor rather
60/// than vanishing silently.
61fn 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
66/// `true` when `mutant` replaces the whole body of a subprocess seam — cargo-mutants' `FnValue`
67/// genre, landing in a branch-free function that runs a `Command`. Calling such a function spawns,
68/// so no unit test can observe the replacement. Every other genre there is still judged.
69fn 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
77/// `true` when `mutant` faces the unit tier's judgment. Three shapes do not: a mutant in a
78/// declaration-only module, one inside an item the test build never compiles, and a whole-body
79/// replacement in a subprocess seam.
80fn 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/// A cargo-mutants `outcomes.json` export, pared to what the rule reads. Unmodeled
87/// fields (`total_mutants`, `caught`, timings, …) are ignored.
88#[derive(Debug, Clone, Deserialize)]
89pub struct MutantsReport {
90    pub outcomes: Vec<MutantOutcome>,
91}
92
93/// One scenario's outcome. `summary` is cargo-mutants' result word — `Success` for the
94/// unmutated baseline, `CaughtMutant` / `MissedMutant` (and `Timeout` / `Unviable`)
95/// for each mutant.
96#[derive(Debug, Clone, Deserialize)]
97pub struct MutantOutcome {
98    pub summary: String,
99    pub scenario: Scenario,
100}
101
102/// The scenario a result came from: the unmutated baseline, or one mutant. Matches
103/// cargo-mutants' externally-tagged JSON (`"Baseline"` vs `{"Mutant": {…}}`).
104#[derive(Debug, Clone, Deserialize)]
105pub enum Scenario {
106    Baseline,
107    Mutant(MutantInfo),
108}
109
110/// The mutant a scenario describes, pared to the location + description the report
111/// needs, plus the `genre` naming which operator produced it. cargo-mutants also carries
112/// `function`, `package`, `replacement`; those are ignored.
113#[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/// A source span; the start and end lines are read.
122#[derive(Debug, Clone, Deserialize)]
123pub struct Span {
124    pub start: LineCol,
125    pub end: LineCol,
126}
127
128/// A line/column position; only the line is read.
129#[derive(Debug, Clone, Deserialize)]
130pub struct LineCol {
131    pub line: u32,
132}
133
134/// Parse a cargo-mutants `outcomes.json` export.
135pub fn parse_mutants_report(json: &str) -> Result<MutantsReport> {
136    serde_json::from_str(json).context("parsing cargo-mutants outcomes.json")
137}
138
139/// Parse a `cargo mutants --list --json` export: the crate's discoverable mutants, each
140/// with its workspace-root-relative file and span.
141fn parse_mutants_list(json: &str) -> Result<Vec<MutantInfo>> {
142    serde_json::from_str(json).context("parsing the cargo-mutants mutant list")
143}
144
145/// The surviving mutants not lifted by a `mutation` exemption — the rule's findings.
146/// `exempt` is the resolved set of crate-root-relative exempt paths; a survivor in an
147/// exempt file is dropped.
148pub fn unexplained_survivors(report: &MutantsReport, exempt: &[String]) -> Vec<Survivor> {
149    evaluate(cargo_mutants_survivors(report), exempt)
150}
151
152/// The surviving mutants in a cargo-mutants report — the raw list before exemptions.
153/// A survivor is a `MissedMutant` outcome (the suite ran the mutated code but no test
154/// failed). `Timeout` / `Unviable` are not survivors.
155fn 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
175/// Strip the `file:line:col: ` prefix cargo-mutants embeds in a mutant's name; a rendered site
176/// already leads with `file:line:`, so keeping the prefix prints the location twice.
177fn 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
190/// The `(file, line)` locations cargo-mutants produced a **viable, conclusive** mutant for —
191/// caught or missed, not the inconclusive `Timeout` / `Unviable`. The line-scoped guard reads
192/// this to tell an over-exemption from a line that has no mutant at all.
193pub 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
209/// The number of viable, conclusive mutants in a cargo-mutants report — `CaughtMutant`
210/// plus `MissedMutant`, the same set [`mutated_lines`] reads. A passing run states this
211/// count as its evidence.
212fn conclusive_count(report: &MutantsReport) -> usize {
213    report
214        .outcomes
215        .iter()
216        .filter(|outcome| outcome.summary == "CaughtMutant" || outcome.summary == "MissedMutant")
217        .count()
218}
219
220/// The shared whole-file evaluation core: drop the survivors lifted by a file-level
221/// `mutation` exemption. [`evaluate_scoped`] generalizes this to per-line exemptions.
222pub 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
229/// Apply file- and line-scoped `mutation` exemptions to the raw `survivors`, with the
230/// determinism guard: a listed line whose mutants were all *caught* is over-exemption and a
231/// hard error, while a listed line with no mutant is left alone (it may be off the diff).
232pub 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/// A mutant's outcome, normalized across the engines (Stryker / cosmic-ray / cargo-mutants)
272/// so the Rust core gates on one representation instead of three report formats. The
273/// serialized form is `snake_case` (`no_coverage`, `compile_error`, …) — the adapters' wire contract.
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum MutantStatus {
277    /// A test ran the mutated code but none failed — a survivor.
278    Survived,
279    /// A test failed on the mutant — caught.
280    Killed,
281    /// No test exercised the mutant at all — a survivor (worse than `Survived`).
282    NoCoverage,
283    /// The mutant ran but the suite timed out — inconclusive, not a survivor (but viable).
284    Timeout,
285    /// The mutant never compiled — not a viable mutant.
286    CompileError,
287    /// The mutant errored at runtime before a test could judge it — not viable.
288    RuntimeError,
289}
290
291impl MutantStatus {
292    /// Whether this outcome is a **survivor** — a mutant the suite failed to catch
293    /// (`Survived` or `NoCoverage`). Mirrors the per-engine survivor rules.
294    fn is_survivor(self) -> bool {
295        matches!(self, MutantStatus::Survived | MutantStatus::NoCoverage)
296    }
297
298    /// Whether this came from a **viable, conclusive** mutant — one that actually ran, not one
299    /// that never compiled or errored out. The determinism guard reads this.
300    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    /// Whether the suite **judged** this mutant (`Survived` / `Killed` / `NoCoverage`) —
311    /// the conclusive set a passing run counts as its evidence. A `Timeout` ran but
312    /// judged nothing; `CompileError` / `RuntimeError` never produced a viable mutant.
313    fn is_conclusive(self) -> bool {
314        matches!(
315            self,
316            MutantStatus::Survived | MutantStatus::Killed | MutantStatus::NoCoverage
317        )
318    }
319}
320
321/// One mutant in the normalized result set: the engine-agnostic shape every language
322/// adapter emits. Extra fields an adapter includes are ignored.
323#[derive(Debug, Clone, Deserialize)]
324pub struct NormalizedMutant {
325    /// Project-relative, `/`-separated path of the mutated file.
326    pub file: String,
327    /// The 1-based line the mutant starts on.
328    pub line: u32,
329    /// The outcome, normalized across engines.
330    pub status: MutantStatus,
331    /// The engine's mutator/operator name (e.g. `ConditionalExpression`).
332    pub mutator: String,
333    /// The replacement text, when the engine reports one — used for a readable description.
334    #[serde(default)]
335    pub replacement: Option<String>,
336}
337
338/// Parse the normalized results an engine adapter emits — a flat JSON array of
339/// [`NormalizedMutant`].
340pub fn parse_normalized_results(json: &str) -> Result<Vec<NormalizedMutant>> {
341    serde_json::from_str(json).context("parsing normalized mutation results")
342}
343
344/// Gate a normalized result set: drop the survivors lifted by a file- or line-scoped
345/// `mutation` exemption (with the determinism guard), leaving the rule's findings. This is
346/// the engine-agnostic core each language arm feeds once its adapter has normalized.
347pub 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
360/// The surviving mutants in a normalized result set — the raw list before exemptions.
361fn 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
373/// The `(file, line)` of every viable, conclusive mutant in a normalized result set — the
374/// input the line-scoped guard in [`evaluate_scoped`] reads.
375fn 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
383/// The number of conclusive mutants in a normalized result set — the count a passing
384/// run states as its evidence, parity with [`conclusive_count`].
385fn normalized_conclusive_count(mutants: &[NormalizedMutant]) -> usize {
386    mutants
387        .iter()
388        .filter(|mutant| mutant.status.is_conclusive())
389        .count()
390}
391
392/// A one-line description for a normalized mutant: the mutator name, plus the replacement
393/// (flattened + capped via [`one_line`]) when the engine reported one.
394fn 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
401/// Run cargo-mutants over the crate at `root` and return the [`Measurement`], or
402/// [`Measurement::EngineNotRun`] for a `base` diff that changes no lines — or no Rust source
403/// — under the crate. The tool provisions cargo-mutants itself ([`ensure_cargo_mutants`]).
404pub 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    // cargo-mutants addresses files relative to the crate's cargo workspace root, so both the
413    // `--in-diff` diff it consumes and the report paths it emits carry the scan path's
414    // workspace-relative prefix. A standalone crate is its own workspace root: no prefix.
415    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    // cargo-mutants writes no `outcomes.json` when a run produces no mutants, so a missing
428    // report here is a run that judged zero.
429    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
437/// Where to run the `--base` diff and with what argv. With no prefix the scan path is its own
438/// cargo workspace root, so the diff runs there unscoped; with one, it runs at the workspace
439/// root scoped by the prefix pathspec, because that is the frame cargo-mutants reads
440/// `--in-diff` paths in. `--relative` either way.
441fn 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
456/// The error a failed `--base` diff becomes. Kept beside [`base_diff_command`] so the spawn
457/// itself stays a thin seam.
458fn 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
468/// What a Rust run is scoped to.
469enum RustScope {
470    /// `--base` changed no lines, or no Rust source, under the crate: the engine has nothing
471    /// to judge and should not run at all.
472    NothingToJudge,
473    /// No `--base`: every mutant in the crate is in scope.
474    WholeCrate,
475    /// `--base` given and non-empty: the written diff file, and the tool's reading of it.
476    Diff(PathBuf, BaseDiff),
477}
478
479/// Resolve what `base` scopes the Rust engine to. Without a `base` the whole crate is in
480/// scope; with one, an empty diff means there is nothing to judge.
481fn 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
499/// The diff to scope the engine by, as the written diff file and the tool's own reading of it.
500/// `None` when `base` changes no lines, or no Rust source, under the crate — the engine has
501/// nothing to judge and should not run.
502fn 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
514/// The scope a base diff describes, as the diff file and the tool's own reading of it. `None`
515/// when `git diff` wrote nothing, or when the diff touches no Rust source — then no mutant of
516/// it could be in scope and the engine should not run. Held apart from [`rust_diff_scope`] so
517/// that seam is branch-free: its body spawns `git`, so no unit test can judge a replacement of
518/// the whole body, while every decision it used to carry is pure and asserted here.
519fn 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
528/// The measurement a finished run's `outcomes.json` reports: the survivors no exemption lifts,
529/// counted over the mutants the test build can actually reach.
530fn 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
554/// The measurement for a run that wrote no report at all. A zero is legitimate only if none of
555/// the crate's mutants sits on the diff, which [`zero_mutant_verdict`] proves before it stands.
556/// An unscoped run has no diff to check the zero against, so its zero stands on its own.
557fn 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
579/// Collapse a (possibly multi-line) replacement to a single trimmed line, capped, so a
580/// survivor's one-line description stays readable.
581fn 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
591/// Run the bundled TypeScript mutation adapter over the scan path at `root` and return the
592/// [`Measurement`] — the TS arm, parity with [`measure_rust`]. The adapter runs at the package
593/// root and its results are rebased scan-path-relative, so exemption paths match every check.
594pub 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
619/// The mutants the TypeScript arm judges: every one outside a declaration-only module, which
620/// has no behaviour for a mutant to change. An unreadable file is judged rather than dropped
621/// silently, which is what `is_declaration_only` already guarantees.
622fn 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
628/// The measurement a judged, normalized mutant set reports: the conclusive count, and the
629/// survivors left once the `mutation` exemptions have been applied.
630fn 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
641/// What a TypeScript run is scoped to.
642enum TsScope {
643    /// `--base` changed no mutable lines: the engine has nothing to judge.
644    NothingToJudge,
645    /// The adapter's `--mutate` specs. `None` leaves the whole package in scope, which is
646    /// what a scan path that *is* the package root wants.
647    Mutate(Option<Vec<String>>),
648}
649
650/// Resolve what `base` scopes the TypeScript adapter to. With a `base`, the changed ranges
651/// become `--mutate` specs and an empty set means there is nothing to judge; without one,
652/// the scan prefix alone scopes the run.
653fn 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
664/// The scan path relative to its package root, as a `/`-joined string. `None` when the scan
665/// path *is* the package root, which also covers a loose tree with no manifest.
666fn 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
679/// Prefix diff-scoped mutate specs (`<file>:<start>-<end>`, scan-path-relative) with the
680/// scan prefix, so they address the same files from the package root the adapter runs at.
681fn 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
691/// Stryker's default `mutate` set re-rooted at the scan path: every source under it except
692/// test files and `__tests__` trees — the same shape Stryker itself defaults to for
693/// `{src,lib}`, addressed from the package root the adapter runs at.
694fn 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
702/// The test files under the scan path, addressed from the package root the adapter runs at.
703/// Stryker matches these against the project's input files and hands the runner that subset,
704/// so vitest stays rooted at the package root and its own `include` resolves unchanged.
705fn scan_scoped_test_file_globs(prefix: &str) -> Vec<String> {
706    vec![format!("{prefix}/**")]
707}
708
709/// Rebase package-root-relative mutant paths onto the scan path: strip the scan prefix so
710/// exemption matching and the reported survivors address scan-path-relative files, as every
711/// other check does. A mutant outside the scan path is outside the gate's scope and dropped.
712fn 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
726/// The checked working directory for an adapter run rooted at `root`, for the named `engine`.
727/// [`crate::tiers::package_root`] hands back `""` for a relative scan path like `src`, and
728/// `Command::current_dir("")` fails with the same ENOENT a missing interpreter gives.
729fn 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
744/// The context a failed adapter spawn carries. `Command::output()` surfaces a bare ENOENT
745/// that names nothing, so the message names every path the spawn used: the interpreter, the
746/// entry point it was handed, and the directory it ran in.
747fn 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
754/// The adapter's optional argv: a `--mutate` pair when the run is scoped to a file list, and
755/// a `--test-files` pair when it is scoped to a test-glob list. Either absent means "no
756/// restriction", which is not the same as an empty list.
757fn 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
770/// Run the bundled TS mutation `adapter` at `package_root` and return the normalized-results
771/// JSON it writes. Results go to a temp file the adapter names via `--out`, so Stryker's own
772/// stdout logging can't corrupt them; a non-zero adapter exit surfaces its captured output.
773fn 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
797/// The adapter's written results JSON, read back after a successful run.
798fn 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
807/// A unique temp dir for one TS mutation adapter run's `--out` JSON, removed on drop so
808/// the scanned project stays pristine and parallel runs don't collide.
809/// Where an adapter run writes its normalized results, with the directory's lifetime guard.
810/// Results go to a file the adapter names via `--out`, never to stdout, so the engine's own
811/// logging cannot corrupt them. Hold the guard for as long as the file is wanted.
812fn 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
819/// The error a failed mutation adapter becomes. Both adapters report the same way, so both
820/// surface the same thing: the directory the run happened in, then its captured stdout and
821/// stderr, because the engine puts the actual cause in one or the other.
822fn 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
854/// Build the Stryker `--mutate` specs scoping a run to the `<base>...HEAD` changed lines, as
855/// `<file>:<start>-<end>` ranges. Test and declaration files are filtered out here because
856/// passing `--mutate` replaces Stryker's configured set rather than narrowing it.
857fn 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
871/// Whether a changed file is a TypeScript/JavaScript *source* Stryker should mutate — a
872/// `.ts`/`.tsx`/`.mts`/`.cts`/`.js`/`.jsx`/`.mjs`/`.cjs` file that is not a declaration
873/// (`.d.ts`) or a test (`.test.` / `.spec.`).
874fn 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
883/// Fold a sorted set of line numbers into inclusive `(start, end)` contiguous runs.
884fn 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
895/// Run the bundled Python mutation adapter over the project at `root` and return the
896/// [`Measurement`] — the Python arm, parity with [`measure_rust`]. maturin ships the binary
897/// directly, so it invokes the adapter as a module resolved from the wheel's own environment.
898pub 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
923/// The modules among `changed` the adapter can mutate. Empty when the diff touches no such
924/// Python source — there is nothing for the engine to do.
925fn 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
933/// The mutants the Python arm judges: on a `changed` line when the run is diff-scoped, and
934/// outside a declaration-only module, which has no behaviour to mutate.
935fn 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
952/// Run the bundled Python mutation adapter over `root` and return the normalized-results
953/// JSON it writes. `modules`, when non-empty, scopes the run to those source files; empty
954/// runs the whole project. `PYTHONDONTWRITEBYTECODE` keeps `__pycache__` out of the tree.
955fn 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
976/// Whether a changed file is a mutatable Python *source* — a `.py` that is not a test
977/// (`*_test.py` / `test_*.py`), a `conftest.py`, or under the root `tests/` pytest ignores.
978fn 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    !(file.starts_with("tests/")
984        || base.ends_with("_test.py")
985        || base.starts_with("test_")
986        || base == "conftest.py")
987}
988
989/// A unique temp dir for one cargo-mutants run's `--output`, removed on drop so the
990/// scanned crate stays pristine and parallel runs don't collide.
991struct MutantsOut(PathBuf);
992
993impl MutantsOut {
994    fn new() -> Self {
995        static COUNTER: AtomicU64 = AtomicU64::new(0);
996        let name = format!(
997            "testing-conventions-mutants-{}-{}",
998            std::process::id(),
999            COUNTER.fetch_add(1, Ordering::Relaxed),
1000        );
1001        MutantsOut(std::env::temp_dir().join(name))
1002    }
1003}
1004
1005impl Drop for MutantsOut {
1006    fn drop(&mut self) {
1007        let _ = std::fs::remove_dir_all(&self.0);
1008    }
1009}
1010
1011/// The directory of the cargo workspace `root` belongs to. `cargo locate-project --workspace`
1012/// is the authoritative lookup: membership involves member globs and `exclude` lists a
1013/// manifest walk can't settle.
1014fn cargo_workspace_root(root: &Path) -> Result<PathBuf> {
1015    let output = Command::new("cargo")
1016        .current_dir(root)
1017        .args(["locate-project", "--workspace", "--message-format", "plain"])
1018        .output()
1019        .context("running `cargo locate-project` (is cargo installed?)")?;
1020    if !output.status.success() {
1021        bail!(
1022            "cargo locate-project failed in `{}`: {}",
1023            root.display(),
1024            String::from_utf8_lossy(&output.stderr)
1025        );
1026    }
1027    let manifest = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
1028    manifest_dir(&manifest)
1029}
1030
1031/// The directory holding the workspace manifest `cargo locate-project` reported.
1032fn manifest_dir(manifest: &Path) -> Result<PathBuf> {
1033    manifest.parent().map(Path::to_path_buf).with_context(|| {
1034        format!(
1035            "no parent dir for the workspace manifest `{}`",
1036            manifest.display()
1037        )
1038    })
1039}
1040
1041/// The scan path's prefix relative to the workspace root ([`scan_prefix`]), over
1042/// canonicalized paths so a relative CLI scan path resolves against the absolute path
1043/// `cargo locate-project` reports. `None` when the scan path *is* the workspace root.
1044fn canonical_scan_prefix(root: &Path, workspace_root: &Path) -> Option<String> {
1045    let root = root.canonicalize().ok()?;
1046    let workspace_root = workspace_root.canonicalize().ok()?;
1047    scan_prefix(&root, &workspace_root)
1048}
1049
1050/// Write the `<base>...HEAD` diff cargo-mutants' `--in-diff` scopes to, returning its path —
1051/// or `None` when the diff is empty. cargo-mutants matches `--in-diff` paths relative to the
1052/// cargo workspace root, so the diff is generated there, `--relative`, with `prefix` as a pathspec.
1053fn write_base_diff(
1054    root: &Path,
1055    workspace_root: &Path,
1056    prefix: Option<&str>,
1057    base: &str,
1058    out: &MutantsOut,
1059) -> Result<Option<PathBuf>> {
1060    let range = format!("{base}...HEAD");
1061    let (dir, args) = base_diff_command(root, workspace_root, prefix, &range);
1062    let output = Command::new("git")
1063        .current_dir(dir)
1064        .args(&args)
1065        .output()
1066        .context("running `git diff` for `--base` (is git installed?)")?;
1067    base_diff_exit(&output, &range)?;
1068    if output.stdout.is_empty() {
1069        return Ok(None);
1070    }
1071    std::fs::create_dir_all(&out.0).context("creating the mutants output dir")?;
1072    let path = out.0.join("base.diff");
1073    std::fs::write(&path, &output.stdout).context("writing the base diff")?;
1074    Ok(Some(path))
1075}
1076
1077/// The written base diff, read back for parsing.
1078fn read_base_diff(path: &Path) -> Result<String> {
1079    std::fs::read_to_string(path)
1080        .with_context(|| format!("reading the written base diff `{}`", path.display()))
1081}
1082
1083/// The tool's own reading of a base diff: the changed files (new-side paths, `b/` stripped)
1084/// and the inserted line numbers per file. Paths stay workspace-root-relative, the basis
1085/// cargo-mutants addresses mutants on.
1086struct BaseDiff {
1087    files: Vec<String>,
1088    inserted: BTreeMap<String, BTreeSet<u32>>,
1089}
1090
1091/// Parse a unified diff into a [`BaseDiff`]. A deleted file (`+++ /dev/null`) carries neither
1092/// a changed file nor inserted lines.
1093fn parse_base_diff(diff: &str) -> BaseDiff {
1094    let mut files = Vec::new();
1095    let mut inserted: BTreeMap<String, BTreeSet<u32>> = BTreeMap::new();
1096    let mut current: Option<String> = None;
1097    let mut lines = diff.lines();
1098    while let Some(line) = lines.next() {
1099        if let Some(path) = line.strip_prefix("+++ ") {
1100            current = (path != "/dev/null").then(|| {
1101                let path = path.strip_prefix("b/").unwrap_or(path).to_string();
1102                files.push(path.clone());
1103                path
1104            });
1105        } else if let Some(header) = line.strip_prefix("@@ ") {
1106            if let Some(counts) = parse_hunk_header(header) {
1107                consume_hunk(&mut lines, counts, current.as_ref(), &mut inserted);
1108            }
1109        }
1110    }
1111    BaseDiff { files, inserted }
1112}
1113
1114/// Record the new-side line numbers of one hunk's inserted lines, consuming its body by the
1115/// `(new start, old count, new count)` its `@@` header declared — so a content line beginning
1116/// `+++` or `---` never reads as a file header.
1117fn consume_hunk(
1118    lines: &mut std::str::Lines<'_>,
1119    (new_start, old_count, new_count): (u32, u32, u32),
1120    file: Option<&String>,
1121    inserted: &mut BTreeMap<String, BTreeSet<u32>>,
1122) {
1123    let mut new_line = new_start;
1124    let (mut old_left, mut new_left) = (old_count, new_count);
1125    while old_left > 0 || new_left > 0 {
1126        let Some(line) = lines.next() else { break };
1127        if line.starts_with('\\') {
1128            // "\ No newline at end of file" annotates the previous line and
1129            // counts against neither side.
1130        } else if line.starts_with('+') {
1131            if let Some(file) = file {
1132                inserted.entry(file.clone()).or_default().insert(new_line);
1133            }
1134            new_line += 1;
1135            new_left = new_left.saturating_sub(1);
1136        } else if line.starts_with('-') {
1137            old_left = old_left.saturating_sub(1);
1138        } else {
1139            new_line += 1;
1140            old_left = old_left.saturating_sub(1);
1141            new_left = new_left.saturating_sub(1);
1142        }
1143    }
1144}
1145
1146/// The `(new_start, old_count, new_count)` of a hunk header's `-a[,b] +c[,d]` part.
1147fn parse_hunk_header(header: &str) -> Option<(u32, u32, u32)> {
1148    let mut parts = header.split(' ');
1149    let (_, old_count) = parse_range(parts.next()?.strip_prefix('-')?)?;
1150    let (new_start, new_count) = parse_range(parts.next()?.strip_prefix('+')?)?;
1151    Some((new_start, old_count, new_count))
1152}
1153
1154/// A hunk range `start[,count]`; the count defaults to 1.
1155fn parse_range(range: &str) -> Option<(u32, u32)> {
1156    match range.split_once(',') {
1157        Some((start, count)) => Some((start.parse().ok()?, count.parse().ok()?)),
1158        None => Some((range.parse().ok()?, 1)),
1159    }
1160}
1161
1162/// Rebase a cargo-mutants report's workspace-root-relative mutant paths onto the scan path, so
1163/// exemption matching and survivor reporting address scan-path-relative files. A baseline
1164/// outcome carries no path and passes through; a mutant outside the scan path is dropped.
1165fn rebase_report_paths(report: MutantsReport, prefix: Option<&str>) -> MutantsReport {
1166    let Some(prefix) = prefix else {
1167        return report;
1168    };
1169    let prefix = format!("{prefix}/");
1170    MutantsReport {
1171        outcomes: report
1172            .outcomes
1173            .into_iter()
1174            .filter_map(|mut outcome| {
1175                if let Scenario::Mutant(mutant) = &mut outcome.scenario {
1176                    mutant.file = mutant.file.strip_prefix(&prefix)?.to_string();
1177                }
1178                Some(outcome)
1179            })
1180            .collect(),
1181    }
1182}
1183
1184/// The cargo-mutants version the Rust arm provisions and pins to. Bumping this points the
1185/// cache at a fresh version-scoped directory, so the next run installs the new release.
1186const CARGO_MUTANTS_VERSION: &str = "27.1.0";
1187
1188/// Ensure the pinned cargo-mutants is available and return the absolute path to its binary,
1189/// provisioning it on first use. cargo ships no library form, so — unlike the in-process
1190/// TS/Python adapters — a pinned `cargo install` runs into the tool's own cache directory.
1191fn ensure_cargo_mutants() -> Result<PathBuf> {
1192    provision_pinned(&cargo_mutants_cache_root(), execute)
1193}
1194
1195/// Provision the pinned cargo-mutants under `root`, executing its `cargo install` with `run`.
1196fn provision_pinned(
1197    root: &Path,
1198    run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1199) -> Result<PathBuf> {
1200    let bin = root.join("bin").join(CARGO_MUTANTS_BIN_NAME);
1201    let lock_path = root.join(".install.lock");
1202    provision(&bin, &lock_path, || run_install(root, run))
1203}
1204
1205/// Execute a prepared command, capturing its output.
1206fn execute(command: &mut Command) -> std::io::Result<Output> {
1207    command.output()
1208}
1209
1210/// The cargo-mutants binary's file name (`.exe` on Windows), as `cargo install --root`
1211/// lays it out under `<root>/bin/`.
1212const CARGO_MUTANTS_BIN_NAME: &str = if cfg!(windows) {
1213    "cargo-mutants.exe"
1214} else {
1215    "cargo-mutants"
1216};
1217
1218/// The tool-owned, version-scoped cache directory cargo-mutants is installed under, so a
1219/// version bump provisions cleanly beside the old one and never clobbers a user's own
1220/// `~/.cargo/bin`.
1221fn cargo_mutants_cache_root() -> PathBuf {
1222    cache_base()
1223        .join("testing-conventions")
1224        .join(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}"))
1225}
1226
1227/// The base cache directory, read from OS-owned config. Split from [`resolve_cache_base`]
1228/// so the resolution logic is unit-tested without touching the process environment.
1229fn cache_base() -> PathBuf {
1230    resolve_cache_base(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))
1231}
1232
1233/// Resolve the base cache dir: `XDG_CACHE_HOME` when set and non-empty, else `$HOME/.cache`,
1234/// else the temp dir. Pure over its inputs.
1235fn resolve_cache_base(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
1236    if let Some(dir) = xdg.filter(|value| !value.is_empty()) {
1237        return PathBuf::from(dir);
1238    }
1239    if let Some(dir) = home.filter(|value| !value.is_empty()) {
1240        return PathBuf::from(dir).join(".cache");
1241    }
1242    std::env::temp_dir()
1243}
1244
1245/// Take the exclusive advisory lock at `lock_path`, creating its parent if needed, and
1246/// return the held file. The lock releases when the returned handle drops, so the caller
1247/// must keep it alive for the critical section.
1248fn hold_lock(lock_path: &Path) -> Result<std::fs::File> {
1249    if let Some(parent) = lock_path.parent() {
1250        std::fs::create_dir_all(parent).context("creating the provisioning lock's parent dir")?;
1251    }
1252    let lock_file = std::fs::OpenOptions::new()
1253        .create(true)
1254        .truncate(false)
1255        .write(true)
1256        .open(lock_path)
1257        .context("opening the provisioning lock file")?;
1258    lock_file
1259        .lock()
1260        .context("acquiring the provisioning lock")?;
1261    Ok(lock_file)
1262}
1263
1264/// `bin`, once an install claims to have put it there. An install that reports success
1265/// without producing the binary is an error rather than a path nothing will find.
1266fn installed_binary(bin: &Path) -> Result<PathBuf> {
1267    if !bin.exists() {
1268        bail!(
1269            "provisioning reported success but cargo-mutants is not at `{}`",
1270            bin.display()
1271        );
1272    }
1273    Ok(bin.to_path_buf())
1274}
1275
1276/// Return `bin` if it already exists, otherwise take an exclusive advisory lock at
1277/// `lock_path`, re-check, and run `install` if still absent. The lock keeps N concurrent
1278/// callers to one from-source compile instead of N. An install producing no binary is an error.
1279fn provision(
1280    bin: &Path,
1281    lock_path: &Path,
1282    install: impl FnOnce() -> Result<()>,
1283) -> Result<PathBuf> {
1284    if bin.exists() {
1285        return Ok(bin.to_path_buf());
1286    }
1287    let _lock = hold_lock(lock_path)?;
1288    // Re-check: another caller may have installed while this one waited for the lock.
1289    if bin.exists() {
1290        return Ok(bin.to_path_buf());
1291    }
1292    install()?;
1293    installed_binary(bin)
1294}
1295
1296/// The argv provisioning the pinned cargo-mutants into `root` (`cargo install cargo-mutants
1297/// --locked --version <X> --root <root>`). Split from execution so a test asserts the pin
1298/// and the isolated `--root` without a real install.
1299fn install_argv(root: &Path) -> Vec<OsString> {
1300    vec![
1301        OsString::from("install"),
1302        OsString::from("cargo-mutants"),
1303        OsString::from("--locked"),
1304        OsString::from("--version"),
1305        OsString::from(CARGO_MUTANTS_VERSION),
1306        OsString::from("--root"),
1307        root.as_os_str().to_os_string(),
1308    ]
1309}
1310
1311/// Provision cargo-mutants into `root`, executing the built `cargo install` with `run`, which
1312/// is injected so a test drives both branches with a fake. The coverage-instrumentation env is
1313/// stripped so the compile doesn't re-enter a `cargo llvm-cov` rustc wrapper.
1314fn run_install(
1315    root: &Path,
1316    run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1317) -> Result<()> {
1318    let mut command = Command::new("cargo");
1319    command.args(install_argv(root));
1320    strip_llvm_cov_env(&mut command);
1321    let output = run(&mut command)
1322        .context("provisioning cargo-mutants via `cargo install` (is cargo installed?)")?;
1323    if !output.status.success() {
1324        bail!(
1325            "failed to provision cargo-mutants {CARGO_MUTANTS_VERSION}:\n{}{}",
1326            String::from_utf8_lossy(&output.stdout),
1327            String::from_utf8_lossy(&output.stderr),
1328        );
1329    }
1330    Ok(())
1331}
1332
1333/// Strip the outer coverage-instrumentation env from a nested cargo invocation (the
1334/// cargo-mutants run, or the `cargo install` that provisions it) so it doesn't re-enter the
1335/// `cargo llvm-cov` rustc wrapper and hang, as when this rule's own tests run under coverage.
1336fn strip_llvm_cov_env(command: &mut Command) {
1337    for var in [
1338        "RUSTFLAGS",
1339        "CARGO_ENCODED_RUSTFLAGS",
1340        "RUSTDOCFLAGS",
1341        "CARGO_ENCODED_RUSTDOCFLAGS",
1342        "LLVM_PROFILE_FILE",
1343        "CARGO_LLVM_COV",
1344        "CARGO_LLVM_COV_SHOW_ENV",
1345        "CARGO_LLVM_COV_TARGET_DIR",
1346        "CARGO_LLVM_COV_BUILD_DIR",
1347        "RUSTC_WRAPPER",
1348        "RUSTC_WORKSPACE_WRAPPER",
1349        "__CARGO_LLVM_COV_RUSTC_WRAPPER",
1350        "__CARGO_LLVM_COV_RUSTC_WRAPPER_RUSTFLAGS",
1351        "__CARGO_LLVM_COV_RUSTC_WRAPPER_CRATE_NAMES",
1352    ] {
1353        command.env_remove(var);
1354    }
1355}
1356
1357/// Run the cargo-mutants argv ([`mutants_argv`]) in `root`, where `engine` is the provisioned
1358/// binary invoked by absolute path, returning its [`Output`]. The outer instrumentation env is
1359/// stripped so a nested run (this rule's own tests under coverage) can't re-enter the wrapper.
1360fn run_cargo_mutants(
1361    engine: &Path,
1362    root: &Path,
1363    out: &Path,
1364    in_diff: Option<&Path>,
1365    features: &[String],
1366) -> Result<Output> {
1367    let mut command = Command::new(engine);
1368    command
1369        .current_dir(root)
1370        .args(mutants_argv(out, in_diff, features));
1371    strip_llvm_cov_env(&mut command);
1372    let output = command.output().context("running cargo-mutants")?;
1373    classify_mutants_exit(root, &output)?;
1374    Ok(output)
1375}
1376
1377/// Decide whether an engine run that judged zero mutants is legitimate: `listed` is the crate's
1378/// full mutant list and `diff` the tool's own reading of the diff the engine filtered by. A
1379/// listed mutant whose span touches an inserted line proves the filter dropped real mutants.
1380fn zero_mutant_verdict(listed: &[MutantInfo], diff: &BaseDiff, run: &Output) -> Result<()> {
1381    let dropped = dropped_mutants(listed, diff);
1382    if dropped.is_empty() {
1383        return Ok(());
1384    }
1385    let sites: Vec<String> = dropped.iter().map(|mutant| mutant_site(mutant)).collect();
1386    bail!(
1387        "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{}{}",
1388        dropped.len(),
1389        listed.len(),
1390        sites.join("\n"),
1391        String::from_utf8_lossy(&run.stdout),
1392        String::from_utf8_lossy(&run.stderr),
1393    )
1394}
1395
1396/// The mutants among `listed` whose span touches one of `diff`'s inserted lines — the ones a
1397/// run that judged zero should have tested.
1398fn dropped_mutants<'a>(listed: &'a [MutantInfo], diff: &BaseDiff) -> Vec<&'a MutantInfo> {
1399    listed
1400        .iter()
1401        .filter(|mutant| {
1402            diff.inserted.get(&mutant.file).is_some_and(|lines| {
1403                lines
1404                    .range(mutant.span.start.line..=mutant.span.end.line)
1405                    .next()
1406                    .is_some()
1407            })
1408        })
1409        .collect()
1410}
1411
1412/// One dropped mutant as an indented `file:line: name` line for the failure message.
1413fn mutant_site(mutant: &MutantInfo) -> String {
1414    format!(
1415        "  {}:{}: {}",
1416        mutant.file,
1417        mutant.span.start.line,
1418        strip_embedded_location(&mutant.name)
1419    )
1420}
1421
1422/// The argv for one cargo-mutants mutant listing: `mutants --list --json
1423/// [--features <list>]`, mirroring the run's own feature selection so both see the same
1424/// mutant set.
1425fn list_argv(features: &[String]) -> Vec<OsString> {
1426    let mut argv = vec![
1427        OsString::from("mutants"),
1428        OsString::from("--list"),
1429        OsString::from("--json"),
1430    ];
1431    if !features.is_empty() {
1432        argv.push(OsString::from("--features"));
1433        argv.push(OsString::from(features.join(",")));
1434    }
1435    argv
1436}
1437
1438/// List the crate's discoverable mutants via `cargo mutants --list --json`, executing the
1439/// built command with `run`. `run` is injected so a test drives the success and failure
1440/// branches with a fake (no real engine).
1441fn list_cargo_mutants(
1442    engine: &Path,
1443    root: &Path,
1444    features: &[String],
1445    run: impl FnOnce(&mut Command) -> std::io::Result<Output>,
1446) -> Result<Vec<MutantInfo>> {
1447    let mut command = Command::new(engine);
1448    command.current_dir(root).args(list_argv(features));
1449    strip_llvm_cov_env(&mut command);
1450    let output = run(&mut command).context("listing the crate's mutants with cargo-mutants")?;
1451    if !output.status.success() {
1452        bail!(
1453            "cargo-mutants --list failed in `{}`:\n{}{}",
1454            root.display(),
1455            String::from_utf8_lossy(&output.stdout),
1456            String::from_utf8_lossy(&output.stderr),
1457        );
1458    }
1459    parse_mutants_list(&String::from_utf8_lossy(&output.stdout))
1460}
1461
1462/// Build cargo-mutants arguments for the library unit tier and requested diff/features.
1463fn mutants_argv(out: &Path, in_diff: Option<&Path>, features: &[String]) -> Vec<OsString> {
1464    let mut argv = vec![
1465        OsString::from("mutants"),
1466        OsString::from("--output"),
1467        out.as_os_str().to_os_string(),
1468        OsString::from("--cargo-test-arg"),
1469        OsString::from("--lib"),
1470    ];
1471    if let Some(diff) = in_diff {
1472        argv.push(OsString::from("--in-diff"));
1473        argv.push(diff.as_os_str().to_os_string());
1474    }
1475    if !features.is_empty() {
1476        argv.push(OsString::from("--features"));
1477        argv.push(OsString::from(features.join(",")));
1478    }
1479    argv
1480}
1481
1482/// Classify a finished cargo-mutants run's exit code as a normal outcome or a fatal error.
1483/// `0` (all caught), `2` (some missed) and `3` (some timed out, none missed) each write an
1484/// `outcomes.json` the gate reads. Any other code — a baseline that didn't build (4) — is fatal.
1485fn classify_mutants_exit(root: &Path, output: &Output) -> Result<()> {
1486    match output.status.code() {
1487        Some(0) | Some(2) | Some(3) => Ok(()),
1488        _ => bail!(
1489            "cargo-mutants did not run cleanly in `{}` (baseline build/test failure?):\n{}{}",
1490            root.display(),
1491            String::from_utf8_lossy(&output.stdout),
1492            String::from_utf8_lossy(&output.stderr),
1493        ),
1494    }
1495}
1496
1497#[cfg(test)]
1498mod tests {
1499    use super::*;
1500
1501    #[test]
1502    fn neither_scope_adds_an_argument() {
1503        assert!(ts_adapter_args(None, None).is_empty());
1504    }
1505
1506    #[test]
1507    fn each_scope_contributes_its_own_flag_and_a_comma_joined_list() {
1508        let mutate = vec!["src/a.ts".to_string(), "src/b.ts".to_string()];
1509        let tests = vec!["src/a.test.ts".to_string()];
1510        assert_eq!(
1511            ts_adapter_args(Some(&mutate), None),
1512            vec!["--mutate", "src/a.ts,src/b.ts"]
1513        );
1514        assert_eq!(
1515            ts_adapter_args(None, Some(&tests)),
1516            vec!["--test-files", "src/a.test.ts"]
1517        );
1518        assert_eq!(
1519            ts_adapter_args(Some(&mutate), Some(&tests)),
1520            vec![
1521                "--mutate",
1522                "src/a.ts,src/b.ts",
1523                "--test-files",
1524                "src/a.test.ts"
1525            ]
1526        );
1527    }
1528
1529    #[test]
1530    fn an_empty_list_still_passes_its_flag() {
1531        // `Some(&[])` is "restrict to nothing", which is not `None`'s "do not restrict".
1532        assert_eq!(ts_adapter_args(Some(&[]), None), vec!["--mutate", ""]);
1533    }
1534
1535    #[test]
1536    fn with_no_prefix_the_base_diff_runs_unscoped_at_the_scan_path() {
1537        let (dir, args) = base_diff_command(
1538            Path::new("/crate"),
1539            Path::new("/workspace"),
1540            None,
1541            "main...HEAD",
1542        );
1543        assert_eq!(dir, Path::new("/crate"));
1544        assert_eq!(args, vec!["diff", "--relative", "main...HEAD"]);
1545    }
1546
1547    #[test]
1548    fn with_a_prefix_the_base_diff_runs_at_the_workspace_root_scoped_by_it() {
1549        // cargo-mutants reads `--in-diff` paths relative to the cargo workspace root, so
1550        // the diff has to be generated in that frame.
1551        let (dir, args) = base_diff_command(
1552            Path::new("/workspace/crate"),
1553            Path::new("/workspace"),
1554            Some("crate/src"),
1555            "main...HEAD",
1556        );
1557        assert_eq!(dir, Path::new("/workspace"));
1558        assert_eq!(
1559            args,
1560            vec!["diff", "--relative", "main...HEAD", "--", "crate/src"]
1561        );
1562    }
1563
1564    #[test]
1565    fn a_failed_base_diff_names_the_range() {
1566        let output = std::process::Output {
1567            status: std::process::Command::new("false").status().unwrap(),
1568            stdout: Vec::new(),
1569            stderr: b"fatal: bad revision".to_vec(),
1570        };
1571        let err = base_diff_exit(&output, "nope...HEAD").unwrap_err();
1572        assert!(err.to_string().contains("nope...HEAD"), "got: {err}");
1573    }
1574
1575    #[test]
1576    fn an_adapter_failure_surfaces_both_captured_streams() {
1577        let output = std::process::Output {
1578            status: std::process::Command::new("false").status().unwrap(),
1579            stdout: b"stryker said this".to_vec(),
1580            stderr: b"and then this".to_vec(),
1581        };
1582        let err = adapter_exit(&output, "TypeScript", Path::new("/pkg")).unwrap_err();
1583        let text = err.to_string();
1584        assert!(
1585            text.contains("TypeScript mutation adapter failed"),
1586            "got: {text}"
1587        );
1588        assert!(text.contains("/pkg"), "got: {text}");
1589        assert!(text.contains("stryker said this"), "got: {text}");
1590        assert!(text.contains("and then this"), "got: {text}");
1591    }
1592
1593    #[test]
1594    fn an_adapter_that_succeeded_is_not_an_error() {
1595        let output = std::process::Output {
1596            status: std::process::Command::new("true").status().unwrap(),
1597            stdout: Vec::new(),
1598            stderr: Vec::new(),
1599        };
1600        assert!(adapter_exit(&output, "Python", Path::new("/pkg")).is_ok());
1601    }
1602
1603    #[test]
1604    fn an_install_that_produced_no_binary_is_an_error() {
1605        let missing = scratch_dir("installed-binary-absent").join("cargo-mutants");
1606        let err = installed_binary(&missing).unwrap_err();
1607        assert!(
1608            err.to_string().contains("provisioning reported success"),
1609            "got: {err}"
1610        );
1611    }
1612
1613    #[test]
1614    fn an_install_that_produced_the_binary_returns_its_path() {
1615        let dir = scratch_dir("installed-binary-present");
1616        std::fs::create_dir_all(&dir).unwrap();
1617        let bin = dir.join("cargo-mutants");
1618        std::fs::write(&bin, "").unwrap();
1619        assert_eq!(installed_binary(&bin).unwrap(), bin);
1620    }
1621
1622    /// A process-unique scratch path, so concurrent test binaries never collide.
1623    fn scratch_dir(name: &str) -> PathBuf {
1624        std::env::temp_dir().join(format!("testing-conventions-{name}-{}", std::process::id()))
1625    }
1626
1627    const NORMALIZED: &str = r#"[
1628        {"file": "src/a.ts", "line": 2, "status": "survived",
1629         "mutator": "ConditionalExpression", "replacement": "true", "id": "ignored"},
1630        {"file": "src/a.ts", "line": 5, "status": "no_coverage", "mutator": "ArithmeticOperator"},
1631        {"file": "src/a.ts", "line": 9, "status": "killed",
1632         "mutator": "BooleanLiteral", "replacement": "false"},
1633        {"file": "src/a.ts", "line": 12, "status": "timeout", "mutator": "BlockStatement"},
1634        {"file": "src/a.ts", "line": 15, "status": "compile_error", "mutator": "OptionalChaining"},
1635        {"file": "src/a.ts", "line": 18, "status": "runtime_error", "mutator": "StringLiteral"}
1636    ]"#;
1637
1638    #[test]
1639    fn parses_the_normalized_schema() {
1640        let mutants = parse_normalized_results(NORMALIZED).expect("valid normalized results");
1641        assert_eq!(mutants.len(), 6);
1642        assert_eq!(mutants[0].status, MutantStatus::Survived);
1643        assert_eq!(mutants[1].status, MutantStatus::NoCoverage);
1644        assert_eq!(mutants[0].replacement.as_deref(), Some("true"));
1645        assert_eq!(mutants[1].replacement, None);
1646    }
1647
1648    #[test]
1649    fn normalized_survivors_are_survived_and_nocoverage_only() {
1650        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1651        let survivors = normalized_survivors(&mutants);
1652        assert_eq!(survivors.len(), 2);
1653        assert_eq!((survivors[0].line, survivors[1].line), (2, 5));
1654        assert!(survivors[0].description.contains("ConditionalExpression"));
1655        assert!(survivors[0].description.contains("-> true"));
1656        assert_eq!(survivors[1].description, "ArithmeticOperator");
1657    }
1658
1659    #[test]
1660    fn normalized_mutated_lines_collects_only_viable_mutants() {
1661        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1662        assert_eq!(
1663            normalized_mutated_lines(&mutants),
1664            [2u32, 5, 9, 12]
1665                .into_iter()
1666                .map(|line| ("src/a.ts".to_string(), line))
1667                .collect()
1668        );
1669    }
1670
1671    #[test]
1672    fn normalized_conclusive_count_is_survived_killed_and_nocoverage() {
1673        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1674        assert_eq!(normalized_conclusive_count(&mutants), 3);
1675        assert_eq!(normalized_conclusive_count(&[]), 0);
1676    }
1677
1678    #[test]
1679    fn a_normalized_measurement_reports_the_conclusive_count_and_the_kept_survivors() {
1680        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1681        assert_eq!(
1682            normalized_measurement(&mutants, &[], &BTreeMap::new()).unwrap(),
1683            Measurement::Tested {
1684                // Survived, no-coverage and killed are conclusive; timeout, compile error
1685                // and runtime error are not.
1686                count: 3,
1687                survivors: normalized_survivors(&mutants),
1688            }
1689        );
1690
1691        // A whole-file exemption drops the survivors without changing what was tested.
1692        assert_eq!(
1693            normalized_measurement(&mutants, &["src/a.ts".to_string()], &BTreeMap::new()).unwrap(),
1694            Measurement::Tested {
1695                count: 3,
1696                survivors: vec![],
1697            }
1698        );
1699    }
1700
1701    #[test]
1702    fn evaluate_normalized_reports_unexempted_survivors() {
1703        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1704        let kept = evaluate_normalized(&mutants, &[], &BTreeMap::new()).unwrap();
1705        assert_eq!(kept.len(), 2, "both survivors stand with no exemptions");
1706    }
1707
1708    #[test]
1709    fn evaluate_normalized_drops_a_whole_file_exemption() {
1710        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1711        let kept =
1712            evaluate_normalized(&mutants, &["src/a.ts".to_string()], &BTreeMap::new()).unwrap();
1713        assert!(
1714            kept.is_empty(),
1715            "the whole-file exemption lifts both survivors"
1716        );
1717    }
1718
1719    #[test]
1720    fn evaluate_normalized_drops_a_line_scoped_exemption() {
1721        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1722        let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([2u32]))]);
1723        let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
1724        assert_eq!(kept.len(), 1);
1725        assert_eq!(kept[0].line, 5);
1726    }
1727
1728    #[test]
1729    fn evaluate_normalized_rejects_exempting_a_caught_line() {
1730        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1731        let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([9u32]))]);
1732        let err = evaluate_normalized(&mutants, &[], &line_scoped).unwrap_err();
1733        assert!(
1734            err.to_string().contains("all caught") && err.to_string().contains("src/a.ts:9"),
1735            "got: {err}"
1736        );
1737    }
1738
1739    #[test]
1740    fn evaluate_normalized_leaves_an_unviable_listed_line_alone() {
1741        let mutants = parse_normalized_results(NORMALIZED).unwrap();
1742        let line_scoped = BTreeMap::from([("src/a.ts".to_string(), BTreeSet::from([15u32]))]);
1743        let kept = evaluate_normalized(&mutants, &[], &line_scoped).unwrap();
1744        assert_eq!(kept.len(), 2);
1745    }
1746
1747    const SAMPLE: &str = r#"{
1748        "outcomes": [
1749            {"scenario": "Baseline", "summary": "Success",
1750             "phase_results": []},
1751            {"scenario": {"Mutant": {"file": "src/lib.rs", "package": "p", "genre": "FnValue",
1752                "replacement": "true", "name": "src/lib.rs:7:7: replace > with == in is_positive",
1753                "function": {"function_name": "is_positive"},
1754                "span": {"start": {"line": 7, "column": 7}, "end": {"line": 7, "column": 8}}}},
1755             "summary": "MissedMutant"},
1756            {"scenario": {"Mutant": {"file": "src/other.rs", "package": "p", "genre": "FnValue",
1757                "replacement": "0", "name": "src/other.rs:3:5: replace add -> i32 with 0",
1758                "span": {"start": {"line": 3, "column": 5}, "end": {"line": 3, "column": 9}}}},
1759             "summary": "CaughtMutant"}
1760        ],
1761        "total_mutants": 2
1762    }"#;
1763
1764    #[test]
1765    fn parses_the_outcomes_export() {
1766        let report = parse_mutants_report(SAMPLE).expect("valid outcomes.json");
1767        assert_eq!(report.outcomes.len(), 3);
1768        assert!(matches!(report.outcomes[0].scenario, Scenario::Baseline));
1769    }
1770
1771    #[test]
1772    fn collects_only_missed_mutants_as_survivors() {
1773        let report = parse_mutants_report(SAMPLE).unwrap();
1774        let survivors = unexplained_survivors(&report, &[]);
1775        assert_eq!(survivors.len(), 1);
1776        assert_eq!(survivors[0].file, "src/lib.rs");
1777        assert_eq!(survivors[0].line, 7);
1778        assert!(survivors[0].description.contains("replace > with =="));
1779    }
1780
1781    #[test]
1782    fn a_survivor_description_carries_no_location_prefix() {
1783        let report = parse_mutants_report(SAMPLE).unwrap();
1784        let survivors = unexplained_survivors(&report, &[]);
1785        assert_eq!(
1786            survivors[0].description, "replace > with == in is_positive",
1787            "the name's embedded `file:line:col:` prefix is stripped"
1788        );
1789    }
1790
1791    #[test]
1792    fn strip_embedded_location_removes_a_file_line_col_prefix() {
1793        assert_eq!(
1794            strip_embedded_location("src/lib.rs:7:5: replace > with == in is_positive"),
1795            "replace > with == in is_positive"
1796        );
1797    }
1798
1799    #[test]
1800    fn strip_embedded_location_keeps_a_name_without_one() {
1801        for name in [
1802            "replace add -> 0",
1803            "note: no location segment",
1804            "7:5: no file segment",
1805            "src/lib.rs:7:x: non-numeric column",
1806            "src/lib.rs:x:5: non-numeric line",
1807        ] {
1808            assert_eq!(strip_embedded_location(name), name);
1809        }
1810    }
1811
1812    #[test]
1813    fn conclusive_count_is_caught_plus_missed() {
1814        let report = parse_mutants_report(SAMPLE).unwrap();
1815        assert_eq!(conclusive_count(&report), 2);
1816        assert_eq!(conclusive_count(&MutantsReport { outcomes: vec![] }), 0);
1817    }
1818
1819    #[test]
1820    fn an_exemption_drops_a_survivor_in_that_file() {
1821        let report = parse_mutants_report(SAMPLE).unwrap();
1822        let exempt = vec!["src/lib.rs".to_string()];
1823        assert!(unexplained_survivors(&report, &exempt).is_empty());
1824    }
1825
1826    #[test]
1827    fn an_exemption_on_another_file_leaves_the_survivor() {
1828        let report = parse_mutants_report(SAMPLE).unwrap();
1829        let exempt = vec!["src/elsewhere.rs".to_string()];
1830        assert_eq!(unexplained_survivors(&report, &exempt).len(), 1);
1831    }
1832
1833    const BASELINE_ONLY: &str = r#"{
1834        "outcomes": [
1835            {"scenario": "Baseline", "summary": "MissedMutant", "phase_results": []},
1836            {"scenario": "Baseline", "summary": "CaughtMutant", "phase_results": []}
1837        ],
1838        "total_mutants": 0
1839    }"#;
1840
1841    #[test]
1842    fn a_baseline_outcome_is_never_a_survivor() {
1843        let report = parse_mutants_report(BASELINE_ONLY).unwrap();
1844        assert!(unexplained_survivors(&report, &[]).is_empty());
1845    }
1846
1847    #[test]
1848    fn a_baseline_outcome_is_never_a_mutated_line() {
1849        let report = parse_mutants_report(BASELINE_ONLY).unwrap();
1850        assert!(mutated_lines(&report).is_empty());
1851    }
1852
1853    #[test]
1854    fn parse_base_diff_skips_a_malformed_hunk_header() {
1855        let diff = "\
1856diff --git a/src/lib.rs b/src/lib.rs
1857--- a/src/lib.rs
1858+++ b/src/lib.rs
1859@@ junk @@
1860";
1861        let parsed = parse_base_diff(diff);
1862        assert_eq!(parsed.files, vec!["src/lib.rs"]);
1863        assert!(parsed.inserted.is_empty());
1864    }
1865
1866    #[test]
1867    fn a_missing_base_diff_read_reports_its_path() {
1868        let missing = unique_tmp().join("base.diff");
1869        let err = read_base_diff(&missing).unwrap_err();
1870        let msg = format!("{err:#}");
1871        assert!(msg.contains("reading the written base diff"), "{msg}");
1872    }
1873
1874    #[test]
1875    fn a_missing_adapter_results_read_names_the_engine_and_path() {
1876        let missing = unique_tmp().join("results.json");
1877        let err = read_adapter_results(&missing, "TypeScript").unwrap_err();
1878        let msg = format!("{err:#}");
1879        assert!(
1880            msg.contains("TypeScript mutation adapter's results"),
1881            "{msg}"
1882        );
1883    }
1884
1885    #[test]
1886    fn manifest_dir_is_the_manifest_parent() {
1887        let dir = manifest_dir(Path::new("/w/Cargo.toml")).unwrap();
1888        assert_eq!(dir, Path::new("/w"));
1889    }
1890
1891    #[test]
1892    fn a_rootless_manifest_path_is_an_error() {
1893        let err = manifest_dir(Path::new("/")).unwrap_err();
1894        let msg = format!("{err:#}");
1895        assert!(msg.contains("no parent dir"), "{msg}");
1896    }
1897
1898    #[test]
1899    fn a_directory_outside_any_workspace_fails_locate_project() {
1900        let dir = unique_tmp();
1901        let err = cargo_workspace_root(&dir).unwrap_err();
1902        let msg = format!("{err:#}");
1903        assert!(msg.contains("cargo locate-project failed"), "{msg}");
1904        std::fs::remove_dir_all(&dir).ok();
1905    }
1906
1907    #[test]
1908    fn a_bad_base_ref_fails_the_base_diff() {
1909        let dir = unique_tmp();
1910        let init = Command::new("git")
1911            .current_dir(&dir)
1912            .args(["init", "-q"])
1913            .output()
1914            .unwrap();
1915        assert!(init.status.success());
1916        let out = MutantsOut::new();
1917        let err = write_base_diff(&dir, &dir, None, "tc-no-such-ref", &out).unwrap_err();
1918        let msg = format!("{err:#}");
1919        assert!(msg.contains("git diff"), "{msg}");
1920        std::fs::remove_dir_all(&dir).ok();
1921    }
1922
1923    #[test]
1924    fn a_python_adapter_failure_reports_the_adapter_output() {
1925        let dir = unique_tmp();
1926        let err = run_py_adapter(&dir, &[]).unwrap_err();
1927        let msg = format!("{err:#}");
1928        assert!(msg.contains("the Python mutation adapter failed"), "{msg}");
1929        std::fs::remove_dir_all(&dir).ok();
1930    }
1931
1932    #[test]
1933    fn is_declaration_only_is_true_for_a_const_only_rust_file() {
1934        let dir = unique_tmp();
1935        std::fs::write(
1936            dir.join("settings.rs"),
1937            "pub const TIMEOUT: u64 = 30 * 60;\n",
1938        )
1939        .unwrap();
1940        assert!(is_declaration_only(&dir, "settings.rs", Language::Rust));
1941        std::fs::remove_dir_all(&dir).ok();
1942    }
1943
1944    #[test]
1945    fn is_declaration_only_is_false_for_a_rust_file_with_a_function() {
1946        let dir = unique_tmp();
1947        std::fs::write(dir.join("lib.rs"), "pub fn run() {}\n").unwrap();
1948        assert!(!is_declaration_only(&dir, "lib.rs", Language::Rust));
1949        std::fs::remove_dir_all(&dir).ok();
1950    }
1951
1952    #[test]
1953    fn is_declaration_only_covers_python_and_typescript_too() {
1954        let dir = unique_tmp();
1955        std::fs::write(dir.join("settings.py"), "TIMEOUT = 30 * 60\n").unwrap();
1956        std::fs::write(dir.join("settings.ts"), "export const TIMEOUT = 30 * 60;\n").unwrap();
1957        assert!(is_declaration_only(&dir, "settings.py", Language::Python));
1958        assert!(is_declaration_only(
1959            &dir,
1960            "settings.ts",
1961            Language::TypeScript
1962        ));
1963        std::fs::remove_dir_all(&dir).ok();
1964    }
1965
1966    #[test]
1967    fn is_declaration_only_is_false_for_an_unreadable_file() {
1968        let dir = unique_tmp();
1969        assert!(!is_declaration_only(&dir, "missing.rs", Language::Rust));
1970        std::fs::remove_dir_all(&dir).ok();
1971    }
1972
1973    fn mutant_at(file: &str, line: u32, genre: &str) -> MutantInfo {
1974        MutantInfo {
1975            file: file.to_string(),
1976            span: Span {
1977                start: LineCol { line },
1978                end: LineCol { line },
1979            },
1980            name: format!("a mutant at {file}:{line}"),
1981            genre: genre.to_string(),
1982        }
1983    }
1984
1985    #[test]
1986    fn is_judged_is_true_for_an_ordinary_mutant() {
1987        let dir = unique_tmp();
1988        std::fs::write(
1989            dir.join("add.rs"),
1990            "pub fn add(a: u64) -> u64 {\n    a + 1\n}\n",
1991        )
1992        .unwrap();
1993        assert!(is_judged(&dir, &mutant_at("add.rs", 2, "FnValue")));
1994        std::fs::remove_dir_all(&dir).ok();
1995    }
1996
1997    #[test]
1998    fn is_judged_is_false_in_a_declaration_only_module() {
1999        let dir = unique_tmp();
2000        std::fs::write(
2001            dir.join("settings.rs"),
2002            "pub const TIMEOUT: u64 = 30 * 60;\n",
2003        )
2004        .unwrap();
2005        assert!(!is_judged(&dir, &mutant_at("settings.rs", 1, "FnValue")));
2006        std::fs::remove_dir_all(&dir).ok();
2007    }
2008
2009    #[test]
2010    fn is_judged_is_false_inside_an_item_the_test_build_skips() {
2011        let dir = unique_tmp();
2012        std::fs::write(
2013            dir.join("entrypoint.rs"),
2014            "#[cfg(not(test))]\npub fn main() -> u8 {\n    1\n}\n",
2015        )
2016        .unwrap();
2017        assert!(!is_judged(&dir, &mutant_at("entrypoint.rs", 3, "FnValue")));
2018        std::fs::remove_dir_all(&dir).ok();
2019    }
2020
2021    #[test]
2022    fn is_judged_is_false_for_a_whole_body_replacement_in_a_seam() {
2023        let dir = unique_tmp();
2024        std::fs::write(
2025            dir.join("probe.rs"),
2026            "pub fn probe() -> bool {\n    Command::new(\"true\").output().is_ok()\n}\n",
2027        )
2028        .unwrap();
2029        assert!(!is_judged(&dir, &mutant_at("probe.rs", 2, "FnValue")));
2030        std::fs::remove_dir_all(&dir).ok();
2031    }
2032
2033    #[test]
2034    fn is_judged_still_judges_an_operator_swap_in_a_seam() {
2035        let dir = unique_tmp();
2036        std::fs::write(
2037            dir.join("probe.rs"),
2038            "pub fn probe() -> bool {\n    Command::new(\"true\").output().is_ok()\n}\n",
2039        )
2040        .unwrap();
2041        assert!(is_judged(&dir, &mutant_at("probe.rs", 2, "BinaryOperator")));
2042        std::fs::remove_dir_all(&dir).ok();
2043    }
2044
2045    #[test]
2046    fn rebase_report_paths_strips_the_workspace_prefix() {
2047        let report = parse_mutants_report(SAMPLE).unwrap();
2048        let prefixed = MutantsReport {
2049            outcomes: report
2050                .outcomes
2051                .iter()
2052                .cloned()
2053                .map(|mut outcome| {
2054                    if let Scenario::Mutant(mutant) = &mut outcome.scenario {
2055                        mutant.file = format!("member/{}", mutant.file);
2056                    }
2057                    outcome
2058                })
2059                .collect(),
2060        };
2061        let rebased = rebase_report_paths(prefixed, Some("member"));
2062        let survivors = unexplained_survivors(&rebased, &[]);
2063        assert_eq!(survivors.len(), 1);
2064        assert_eq!(survivors[0].file, "src/lib.rs");
2065        assert_eq!(rebased.outcomes.len(), 3);
2066    }
2067
2068    #[test]
2069    fn rebase_report_paths_drops_an_out_of_scope_mutant_and_keeps_none_identity() {
2070        let report = parse_mutants_report(SAMPLE).unwrap();
2071        let rebased = rebase_report_paths(report.clone(), Some("member"));
2072        assert_eq!(
2073            rebased.outcomes.len(),
2074            1,
2075            "only the pathless baseline outcome remains"
2076        );
2077        let unchanged = rebase_report_paths(report, None);
2078        assert_eq!(unchanged.outcomes.len(), 3);
2079        assert_eq!(unexplained_survivors(&unchanged, &[])[0].file, "src/lib.rs");
2080    }
2081
2082    #[test]
2083    fn adapter_cwd_normalises_the_empty_package_root_to_the_current_dir() {
2084        // `tiers::package_root` yields `""` for a relative scan path such as `src`, and
2085        // `Command::current_dir("")` fails with ENOENT — which the adapter's error context
2086        // mislabelled as a missing `node`, hitting every TypeScript consumer of the gate.
2087        assert_eq!(
2088            adapter_cwd(Path::new(""), "TypeScript").unwrap(),
2089            Path::new(".")
2090        );
2091        assert_eq!(
2092            adapter_cwd(Path::new("src"), "TypeScript").unwrap(),
2093            Path::new("src")
2094        );
2095    }
2096
2097    #[test]
2098    fn adapter_cwd_rejects_a_directory_that_is_not_there() {
2099        // `Command::output()` reports a missing working directory with the same ENOENT as a
2100        // missing interpreter, so an unchecked spawn blames the interpreter for a wrong path.
2101        let err = adapter_cwd(Path::new("no/such/dir"), "Python")
2102            .expect_err("a directory that is not there is an error");
2103        assert_eq!(
2104            err.to_string(),
2105            "the Python mutation adapter's working directory `no/such/dir` is not a directory"
2106        );
2107    }
2108
2109    #[test]
2110    fn spawn_context_names_the_interpreter_the_entry_and_the_working_directory() {
2111        assert_eq!(
2112            spawn_context("node", "/pkg/dist/mutation/main.js", Path::new("/pkg")),
2113            "spawning `node /pkg/dist/mutation/main.js` in `/pkg` (is `node` on PATH?)"
2114        );
2115    }
2116
2117    #[test]
2118    fn scan_prefix_is_the_scan_path_relative_to_the_package_root() {
2119        assert_eq!(
2120            scan_prefix(Path::new("/repo/pkg/src"), Path::new("/repo/pkg")),
2121            Some("src".to_string())
2122        );
2123        assert_eq!(
2124            scan_prefix(Path::new("/repo/pkg/src/nested"), Path::new("/repo/pkg")),
2125            Some("src/nested".to_string())
2126        );
2127        assert_eq!(
2128            scan_prefix(Path::new("/repo/pkg"), Path::new("/repo/pkg")),
2129            None
2130        );
2131        assert_eq!(
2132            scan_prefix(Path::new("pkg/src"), Path::new("pkg")),
2133            Some("src".to_string())
2134        );
2135    }
2136
2137    #[test]
2138    fn prefix_mutate_specs_rebases_diff_ranges_onto_the_package_root() {
2139        let specs = vec!["index.ts:8-11".to_string(), "a/b.ts:2-2".to_string()];
2140        assert_eq!(
2141            prefix_mutate_specs(specs.clone(), Some("src")),
2142            vec![
2143                "src/index.ts:8-11".to_string(),
2144                "src/a/b.ts:2-2".to_string()
2145            ]
2146        );
2147        assert_eq!(prefix_mutate_specs(specs.clone(), None), specs);
2148    }
2149
2150    #[test]
2151    fn scan_scoped_mutate_globs_mirror_strykers_default_under_the_scan_path() {
2152        assert_eq!(
2153            scan_scoped_mutate_globs("src"),
2154            vec![
2155                "src/**/!(*.+(s|S)pec|*.+(t|T)est).+(cjs|mjs|js|ts|mts|cts|jsx|tsx|html|vue|svelte)"
2156                    .to_string(),
2157                "!src/**/__tests__/**/*.+(cjs|mjs|js|ts|mts|cts|jsx|tsx|html|vue|svelte)"
2158                    .to_string(),
2159            ]
2160        );
2161    }
2162
2163    #[test]
2164    fn scan_scoped_test_file_globs_narrow_the_run_without_moving_the_runner_root() {
2165        assert_eq!(
2166            scan_scoped_test_file_globs("src"),
2167            vec!["src/**".to_string()]
2168        );
2169        assert_eq!(
2170            scan_scoped_test_file_globs("packages/core/src"),
2171            vec!["packages/core/src/**".to_string()]
2172        );
2173    }
2174
2175    #[test]
2176    fn to_scan_relative_strips_the_prefix_and_drops_out_of_scope_mutants() {
2177        let mutants = parse_normalized_results(
2178            r#"[
2179                {"file": "src/a.ts", "line": 2, "status": "survived", "mutator": "X"},
2180                {"file": "tests/e2e/t.ts", "line": 9, "status": "survived", "mutator": "X"}
2181            ]"#,
2182        )
2183        .unwrap();
2184        let rebased = to_scan_relative(mutants.clone(), Some("src"));
2185        assert_eq!(rebased.len(), 1, "the out-of-scan-path mutant is dropped");
2186        assert_eq!(rebased[0].file, "a.ts");
2187        let unchanged = to_scan_relative(mutants, None);
2188        assert_eq!(unchanged.len(), 2);
2189        assert_eq!(unchanged[0].file, "src/a.ts");
2190    }
2191
2192    #[test]
2193    fn is_mutatable_ts_keeps_sources_and_drops_tests_and_decls() {
2194        assert!(is_mutatable_ts("src/index.ts"));
2195        assert!(is_mutatable_ts("src/util.tsx"));
2196        assert!(is_mutatable_ts("src/util.js"));
2197        assert!(!is_mutatable_ts("src/index.test.ts"));
2198        assert!(!is_mutatable_ts("src/index.spec.ts"));
2199        assert!(!is_mutatable_ts("src/types.d.ts"));
2200        assert!(!is_mutatable_ts("README.md"));
2201    }
2202
2203    #[test]
2204    fn contiguous_runs_collapses_adjacent_lines() {
2205        let lines: BTreeSet<u64> = [2u64, 3, 4, 7, 9, 10].into_iter().collect();
2206        assert_eq!(contiguous_runs(&lines), vec![(2, 4), (7, 7), (9, 10)]);
2207        assert!(contiguous_runs(&BTreeSet::new()).is_empty());
2208    }
2209
2210    #[test]
2211    fn one_line_flattens_and_caps() {
2212        assert_eq!(one_line("a -\n  b"), "a - b");
2213        let long = "x".repeat(80);
2214        let capped = one_line(&long);
2215        assert!(capped.chars().count() <= 61 && capped.ends_with('…'));
2216    }
2217
2218    #[test]
2219    fn mutatable_py_modules_keeps_only_the_changed_python_sources() {
2220        let changed = BTreeMap::from([
2221            ("pkg/calc.py".to_string(), BTreeSet::from([3u64])),
2222            ("pkg/calc_test.py".to_string(), BTreeSet::from([4u64])),
2223            ("README.md".to_string(), BTreeSet::from([1u64])),
2224            ("pkg/util.py".to_string(), BTreeSet::from([9u64])),
2225        ]);
2226
2227        assert_eq!(
2228            mutatable_py_modules(&changed),
2229            ["pkg/calc.py", "pkg/util.py"]
2230        );
2231    }
2232
2233    #[test]
2234    fn mutatable_py_modules_is_empty_when_the_diff_touches_no_python_source() {
2235        let changed = BTreeMap::from([("docs/guide.md".to_string(), BTreeSet::from([1u64]))]);
2236
2237        assert!(mutatable_py_modules(&changed).is_empty());
2238    }
2239
2240    #[test]
2241    fn a_diff_scoped_python_run_judges_only_mutants_on_a_changed_line() {
2242        let mutants = vec![py_mutant("pkg/calc.py", 3), py_mutant("pkg/calc.py", 99)];
2243        let changed = BTreeMap::from([("pkg/calc.py".to_string(), BTreeSet::from([3u64]))]);
2244
2245        let judged = judged_py_mutants(mutants, Path::new("/nonexistent-tc-py"), Some(&changed));
2246
2247        assert_eq!(
2248            judged.iter().map(|m| m.line).collect::<Vec<_>>(),
2249            [3],
2250            "a mutant off the diff is not this run's to judge"
2251        );
2252    }
2253
2254    #[test]
2255    fn a_typescript_run_drops_the_mutants_in_a_declaration_only_module() {
2256        let dir = unique_tmp();
2257        std::fs::write(dir.join("types.ts"), "export type Id = string;\n").unwrap();
2258        std::fs::write(dir.join("calc.ts"), "export const add = (a, b) => a + b;\n").unwrap();
2259        let mutants = vec![py_mutant("types.ts", 1), py_mutant("calc.ts", 1)];
2260
2261        let judged = judged_ts_mutants(mutants, &dir);
2262
2263        // `types.ts` declares and branches on nothing, so it has no behaviour to mutate;
2264        // `calc.ts` does, so its mutant is this run's to judge.
2265        assert_eq!(
2266            judged.iter().map(|m| m.file.as_str()).collect::<Vec<_>>(),
2267            ["calc.ts"]
2268        );
2269        std::fs::remove_dir_all(&dir).ok();
2270    }
2271
2272    #[test]
2273    fn an_unscoped_python_run_judges_every_mutant() {
2274        let mutants = vec![py_mutant("pkg/calc.py", 3), py_mutant("pkg/calc.py", 99)];
2275
2276        let judged = judged_py_mutants(mutants, Path::new("/nonexistent-tc-py"), None);
2277
2278        assert_eq!(judged.iter().map(|m| m.line).collect::<Vec<_>>(), [3, 99]);
2279    }
2280
2281    fn py_mutant(file: &str, line: u32) -> NormalizedMutant {
2282        NormalizedMutant {
2283            file: file.to_string(),
2284            line,
2285            status: MutantStatus::Survived,
2286            mutator: "ConditionalExpression".to_string(),
2287            replacement: None,
2288        }
2289    }
2290
2291    #[test]
2292    fn is_mutatable_py_keeps_sources_and_drops_tests() {
2293        assert!(is_mutatable_py("calc.py"));
2294        assert!(is_mutatable_py("pkg/util.py"));
2295        assert!(!is_mutatable_py("calc_test.py"));
2296        assert!(!is_mutatable_py("test_calc.py"));
2297        assert!(!is_mutatable_py("pkg/conftest.py"));
2298        assert!(!is_mutatable_py("README.md"));
2299        assert!(!is_mutatable_py("tests/served.py"));
2300        assert!(!is_mutatable_py("tests/integration/served.py"));
2301        assert!(is_mutatable_py("pkg/tests/helper.py"));
2302    }
2303
2304    #[test]
2305    fn mutated_lines_collects_caught_and_missed() {
2306        let report = parse_mutants_report(SAMPLE).unwrap();
2307        assert_eq!(
2308            mutated_lines(&report),
2309            [
2310                ("src/lib.rs".to_string(), 7),
2311                ("src/other.rs".to_string(), 3)
2312            ]
2313            .into_iter()
2314            .collect()
2315        );
2316    }
2317
2318    #[test]
2319    fn evaluate_scoped_drops_a_survivor_on_an_exempt_line() {
2320        let report = parse_mutants_report(SAMPLE).unwrap();
2321        let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([7u32]))]);
2322        let kept = evaluate_scoped(
2323            cargo_mutants_survivors(&report),
2324            &mutated_lines(&report),
2325            &[],
2326            &line_scoped,
2327        )
2328        .unwrap();
2329        assert!(
2330            kept.is_empty(),
2331            "the src/lib.rs:7 survivor should be lifted"
2332        );
2333    }
2334
2335    #[test]
2336    fn evaluate_scoped_rejects_exempting_a_caught_line() {
2337        let report = parse_mutants_report(SAMPLE).unwrap();
2338        let line_scoped = BTreeMap::from([("src/other.rs".to_string(), BTreeSet::from([3u32]))]);
2339        let err = evaluate_scoped(
2340            cargo_mutants_survivors(&report),
2341            &mutated_lines(&report),
2342            &[],
2343            &line_scoped,
2344        )
2345        .unwrap_err();
2346        assert!(
2347            err.to_string().contains("all caught") && err.to_string().contains("src/other.rs:3"),
2348            "got: {err}"
2349        );
2350    }
2351
2352    #[test]
2353    fn evaluate_scoped_leaves_an_unmutated_listed_line_alone() {
2354        let report = parse_mutants_report(SAMPLE).unwrap();
2355        let line_scoped = BTreeMap::from([("src/lib.rs".to_string(), BTreeSet::from([99u32]))]);
2356        let kept = evaluate_scoped(
2357            cargo_mutants_survivors(&report),
2358            &mutated_lines(&report),
2359            &[],
2360            &line_scoped,
2361        )
2362        .unwrap();
2363        assert_eq!(kept.len(), 1);
2364        assert_eq!(kept[0].line, 7);
2365    }
2366
2367    #[test]
2368    fn evaluate_scoped_still_honors_a_whole_file_exemption() {
2369        let report = parse_mutants_report(SAMPLE).unwrap();
2370        let kept = evaluate_scoped(
2371            cargo_mutants_survivors(&report),
2372            &mutated_lines(&report),
2373            &["src/lib.rs".to_string()],
2374            &BTreeMap::new(),
2375        )
2376        .unwrap();
2377        assert!(kept.is_empty());
2378    }
2379
2380    fn unique_tmp() -> PathBuf {
2381        static COUNTER: AtomicU64 = AtomicU64::new(0);
2382        let dir = std::env::temp_dir().join(format!(
2383            "tc-provision-test-{}-{}",
2384            std::process::id(),
2385            COUNTER.fetch_add(1, Ordering::Relaxed)
2386        ));
2387        std::fs::create_dir_all(&dir).unwrap();
2388        dir
2389    }
2390
2391    enum Install {
2392        MustNotRun,
2393        WritesNothing,
2394        WritesBin,
2395        Fails,
2396        CountsSleepsAndWritesBin(std::sync::Arc<AtomicU64>),
2397    }
2398
2399    fn write_bin(bin: &Path) {
2400        std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
2401        std::fs::write(bin, b"binary").unwrap();
2402    }
2403
2404    fn drive_provision(bin: &Path, lock: &Path, install: Install) -> Result<PathBuf> {
2405        provision(bin, lock, || match install {
2406            Install::MustNotRun => panic!("must not reinstall"),
2407            Install::WritesNothing => Ok(()),
2408            Install::WritesBin => {
2409                write_bin(bin);
2410                Ok(())
2411            }
2412            Install::Fails => bail!("install blew up"),
2413            Install::CountsSleepsAndWritesBin(count) => {
2414                count.fetch_add(1, Ordering::SeqCst);
2415                std::thread::sleep(std::time::Duration::from_millis(50));
2416                write_bin(bin);
2417                Ok(())
2418            }
2419        })
2420    }
2421
2422    #[test]
2423    fn provision_returns_an_existing_binary_without_installing() {
2424        let tmp = unique_tmp();
2425        let bin = tmp.join("bin").join("cargo-mutants");
2426        let lock = tmp.join(".install.lock");
2427        write_bin(&bin);
2428        let got = drive_provision(&bin, &lock, Install::MustNotRun).unwrap();
2429        assert_eq!(got, bin);
2430        std::fs::remove_dir_all(&tmp).unwrap();
2431    }
2432
2433    #[test]
2434    fn the_must_not_run_sentinel_panics_when_installation_runs() {
2435        let tmp = unique_tmp();
2436        std::fs::create_dir_all(&tmp).unwrap();
2437        let bin = tmp.join("bin").join("cargo-mutants");
2438        let lock = tmp.join(".install.lock");
2439        let panicked =
2440            std::panic::catch_unwind(|| drive_provision(&bin, &lock, Install::MustNotRun)).is_err();
2441        std::fs::remove_dir_all(&tmp).unwrap();
2442        assert!(panicked);
2443    }
2444
2445    #[test]
2446    fn provision_with_a_rootless_lock_path_fails_to_open_the_lock() {
2447        let bin = unique_tmp().join("bin").join("cargo-mutants");
2448        let err = drive_provision(&bin, Path::new("/"), Install::WritesNothing).unwrap_err();
2449        let msg = format!("{err:#}");
2450        assert!(msg.contains("opening the provisioning lock"), "{msg}");
2451    }
2452
2453    #[test]
2454    fn provision_installs_when_the_binary_is_absent() {
2455        let tmp = unique_tmp();
2456        let bin = tmp.join("bin").join("cargo-mutants");
2457        let lock = tmp.join(".install.lock");
2458        let got = drive_provision(&bin, &lock, Install::WritesBin).unwrap();
2459        assert_eq!(got, bin);
2460        assert_eq!(
2461            std::fs::read(&bin).unwrap(),
2462            b"binary",
2463            "an absent binary must be installed"
2464        );
2465        std::fs::remove_dir_all(&tmp).unwrap();
2466    }
2467
2468    #[test]
2469    fn provision_errors_when_install_produces_no_binary() {
2470        let tmp = unique_tmp();
2471        let bin = tmp.join("bin").join("cargo-mutants");
2472        let lock = tmp.join(".install.lock");
2473        let err = drive_provision(&bin, &lock, Install::WritesNothing).unwrap_err();
2474        assert!(
2475            err.to_string().contains("cargo-mutants is not at"),
2476            "got: {err}"
2477        );
2478        std::fs::remove_dir_all(&tmp).unwrap();
2479    }
2480
2481    #[test]
2482    fn provision_propagates_an_install_failure() {
2483        let tmp = unique_tmp();
2484        let bin = tmp.join("bin").join("cargo-mutants");
2485        let lock = tmp.join(".install.lock");
2486        let err = drive_provision(&bin, &lock, Install::Fails).unwrap_err();
2487        assert!(err.to_string().contains("install blew up"), "got: {err}");
2488        std::fs::remove_dir_all(&tmp).unwrap();
2489    }
2490
2491    #[test]
2492    fn provision_does_not_duplicate_the_install_under_concurrent_callers() {
2493        // On a cold cache, N concurrent callers must share one install: cargo-mutants' compile
2494        // duplicated N times turned a ~1-minute cold-cache cost into ~7 minutes. The barrier and
2495        // the sleeping installer widen the race window so this reproduces deterministically.
2496        use std::sync::{Arc, Barrier};
2497        use std::thread;
2498
2499        let tmp = unique_tmp();
2500        let bin = tmp.join("bin").join("cargo-mutants");
2501        let lock = tmp.join(".install.lock");
2502        let install_count = Arc::new(AtomicU64::new(0));
2503        let barrier = Arc::new(Barrier::new(2));
2504
2505        let handles: Vec<_> = (0..2)
2506            .map(|_| {
2507                let bin = bin.clone();
2508                let lock = lock.clone();
2509                let install_count = Arc::clone(&install_count);
2510                let barrier = Arc::clone(&barrier);
2511                thread::spawn(move || {
2512                    barrier.wait();
2513                    drive_provision(
2514                        &bin,
2515                        &lock,
2516                        Install::CountsSleepsAndWritesBin(install_count),
2517                    )
2518                })
2519            })
2520            .collect();
2521
2522        for h in handles {
2523            h.join()
2524                .expect("provisioning thread must not panic")
2525                .unwrap();
2526        }
2527
2528        assert_eq!(
2529            install_count.load(Ordering::SeqCst),
2530            1,
2531            "two concurrent callers on a cold cache must share one install, not each run their own"
2532        );
2533        std::fs::remove_dir_all(&tmp).unwrap();
2534    }
2535
2536    #[test]
2537    fn resolve_cache_base_prefers_xdg_then_home_then_temp() {
2538        let xdg = |s: &str| Some(OsString::from(s));
2539        assert_eq!(
2540            resolve_cache_base(xdg("/xdg"), xdg("/home")),
2541            PathBuf::from("/xdg")
2542        );
2543        assert_eq!(
2544            resolve_cache_base(xdg(""), xdg("/home")),
2545            PathBuf::from("/home/.cache")
2546        );
2547        assert_eq!(
2548            resolve_cache_base(None, xdg("/home")),
2549            PathBuf::from("/home/.cache")
2550        );
2551        assert_eq!(resolve_cache_base(None, None), std::env::temp_dir());
2552        assert_eq!(
2553            resolve_cache_base(xdg(""), Some(OsString::new())),
2554            std::env::temp_dir()
2555        );
2556    }
2557
2558    #[test]
2559    fn cache_root_is_absolute_and_version_scoped() {
2560        let root = cargo_mutants_cache_root();
2561        assert!(
2562            root.ends_with(format!("cargo-mutants-{CARGO_MUTANTS_VERSION}")),
2563            "version-scoped; got {root:?}"
2564        );
2565        assert!(
2566            root.to_string_lossy().contains("testing-conventions"),
2567            "tool-namespaced; got {root:?}"
2568        );
2569        assert!(
2570            root.is_absolute(),
2571            "expected an absolute path; got {root:?}"
2572        );
2573    }
2574
2575    #[test]
2576    fn install_argv_pins_the_version_and_isolates_the_root() {
2577        let argv: Vec<String> = install_argv(Path::new("/cache/cargo-mutants-27"))
2578            .iter()
2579            .map(|arg| arg.to_string_lossy().into_owned())
2580            .collect();
2581        assert_eq!(
2582            argv,
2583            vec![
2584                "install",
2585                "cargo-mutants",
2586                "--locked",
2587                "--version",
2588                CARGO_MUTANTS_VERSION,
2589                "--root",
2590                "/cache/cargo-mutants-27",
2591            ]
2592        );
2593    }
2594
2595    #[test]
2596    fn mutants_argv_enables_features_on_the_engine_itself() {
2597        let argv = |diff, features: &[&str]| -> Vec<String> {
2598            mutants_argv(
2599                Path::new("/out"),
2600                diff,
2601                &features.iter().map(|f| f.to_string()).collect::<Vec<_>>(),
2602            )
2603            .iter()
2604            .map(|arg| arg.to_string_lossy().into_owned())
2605            .collect()
2606        };
2607        assert_eq!(
2608            argv(None, &["cli", "boost"]),
2609            vec![
2610                "mutants",
2611                "--output",
2612                "/out",
2613                "--cargo-test-arg",
2614                "--lib",
2615                "--features",
2616                "cli,boost"
2617            ]
2618        );
2619        assert_eq!(
2620            argv(Some(Path::new("/out/base.diff")), &["cli"]),
2621            vec![
2622                "mutants",
2623                "--output",
2624                "/out",
2625                "--cargo-test-arg",
2626                "--lib",
2627                "--in-diff",
2628                "/out/base.diff",
2629                "--features",
2630                "cli",
2631            ]
2632        );
2633        assert_eq!(
2634            argv(None, &[]),
2635            vec!["mutants", "--output", "/out", "--cargo-test-arg", "--lib"]
2636        );
2637    }
2638
2639    #[test]
2640    fn list_argv_mirrors_the_run_feature_selection() {
2641        let argv = |features: &[&str]| -> Vec<String> {
2642            list_argv(&features.iter().map(|f| f.to_string()).collect::<Vec<_>>())
2643                .iter()
2644                .map(|arg| arg.to_string_lossy().into_owned())
2645                .collect()
2646        };
2647        assert_eq!(argv(&[]), vec!["mutants", "--list", "--json"]);
2648        assert_eq!(
2649            argv(&["cli", "boost"]),
2650            vec!["mutants", "--list", "--json", "--features", "cli,boost"]
2651        );
2652    }
2653
2654    #[test]
2655    fn parse_base_diff_maps_inserted_lines_per_hunk() {
2656        let diff = "\
2657diff --git a/src/lib.rs b/src/lib.rs
2658--- a/src/lib.rs
2659+++ b/src/lib.rs
2660@@ -1,4 +1,5 @@
2661 fn a() {}
2662+fn b() {}
2663 fn c() {}
2664-fn d() {}
2665+fn e() {}
2666 fn f() {}
2667@@ -10,2 +11,4 @@
2668 tail
2669+one
2670+two
2671 more
2672";
2673        let parsed = parse_base_diff(diff);
2674        assert_eq!(parsed.files, vec!["src/lib.rs"]);
2675        assert_eq!(
2676            parsed.inserted.get("src/lib.rs"),
2677            Some(&BTreeSet::from([2, 4, 12, 13]))
2678        );
2679    }
2680
2681    #[test]
2682    fn parse_base_diff_leaves_a_deletion_only_file_without_inserted_lines() {
2683        let diff = "\
2684--- a/src/gone.rs
2685+++ b/src/gone.rs
2686@@ -5,2 +4,0 @@
2687-x
2688-y
2689";
2690        let parsed = parse_base_diff(diff);
2691        assert_eq!(parsed.files, vec!["src/gone.rs"]);
2692        assert!(parsed.inserted.is_empty());
2693    }
2694
2695    #[test]
2696    fn parse_base_diff_skips_a_deleted_file() {
2697        let diff = "\
2698--- a/src/dead.rs
2699+++ /dev/null
2700@@ -1,2 +0,0 @@
2701-a
2702-b
2703";
2704        let parsed = parse_base_diff(diff);
2705        assert!(parsed.files.is_empty());
2706        assert!(parsed.inserted.is_empty());
2707    }
2708
2709    #[test]
2710    fn parse_base_diff_consumes_hunk_bodies_by_count_so_content_never_reads_as_a_header() {
2711        // The inserted content line begins with `+++`; consuming the hunk by its declared
2712        // counts keeps it a body line, not a second file header.
2713        let diff = "\
2714+++ b/notes.txt
2715@@ -1,1 +1,2 @@
2716 keep
2717++++ not a header
2718";
2719        let parsed = parse_base_diff(diff);
2720        assert_eq!(parsed.files, vec!["notes.txt"]);
2721        assert_eq!(parsed.inserted.get("notes.txt"), Some(&BTreeSet::from([2])));
2722    }
2723
2724    #[test]
2725    fn parse_base_diff_defaults_an_elided_hunk_count_to_one() {
2726        let diff = "\
2727+++ b/one.txt
2728@@ -1 +1 @@
2729-old
2730+new
2731";
2732        let parsed = parse_base_diff(diff);
2733        assert_eq!(parsed.inserted.get("one.txt"), Some(&BTreeSet::from([1])));
2734    }
2735
2736    #[test]
2737    fn parse_base_diff_skips_no_newline_annotations_mid_hunk() {
2738        let diff = "\
2739+++ b/n.txt
2740@@ -1 +1 @@
2741-old
2742\\ No newline at end of file
2743+new
2744\\ No newline at end of file
2745";
2746        let parsed = parse_base_diff(diff);
2747        assert_eq!(parsed.inserted.get("n.txt"), Some(&BTreeSet::from([1])));
2748    }
2749
2750    #[cfg(unix)]
2751    fn fake_output(code: i32, stderr: &str) -> Output {
2752        use std::os::unix::process::ExitStatusExt;
2753        Output {
2754            status: std::process::ExitStatus::from_raw(code << 8),
2755            stdout: Vec::new(),
2756            stderr: stderr.as_bytes().to_vec(),
2757        }
2758    }
2759
2760    #[cfg(unix)]
2761    enum FakeRun {
2762        AssertsVersionAndSucceeds,
2763        FailsWith(&'static str),
2764        SpawnError,
2765    }
2766
2767    #[cfg(unix)]
2768    fn drive_install(root: &Path, run: FakeRun) -> Result<()> {
2769        run_install(root, |command| match run {
2770            FakeRun::AssertsVersionAndSucceeds => {
2771                let argv: Vec<String> = command
2772                    .get_args()
2773                    .map(|arg| arg.to_string_lossy().into_owned())
2774                    .collect();
2775                assert!(argv.contains(&CARGO_MUTANTS_VERSION.to_string()));
2776                Ok(fake_output(0, ""))
2777            }
2778            FakeRun::FailsWith(stderr) => Ok(fake_output(1, stderr)),
2779            FakeRun::SpawnError => Err(std::io::Error::new(
2780                std::io::ErrorKind::NotFound,
2781                "no cargo",
2782            )),
2783        })
2784    }
2785
2786    #[cfg(unix)]
2787    #[test]
2788    fn run_install_succeeds_on_a_zero_exit() {
2789        drive_install(Path::new("/cache/root"), FakeRun::AssertsVersionAndSucceeds).unwrap();
2790    }
2791
2792    #[cfg(unix)]
2793    #[test]
2794    fn run_install_reports_a_nonzero_exit_with_the_engine_output() {
2795        let err = drive_install(
2796            Path::new("/cache/root"),
2797            FakeRun::FailsWith("error: could not compile cargo-mutants"),
2798        )
2799        .unwrap_err();
2800        assert!(
2801            err.to_string()
2802                .contains("failed to provision cargo-mutants")
2803                && err.to_string().contains("could not compile"),
2804            "got: {err}"
2805        );
2806    }
2807
2808    #[cfg(unix)]
2809    #[test]
2810    fn run_install_propagates_a_spawn_failure() {
2811        let err = drive_install(Path::new("/cache/root"), FakeRun::SpawnError).unwrap_err();
2812        assert!(
2813            err.to_string().contains("is cargo installed?"),
2814            "got: {err}"
2815        );
2816    }
2817
2818    #[cfg(unix)]
2819    #[test]
2820    fn provision_pinned_installs_via_the_injected_runner() {
2821        let root = unique_tmp();
2822        let bin = root.join("bin").join(CARGO_MUTANTS_BIN_NAME);
2823        let expected = bin.clone();
2824        let got = provision_pinned(&root, |_| {
2825            write_bin(&bin);
2826            Ok(fake_output(0, ""))
2827        })
2828        .unwrap();
2829        assert_eq!(got, expected);
2830        std::fs::remove_dir_all(&root).unwrap();
2831    }
2832
2833    #[test]
2834    fn execute_surfaces_a_spawn_failure() {
2835        let err = execute(&mut Command::new("/nonexistent-tc-cargo")).unwrap_err();
2836        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
2837    }
2838
2839    #[cfg(unix)]
2840    fn fake_stdout(code: i32, stdout: &str) -> Output {
2841        use std::os::unix::process::ExitStatusExt;
2842        Output {
2843            status: std::process::ExitStatus::from_raw(code << 8),
2844            stdout: stdout.as_bytes().to_vec(),
2845            stderr: Vec::new(),
2846        }
2847    }
2848
2849    #[cfg(unix)]
2850    enum FakeList {
2851        AssertsArgvAndReturns(&'static str, Vec<&'static str>),
2852        FailsWith(&'static str),
2853        SpawnError,
2854    }
2855
2856    #[cfg(unix)]
2857    fn drive_list(features: &[String], run: FakeList) -> Result<Vec<MutantInfo>> {
2858        list_cargo_mutants(
2859            Path::new("/cache/bin/cargo-mutants"),
2860            Path::new("/crate"),
2861            features,
2862            |command| match run {
2863                FakeList::AssertsArgvAndReturns(json, expected) => {
2864                    let argv: Vec<String> = command
2865                        .get_args()
2866                        .map(|arg| arg.to_string_lossy().into_owned())
2867                        .collect();
2868                    assert_eq!(argv, expected);
2869                    assert_eq!(command.get_current_dir(), Some(Path::new("/crate")));
2870                    Ok(fake_stdout(0, json))
2871                }
2872                FakeList::FailsWith(stderr) => Ok(fake_output(1, stderr)),
2873                FakeList::SpawnError => Err(std::io::Error::new(
2874                    std::io::ErrorKind::NotFound,
2875                    "no engine",
2876                )),
2877            },
2878        )
2879    }
2880
2881    #[cfg(unix)]
2882    #[test]
2883    fn list_cargo_mutants_parses_the_listing_from_a_clean_run() {
2884        let json = r#"[{"file": "src/lib.rs", "name": "replace add -> 0", "genre": "FnValue",
2885            "span": {"start": {"line": 3, "column": 1}, "end": {"line": 5, "column": 2}}}]"#;
2886        let listed = drive_list(
2887            &["cli".to_string()],
2888            FakeList::AssertsArgvAndReturns(
2889                json,
2890                vec!["mutants", "--list", "--json", "--features", "cli"],
2891            ),
2892        )
2893        .unwrap();
2894        assert_eq!(listed.len(), 1);
2895        assert_eq!(listed[0].file, "src/lib.rs");
2896        assert_eq!(listed[0].span.start.line, 3);
2897        assert_eq!(listed[0].span.end.line, 5);
2898        assert_eq!(listed[0].name, "replace add -> 0");
2899    }
2900
2901    #[cfg(unix)]
2902    #[test]
2903    fn list_cargo_mutants_reports_a_nonzero_exit_with_the_engine_output() {
2904        let err = drive_list(&[], FakeList::FailsWith("error: no such option")).unwrap_err();
2905        assert!(
2906            err.to_string().contains("cargo-mutants --list failed")
2907                && err.to_string().contains("no such option"),
2908            "got: {err}"
2909        );
2910    }
2911
2912    #[cfg(unix)]
2913    #[test]
2914    fn list_cargo_mutants_propagates_a_spawn_failure() {
2915        let err = drive_list(&[], FakeList::SpawnError).unwrap_err();
2916        assert!(
2917            err.to_string()
2918                .contains("listing the crate's mutants with cargo-mutants"),
2919            "got: {err}"
2920        );
2921    }
2922
2923    #[cfg(unix)]
2924    #[test]
2925    fn a_dropped_site_renders_indented_with_its_location_stripped_from_the_name() {
2926        let mutant = listed_mutant("src/a.rs", 12, 14, "src/a.rs:12:5: replace foo with bar");
2927
2928        assert_eq!(mutant_site(&mutant), "  src/a.rs:12: replace foo with bar");
2929    }
2930
2931    #[cfg(unix)]
2932    fn listed_mutant(file: &str, start: u32, end: u32, name: &str) -> MutantInfo {
2933        MutantInfo {
2934            file: file.to_string(),
2935            span: Span {
2936                start: LineCol { line: start },
2937                end: LineCol { line: end },
2938            },
2939            name: name.to_string(),
2940            genre: "FnValue".to_string(),
2941        }
2942    }
2943
2944    #[cfg(unix)]
2945    fn diff_with_inserted(file: &str, lines: &[u32]) -> BaseDiff {
2946        BaseDiff {
2947            files: vec![file.to_string()],
2948            inserted: BTreeMap::from([(file.to_string(), lines.iter().copied().collect())]),
2949        }
2950    }
2951
2952    #[cfg(unix)]
2953    #[test]
2954    fn zero_mutant_verdict_accepts_a_zero_with_no_mutant_on_the_inserted_lines() {
2955        let run = fake_output(0, "");
2956        zero_mutant_verdict(&[], &diff_with_inserted("src/lib.rs", &[5]), &run).unwrap();
2957        let listed = [listed_mutant("src/lib.rs", 5, 8, "replace add -> 0")];
2958        zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[4, 9]), &run).unwrap();
2959        zero_mutant_verdict(&listed, &diff_with_inserted("src/other.rs", &[6]), &run).unwrap();
2960    }
2961
2962    #[cfg(unix)]
2963    #[test]
2964    fn zero_mutant_verdict_is_fatal_on_a_mutant_at_either_span_boundary() {
2965        let listed = [listed_mutant("src/lib.rs", 5, 8, "replace add -> 0")];
2966        let run = fake_stdout(0, "0 mutants tested");
2967        for line in [5, 8] {
2968            let err =
2969                zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[line]), &run)
2970                    .unwrap_err();
2971            let message = err.to_string();
2972            assert!(
2973                message.contains("1 of the crate's 1 mutant site(s)")
2974                    && message.contains("src/lib.rs:5: replace add -> 0")
2975                    && message.contains("0 mutants tested"),
2976                "got: {message}"
2977            );
2978        }
2979    }
2980
2981    #[cfg(unix)]
2982    #[test]
2983    fn zero_mutant_verdict_names_each_dropped_site_once() {
2984        let listed = [
2985            listed_mutant(
2986                "src/lib.rs",
2987                7,
2988                7,
2989                "src/lib.rs:7:7: replace > with == in is_positive",
2990            ),
2991            listed_mutant("src/lib.rs", 7, 7, "replace add -> 0"),
2992        ];
2993        let run = fake_stdout(0, "0 mutants tested");
2994        let message = zero_mutant_verdict(&listed, &diff_with_inserted("src/lib.rs", &[7]), &run)
2995            .unwrap_err()
2996            .to_string();
2997        assert!(
2998            message.contains("  src/lib.rs:7: replace > with == in is_positive"),
2999            "the name's embedded `file:line:col:` prefix is stripped; got: {message}"
3000        );
3001        assert!(
3002            !message.contains(": src/lib.rs:7:7:"),
3003            "a dropped site carries one location; got: {message}"
3004        );
3005        assert!(
3006            message.contains("  src/lib.rs:7: replace add -> 0"),
3007            "a name with no embedded location keeps its rendered location; got: {message}"
3008        );
3009    }
3010
3011    #[cfg(unix)]
3012    #[test]
3013    fn classify_mutants_exit_accepts_the_caught_and_survivor_exits() {
3014        classify_mutants_exit(Path::new("/crate"), &fake_output(0, "")).unwrap();
3015        classify_mutants_exit(Path::new("/crate"), &fake_output(2, "")).unwrap();
3016    }
3017
3018    #[cfg(unix)]
3019    #[test]
3020    fn classify_mutants_exit_accepts_a_timeout_exit_3() {
3021        classify_mutants_exit(Path::new("/crate"), &fake_output(3, ""))
3022            .expect("a timeout (exit 3) is inconclusive, not fatal");
3023    }
3024
3025    #[cfg(unix)]
3026    #[test]
3027    fn classify_mutants_exit_is_fatal_on_a_baseline_failure() {
3028        let err = classify_mutants_exit(Path::new("/crate"), &fake_output(4, "baseline broke"))
3029            .unwrap_err();
3030        assert!(
3031            err.to_string().contains("did not run cleanly")
3032                && err.to_string().contains("baseline broke"),
3033            "got: {err}"
3034        );
3035    }
3036
3037    #[test]
3038    fn cargo_mutants_bin_name_matches_the_platform() {
3039        #[cfg(windows)]
3040        assert_eq!(CARGO_MUTANTS_BIN_NAME, "cargo-mutants.exe");
3041        #[cfg(not(windows))]
3042        assert_eq!(CARGO_MUTANTS_BIN_NAME, "cargo-mutants");
3043    }
3044
3045    /// A one-file unified diff inserting a single line, for scope decisions.
3046    fn one_file_diff(file: &str) -> String {
3047        format!("diff --git a/{file} b/{file}\n--- a/{file}\n+++ b/{file}\n@@ -1,0 +1,1 @@\n+x\n")
3048    }
3049
3050    #[test]
3051    fn a_diff_touching_rust_source_is_in_scope_with_its_parsed_reading() {
3052        let (path, parsed) = rust_scope(
3053            Some(PathBuf::from("base.diff")),
3054            Some(one_file_diff("src/lib.rs")),
3055        )
3056        .expect("a diff touching a .rs file is in scope");
3057
3058        assert_eq!(path, PathBuf::from("base.diff"));
3059        assert_eq!(parsed.files, vec!["src/lib.rs".to_string()]);
3060    }
3061
3062    #[test]
3063    fn a_diff_touching_no_rust_source_is_out_of_scope() {
3064        assert!(rust_scope(
3065            Some(PathBuf::from("base.diff")),
3066            Some(one_file_diff("docs/readme.md")),
3067        )
3068        .is_none());
3069    }
3070
3071    #[test]
3072    fn a_run_whose_git_diff_wrote_nothing_is_out_of_scope() {
3073        assert!(rust_scope(None, None).is_none());
3074        assert!(rust_scope(Some(PathBuf::from("base.diff")), None).is_none());
3075    }
3076
3077    #[test]
3078    fn a_deletion_only_hunk_still_consumes_the_lines_it_declared() {
3079        // The old-side count has to be walked even when the hunk inserts nothing, or the
3080        // line after the hunk — which may itself begin `---` or `+++` — reads as a file
3081        // header in the caller.
3082        let text = "-gone\n--- a/not-a-file.rs\n";
3083        let mut lines = text.lines();
3084        let mut inserted = BTreeMap::new();
3085
3086        consume_hunk(
3087            &mut lines,
3088            (1, 1, 0),
3089            Some(&"src/lib.rs".to_string()),
3090            &mut inserted,
3091        );
3092
3093        assert!(inserted.is_empty(), "a deletion inserts nothing");
3094        assert_eq!(lines.next(), Some("--- a/not-a-file.rs"));
3095    }
3096}