Skip to main content

targeted_mutation/
report.rs

1//! Turns planner results into findings a person can act on: which wrong implementation
2//! survives, and which input or assertion would catch it.
3
4use serde::Serialize;
5
6use crate::instrument::{ArithOp, LiteralSide, Site, SiteKind};
7use crate::plan::{CmpOp, InputGap, LogicGap, Mutation, Obs};
8
9#[derive(Clone, Debug, Default, PartialEq, Serialize)]
10pub struct Location {
11    pub file: String,
12    pub line: usize,
13    pub column: usize,
14    pub code: String,
15    /// The function or constant the code is in (`Store::commit`); empty where unknown.
16    #[serde(skip_serializing_if = "String::is_empty")]
17    pub item: String,
18    /// What the finding at this place is known by across runs: see [`finding_id`].
19    #[serde(skip_serializing_if = "String::is_empty")]
20    pub id: String,
21}
22
23/// The name a finding keeps from run to run: its kind, its file, the item it is in, its
24/// code, and which of the places with that code in that item it is (0 for the first).
25/// Lines are not in it, so code that moves keeps its name, and neither are the words
26/// that describe the surviving mutants, so those can be improved.
27pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
28    format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
29}
30
31#[derive(Clone, Debug, PartialEq, Serialize)]
32#[serde(rename_all = "snake_case", tag = "kind")]
33pub enum Finding {
34    /// No test input can tell these mutants from the original.
35    InputGap {
36        #[serde(flatten)]
37        at: Location,
38        /// Source-level form of mutants that pass every test.
39        survivors: Vec<String>,
40        /// How many mutants the gap lets through in total.
41        survivor_count: u128,
42        /// Inputs to add, in words.
43        add_tests: Vec<String>,
44        /// What the tests did feed the comparison.
45        observed: Option<String>,
46        /// Whether the tests were re-run against a survivor to confirm.
47        verified: bool,
48    },
49    /// Tests execute the changed behaviour, and still pass.
50    AssertionGap {
51        #[serde(flatten)]
52        at: Location,
53        survivors: Vec<String>,
54        /// Tests whose execution changed under the mutants but did not fail.
55        tests: Vec<String>,
56        /// What one surviving mutant changes later in those tests: the places an
57        /// assertion could catch it. Empty when that was not looked into.
58        effects: Vec<String>,
59        /// The mutant whose effects those are, as it is written in `survivors`.
60        effects_of: Option<String>,
61    },
62    /// A mutant that was built on its own passes every test, and nothing was recorded
63    /// that says why: whether no test runs the code (nothing can be recorded in a
64    /// `const fn`), or one does and does not look at the result.
65    Survivor {
66        #[serde(flatten)]
67        at: Location,
68        survivors: Vec<String>,
69    },
70}
71
72impl Finding {
73    pub fn at(&self) -> &Location {
74        let (Finding::InputGap { at, .. }
75        | Finding::AssertionGap { at, .. }
76        | Finding::Survivor { at, .. }) = self;
77        at
78    }
79
80    pub fn at_mut(&mut self) -> &mut Location {
81        let (Finding::InputGap { at, .. }
82        | Finding::AssertionGap { at, .. }
83        | Finding::Survivor { at, .. }) = self;
84        at
85    }
86
87    pub fn survivors(&self) -> &[String] {
88        let (Finding::InputGap { survivors, .. }
89        | Finding::AssertionGap { survivors, .. }
90        | Finding::Survivor { survivors, .. }) = self;
91        survivors
92    }
93
94    /// The kind as the JSON report and the names of findings spell it.
95    pub fn kind(&self) -> &'static str {
96        match self {
97            Finding::InputGap { .. } => "input_gap",
98            Finding::AssertionGap { .. } => "assertion_gap",
99            Finding::Survivor { .. } => "survivor",
100        }
101    }
102}
103
104/// What decides which code cargo compiles, as given on the command line.
105#[derive(Clone, Debug, Default, PartialEq, Serialize)]
106pub struct CargoConfig {
107    pub features: Vec<String>,
108    pub all_features: bool,
109    pub no_default_features: bool,
110    pub locked: bool,
111}
112
113/// What a run looked at and how: a report says nothing about what is outside of it.
114#[derive(Clone, Debug, Default, PartialEq, Serialize)]
115pub struct Analysis {
116    /// The package's directory in its git repository (`crates/core/`; empty at the top).
117    pub package_path: String,
118    /// Only the code changed since this revision.
119    pub since: Option<String>,
120    /// Only these lines.
121    pub lines: Vec<String>,
122    /// The packages whose tests were run.
123    pub tests_of: Vec<String>,
124    pub cargo: CargoConfig,
125    pub opt_level: Option<u8>,
126    /// Mutants that need a build of their own were run.
127    pub rebuild: bool,
128    /// Predicted survivors were re-run.
129    pub verified: bool,
130    pub doc_tests: bool,
131}
132
133/// What a run that was asked to check itself found (`--audit`).
134#[derive(Clone, Debug, Default, PartialEq, Serialize)]
135pub struct Audit {
136    /// Surviving mutants that were run once more, against every test of every binary.
137    pub sampled: usize,
138    /// How many surviving mutants there were to choose from.
139    pub survivors: usize,
140    /// Where one of those failed a test it had not been run against: the tests were not
141    /// chosen as they should have been, or do not always do the same.
142    pub disagreements: Vec<Location>,
143    /// Test binaries whose second recorded run was not like the first, with the number
144    /// of records (what one test saw at one site) that differ.
145    pub trace_differences: Vec<TraceDifference>,
146    /// Mutants that were run as probes and chosen to be built from the source as well.
147    pub rebuilt: usize,
148    /// Of those, the ones that built and whose two results could be compared.
149    pub compared: usize,
150    /// And the ones that did not build (or whose probe run could not be evaluated):
151    /// nothing is known about them.
152    pub not_compared: usize,
153    /// Where the two did not agree on whether the tests pass.
154    pub source_disagreements: Vec<SourceDisagreement>,
155}
156
157/// A mutant on which its probe and its source form do not agree.
158#[derive(Clone, Debug, Default, PartialEq, Serialize)]
159pub struct SourceDisagreement {
160    #[serde(flatten)]
161    pub at: Location,
162    pub mutant: String,
163    /// `passes` or `fails`: what the tests did with the probe, and with the source.
164    pub as_probe: String,
165    pub built: String,
166}
167
168#[derive(Clone, Debug, Default, PartialEq, Serialize)]
169pub struct TraceDifference {
170    pub binary: String,
171    pub records: usize,
172}
173
174#[derive(Clone, Debug, Default, PartialEq, Serialize)]
175pub struct Report {
176    pub package: String,
177    pub analysis: Analysis,
178    /// Present when the run was asked to check itself.
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub audit: Option<Audit>,
181    pub sites: usize,
182    /// Sites that could not be instrumented (the probe did not compile there).
183    pub skipped_sites: usize,
184    /// Values a function's body was to be replaced by that do not have its type
185    /// (`Default::default()` for a type without a default): those mutants do not exist.
186    pub unviable_mutants: usize,
187    /// Mutants that need a build of their own and were not asked for (`--rebuild`).
188    pub mutants_not_built: usize,
189    /// Mutants that could not be run as what they are (a range that ends at the largest
190    /// value of its type cannot be made to include it): neither killed nor survivors.
191    pub mutants_not_evaluated: usize,
192    pub mutants_run: usize,
193    pub mutants_killed: usize,
194    /// Killed mutants that were stopped by the timeout (typically an endless loop).
195    pub mutants_timed_out: usize,
196    pub findings: Vec<Finding>,
197    /// Findings left out because of a `// tmt:ignore` comment or the baseline.
198    pub suppressed: usize,
199    /// Code no test executes.
200    pub unreached: Vec<Location>,
201    /// Survivors predicted from the trace that a re-run killed: the tests are not deterministic.
202    pub unstable: Vec<Location>,
203}
204
205impl Report {
206    /// Puts the findings in reading order. Sites are numbered as they are discovered, and
207    /// a statement is discovered before the expressions of the statements above it.
208    pub fn sort_findings(&mut self) {
209        self.findings.sort_by(|a, b| {
210            let key = |finding: &Finding| {
211                let at = finding.at();
212                (at.file.clone(), at.line, at.column)
213            };
214            key(a).cmp(&key(b))
215        });
216    }
217
218    /// Whether the run found something to act on: a gap, or a prediction that did not
219    /// hold (which means the report cannot be trusted as it stands).
220    pub fn has_gaps(&self) -> bool {
221        !self.findings.is_empty() || !self.unstable.is_empty()
222    }
223}
224
225pub fn location(file: &str, site: &Site) -> Location {
226    Location {
227        file: file.to_string(),
228        line: site.line,
229        column: site.column,
230        code: one_line(&site.text),
231        ..Location::default()
232    }
233}
234
235fn one_line(code: &str) -> String {
236    let joined = code.split_whitespace().collect::<Vec<_>>().join(" ");
237    if joined.chars().count() > 100 {
238        format!("{}...", joined.chars().take(97).collect::<String>())
239    } else {
240        joined
241    }
242}
243
244/// Value of a float literal such as `30.5`, `1e3` or `2.5_f32`.
245fn float_literal(text: &str) -> Option<f64> {
246    let text = text.trim().replace('_', "");
247    let text = text
248        .strip_suffix("f32")
249        .or(text.strip_suffix("f64"))
250        .unwrap_or(&text);
251    let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
252        && text
253            .chars()
254            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
255    if looks_numeric {
256        text.parse().ok()
257    } else {
258        None
259    }
260}
261
262/// Floats in reports: the shortest text that reads back as the same value, so nothing is
263/// rounded away.
264fn show_float(v: f64) -> String {
265    format!("{v:?}")
266}
267
268/// Source-level form of a mutant.
269pub fn describe(site: &Site, m: Mutation) -> String {
270    match &site.kind {
271        SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
272        SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
273        SiteKind::Guard { .. } => match m {
274            Mutation::Const(value) => {
275                format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
276            }
277            _ => format!("another guard than `{}`", one_line(&site.text)),
278        },
279        SiteKind::Field { from_base, .. } => format!(
280            "without the field `{}` (it is then `{from_base}`)",
281            one_line(&site.text)
282        ),
283        SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
284        SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
285        SiteKind::Return { name, option, .. } => match (m, option) {
286            (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
287            (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
288            _ => format!("`{name}` returning something else"),
289        },
290        SiteKind::Range {
291            inclusive,
292            lhs,
293            rhs,
294            ..
295        } => {
296            let dots = if *inclusive { ".." } else { "..=" };
297            format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
298        }
299        SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
300        SiteKind::MinMax {
301            max,
302            receiver,
303            argument,
304            ..
305        } => {
306            let other = if *max { "min" } else { "max" };
307            format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
308        }
309        SiteKind::Logic { and, lhs, rhs, .. } => {
310            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
311            match m {
312                // Both operands are still evaluated whenever the original evaluates them;
313                // only the value of one is ignored. The forms below say exactly that.
314                Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
315                Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
316                Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
317                _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
318            }
319        }
320        SiteKind::Arith {
321            op,
322            assign,
323            lhs,
324            rhs,
325            ..
326        } => {
327            let eq = if *assign { "=" } else { "" };
328            let other = match m {
329                Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
330                _ => op.swapped(),
331            };
332            format!(
333                "`{} {}{eq} {}`",
334                one_line(lhs),
335                other.symbol(),
336                one_line(rhs)
337            )
338        }
339        SiteKind::Cmp {
340            op,
341            lhs,
342            rhs,
343            literal,
344            ..
345        } => {
346            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
347            let sym = op.symbol();
348            match m {
349                Mutation::Const(c) => format!("`{c}`"),
350                Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
351                Mutation::Shift(d) => match literal {
352                    LiteralSide::Rhs(k) => format!("`{lhs} {sym} {}`", k + d),
353                    // k op rhs + d  <=>  k - d op rhs
354                    LiteralSide::Lhs(k) => format!("`{} {sym} {rhs}`", k - d),
355                    LiteralSide::None => match (op, d) {
356                        (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
357                        (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
358                        (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
359                        (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
360                        // Meant as arithmetic on whole numbers: in the operands' own
361                        // type the addition could overflow, the mutant that was run cannot.
362                        // tmt:ignore a shift of 0 is never planned, so `>=` is the same
363                        (_, d) if d > 0 => format!("`{lhs} {sym} {rhs} + {d}` (without overflow)"),
364                        (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
365                    },
366                },
367                Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
368                    (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
369                    (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
370                    // tmt:ignore a shift of 0 is never planned, so any threshold near it is the same
371                    _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
372                    _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
373                },
374                _ => format!("`!({lhs} {sym} {rhs})`"),
375            }
376        }
377    }
378}
379
380/// The operand values that give `lhs - rhs = d`, in words.
381fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
382    match (literal, d) {
383        (LiteralSide::Rhs(k), d) => format!("`{lhs}` = {}", k + d),
384        (LiteralSide::Lhs(k), d) => format!("`{rhs}` = {}", k - d),
385        (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
386        // tmt:ignore 0 is taken by the arm above, so `>=` is the same
387        (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
388        (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
389    }
390}
391
392fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
393    if !obs.valued() {
394        return None;
395    }
396    let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
397        .into_iter()
398        .flatten()
399        .collect();
400    let text = match literal {
401        LiteralSide::Rhs(k) => {
402            let values: Vec<String> = ds.iter().map(|d| (k + d).to_string()).collect();
403            format!("`{lhs}` = {}", values.join(", "))
404        }
405        LiteralSide::Lhs(k) => {
406            let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
407            values.sort();
408            let values: Vec<String> = values.iter().map(i128::to_string).collect();
409            format!("`{rhs}` = {}", values.join(", "))
410        }
411        LiteralSide::None => {
412            let values: Vec<String> = ds.iter().map(i128::to_string).collect();
413            format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
414        }
415    };
416    Some(format!("nearest values the tests passed: {text}"))
417}
418
419/// Builds the input-gap finding for a comparison site. `None` for gaps that are reported
420/// elsewhere (unreached code).
421pub fn input_gap_finding(
422    file: &str,
423    site: &Site,
424    gap: &InputGap,
425    obs: &Obs,
426    verified: bool,
427) -> Option<Finding> {
428    let SiteKind::Cmp {
429        op,
430        lhs,
431        rhs,
432        literal,
433        ..
434    } = &site.kind
435    else {
436        return None;
437    };
438    let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
439    // A float shift too small to move the literal is not a different program. The
440    // literal moves the way `describe` writes it.
441    let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
442        (None, Some(k)) => k + d != k,
443        (Some(k), None) => k - d != k,
444        _ => true,
445    };
446    let survivors: Vec<String> = gap
447        .survivors()
448        .into_iter()
449        .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
450        .map(|m| describe(site, m))
451        .collect();
452    let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
453    let (survivor_count, add_tests) = match gap {
454        InputGap::Unreached => return None,
455        InputGap::OneSided { always } => (
456            1,
457            vec![format!(
458                "an input that makes `{}` {}",
459                one_line(&site.text),
460                !always
461            )],
462        ),
463        InputGap::EqualNeverObserved { flipped, float_gap } => {
464            if let Some((lo, hi)) = float_gap {
465                observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
466                    (None, Some(k)) => format!(
467                        "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
468                        show_float(k + lo),
469                        show_float(k + hi)
470                    ),
471                    (Some(k), None) => format!(
472                        "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
473                        show_float(k - hi),
474                        show_float(k - lo)
475                    ),
476                    _ => format!(
477                        "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
478                        show_float(*lo),
479                        show_float(*hi)
480                    ),
481                });
482            }
483            (
484                survivors.len() as u128,
485                vec![format!(
486                    "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
487                    op.eval_d(0),
488                    flipped.eval_d(0)
489                )],
490            )
491        }
492        InputGap::Boundary {
493            min_shift,
494            max_shift,
495            missing,
496        } => {
497            let add = missing
498                .iter()
499                .map(|d| {
500                    format!(
501                        "{} (the original gives {})",
502                        input_for(&lhs_text, &rhs_text, *literal, *d),
503                        op.eval_d(*d)
504                    )
505                })
506                .collect();
507            ((max_shift - min_shift) as u128, add)
508        }
509    };
510    Some(Finding::InputGap {
511        at: location(file, site),
512        survivors,
513        survivor_count,
514        add_tests,
515        observed,
516        verified,
517    })
518}
519
520/// Input gap at `a && b` / `a || b`: one operand never decides the result in any test.
521pub fn logic_gap_finding(
522    file: &str,
523    site: &Site,
524    gap: LogicGap,
525    verified: bool,
526) -> Option<Finding> {
527    let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
528        return None;
529    };
530    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
531    let (mutation, add) = match (gap, and) {
532        (LogicGap::Unreached, _) => return None,
533        (LogicGap::RhsNeverDecides, true) => (
534            Mutation::LogicDropRhs,
535            format!("a case where `{lhs}` is true and `{rhs}` is false"),
536        ),
537        (LogicGap::RhsNeverDecides, false) => (
538            Mutation::LogicDropRhs,
539            format!("a case where `{lhs}` is false and `{rhs}` is true"),
540        ),
541        (LogicGap::LhsNeverDecides, true) => (
542            Mutation::LogicDropLhs,
543            format!("a case where `{lhs}` is false"),
544        ),
545        (LogicGap::LhsNeverDecides, false) => (
546            Mutation::LogicDropLhs,
547            format!("a case where `{lhs}` is true"),
548        ),
549    };
550    Some(Finding::InputGap {
551        at: location(file, site),
552        survivors: vec![describe(site, mutation)],
553        survivor_count: 1,
554        add_tests: vec![add],
555        observed: None,
556        verified,
557    })
558}
559
560/// Input gap at `a.max(b)` / `a.min(b)`: the two operands were equal in every test.
561pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
562    let SiteKind::MinMax {
563        receiver, argument, ..
564    } = &site.kind
565    else {
566        return None;
567    };
568    Some(Finding::InputGap {
569        at: location(file, site),
570        survivors: vec![describe(site, Mutation::MinMax)],
571        survivor_count: 1,
572        add_tests: vec![format!(
573            "`{}` different from `{}`",
574            one_line(receiver),
575            one_line(argument)
576        )],
577        observed: None,
578        verified,
579    })
580}
581
582/// Input gap at a `-> bool` function that returned the same value in every test.
583pub fn return_gap_finding(
584    file: &str,
585    site: &Site,
586    always: bool,
587    verified: bool,
588) -> Option<Finding> {
589    let SiteKind::Return { name, option, .. } = &site.kind else {
590        return None;
591    };
592    let other = match (option, always) {
593        (None, always) => format!("{}", !always),
594        (Some(_), false) => "`Some`".to_string(),
595        (Some(_), true) => "`None`".to_string(),
596    };
597    Some(Finding::InputGap {
598        at: location(file, site),
599        survivors: vec![describe(site, Mutation::Const(always))],
600        survivor_count: 1,
601        add_tests: vec![format!("a case where `{name}` returns {other}")],
602        observed: None,
603        verified,
604    })
605}
606
607/// Input gap at the guard of a match arm that had the same value in every test.
608pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
609    Finding::InputGap {
610        at: location(file, site),
611        survivors: vec![describe(site, Mutation::Const(always))],
612        survivor_count: 1,
613        add_tests: vec![format!(
614            "a case where the guard `{}` is {}",
615            one_line(&site.text),
616            !always
617        )],
618        observed: None,
619        verified,
620    }
621}
622
623/// Input gap at an arithmetic operator: the swapped operator computes the same value on
624/// every pair of operands the tests pass.
625pub fn arith_gap_finding(
626    file: &str,
627    site: &Site,
628    mutation: Mutation,
629    verified: bool,
630) -> Option<Finding> {
631    let SiteKind::Arith {
632        op,
633        assign,
634        lhs,
635        rhs,
636        ..
637    } = &site.kind
638    else {
639        return None;
640    };
641    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
642    let eq = if *assign { "=" } else { "" };
643    let other = match mutation {
644        Mutation::ArithSwap2 => op.second(*assign)?,
645        _ => op.swapped(),
646    };
647    let add = match (op, other) {
648        (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
649            format!("`{rhs}` other than 0")
650        }
651        _ => format!(
652            "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
653            op.symbol(),
654            other.symbol()
655        ),
656    };
657    Some(Finding::InputGap {
658        at: location(file, site),
659        survivors: vec![describe(site, mutation)],
660        survivor_count: 1,
661        add_tests: vec![add],
662        observed: None,
663        verified,
664    })
665}
666
667/// The report as SARIF 2.1.0, for code scanning UIs. `prefix` is put in front of the file
668/// names (the package's path inside the repository).
669/// SARIF with the files named from the top of the repository.
670pub fn render_sarif(report: &Report) -> String {
671    let prefix = report.analysis.package_path.as_str();
672    let results: Vec<serde_json::Value> = report
673        .findings
674        .iter()
675        .map(|finding| {
676            let (kind, at) = finding_parts(finding);
677            let rule = match kind {
678                "INPUT GAP" => "input-gap",
679                "ASSERTION GAP" => "assertion-gap",
680                _ => "survivor",
681            };
682            let text = format!("`{}`: {}", at.code, finding_body(finding).join("; "));
683            serde_json::json!({
684                "ruleId": rule,
685                "level": "warning",
686                "message": { "text": text },
687                // What the service tells a finding of one run from that of another by.
688                "partialFingerprints": { "tmtFindingId/v2": at.id },
689                "locations": [{
690                    "physicalLocation": {
691                        "artifactLocation": { "uri": format!("{prefix}{}", at.file) },
692                        "region": { "startLine": at.line, "startColumn": at.column }
693                    }
694                }]
695            })
696        })
697        .collect();
698    let sarif = serde_json::json!({
699        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
700        "version": "2.1.0",
701        "runs": [{
702            "tool": { "driver": {
703                "name": "tmt",
704                "rules": [
705                    { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
706                    { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
707                    { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } }
708                ]
709            } },
710            // What was looked at: a run of a part says nothing about the rest.
711            "properties": { "analysis": report.analysis },
712            "results": results
713        }]
714    });
715    serde_json::to_string_pretty(&sarif).expect("JSON values serialise")
716}
717
718fn list(items: &[String], limit: usize) -> String {
719    let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
720    let more = items.len().saturating_sub(limit);
721    if more > 0 {
722        format!("{} (+{more} more)", shown.join(", "))
723    } else {
724        shown.join(", ")
725    }
726}
727
728/// The lines of one finding, without its header.
729fn finding_body(finding: &Finding) -> Vec<String> {
730    let mut lines = vec![];
731    match finding {
732        Finding::InputGap {
733            survivors,
734            survivor_count,
735            add_tests,
736            observed,
737            verified,
738            ..
739        } => {
740            let more = survivor_count.saturating_sub(survivors.len() as u128);
741            let more = if more > 0 {
742                format!(" (+{more} more)")
743            } else {
744                String::new()
745            };
746            let note = if *verified {
747                "re-run: tests pass"
748            } else {
749                "from the trace, not re-run"
750            };
751            lines.push(format!(
752                "passes every test as: {}{more}  [{note}]",
753                survivors.join(", ")
754            ));
755            lines.extend(observed.iter().cloned());
756            lines.extend(
757                add_tests
758                    .iter()
759                    .map(|test| format!("add a test with {test}")),
760            );
761        }
762        Finding::AssertionGap {
763            survivors,
764            tests,
765            effects,
766            effects_of,
767            ..
768        } => {
769            lines.push(format!("passes every test as: {}", survivors.join(", ")));
770            lines.push(format!(
771                "these tests run the changed code and still pass: {}",
772                list(tests, 5)
773            ));
774            if effects.is_empty() {
775                lines.push("add an assertion on what this code is responsible for".to_string());
776            } else {
777                // Which of several mutants was followed, so that what is said of "the
778                // mutant" below can be tried.
779                if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
780                    lines.push(format!(
781                        "followed one of them through the tests: {followed}"
782                    ));
783                }
784                lines.extend(effects.iter().cloned());
785            }
786        }
787        Finding::Survivor { survivors, .. } => {
788            lines.push(format!("passes every test as: {}", survivors.join(", ")));
789            lines.push(
790                "built on its own, where nothing can be recorded: either no test runs this code, or one does and does not check what it gives"
791                    .to_string(),
792            );
793        }
794    }
795    lines
796}
797
798fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
799    match finding {
800        Finding::InputGap { at, .. } => ("INPUT GAP", at),
801        Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
802        Finding::Survivor { at, .. } => ("SURVIVOR", at),
803    }
804}
805
806pub fn render_text(report: &Report, show_unreached: bool) -> String {
807    let mut out = String::new();
808    let mut previous: Option<(&str, usize)> = None;
809    for finding in &report.findings {
810        let (kind, at) = finding_parts(finding);
811        // Findings on one line are usually one thought (a chain of conditions): they are
812        // printed as one block.
813        let same_line = previous == Some((at.file.as_str(), at.line));
814        if same_line {
815            out.push_str(&format!(
816                "  + {kind}  column {}\n    {}\n",
817                at.column, at.code
818            ));
819        } else {
820            if previous.is_some() {
821                out.push('\n');
822            }
823            out.push_str(&format!(
824                "{kind}  {}:{}:{}\n    {}\n",
825                at.file, at.line, at.column, at.code
826            ));
827        }
828        for line in finding_body(finding) {
829            out.push_str(&format!("  {line}\n"));
830        }
831        previous = Some((at.file.as_str(), at.line));
832    }
833    if previous.is_some() {
834        out.push('\n');
835    }
836    if show_unreached {
837        for at in &report.unreached {
838            out.push_str(&format!(
839                "UNREACHED  {}:{}:{}\n    {}\n\n",
840                at.file, at.line, at.column, at.code
841            ));
842        }
843    }
844    for at in &report.unstable {
845        out.push_str(&format!(
846            "UNSTABLE  {}:{}:{}\n    {}\n  the trace predicted a survivor but the re-run failed: the tests are not deterministic, or do something the trace cannot see\n\n",
847            at.file, at.line, at.column, at.code
848        ));
849    }
850    let input = report
851        .findings
852        .iter()
853        .filter(|f| matches!(f, Finding::InputGap { .. }))
854        .count();
855    let assertion = report
856        .findings
857        .iter()
858        .filter(|f| matches!(f, Finding::AssertionGap { .. }))
859        .count();
860    let unexplained = report.findings.len() - input - assertion;
861    // A mutant stopped by the time limit costs the limit: worth knowing when a run is slow.
862    let by_time_limit = if report.mutants_timed_out > 0 {
863        format!(", {} of them by the time limit", report.mutants_timed_out)
864    } else {
865        String::new()
866    };
867    out.push_str(&format!(
868        "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
869        report.package,
870        report.sites,
871        input,
872        assertion,
873        report.mutants_run,
874        report.mutants_killed,
875        report.unreached.len()
876    ));
877    if unexplained > 0 {
878        out.push_str(&format!(
879            ", {unexplained} survivors of mutants built on their own"
880        ));
881    }
882    if report.suppressed > 0 {
883        out.push_str(&format!(", {} findings suppressed", report.suppressed));
884    }
885    if report.skipped_sites > 0 {
886        out.push_str(&format!(
887            ", {} sites skipped (probe did not compile)",
888            report.skipped_sites
889        ));
890    }
891    if report.unviable_mutants > 0 {
892        out.push_str(&format!(
893            ", {} mutants left out (they do not compile)",
894            report.unviable_mutants
895        ));
896    }
897    out.push('\n');
898    if let Some(audit) = &report.audit {
899        out.push_str(&format!(
900            "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against\n",
901            audit.sampled,
902            audit.survivors,
903            audit.disagreements.len()
904        ));
905        for at in &audit.disagreements {
906            out.push_str(&format!(
907                "  {}:{}:{}  {}\n",
908                at.file, at.line, at.column, at.code
909            ));
910        }
911        if audit.rebuilt > 0 {
912            out.push_str(&format!(
913                "audit: {} mutants chosen to be built from the source as well: {} compared, {} with another result than as a probe, {} that could not be compared\n",
914                audit.rebuilt,
915                audit.compared,
916                audit.source_disagreements.len(),
917                audit.not_compared
918            ));
919        }
920        for differs in &audit.source_disagreements {
921            out.push_str(&format!(
922                "  {}:{}:{}  {}: {} as a probe, {} built\n",
923                differs.at.file,
924                differs.at.line,
925                differs.at.column,
926                differs.mutant,
927                differs.as_probe,
928                differs.built
929            ));
930        }
931        if audit.trace_differences.is_empty() {
932            out.push_str("audit: recorded once more, the tests did the same\n");
933        }
934        for binary in &audit.trace_differences {
935            out.push_str(&format!(
936                "audit: recorded once more, `{}` differs in {} records: its tests do not always do the same\n",
937                binary.binary, binary.records
938            ));
939        }
940    }
941    if report.mutants_not_evaluated > 0 {
942        out.push_str(&format!(
943            "({} mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n",
944            report.mutants_not_evaluated
945        ));
946    }
947    if report.mutants_not_built > 0 {
948        out.push_str(&format!(
949            "({} more mutants need a build of their own: --rebuild runs them)\n",
950            report.mutants_not_built
951        ));
952    }
953    if !show_unreached && !report.unreached.is_empty() {
954        out.push_str("(--show-unreached lists the code no test executes)\n");
955    }
956    out
957}
958
959#[cfg(test)]
960mod tests {
961    use super::*;
962    use crate::instrument::discover;
963
964    fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
965        sarif["runs"][0]["results"].as_array().unwrap()
966    }
967
968    fn or_site() -> Site {
969        site_of("fn f(a: bool, b: bool) -> bool { a || b }")
970    }
971
972    fn assign_kind() -> SiteKind {
973        SiteKind::Arith {
974            op: ArithOp::Add,
975            assign: true,
976            lhs: "*total".into(),
977            rhs: "fee".into(),
978            gap: (0, 0),
979        }
980    }
981
982    fn site_of(src: &str) -> Site {
983        discover(src, 0)
984            .unwrap()
985            .sites
986            .into_iter()
987            .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
988            .unwrap()
989    }
990
991    #[test]
992    fn describes_mutants_at_source_level() {
993        let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
994        assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
995        assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
996        assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
997        assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
998        assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
999
1000        // 18 <= age shifted by +1 is 18 <= age + 1, i.e. 17 <= age.
1001        let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
1002        assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
1003
1004        let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
1005        assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
1006        assert_eq!(
1007            describe(&none, Mutation::Shift(2)),
1008            "`a >= b + 2` (without overflow)"
1009        );
1010        assert_eq!(
1011            describe(&none, Mutation::Shift(-1)),
1012            "`a >= b - 1` (without overflow)"
1013        );
1014        let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
1015        assert_eq!(describe(&lt, Mutation::Shift(1)), "`a <= b`");
1016
1017        let stmt = site_of("fn f(s: &mut S) { s.check(\n  1,\n  2); }");
1018        assert_eq!(
1019            describe(&stmt, Mutation::Delete),
1020            "delete `s.check( 1, 2);`"
1021        );
1022    }
1023
1024    /// The source-level form must mean the same as the planner's `Shift`.
1025    #[test]
1026    fn literal_shift_rendering_matches_shift_semantics() {
1027        use crate::plan::eval_mutated_d;
1028        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1029            for shift in [-2, -1, 1, 2] {
1030                for other in -5..=5i128 {
1031                    let k = 1i128;
1032                    // literal on the right: `x op k+shift`
1033                    assert_eq!(
1034                        op.eval_d(other - (k + shift)),
1035                        eval_mutated_d(op, Mutation::Shift(shift), other - k)
1036                    );
1037                    // literal on the left: `k-shift op x`
1038                    assert_eq!(
1039                        op.eval_d((k - shift) - other),
1040                        eval_mutated_d(op, Mutation::Shift(shift), k - other)
1041                    );
1042                }
1043            }
1044        }
1045        // And the operator flips used when neither side is a literal.
1046        for (op, shift, flipped) in [
1047            (CmpOp::Ge, 1, CmpOp::Gt),
1048            (CmpOp::Gt, -1, CmpOp::Ge),
1049            (CmpOp::Le, -1, CmpOp::Lt),
1050            (CmpOp::Lt, 1, CmpOp::Le),
1051        ] {
1052            for d in -3..=3 {
1053                assert_eq!(
1054                    flipped.eval_d(d),
1055                    eval_mutated_d(op, Mutation::Shift(shift), d)
1056                );
1057            }
1058        }
1059    }
1060
1061    #[test]
1062    fn boundary_finding_for_the_age_check() {
1063        let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
1064        let mut obs = Obs::of_d(-1);
1065        obs.merge(&Obs::of_d(2));
1066        let gap = InputGap::Boundary {
1067            min_shift: 0,
1068            max_shift: 2,
1069            missing: vec![0],
1070        };
1071        let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
1072        assert_eq!(
1073            finding,
1074            Finding::InputGap {
1075                at: Location {
1076                    file: "src/lib.rs".into(),
1077                    line: 1,
1078                    column: 26,
1079                    code: "age >= 18".into(),
1080                    ..Location::default()
1081                },
1082                survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
1083                survivor_count: 2,
1084                add_tests: vec!["`age` = 18 (the original gives true)".into()],
1085                observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
1086                verified: true,
1087            }
1088        );
1089        let report = Report {
1090            package: "p".into(),
1091            sites: 1,
1092            findings: vec![finding],
1093            ..Report::default()
1094        };
1095        let text = render_text(&report, false);
1096        assert!(text.contains("INPUT GAP  src/lib.rs:1:26"), "{text}");
1097        assert!(
1098            text.contains("passes every test as: `age >= 19`, `age >= 20`  [re-run: tests pass]"),
1099            "{text}"
1100        );
1101        assert!(
1102            text.contains("add a test with `age` = 18 (the original gives true)"),
1103            "{text}"
1104        );
1105        assert!(
1106            text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
1107            "{text}"
1108        );
1109        assert!(report.has_gaps());
1110    }
1111
1112    #[test]
1113    fn other_gap_kinds() {
1114        let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
1115        let mut obs = Obs::of_rel(crate::plan::Rel::Less);
1116        obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
1117        let gap = InputGap::EqualNeverObserved {
1118            flipped: CmpOp::Le,
1119            float_gap: None,
1120        };
1121        let Some(Finding::InputGap {
1122            survivors,
1123            add_tests,
1124            observed,
1125            ..
1126        }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
1127        else {
1128            panic!()
1129        };
1130        assert_eq!(survivors, ["`a <= b`"]);
1131        assert_eq!(
1132            add_tests,
1133            ["`a` equal to `b` (the original gives false, the mutant true)"]
1134        );
1135        assert_eq!(observed, None);
1136
1137        let Some(Finding::InputGap {
1138            survivors,
1139            add_tests,
1140            ..
1141        }) = input_gap_finding(
1142            "f.rs",
1143            &site,
1144            &InputGap::OneSided { always: true },
1145            &obs,
1146            false,
1147        )
1148        else {
1149            panic!()
1150        };
1151        assert_eq!(survivors, ["`true`"]);
1152        assert_eq!(add_tests, ["an input that makes `a < b` false"]);
1153
1154        assert_eq!(
1155            input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
1156            None
1157        );
1158    }
1159
1160    #[test]
1161    fn float_gap_finding() {
1162        let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
1163        let mut obs = Obs::of_f(-20.5);
1164        obs.merge(&Obs::of_f(9.5));
1165        let gap = InputGap::EqualNeverObserved {
1166            flipped: CmpOp::Ge,
1167            float_gap: obs.float_gap(),
1168        };
1169        let Some(Finding::InputGap {
1170            survivors,
1171            add_tests,
1172            observed,
1173            survivor_count,
1174            ..
1175        }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
1176        else {
1177            panic!()
1178        };
1179        assert_eq!(
1180            survivors,
1181            [
1182                "`celsius >= 30.5`",
1183                "`celsius > 35.25`",
1184                "`celsius > 20.25`"
1185            ]
1186        );
1187        assert_eq!(survivor_count, 3);
1188        assert_eq!(
1189            add_tests,
1190            ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
1191        );
1192        assert_eq!(
1193            observed.as_deref(),
1194            Some(
1195                "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
1196            )
1197        );
1198
1199        let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
1200        assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
1201        let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
1202        assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
1203        assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
1204        let finding = input_gap_finding(
1205            "f.rs",
1206            &none,
1207            &InputGap::EqualNeverObserved {
1208                flipped: CmpOp::Le,
1209                float_gap: Some((-1.0, 2.0)),
1210            },
1211            &obs,
1212            false,
1213        );
1214        let Some(Finding::InputGap { observed, .. }) = finding else {
1215            panic!()
1216        };
1217        assert_eq!(
1218            observed.as_deref(),
1219            Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
1220        );
1221
1222        assert_eq!(float_literal("30.5"), Some(30.5));
1223        assert_eq!(float_literal("-1e3"), Some(-1000.0));
1224        assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
1225        assert_eq!(float_literal("limit"), None);
1226        assert_eq!(float_literal("x1"), None);
1227        assert_eq!(float_literal("1x"), None);
1228        assert_eq!(float_literal("-x"), None);
1229        assert_eq!(float_literal("-2.5"), Some(-2.5));
1230        assert_eq!(float_literal("e"), None);
1231        // Nothing is rounded away: a tiny shift stays visible.
1232        assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
1233        assert_eq!(show_float(1e-10), "1e-10");
1234        assert_eq!(show_float(10.0), "10.0");
1235        assert_eq!(show_float(35.25), "35.25");
1236        // A shift that does not change the literal is not listed as a mutant.
1237        let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
1238        let tiny = InputGap::EqualNeverObserved {
1239            flipped: CmpOp::Ge,
1240            float_gap: Some((-2e-300, 2e-300)),
1241        };
1242        let Some(Finding::InputGap { survivors, .. }) =
1243            input_gap_finding("f.rs", &big, &tiny, &obs, true)
1244        else {
1245            panic!()
1246        };
1247        assert_eq!(survivors, ["`x >= 1e300`"]);
1248    }
1249
1250    #[test]
1251    fn logic_and_arithmetic_findings() {
1252        let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
1253        assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
1254        assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
1255        assert_eq!(
1256            describe(&or_site(), Mutation::LogicDropRhs),
1257            "`a || { b; false }`"
1258        );
1259        assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
1260        let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
1261        assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
1262        let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
1263            Some(Finding::InputGap {
1264                survivors,
1265                add_tests,
1266                ..
1267            }) => (survivors[0].clone(), add_tests[0].clone()),
1268            _ => panic!(),
1269        };
1270        assert_eq!(
1271            advice(&and, LogicGap::RhsNeverDecides),
1272            (
1273                "`a && { b; true }`".into(),
1274                "a case where `a` is true and `b` is false".into()
1275            )
1276        );
1277        assert_eq!(
1278            advice(&and, LogicGap::LhsNeverDecides),
1279            ("`{ a; b }`".into(), "a case where `a` is false".into())
1280        );
1281        assert_eq!(
1282            advice(&or, LogicGap::RhsNeverDecides),
1283            (
1284                "`a || { b; false }`".into(),
1285                "a case where `a` is false and `b` is true".into()
1286            )
1287        );
1288        assert_eq!(
1289            advice(&or, LogicGap::LhsNeverDecides),
1290            ("`{ a; b }`".into(), "a case where `a` is true".into())
1291        );
1292        assert_eq!(
1293            logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
1294            None
1295        );
1296        assert_eq!(
1297            arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
1298            None
1299        );
1300
1301        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
1302        assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
1303        let Some(Finding::InputGap {
1304            survivors,
1305            add_tests,
1306            ..
1307        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
1308        else {
1309            panic!()
1310        };
1311        assert_eq!(
1312            (survivors[0].as_str(), add_tests[0].as_str()),
1313            ("`total - fee`", "`fee` other than 0")
1314        );
1315        let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
1316        let Some(Finding::InputGap {
1317            survivors,
1318            add_tests,
1319            ..
1320        }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
1321        else {
1322            panic!()
1323        };
1324        assert_eq!(survivors[0], "`n / scale`");
1325        assert_eq!(
1326            add_tests[0],
1327            "operands for which `n * scale` and `n / scale` differ"
1328        );
1329        let assign = Site {
1330            kind: assign_kind(),
1331            ..add.clone()
1332        };
1333        assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
1334        let Some(Finding::InputGap { add_tests, .. }) =
1335            arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
1336        else {
1337            panic!()
1338        };
1339        assert_eq!(add_tests[0], "`fee` other than 0");
1340        let shift = Site {
1341            kind: SiteKind::Arith {
1342                op: ArithOp::Shl,
1343                assign: true,
1344                lhs: "bits".into(),
1345                rhs: "n".into(),
1346                gap: (0, 0),
1347            },
1348            ..assign.clone()
1349        };
1350        assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
1351        let Some(Finding::InputGap { add_tests, .. }) =
1352            arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
1353        else {
1354            panic!()
1355        };
1356        assert_eq!(
1357            add_tests[0],
1358            "operands for which `bits <<= n` and `bits >>= n` differ"
1359        );
1360
1361        let not = Site {
1362            kind: SiteKind::Not {
1363                bang: (0, 1),
1364                operand: "is_ready(x)".into(),
1365            },
1366            ..assign.clone()
1367        };
1368        assert_eq!(describe(&not, Mutation::DropNot), "`is_ready(x)`");
1369        let ret = Site {
1370            kind: SiteKind::Return {
1371                name: "is_ready".into(),
1372                option: None,
1373                sole_expr: None,
1374            },
1375            ..assign.clone()
1376        };
1377        assert_eq!(
1378            describe(&ret, Mutation::Const(true)),
1379            "`is_ready` returning `true`"
1380        );
1381        let Some(Finding::InputGap {
1382            survivors,
1383            add_tests,
1384            ..
1385        }) = return_gap_finding("f.rs", &ret, false, true)
1386        else {
1387            panic!()
1388        };
1389        assert_eq!(survivors[0], "`is_ready` returning `false`");
1390        assert_eq!(add_tests[0], "a case where `is_ready` returns true");
1391        assert_eq!(return_gap_finding("f.rs", &not, false, true), None);
1392
1393        let find = Site {
1394            kind: SiteKind::Return {
1395                name: "find".into(),
1396                option: Some("Option<&str>".into()),
1397                sole_expr: None,
1398            },
1399            ..assign.clone()
1400        };
1401        assert_eq!(
1402            describe(&find, Mutation::Const(false)),
1403            "`find` returning `None`"
1404        );
1405        let Some(Finding::InputGap { add_tests, .. }) =
1406            return_gap_finding("f.rs", &find, false, true)
1407        else {
1408            panic!()
1409        };
1410        assert_eq!(add_tests[0], "a case where `find` returns `Some`");
1411        let range = Site {
1412            kind: SiteKind::Range {
1413                inclusive: false,
1414                lhs: "0".into(),
1415                rhs: "n".into(),
1416                gap: (0, 0),
1417            },
1418            ..assign.clone()
1419        };
1420        assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
1421        let closed = Site {
1422            kind: SiteKind::Range {
1423                inclusive: true,
1424                lhs: "1".into(),
1425                rhs: "n".into(),
1426                gap: (0, 0),
1427            },
1428            ..assign.clone()
1429        };
1430        assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
1431        let arm = Site {
1432            kind: SiteKind::Arm {
1433                pattern: "Kind::Update { key, .. }".into(),
1434                guard: crate::instrument::ArmGuard::None(0),
1435            },
1436            ..assign.clone()
1437        };
1438        assert_eq!(
1439            describe(&arm, Mutation::Delete),
1440            "remove the arm `Kind::Update { key, .. } => ..`"
1441        );
1442
1443        let clamp = Site {
1444            kind: SiteKind::MinMax {
1445                max: true,
1446                receiver: "drift".into(),
1447                argument: "peak.get()".into(),
1448                call: (0, 0),
1449                close: (0, 0),
1450            },
1451            ..assign.clone()
1452        };
1453        assert_eq!(
1454            describe(&clamp, Mutation::MinMax),
1455            "`drift.min(peak.get())`"
1456        );
1457        let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
1458        else {
1459            panic!()
1460        };
1461        assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
1462        assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
1463
1464        let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
1465        assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
1466        assert_eq!(
1467            logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
1468            None
1469        );
1470    }
1471
1472    #[test]
1473    fn long_code_is_shortened() {
1474        let exactly_100 = "x".repeat(100);
1475        assert_eq!(one_line(&exactly_100), exactly_100);
1476        let shortened = one_line(&"x".repeat(101));
1477        assert_eq!(shortened, format!("{}...", "x".repeat(97)));
1478        assert_eq!(one_line("a\n   b"), "a b");
1479    }
1480
1481    #[test]
1482    fn at_most_three_survivors_are_listed_nearest_first() {
1483        let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
1484        let obs = Obs::default();
1485        let survivors = |min_shift, max_shift| {
1486            let gap = InputGap::Boundary {
1487                min_shift,
1488                max_shift,
1489                missing: vec![0],
1490            };
1491            match input_gap_finding("f.rs", &site, &gap, &obs, false) {
1492                Some(Finding::InputGap {
1493                    survivors,
1494                    survivor_count,
1495                    ..
1496                }) => (survivors, survivor_count),
1497                _ => panic!(),
1498            }
1499        };
1500        assert_eq!(
1501            survivors(-9, 9),
1502            (
1503                vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
1504                18
1505            )
1506        );
1507        assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
1508        assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
1509        assert_eq!(
1510            survivors(-2, 0),
1511            (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
1512        );
1513    }
1514
1515    #[test]
1516    fn text_report_is_exact() {
1517        let at = Location {
1518            file: "src/lib.rs".into(),
1519            line: 3,
1520            column: 9,
1521            code: "a >= b".into(),
1522            ..Location::default()
1523        };
1524        let below = Location {
1525            file: "src/lib.rs".into(),
1526            line: 7,
1527            column: 5,
1528            code: "s.reset();".into(),
1529            ..Location::default()
1530        };
1531        let report = Report {
1532            package: "p".into(),
1533            sites: 2,
1534            mutants_run: 1,
1535            suppressed: 2,
1536            findings: vec![
1537                Finding::InputGap {
1538                    at: at.clone(),
1539                    survivors: vec!["`a > b`".into()],
1540                    survivor_count: 4,
1541                    add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
1542                    observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
1543                    verified: false,
1544                },
1545                Finding::InputGap {
1546                    at: at.clone(),
1547                    survivors: vec!["`true`".into()],
1548                    survivor_count: 1,
1549                    add_tests: vec![],
1550                    observed: None,
1551                    verified: true,
1552                },
1553                Finding::AssertionGap {
1554                    at: Location { column: 4, ..at },
1555                    survivors: vec!["`!(a >= b)`".into()],
1556                    tests: vec!["t".into()],
1557                    effects: vec![],
1558                    effects_of: None,
1559                },
1560                Finding::AssertionGap {
1561                    at: below,
1562                    survivors: vec!["delete `s.reset();`".into()],
1563                    tests: vec!["t".into()],
1564                    effects: vec![
1565                        "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
1566                    ],
1567                    effects_of: None,
1568                },
1569            ],
1570            ..Report::default()
1571        };
1572        // Findings on one line form one block; a new line starts a new block.
1573        assert_eq!(
1574            render_text(&report, false),
1575            "INPUT GAP  src/lib.rs:3:9\n    a >= b\n\
1576             \x20 passes every test as: `a > b` (+3 more)  [from the trace, not re-run]\n\
1577             \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
1578             \x20 add a test with `a` equal to `b` (the original gives true)\n\
1579             \x20 + INPUT GAP  column 9\n    a >= b\n\
1580             \x20 passes every test as: `true`  [re-run: tests pass]\n\
1581             \x20 + ASSERTION GAP  column 4\n    a >= b\n\
1582             \x20 passes every test as: `!(a >= b)`\n\
1583             \x20 these tests run the changed code and still pass: t\n\
1584             \x20 add an assertion on what this code is responsible for\n\
1585             \n\
1586             ASSERTION GAP  src/lib.rs:7:5\n    s.reset();\n\
1587             \x20 passes every test as: delete `s.reset();`\n\
1588             \x20 these tests run the changed code and still pass: t\n\
1589             \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
1590             \n\
1591             p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
1592        );
1593        assert_eq!(
1594            render_text(
1595                &Report {
1596                    package: "q".into(),
1597                    ..Report::default()
1598                },
1599                false
1600            ),
1601            "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
1602        );
1603
1604        let mut in_repository = report.clone();
1605        in_repository.analysis.package_path = "crates/p/".into();
1606        in_repository.analysis.since = Some("abc".into());
1607        if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
1608            at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
1609        }
1610        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
1611        assert_eq!(
1612            results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
1613            "assertion_gap|src/lib.rs|f|s.reset();|0"
1614        );
1615        assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
1616        assert_eq!(sarif["version"], "2.1.0");
1617        let results = sarif["runs"][0]["results"].as_array().unwrap();
1618        assert_eq!(results.len(), 4);
1619        assert_eq!(results[0]["ruleId"], "input-gap");
1620        assert_eq!(results[3]["ruleId"], "assertion-gap");
1621        let location = &results[3]["locations"][0]["physicalLocation"];
1622        assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
1623        assert_eq!(
1624            (
1625                &location["region"]["startLine"],
1626                &location["region"]["startColumn"]
1627            ),
1628            (&serde_json::json!(7), &serde_json::json!(5))
1629        );
1630        assert!(
1631            results[3]["message"]["text"]
1632                .as_str()
1633                .unwrap()
1634                .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
1635        );
1636        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1637            .as_array()
1638            .unwrap();
1639        assert_eq!(rules.len(), 3);
1640    }
1641
1642    #[test]
1643    fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
1644        let survivor = Finding::Survivor {
1645            at: Location {
1646                file: "src/lib.rs".into(),
1647                line: 2,
1648                column: 1,
1649                code: "const fn limit() -> u8".into(),
1650                ..Location::default()
1651            },
1652            survivors: vec!["the body of `limit` replaced by `0`".into()],
1653        };
1654        assert_eq!(survivor.kind(), "survivor");
1655        assert_eq!(survivor.at().line, 2);
1656        assert_eq!(survivor.survivors().len(), 1);
1657        let report = Report {
1658            package: "p".into(),
1659            findings: vec![survivor],
1660            ..Report::default()
1661        };
1662        // Neither of the two gaps: it is counted and named as what it is.
1663        assert_eq!(
1664            render_text(&report, false),
1665            "SURVIVOR  src/lib.rs:2:1\n    const fn limit() -> u8\n\
1666             \x20 passes every test as: the body of `limit` replaced by `0`\n\
1667             \x20 built on its own, where nothing can be recorded: either no test runs this code, or one does and does not check what it gives\n\
1668             \n\
1669             p: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached, 1 survivors of mutants built on their own\n"
1670        );
1671        let json = serde_json::to_value(&report).unwrap();
1672        assert_eq!(json["findings"][0]["kind"], "survivor");
1673        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
1674        assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
1675        assert!(report.has_gaps());
1676    }
1677
1678    #[test]
1679    fn non_literal_inputs_in_words() {
1680        assert_eq!(
1681            input_for("a", "b", LiteralSide::None, 0),
1682            "`a` equal to `b`"
1683        );
1684        assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
1685        assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
1686        assert_eq!(
1687            input_for("18", "age", LiteralSide::Lhs(18), -1),
1688            "`age` = 19"
1689        );
1690    }
1691
1692    #[test]
1693    fn text_report_sections() {
1694        let at = Location {
1695            file: "src/lib.rs".into(),
1696            line: 3,
1697            column: 9,
1698            code: "s.check()?;".into(),
1699            ..Location::default()
1700        };
1701        let report = Report {
1702            package: "p".into(),
1703            analysis: Analysis::default(),
1704            audit: None,
1705            sites: 4,
1706            skipped_sites: 1,
1707            unviable_mutants: 2,
1708            mutants_not_built: 0,
1709            mutants_not_evaluated: 0,
1710            mutants_run: 3,
1711            mutants_killed: 2,
1712            mutants_timed_out: 0,
1713            suppressed: 0,
1714            findings: vec![Finding::AssertionGap {
1715                at: at.clone(),
1716                survivors: vec!["delete `s.check()?;`".into()],
1717                tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
1718                effects: vec![],
1719                effects_of: None,
1720            }],
1721            unreached: vec![at.clone()],
1722            unstable: vec![at],
1723        };
1724        let text = render_text(&report, false);
1725        assert!(
1726            text.contains("ASSERTION GAP  src/lib.rs:3:9\n    s.check()?;"),
1727            "{text}"
1728        );
1729        assert!(text.contains("tests::t4 (+2 more)"), "{text}");
1730        assert!(text.contains("UNSTABLE  src/lib.rs:3:9"), "{text}");
1731        assert!(!text.contains("UNREACHED"), "{text}");
1732        assert!(
1733            text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
1734            "{text}"
1735        );
1736        assert!(
1737            text.contains(", 2 mutants left out (they do not compile)\n"),
1738            "{text}"
1739        );
1740        assert!(text.contains("--show-unreached"), "{text}");
1741        let listed = render_text(&report, true);
1742        assert!(listed.contains("UNREACHED  src/lib.rs:3:9"));
1743        assert!(!listed.contains("--show-unreached"), "{listed}");
1744        let one_more = Report {
1745            findings: vec![Finding::InputGap {
1746                at: report.unreached[0].clone(),
1747                survivors: vec!["`a`".into()],
1748                survivor_count: 2,
1749                add_tests: vec![],
1750                observed: None,
1751                verified: true,
1752            }],
1753            ..report.clone()
1754        };
1755        assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
1756        let nothing_unreached = Report {
1757            unreached: vec![],
1758            ..report.clone()
1759        };
1760        assert!(!render_text(&nothing_unreached, false).contains("--show-unreached"));
1761        assert!(!Report::default().has_gaps());
1762    }
1763    #[test]
1764    fn unstable_predictions_alone_are_something_to_act_on() {
1765        let at = Location {
1766            file: "src/lib.rs".into(),
1767            line: 1,
1768            column: 1,
1769            code: "a > b".into(),
1770            ..Location::default()
1771        };
1772        assert!(!Report::default().has_gaps());
1773        assert!(
1774            Report {
1775                unstable: vec![at],
1776                ..Report::default()
1777            }
1778            .has_gaps()
1779        );
1780    }
1781
1782    #[test]
1783    fn what_counts_as_a_float_literal() {
1784        assert_eq!(float_literal("30.5"), Some(30.5));
1785        assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
1786        assert_eq!(float_literal("-1e3"), Some(-1000.0));
1787        // These parse as floats too, and are not literals: a variable called `inf`, and
1788        // forms Rust does not accept.
1789        for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
1790            assert_eq!(float_literal(text), None, "{text}");
1791        }
1792    }
1793
1794    #[test]
1795    fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
1796        // At 2^53 the next float below is 1 away and the next above 2 away.
1797        let survivors_of = |source: &str| {
1798            let site = site_of(source);
1799            let mut obs = Obs::of_f(-4.0);
1800            obs.merge(&Obs::of_f(4.0));
1801            let gap = InputGap::EqualNeverObserved {
1802                flipped: CmpOp::Ge,
1803                float_gap: obs.float_gap(),
1804            };
1805            match input_gap_finding("f.rs", &site, &gap, &obs, true) {
1806                Some(Finding::InputGap {
1807                    survivors,
1808                    survivor_count,
1809                    ..
1810                }) => (survivors, survivor_count),
1811                _ => panic!(),
1812            }
1813        };
1814        // Shifts of +2 and -2 are proposed. Both move the literal.
1815        assert_eq!(
1816            survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
1817            (
1818                vec![
1819                    "`x >= 9007199254740992.0`".to_string(),
1820                    "`x > 9007199254740994.0`".to_string(),
1821                    "`x > 9007199254740990.0`".to_string(),
1822                ],
1823                3
1824            )
1825        );
1826        // At 2^54 only the step down is a different number, and on the left of the
1827        // comparison the literal moves the other way.
1828        assert_eq!(
1829            survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
1830            (
1831                vec![
1832                    "`x >= 18014398509481984.0`".to_string(),
1833                    "`x > 1.8014398509481982e16`".to_string(),
1834                ],
1835                2
1836            )
1837        );
1838        assert_eq!(
1839            survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
1840            (
1841                vec![
1842                    "`18014398509481984.0 >= x`".to_string(),
1843                    "`1.8014398509481982e16 > x`".to_string(),
1844                ],
1845                2
1846            )
1847        );
1848        // With the literal on the left, the nearest values are those of the other side.
1849        let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
1850        let mut obs = Obs::of_f(-1.0);
1851        obs.merge(&Obs::of_f(2.0));
1852        let gap = InputGap::EqualNeverObserved {
1853            flipped: CmpOp::Ge,
1854            float_gap: obs.float_gap(),
1855        };
1856        let Some(Finding::InputGap { observed, .. }) =
1857            input_gap_finding("f.rs", &site, &gap, &obs, true)
1858        else {
1859            panic!()
1860        };
1861        assert_eq!(
1862            observed.as_deref(),
1863            Some(
1864                "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
1865            )
1866        );
1867        // Far above, neither does.
1868        assert_eq!(
1869            survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
1870            (vec!["`x >= 1e30`".to_string()], 1)
1871        );
1872    }
1873
1874    #[test]
1875    fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
1876        let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
1877            at: Location {
1878                file: "src/lib.rs".into(),
1879                line: 1,
1880                column: 1,
1881                code: "a < b".into(),
1882                ..Location::default()
1883            },
1884            survivors: survivors.iter().map(|s| s.to_string()).collect(),
1885            tests: vec!["tests::t".into()],
1886            effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
1887            effects_of: effects_of.map(str::to_string),
1888        };
1889        // Of several mutants one was followed: the report says which.
1890        let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")));
1891        assert_eq!(
1892            body[2..],
1893            [
1894                "followed one of them through the tests: `a <= b`",
1895                "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
1896            ]
1897        );
1898        // A single mutant needs no saying, and nothing is said where nothing is known.
1899        for single in [
1900            gap(&["`a <= b`"], Some("`a <= b`")),
1901            gap(&["`a <= b`", "`a == b`"], None),
1902        ] {
1903            let body = finding_body(&single);
1904            assert_eq!(body.len(), 3, "{body:?}");
1905            assert!(body[2].starts_with("with the mutant"), "{body:?}");
1906        }
1907    }
1908
1909    #[test]
1910    fn an_audit_is_said_in_the_summary() {
1911        let mut report = Report {
1912            package: "p".into(),
1913            audit: Some(Audit {
1914                sampled: 2,
1915                survivors: 7,
1916                ..Audit::default()
1917            }),
1918            ..Report::default()
1919        };
1920        let text = render_text(&report, false);
1921        assert!(
1922            text.ends_with(
1923                "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
1924                 audit: recorded once more, the tests did the same\n"
1925            ),
1926            "{text}"
1927        );
1928        let audit = report.audit.as_mut().unwrap();
1929        audit.disagreements.push(Location {
1930            file: "src/lib.rs".into(),
1931            line: 3,
1932            column: 5,
1933            code: "x > 5".into(),
1934            ..Location::default()
1935        });
1936        audit.trace_differences.push(TraceDifference {
1937            binary: "p".into(),
1938            records: 4,
1939        });
1940        let text = render_text(&report, false);
1941        assert!(
1942            text.ends_with(
1943                "all tests, 1 failed one they had not been run against\n\
1944                 \x20 src/lib.rs:3:5  x > 5\n\
1945                 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
1946            ),
1947            "{text}"
1948        );
1949        // Mutants built from the source are said only where some were, with what differs.
1950        assert!(!text.contains("built from the source"), "{text}");
1951        let audit = report.audit.as_mut().unwrap();
1952        audit.rebuilt = 1;
1953        audit.not_compared = 1;
1954        let text = render_text(&report, false);
1955        assert!(
1956            text.contains(
1957                "\naudit: 1 mutants chosen to be built from the source as well: 0 compared, 0 with another result than as a probe, 1 that could not be compared\n"
1958            ),
1959            "{text}"
1960        );
1961        let audit = report.audit.as_mut().unwrap();
1962        audit.rebuilt = 5;
1963        audit.compared = 4;
1964        audit.source_disagreements.push(SourceDisagreement {
1965            at: Location {
1966                file: "src/lib.rs".into(),
1967                line: 9,
1968                column: 14,
1969                code: "note(asked)".into(),
1970                ..Location::default()
1971            },
1972            mutant: "the guard `note(asked)` replaced by `true`".into(),
1973            as_probe: "passes".into(),
1974            built: "fails".into(),
1975        });
1976        let text = render_text(&report, false);
1977        assert!(
1978            text.contains(
1979                "\naudit: 5 mutants chosen to be built from the source as well: 4 compared, 1 with another result than as a probe, 1 that could not be compared\n\
1980                 \x20 src/lib.rs:9:14  the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
1981            ),
1982            "{text}"
1983        );
1984        assert!(!render_text(&Report::default(), false).contains("audit"));
1985    }
1986
1987    #[test]
1988    fn lists_and_counts_at_their_limits() {
1989        let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
1990        assert_eq!(list(&items, 3), "a, b, c");
1991        assert_eq!(list(&items, 2), "a, b (+1 more)");
1992        assert_eq!(list(&items, 1), "a (+2 more)");
1993        let one = Report {
1994            package: "p".into(),
1995            suppressed: 1,
1996            unviable_mutants: 1,
1997            ..Report::default()
1998        };
1999        assert!(
2000            render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
2001            "{}",
2002            render_text(&one, false)
2003        );
2004        assert!(!render_text(&Report::default(), false).contains("left out"));
2005        assert!(!render_text(&one, false).contains("--rebuild"));
2006        assert!(!render_text(&one, false).contains("not evaluated"));
2007        let at_top = Report {
2008            mutants_not_evaluated: 1,
2009            ..Report::default()
2010        };
2011        assert!(
2012            render_text(&at_top, false).ends_with(
2013                "\n(1 mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n"
2014            ),
2015            "{}",
2016            render_text(&at_top, false)
2017        );
2018        let quick = Report {
2019            mutants_not_built: 1,
2020            ..Report::default()
2021        };
2022        assert!(
2023            render_text(&quick, false)
2024                .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
2025            "{}",
2026            render_text(&quick, false)
2027        );
2028        let slow = Report {
2029            mutants_run: 5,
2030            mutants_killed: 4,
2031            mutants_timed_out: 2,
2032            ..Report::default()
2033        };
2034        assert!(
2035            render_text(&slow, false)
2036                .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
2037            "{}",
2038            render_text(&slow, false)
2039        );
2040        assert!(!render_text(&one, false).contains("time limit"));
2041        let once = Report {
2042            mutants_timed_out: 1,
2043            ..slow.clone()
2044        };
2045        assert!(
2046            render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
2047            "{}",
2048            render_text(&once, false)
2049        );
2050        assert!(
2051            render_text(&one, false).contains(", 1 findings suppressed"),
2052            "{}",
2053            render_text(&one, false)
2054        );
2055        assert!(!render_text(&Report::default(), false).contains("suppressed"));
2056    }
2057
2058    #[test]
2059    fn findings_are_put_in_reading_order() {
2060        let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
2061            at: Location {
2062                file: file.into(),
2063                line,
2064                column,
2065                code: "x".into(),
2066                ..Location::default()
2067            },
2068            survivors: vec![survivor.into()],
2069            tests: vec![],
2070            effects: vec![],
2071            effects_of: None,
2072        };
2073        let mut report = Report {
2074            findings: vec![
2075                gap("src/b.rs", 1, 1, "b"),
2076                gap("src/a.rs", 9, 5, "statement"),
2077                gap("src/a.rs", 7, 2, "above it"),
2078                gap("src/a.rs", 9, 5, "its operator"),
2079                gap("src/a.rs", 9, 3, "left of both"),
2080            ],
2081            ..Report::default()
2082        };
2083        report.sort_findings();
2084        let order: Vec<&str> = report
2085            .findings
2086            .iter()
2087            .map(|f| match f {
2088                Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
2089                _ => panic!(),
2090            })
2091            .collect();
2092        // Findings at one position keep the order they were made in.
2093        assert_eq!(
2094            order,
2095            ["above it", "left of both", "statement", "its operator", "b"]
2096        );
2097    }
2098    #[test]
2099    fn second_replacements_guards_fields_and_bodies_in_words() {
2100        let all = |src: &str| discover(src, 0).unwrap().sites;
2101        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
2102        assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
2103        let Some(Finding::InputGap {
2104            survivors,
2105            add_tests,
2106            ..
2107        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
2108        else {
2109            panic!()
2110        };
2111        assert_eq!(survivors, ["`total * fee`"]);
2112        assert_eq!(
2113            add_tests,
2114            ["operands for which `total + fee` and `total * fee` differ"]
2115        );
2116        let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
2117        let arith: Vec<&Site> = sites
2118            .iter()
2119            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
2120            .collect();
2121        assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
2122        assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
2123        let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
2124        assert_eq!(
2125            arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
2126            None
2127        );
2128        // A shift has one replacement: no second finding.
2129        assert_eq!(
2130            arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
2131            None
2132        );
2133
2134        let sites = all("fn f(k: Option<i32>, base: O) -> O { \
2135             let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
2136        let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
2137        let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
2138        assert_eq!(
2139            describe(guard, Mutation::Const(true)),
2140            "the guard `n > 1` replaced by `true`"
2141        );
2142        assert_eq!(
2143            guard_gap_finding("f.rs", guard, false, true),
2144            Finding::InputGap {
2145                at: location("f.rs", guard),
2146                survivors: vec!["the guard `n > 1` replaced by `false`".into()],
2147                survivor_count: 1,
2148                add_tests: vec!["a case where the guard `n > 1` is true".into()],
2149                observed: None,
2150                verified: true,
2151            }
2152        );
2153        let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
2154        assert_eq!(describe(neg, Mutation::Delete), "`n`");
2155        let field = of(&|k| matches!(k, SiteKind::Field { .. }));
2156        assert_eq!(
2157            describe(field, Mutation::Delete),
2158            "without the field `depth: d` (it is then `(base).depth`)"
2159        );
2160        let body = of(&|k| matches!(k, SiteKind::Body { .. }));
2161        assert_eq!(
2162            describe(body, Mutation::Delete),
2163            "the body of `f` replaced by `Default::default()`"
2164        );
2165        assert_eq!(
2166            location("f.rs", body).code,
2167            "fn f(k: Option<i32>, base: O) -> O"
2168        );
2169    }
2170}