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;
5use std::path::PathBuf;
6
7use crate::instrument::{ArithOp, LiteralSide, Site, SiteKind};
8use crate::plan::{CmpOp, InputGap, LogicGap, Mutation, Obs};
9
10#[derive(Clone, Debug, Default, PartialEq, Serialize)]
11pub struct Location {
12    pub file: String,
13    pub line: usize,
14    pub column: usize,
15    pub code: String,
16    /// The function or constant the code is in (`Store::commit`); empty where unknown.
17    #[serde(skip_serializing_if = "String::is_empty")]
18    pub item: String,
19    /// What the finding at this place is known by across runs: see [`finding_id`].
20    #[serde(skip_serializing_if = "String::is_empty")]
21    pub id: String,
22}
23
24/// The name a finding keeps from run to run: its kind, its file, the item it is in, its
25/// code, and which of the places with that code in that item it is (0 for the first).
26/// Lines are not in it, so code that moves keeps its name, and neither are the words
27/// that describe the surviving mutants, so those can be improved.
28pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
29    format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
30}
31
32#[derive(Clone, Debug, PartialEq, Serialize)]
33#[serde(rename_all = "snake_case", tag = "kind")]
34pub enum Finding {
35    /// No test input can tell these mutants from the original.
36    InputGap {
37        #[serde(flatten)]
38        at: Location,
39        /// Source-level form of mutants that pass every test.
40        survivors: Vec<String>,
41        /// How many mutants the gap lets through in total.
42        survivor_count: u128,
43        /// Inputs to add, in words.
44        add_tests: Vec<String>,
45        /// What the tests did feed the comparison.
46        observed: Option<String>,
47        /// Whether the tests were re-run against a survivor to confirm.
48        verified: bool,
49    },
50    /// Tests execute the changed behaviour, and still pass.
51    AssertionGap {
52        #[serde(flatten)]
53        at: Location,
54        survivors: Vec<String>,
55        /// Tests whose execution changed under the mutants but did not fail.
56        tests: Vec<String>,
57        /// What one surviving mutant changes later in those tests: the places an
58        /// assertion could catch it. Empty when that was not looked into.
59        effects: Vec<String>,
60        /// The mutant whose effects those are, as it is written in `survivors`.
61        effects_of: Option<String>,
62        #[serde(skip_serializing_if = "Option::is_none")]
63        witness: Option<VerifiedWitness>,
64    },
65    /// A mutant that was built on its own passes every test, and nothing was recorded
66    /// that says why: whether no test runs the code (nothing can be recorded in a
67    /// `const fn`), or one does and does not look at the result.
68    Survivor {
69        #[serde(flatten)]
70        at: Location,
71        survivors: Vec<String>,
72        #[serde(skip_serializing_if = "Option::is_none")]
73        witness: Option<VerifiedWitness>,
74    },
75}
76
77#[derive(Clone, Debug, PartialEq, Serialize)]
78pub struct VerifiedWitness {
79    pub call: String,
80    pub original: String,
81    pub mutant: String,
82    pub assertion: String,
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub guidance: Option<String>,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub individually_killed: Option<usize>,
87}
88
89impl Finding {
90    pub fn at(&self) -> &Location {
91        let (Finding::InputGap { at, .. }
92        | Finding::AssertionGap { at, .. }
93        | Finding::Survivor { at, .. }) = self;
94        at
95    }
96
97    pub fn at_mut(&mut self) -> &mut Location {
98        let (Finding::InputGap { at, .. }
99        | Finding::AssertionGap { at, .. }
100        | Finding::Survivor { at, .. }) = self;
101        at
102    }
103
104    pub fn survivors(&self) -> &[String] {
105        let (Finding::InputGap { survivors, .. }
106        | Finding::AssertionGap { survivors, .. }
107        | Finding::Survivor { survivors, .. }) = self;
108        survivors
109    }
110
111    pub(crate) fn set_witness(&mut self, evidence: VerifiedWitness) {
112        match self {
113            Self::AssertionGap { witness, .. } | Self::Survivor { witness, .. } => {
114                if witness.is_none() {
115                    *witness = Some(evidence);
116                }
117            }
118            Self::InputGap { .. } => {}
119        }
120    }
121
122    /// The kind as the JSON report and the names of findings spell it.
123    pub fn kind(&self) -> &'static str {
124        match self {
125            Finding::InputGap { .. } => "input_gap",
126            Finding::AssertionGap { .. } => "assertion_gap",
127            Finding::Survivor { .. } => "survivor",
128        }
129    }
130}
131
132/// What decides which code cargo compiles, as given on the command line.
133#[derive(Clone, Debug, Default, PartialEq, Serialize)]
134pub struct CargoConfig {
135    pub features: Vec<String>,
136    pub all_features: bool,
137    pub no_default_features: bool,
138    pub locked: bool,
139}
140
141/// What a run looked at and how: a report says nothing about what is outside of it.
142#[derive(Clone, Debug, Default, PartialEq, Serialize)]
143pub struct Nextest {
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub profile: Option<String>,
146}
147
148#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
149pub struct Shard {
150    pub index: usize,
151    pub count: usize,
152    pub round_robin: bool,
153}
154
155#[derive(Clone, Debug, Default, PartialEq, Serialize)]
156pub struct Analysis {
157    /// The package's directory in its git repository (`crates/core/`; empty at the top).
158    pub package_path: String,
159    /// Only the code changed since this revision.
160    pub since: Option<String>,
161    /// Only these lines.
162    pub lines: Vec<String>,
163    /// The packages whose tests were run.
164    pub tests_of: Vec<String>,
165    pub cargo: CargoConfig,
166    pub opt_level: Option<u8>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub timeout_seconds: Option<u64>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub baseline_jobs: Option<usize>,
171    pub timeout_recheck: &'static str,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub wrapper_grace_seconds: Option<u64>,
174    /// Mutants that need a build of their own were run.
175    pub rebuild: bool,
176    /// Predicted survivors were re-run.
177    pub verified: bool,
178    pub doc_tests: bool,
179    #[serde(skip_serializing_if = "std::ops::Not::not")]
180    pub source_only: bool,
181    #[serde(skip_serializing_if = "std::ops::Not::not")]
182    pub literal_operators: bool,
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub shard: Option<Shard>,
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub nextest: Option<Nextest>,
187    #[serde(skip_serializing_if = "Vec::is_empty")]
188    pub error_values: Vec<String>,
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub test_selection: Option<TestSelection>,
191    #[serde(skip_serializing_if = "std::ops::Not::not")]
192    pub git_index: bool,
193    #[serde(skip_serializing_if = "Vec::is_empty")]
194    pub copy_fixtures: Vec<PathBuf>,
195    #[serde(skip_serializing_if = "Vec::is_empty")]
196    pub copy_fixture_excludes: Vec<PathBuf>,
197    #[serde(skip_serializing_if = "Vec::is_empty")]
198    pub output_fixtures: Vec<crate::output_fixture::Fixture>,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub checkpoint: Option<PathBuf>,
201}
202
203#[derive(Clone, Debug, Default, PartialEq, Serialize)]
204pub struct TestSelection {
205    pub build_scope: TestBuildScope,
206    pub wrapper: Option<String>,
207    pub tests: Vec<String>,
208}
209
210#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
211#[serde(rename_all = "snake_case")]
212pub enum TestBuildScope {
213    #[default]
214    PackageWide,
215    SelectedTargets,
216}
217
218#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
219#[serde(rename_all = "snake_case")]
220pub enum Evaluation {
221    NoSites,
222    NoMutantsExecuted,
223}
224
225#[derive(Clone, Debug, Default, PartialEq, Serialize)]
226pub struct TimeoutRechecks {
227    pub first_pass: usize,
228    pub confirmed: usize,
229    pub recovered: usize,
230    pub unconfirmed: usize,
231}
232
233impl TimeoutRechecks {
234    fn is_empty(&self) -> bool {
235        self.first_pass == 0
236    }
237}
238
239#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
240#[serde(rename_all = "snake_case")]
241pub enum SkipReason {
242    ProbeCompileError,
243    ProbeReplacedBySourceRebuild,
244    RequiresSourceRebuild,
245    SourceNotBuilt,
246    UnparseableSource,
247}
248
249#[derive(Clone, Debug, PartialEq, Serialize)]
250pub struct SkippedSite {
251    #[serde(flatten)]
252    pub at: Location,
253    pub end_line: usize,
254    pub end_column: usize,
255    pub reason: SkipReason,
256    #[serde(skip_serializing_if = "Option::is_none")]
257    pub diagnostic: Option<String>,
258}
259
260impl SkippedSite {
261    pub(crate) fn new(
262        at: Location,
263        (end_line, end_column): (usize, usize),
264        reason: SkipReason,
265        diagnostic: Option<String>,
266    ) -> Self {
267        Self {
268            at,
269            end_line,
270            end_column,
271            reason,
272            diagnostic,
273        }
274    }
275}
276
277/// What a run that was asked to check itself found (`--audit`).
278#[derive(Clone, Debug, Default, PartialEq, Serialize)]
279pub struct Audit {
280    /// Surviving mutants that were run once more, against every test of every binary.
281    pub sampled: usize,
282    /// How many surviving mutants there were to choose from.
283    pub survivors: usize,
284    /// Where one of those failed a test it had not been run against: the tests were not
285    /// chosen as they should have been, or do not always do the same.
286    pub disagreements: Vec<Location>,
287    /// Test binaries whose second recorded run was not like the first, with the number
288    /// of records (what one test saw at one site) that differ.
289    pub trace_differences: Vec<TraceDifference>,
290    /// Mutants that were run as probes and chosen to be built from the source as well.
291    pub rebuilt: usize,
292    /// Of those, the ones that built and whose two results could be compared.
293    pub compared: usize,
294    /// And the ones that did not build (or whose probe run could not be evaluated):
295    /// nothing is known about them.
296    pub not_compared: usize,
297    /// Where the two did not agree on whether the tests pass.
298    pub source_disagreements: Vec<SourceDisagreement>,
299}
300
301/// A mutant on which its probe and its source form do not agree.
302#[derive(Clone, Debug, Default, PartialEq, Serialize)]
303pub struct SourceDisagreement {
304    #[serde(flatten)]
305    pub at: Location,
306    pub mutant: String,
307    /// `passes` or `fails`: what the tests did with the probe, and with the source.
308    pub as_probe: String,
309    pub built: String,
310}
311
312#[derive(Clone, Debug, Default, PartialEq, Serialize)]
313pub struct TraceDifference {
314    pub binary: String,
315    pub records: usize,
316}
317
318/// A source edit in the candidate catalogue. Byte offsets refer to the original file.
319#[derive(Clone, Debug, PartialEq, Serialize)]
320pub struct CandidateEdit {
321    pub file: String,
322    pub line: usize,
323    pub column: usize,
324    pub start: usize,
325    pub end: usize,
326    pub before: String,
327    pub replacement: String,
328}
329
330#[derive(Clone, Debug, PartialEq, Serialize)]
331pub struct Candidate {
332    pub what: String,
333    pub into: String,
334    pub requires_rebuild: bool,
335    pub edits: Vec<CandidateEdit>,
336}
337
338#[derive(Clone, Debug, Default, PartialEq, Serialize)]
339pub struct Report {
340    pub package: String,
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub mutants: Option<Vec<Candidate>>,
343    pub analysis: Analysis,
344    /// Present when the run was asked to check itself.
345    #[serde(skip_serializing_if = "Option::is_none")]
346    pub audit: Option<Audit>,
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub evaluation: Option<Evaluation>,
349    pub sites: usize,
350    /// Sites that could not be instrumented (the probe did not compile there).
351    pub skipped_sites: usize,
352    #[serde(skip_serializing_if = "Vec::is_empty")]
353    pub skipped: Vec<SkippedSite>,
354    /// Values a function's body was to be replaced by that do not have its type
355    /// (`Default::default()` for a type without a default): those mutants do not exist.
356    pub unviable_mutants: usize,
357    /// Mutants that need a build of their own and were not asked for (`--rebuild`).
358    pub mutants_not_built: usize,
359    /// Mutants that could not be run as what they are (a range that ends at the largest
360    /// value of its type cannot be made to include it): neither killed nor survivors.
361    pub mutants_not_evaluated: usize,
362    pub mutants_run: usize,
363    pub mutants_killed: usize,
364    /// Killed mutants that were stopped by the timeout (typically an endless loop).
365    pub mutants_timed_out: usize,
366    #[serde(skip_serializing_if = "TimeoutRechecks::is_empty")]
367    pub timeout_rechecks: TimeoutRechecks,
368    pub findings: Vec<Finding>,
369    /// Findings left out because of a `// tmt:ignore` comment or the baseline.
370    pub suppressed: usize,
371    /// Code no test executes.
372    pub unreached: Vec<Location>,
373    /// Survivors predicted from the trace that a re-run killed: the tests are not deterministic.
374    pub unstable: Vec<Location>,
375}
376
377impl Report {
378    pub(crate) fn record_evaluation(&mut self) {
379        self.evaluation = match (self.sites, self.mutants_run, self.skipped.is_empty()) {
380            (_, 1.., _) => None,
381            (0, 0, true) => Some(Evaluation::NoSites),
382            _ => Some(Evaluation::NoMutantsExecuted),
383        };
384    }
385
386    /// Puts the findings in reading order. Sites are numbered as they are discovered, and
387    /// a statement is discovered before the expressions of the statements above it.
388    pub fn sort_findings(&mut self) {
389        self.findings.sort_by(|a, b| {
390            let (a, b) = (a.at(), b.at());
391            (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
392        });
393    }
394
395    /// Whether the run found something to act on: a gap, or a prediction that did not
396    /// hold (which means the report cannot be trusted as it stands).
397    pub fn has_gaps(&self) -> bool {
398        !self.findings.is_empty() || !self.unstable.is_empty()
399    }
400}
401
402pub fn location(file: &str, site: &Site) -> Location {
403    Location {
404        file: file.to_string(),
405        line: site.line,
406        column: site.column,
407        code: one_line(&site.text),
408        ..Location::default()
409    }
410}
411
412pub(crate) fn one_line(code: &str) -> String {
413    const LIMIT: usize = 100;
414    const ELLIPSIS: &str = "...";
415    const PREFIX: usize = LIMIT - ELLIPSIS.len();
416
417    // A code preview can contain four bytes per displayed character.
418    // tmt:ignore performance only: the loop below gives the same text for code of any length
419    if code.len() <= 4 * LIMIT {
420        let mut words = code.split_whitespace();
421        let Some(first) = words.next() else {
422            return String::new();
423        };
424        let mut output = String::with_capacity(code.len());
425        output.push_str(first);
426        for word in words {
427            output.push(' ');
428            output.push_str(word);
429        }
430        // tmt:ignore performance only: text of more than LIMIT characters has more than LIMIT bytes, the first test only saves counting
431        if output.len() > LIMIT && output.chars().count() > LIMIT {
432            let cut = output.char_indices().nth(PREFIX).unwrap().0;
433            output.truncate(cut);
434            output.push_str(ELLIPSIS);
435        }
436        return output;
437    }
438
439    let mut output = String::with_capacity(LIMIT);
440    let mut width = 0;
441    let mut shortened_at = 0;
442    let mut separated = false;
443    for ch in code.chars() {
444        if ch.is_whitespace() {
445            separated = width != 0;
446            continue;
447        }
448        for ch in [separated.then_some(' '), Some(ch)].into_iter().flatten() {
449            if width == LIMIT {
450                output.truncate(shortened_at);
451                output.push_str(ELLIPSIS);
452                return output;
453            }
454            output.push(ch);
455            width += 1;
456            if width == PREFIX {
457                shortened_at = output.len();
458            }
459        }
460        separated = false;
461    }
462    output
463}
464
465/// Value of a float literal such as `30.5`, `1e3` or `2.5_f32`.
466fn float_literal(text: &str) -> Option<f64> {
467    let text = text.trim().replace('_', "");
468    let text = text
469        .strip_suffix("f32")
470        .or(text.strip_suffix("f64"))
471        .unwrap_or(&text);
472    let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
473        && text
474            .chars()
475            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
476    if looks_numeric {
477        text.parse().ok()
478    } else {
479        None
480    }
481}
482
483/// Floats in reports: the shortest text that reads back as the same value, so nothing is
484/// rounded away.
485fn show_float(v: f64) -> String {
486    format!("{v:?}")
487}
488
489/// Source-level form of a mutant.
490pub fn describe(site: &Site, m: Mutation) -> String {
491    match &site.kind {
492        SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
493        SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
494        SiteKind::Guard { .. } => match m {
495            Mutation::Const(value) => {
496                format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
497            }
498            _ => format!("another guard than `{}`", one_line(&site.text)),
499        },
500        SiteKind::Field {
501            from_base: Some(from_base),
502            ..
503        } => format!(
504            "without the field `{}` (it is then `{from_base}`)",
505            one_line(&site.text)
506        ),
507        SiteKind::Field {
508            from_base: None, ..
509        } => format!("without the field `{}`", one_line(&site.text)),
510        SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
511        SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
512        SiteKind::Return { name, option, .. } => match (m, option) {
513            (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
514            (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
515            _ => format!("`{name}` returning something else"),
516        },
517        SiteKind::Range {
518            inclusive,
519            lhs,
520            rhs,
521            ..
522        } => {
523            let dots = if *inclusive { ".." } else { "..=" };
524            format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
525        }
526        SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
527        SiteKind::MinMax {
528            max,
529            receiver,
530            argument,
531            ..
532        } => {
533            let other = if *max { "min" } else { "max" };
534            format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
535        }
536        SiteKind::Logic { and, lhs, rhs, .. } => {
537            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
538            match m {
539                // Both operands are still evaluated whenever the original evaluates them;
540                // only the value of one is ignored. The forms below say exactly that.
541                Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
542                Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
543                Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
544                _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
545            }
546        }
547        SiteKind::Arith {
548            op,
549            assign,
550            lhs,
551            rhs,
552            ..
553        } => {
554            let eq = if *assign { "=" } else { "" };
555            let other = match m {
556                Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
557                _ => op.swapped(),
558            };
559            format!(
560                "`{} {}{eq} {}`",
561                one_line(lhs),
562                other.symbol(),
563                one_line(rhs)
564            )
565        }
566        SiteKind::Cmp {
567            op,
568            lhs,
569            rhs,
570            literal,
571            ..
572        } => {
573            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
574            let sym = op.symbol();
575            match m {
576                Mutation::Const(c) => format!("`{c}`"),
577                Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
578                Mutation::Shift(d) => match literal {
579                    LiteralSide::Rhs(k) => format!("`{lhs} {sym} {}`", k + d),
580                    // k op rhs + d  <=>  k - d op rhs
581                    LiteralSide::Lhs(k) => format!("`{} {sym} {rhs}`", k - d),
582                    LiteralSide::None => match (op, d) {
583                        (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
584                        (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
585                        (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
586                        (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
587                        // Meant as arithmetic on whole numbers: in the operands' own
588                        // type the addition could overflow, the mutant that was run cannot.
589                        // tmt:ignore a shift of 0 is never planned, so `>=` is the same
590                        (_, d) if d > 0 => format!("`{lhs} {sym} {rhs} + {d}` (without overflow)"),
591                        (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
592                    },
593                },
594                Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
595                    (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
596                    (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
597                    // tmt:ignore a shift of 0 is never planned, so any threshold near it is the same
598                    _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
599                    _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
600                },
601                _ => format!("`!({lhs} {sym} {rhs})`"),
602            }
603        }
604    }
605}
606
607/// The operand values that give `lhs - rhs = d`, in words.
608fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
609    match (literal, d) {
610        (LiteralSide::Rhs(k), d) => format!("`{lhs}` = {}", k + d),
611        (LiteralSide::Lhs(k), d) => format!("`{rhs}` = {}", k - d),
612        (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
613        // tmt:ignore 0 is taken by the arm above, so `>=` is the same
614        (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
615        (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
616    }
617}
618
619fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
620    if !obs.valued() {
621        return None;
622    }
623    let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
624        .into_iter()
625        .flatten()
626        .collect();
627    let text = match literal {
628        LiteralSide::Rhs(k) => {
629            let values: Vec<String> = ds.iter().map(|d| (k + d).to_string()).collect();
630            format!("`{lhs}` = {}", values.join(", "))
631        }
632        LiteralSide::Lhs(k) => {
633            let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
634            values.sort();
635            let values: Vec<String> = values.iter().map(i128::to_string).collect();
636            format!("`{rhs}` = {}", values.join(", "))
637        }
638        LiteralSide::None => {
639            let values: Vec<String> = ds.iter().map(i128::to_string).collect();
640            format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
641        }
642    };
643    Some(format!("nearest values the tests passed: {text}"))
644}
645
646/// Builds the input-gap finding for a comparison site. `None` for gaps that are reported
647/// elsewhere (unreached code).
648pub fn input_gap_finding(
649    file: &str,
650    site: &Site,
651    gap: &InputGap,
652    obs: &Obs,
653    verified: bool,
654) -> Option<Finding> {
655    let SiteKind::Cmp {
656        op,
657        lhs,
658        rhs,
659        literal,
660        ..
661    } = &site.kind
662    else {
663        return None;
664    };
665    let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
666    // A float shift too small to move the literal is not a different program. The
667    // literal moves the way `describe` writes it.
668    let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
669        (None, Some(k)) => k + d != k,
670        (Some(k), None) => k - d != k,
671        _ => true,
672    };
673    let survivors: Vec<String> = gap
674        .survivors()
675        .into_iter()
676        .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
677        .map(|m| describe(site, m))
678        .collect();
679    let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
680    let (survivor_count, add_tests) = match gap {
681        InputGap::Unreached => return None,
682        InputGap::OneSided { always } => (
683            1,
684            vec![format!(
685                "an input that makes `{}` {}",
686                one_line(&site.text),
687                !always
688            )],
689        ),
690        InputGap::EqualNeverObserved { flipped, float_gap } => {
691            if let Some((lo, hi)) = float_gap {
692                observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
693                    (None, Some(k)) => format!(
694                        "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
695                        show_float(k + lo),
696                        show_float(k + hi)
697                    ),
698                    (Some(k), None) => format!(
699                        "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
700                        show_float(k - hi),
701                        show_float(k - lo)
702                    ),
703                    _ => format!(
704                        "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
705                        show_float(*lo),
706                        show_float(*hi)
707                    ),
708                });
709            }
710            (
711                survivors.len() as u128,
712                vec![format!(
713                    "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
714                    op.eval_d(0),
715                    flipped.eval_d(0)
716                )],
717            )
718        }
719        InputGap::Boundary {
720            min_shift,
721            max_shift,
722            missing,
723        } => {
724            let add = missing
725                .iter()
726                .map(|d| {
727                    format!(
728                        "{} (the original gives {})",
729                        input_for(&lhs_text, &rhs_text, *literal, *d),
730                        op.eval_d(*d)
731                    )
732                })
733                .collect();
734            ((max_shift - min_shift) as u128, add)
735        }
736    };
737    Some(Finding::InputGap {
738        at: location(file, site),
739        survivors,
740        survivor_count,
741        add_tests,
742        observed,
743        verified,
744    })
745}
746
747/// Input gap at `a && b` / `a || b`: one operand never decides the result in any test.
748pub fn logic_gap_finding(
749    file: &str,
750    site: &Site,
751    gap: LogicGap,
752    verified: bool,
753) -> Option<Finding> {
754    let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
755        return None;
756    };
757    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
758    let (mutation, add) = match (gap, and) {
759        (LogicGap::Unreached, _) => return None,
760        (LogicGap::RhsNeverDecides, true) => (
761            Mutation::LogicDropRhs,
762            format!("a case where `{lhs}` is true and `{rhs}` is false"),
763        ),
764        (LogicGap::RhsNeverDecides, false) => (
765            Mutation::LogicDropRhs,
766            format!("a case where `{lhs}` is false and `{rhs}` is true"),
767        ),
768        (LogicGap::LhsNeverDecides, true) => (
769            Mutation::LogicDropLhs,
770            format!("a case where `{lhs}` is false"),
771        ),
772        (LogicGap::LhsNeverDecides, false) => (
773            Mutation::LogicDropLhs,
774            format!("a case where `{lhs}` is true"),
775        ),
776    };
777    Some(Finding::InputGap {
778        at: location(file, site),
779        survivors: vec![describe(site, mutation)],
780        survivor_count: 1,
781        add_tests: vec![add],
782        observed: None,
783        verified,
784    })
785}
786
787/// Input gap at `a.max(b)` / `a.min(b)`: the two operands were equal in every test.
788pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
789    let SiteKind::MinMax {
790        receiver, argument, ..
791    } = &site.kind
792    else {
793        return None;
794    };
795    Some(Finding::InputGap {
796        at: location(file, site),
797        survivors: vec![describe(site, Mutation::MinMax)],
798        survivor_count: 1,
799        add_tests: vec![format!(
800            "`{}` different from `{}`",
801            one_line(receiver),
802            one_line(argument)
803        )],
804        observed: None,
805        verified,
806    })
807}
808
809/// Input gap at a `-> bool` function that returned the same value in every test.
810pub fn return_gap_finding(
811    file: &str,
812    site: &Site,
813    always: bool,
814    verified: bool,
815) -> Option<Finding> {
816    let SiteKind::Return { name, option, .. } = &site.kind else {
817        return None;
818    };
819    let other = match (option, always) {
820        (None, always) => format!("{}", !always),
821        (Some(_), false) => "`Some`".to_string(),
822        (Some(_), true) => "`None`".to_string(),
823    };
824    Some(Finding::InputGap {
825        at: location(file, site),
826        survivors: vec![describe(site, Mutation::Const(always))],
827        survivor_count: 1,
828        add_tests: vec![format!("a case where `{name}` returns {other}")],
829        observed: None,
830        verified,
831    })
832}
833
834/// Input gap at the guard of a match arm that had the same value in every test.
835pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
836    Finding::InputGap {
837        at: location(file, site),
838        survivors: vec![describe(site, Mutation::Const(always))],
839        survivor_count: 1,
840        add_tests: vec![format!(
841            "a case where the guard `{}` is {}",
842            one_line(&site.text),
843            !always
844        )],
845        observed: None,
846        verified,
847    }
848}
849
850/// Input gap at an arithmetic operator: the swapped operator computes the same value on
851/// every pair of operands the tests pass.
852pub fn arith_gap_finding(
853    file: &str,
854    site: &Site,
855    mutation: Mutation,
856    verified: bool,
857) -> Option<Finding> {
858    let SiteKind::Arith {
859        op,
860        assign,
861        lhs,
862        rhs,
863        ..
864    } = &site.kind
865    else {
866        return None;
867    };
868    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
869    let eq = if *assign { "=" } else { "" };
870    let other = match mutation {
871        Mutation::ArithSwap2 => op.second(*assign)?,
872        _ => op.swapped(),
873    };
874    let add = match (op, other) {
875        (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
876            format!("`{rhs}` other than 0")
877        }
878        _ => format!(
879            "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
880            op.symbol(),
881            other.symbol()
882        ),
883    };
884    Some(Finding::InputGap {
885        at: location(file, site),
886        survivors: vec![describe(site, mutation)],
887        survivor_count: 1,
888        add_tests: vec![add],
889        observed: None,
890        verified,
891    })
892}
893
894/// The report as SARIF 2.1.0, with file names relative to the repository root.
895pub fn render_sarif(report: &Report) -> String {
896    serde_json::to_string_pretty(&sarif_document(vec![sarif_run(report)]))
897        .expect("JSON values serialise")
898}
899
900/// The CLI's workspace SARIF has one run per member, the analysed ones in report order
901/// and then those whose analysis could not run (`failed`: package and what went wrong).
902/// A member that failed is a run that says so: a document without it would read as a
903/// package with nothing to report. Each run has an id of its own, by which a service
904/// that takes several runs of one tool keeps them apart.
905#[doc(hidden)]
906pub fn workspace_sarif(reports: &[Report], failed: &[(String, String)]) -> impl std::fmt::Display {
907    let category = |package: &str| serde_json::json!({ "id": format!("tmt/{package}/") });
908    let mut runs: Vec<serde_json::Value> = reports
909        .iter()
910        .map(|report| {
911            let mut run = sarif_run(report);
912            run["properties"]["package"] = serde_json::json!(report.package);
913            run["automationDetails"] = category(&report.package);
914            run["invocations"] = serde_json::json!([{ "executionSuccessful": true }]);
915            run
916        })
917        .collect();
918    for (package, error) in failed {
919        runs.push(serde_json::json!({
920            "tool": sarif_tool(),
921            "automationDetails": category(package),
922            "invocations": [{
923                "executionSuccessful": false,
924                "toolExecutionNotifications": [{
925                    "level": "error",
926                    "message": { "text": error },
927                }],
928            }],
929            "properties": { "package": package },
930            "results": [],
931        }));
932    }
933    sarif_document(runs)
934}
935
936/// A path as the URI reference SARIF wants: `/` between its parts, and in the parts
937/// every byte that is not plainly allowed in one (a space, `#`, `%`, what is not ASCII)
938/// written as `%XX`.
939fn sarif_uri(prefix: &str, file: &str) -> String {
940    let mut uri = String::new();
941    for byte in prefix.bytes().chain(file.bytes()) {
942        match byte {
943            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
944                uri.push(byte as char)
945            }
946            _ => uri.push_str(&format!("%{byte:02X}")),
947        }
948    }
949    uri
950}
951
952fn sarif_tool() -> serde_json::Value {
953    serde_json::json!({ "driver": {
954        "name": "tmt",
955        "rules": [
956            { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
957            { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
958            { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } }
959        ]
960    } })
961}
962
963fn sarif_document(runs: Vec<serde_json::Value>) -> serde_json::Value {
964    let mut document = serde_json::json!({
965        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
966        "version": "2.1.0",
967    });
968    document["runs"] = serde_json::Value::Array(runs);
969    document
970}
971
972fn sarif_run(report: &Report) -> serde_json::Value {
973    let prefix = report.analysis.package_path.as_str();
974    let results: Vec<serde_json::Value> = report
975        .findings
976        .iter()
977        .map(|finding| {
978            let (kind, at) = finding_parts(finding);
979            let rule = match kind {
980                "INPUT GAP" => "input-gap",
981                "ASSERTION GAP" => "assertion-gap",
982                _ => "survivor",
983            };
984            let text = format!("`{}`: {}", at.code, finding_body(finding).join("; "));
985            serde_json::json!({
986                "ruleId": rule,
987                "level": "warning",
988                "message": { "text": text },
989                // What the service tells a finding of one run from that of another by.
990                "partialFingerprints": { "tmtFindingId/v2": at.id },
991                "locations": [{
992                    "physicalLocation": {
993                        "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
994                        "region": { "startLine": at.line, "startColumn": at.column }
995                    }
996                }]
997            })
998        })
999        .collect();
1000    let mut run = serde_json::json!({
1001        "tool": sarif_tool(),
1002        // What was looked at: a run of a part says nothing about the rest.
1003        "properties": { "analysis": report.analysis, "evaluation": report.evaluation, "skipped": report.skipped },
1004    });
1005    run["results"] = serde_json::Value::Array(results);
1006    run
1007}
1008
1009fn list(items: &[String], limit: usize) -> String {
1010    let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
1011    let more = items.len().saturating_sub(limit);
1012    if more > 0 {
1013        format!("{} (+{more} more)", shown.join(", "))
1014    } else {
1015        shown.join(", ")
1016    }
1017}
1018
1019/// The lines of one finding, without its header.
1020fn finding_body(finding: &Finding) -> Vec<String> {
1021    let mut lines = vec![];
1022    match finding {
1023        Finding::InputGap {
1024            survivors,
1025            survivor_count,
1026            add_tests,
1027            observed,
1028            verified,
1029            ..
1030        } => {
1031            let more = survivor_count.saturating_sub(survivors.len() as u128);
1032            let more = if more > 0 {
1033                format!(" (+{more} more)")
1034            } else {
1035                String::new()
1036            };
1037            let note = if *verified {
1038                "re-run: tests pass"
1039            } else {
1040                "from the trace, not re-run"
1041            };
1042            lines.push(format!(
1043                "passes every test as: {}{more}  [{note}]",
1044                survivors.join(", ")
1045            ));
1046            lines.extend(observed.iter().cloned());
1047            lines.extend(
1048                add_tests
1049                    .iter()
1050                    .map(|test| format!("add a test with {test}")),
1051            );
1052        }
1053        Finding::AssertionGap {
1054            survivors,
1055            tests,
1056            effects,
1057            effects_of,
1058            witness,
1059            ..
1060        } => {
1061            lines.push(format!("passes every test as: {}", survivors.join(", ")));
1062            lines.push(format!(
1063                "these tests run the changed code and still pass: {}",
1064                list(tests, 5)
1065            ));
1066            if effects.is_empty() {
1067                lines.push("add an assertion on what this code is responsible for".to_string());
1068            } else {
1069                // Which of several mutants was followed, so that what is said of "the
1070                // mutant" below can be tried.
1071                if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
1072                    lines.push(format!(
1073                        "followed one of them through the tests: {followed}"
1074                    ));
1075                }
1076                lines.extend(effects.iter().cloned());
1077            }
1078            if let Some(witness) = witness {
1079                lines.extend(witness_lines(witness));
1080            }
1081        }
1082        Finding::Survivor {
1083            survivors, witness, ..
1084        } => {
1085            lines.push(format!("passes every test as: {}", survivors.join(", ")));
1086            if let Some(witness) = witness {
1087                lines.extend(witness_lines(witness));
1088            } else {
1089                lines.push(
1090                    "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"
1091                        .to_string(),
1092                );
1093            }
1094        }
1095    }
1096    lines
1097}
1098
1099fn witness_lines(witness: &VerifiedWitness) -> Vec<String> {
1100    let mut lines = vec![format!(
1101        "verified on `{}`: original returned {}, mutant returned {}",
1102        witness.call, witness.original, witness.mutant,
1103    )];
1104    if let Some(killed) = witness.individually_killed {
1105        lines.push(format!(
1106            "the selected tests detected all {killed} component changes in isolation"
1107        ));
1108    }
1109    lines.extend(witness.guidance.iter().cloned());
1110    lines.push(format!("add a test with `{}`", witness.assertion));
1111    lines
1112}
1113
1114fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
1115    match finding {
1116        Finding::InputGap { at, .. } => ("INPUT GAP", at),
1117        Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
1118        Finding::Survivor { at, .. } => ("SURVIVOR", at),
1119    }
1120}
1121
1122pub fn render_text(report: &Report, show_unreached: bool) -> String {
1123    let mut out = String::new();
1124    let mut previous: Option<(&str, usize)> = None;
1125    for finding in &report.findings {
1126        let (kind, at) = finding_parts(finding);
1127        // Findings on one line are usually one thought (a chain of conditions): they are
1128        // printed as one block.
1129        let same_line = previous == Some((at.file.as_str(), at.line));
1130        if same_line {
1131            out.push_str(&format!(
1132                "  + {kind}  column {}\n    {}\n",
1133                at.column, at.code
1134            ));
1135        } else {
1136            if previous.is_some() {
1137                out.push('\n');
1138            }
1139            out.push_str(&format!(
1140                "{kind}  {}:{}:{}\n    {}\n",
1141                at.file, at.line, at.column, at.code
1142            ));
1143        }
1144        for line in finding_body(finding) {
1145            out.push_str(&format!("  {line}\n"));
1146        }
1147        previous = Some((at.file.as_str(), at.line));
1148    }
1149    if previous.is_some() {
1150        out.push('\n');
1151    }
1152    if show_unreached {
1153        for at in &report.unreached {
1154            out.push_str(&format!(
1155                "UNREACHED  {}:{}:{}\n    {}\n\n",
1156                at.file, at.line, at.column, at.code
1157            ));
1158        }
1159    }
1160    for at in &report.unstable {
1161        out.push_str(&format!(
1162            "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",
1163            at.file, at.line, at.column, at.code
1164        ));
1165    }
1166    let input = report
1167        .findings
1168        .iter()
1169        .filter(|f| matches!(f, Finding::InputGap { .. }))
1170        .count();
1171    let assertion = report
1172        .findings
1173        .iter()
1174        .filter(|f| matches!(f, Finding::AssertionGap { .. }))
1175        .count();
1176    let unexplained = report.findings.len() - input - assertion;
1177    // A mutant stopped by the time limit costs the limit: worth knowing when a run is slow.
1178    let by_time_limit = if report.mutants_timed_out > 0 {
1179        format!(", {} of them by the time limit", report.mutants_timed_out)
1180    } else {
1181        String::new()
1182    };
1183    out.push_str(&format!(
1184        "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
1185        report.package,
1186        report.sites,
1187        input,
1188        assertion,
1189        report.mutants_run,
1190        report.mutants_killed,
1191        report.unreached.len()
1192    ));
1193    if unexplained > 0 {
1194        out.push_str(&format!(
1195            ", {unexplained} survivors of mutants built on their own"
1196        ));
1197    }
1198    if !report.timeout_rechecks.is_empty() {
1199        let rechecks = &report.timeout_rechecks;
1200        out.push_str(&format!(
1201            ", {} parallel timeouts ({} confirmed, {} recovered, {} unconfirmed)",
1202            rechecks.first_pass, rechecks.confirmed, rechecks.recovered, rechecks.unconfirmed
1203        ));
1204    }
1205    if report.suppressed > 0 {
1206        out.push_str(&format!(", {} findings suppressed", report.suppressed));
1207    }
1208    if report.skipped_sites > 0 {
1209        out.push_str(&format!(
1210            ", {} sites skipped (probe did not compile)",
1211            report.skipped_sites
1212        ));
1213    }
1214    if report.unviable_mutants > 0 {
1215        out.push_str(&format!(
1216            ", {} mutants left out (they do not compile)",
1217            report.unviable_mutants
1218        ));
1219    }
1220    out.push('\n');
1221    if let Some(audit) = &report.audit {
1222        out.push_str(&format!(
1223            "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against\n",
1224            audit.sampled,
1225            audit.survivors,
1226            audit.disagreements.len()
1227        ));
1228        for at in &audit.disagreements {
1229            out.push_str(&format!(
1230                "  {}:{}:{}  {}\n",
1231                at.file, at.line, at.column, at.code
1232            ));
1233        }
1234        if audit.rebuilt > 0 {
1235            out.push_str(&format!(
1236                "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",
1237                audit.rebuilt,
1238                audit.compared,
1239                audit.source_disagreements.len(),
1240                audit.not_compared
1241            ));
1242        }
1243        for differs in &audit.source_disagreements {
1244            out.push_str(&format!(
1245                "  {}:{}:{}  {}: {} as a probe, {} built\n",
1246                differs.at.file,
1247                differs.at.line,
1248                differs.at.column,
1249                differs.mutant,
1250                differs.as_probe,
1251                differs.built
1252            ));
1253        }
1254        if audit.trace_differences.is_empty() {
1255            out.push_str("audit: recorded once more, the tests did the same\n");
1256        }
1257        for binary in &audit.trace_differences {
1258            out.push_str(&format!(
1259                "audit: recorded once more, `{}` differs in {} records: its tests do not always do the same\n",
1260                binary.binary, binary.records
1261            ));
1262        }
1263    }
1264    if report.mutants_not_evaluated > 0 {
1265        out.push_str(&format!(
1266            "({} mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n",
1267            report.mutants_not_evaluated
1268        ));
1269    }
1270    if report.mutants_not_built > 0 {
1271        out.push_str(&format!(
1272            "({} more mutants need a build of their own: --rebuild runs them)\n",
1273            report.mutants_not_built
1274        ));
1275    }
1276    if !report.skipped.is_empty() {
1277        out.push_str(&format!(
1278            "({} skipped entries with locations and reasons in --json)\n",
1279            report.skipped.len()
1280        ));
1281    }
1282    if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
1283        out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
1284    }
1285    if !show_unreached && !report.unreached.is_empty() {
1286        out.push_str("(--show-unreached lists the code no test executes)\n");
1287    }
1288    out
1289}
1290
1291#[cfg(test)]
1292mod tests {
1293    use super::*;
1294    use crate::instrument::discover;
1295
1296    #[test]
1297    fn evaluation_distinguishes_no_sites_no_mutants_and_completed_work() {
1298        let mut report = Report::default();
1299        report.record_evaluation();
1300        assert_eq!(report.evaluation, Some(Evaluation::NoSites));
1301        report.sites = 1;
1302        report.record_evaluation();
1303        assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
1304        assert!(render_text(&report, false).contains("No mutants executed."));
1305        report.mutants_run = 1;
1306        report.record_evaluation();
1307        assert_eq!(report.evaluation, None);
1308        assert!(!render_text(&report, false).contains("No mutants executed."));
1309    }
1310
1311    fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
1312        sarif["runs"][0]["results"].as_array().unwrap()
1313    }
1314
1315    fn or_site() -> Site {
1316        site_of("fn f(a: bool, b: bool) -> bool { a || b }")
1317    }
1318
1319    fn assign_kind() -> SiteKind {
1320        SiteKind::Arith {
1321            op: ArithOp::Add,
1322            assign: true,
1323            lhs: "*total".into(),
1324            rhs: "fee".into(),
1325            gap: (0, 0),
1326        }
1327    }
1328
1329    fn site_of(src: &str) -> Site {
1330        discover(src, 0)
1331            .unwrap()
1332            .sites
1333            .into_iter()
1334            .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
1335            .unwrap()
1336    }
1337
1338    #[test]
1339    fn describes_mutants_at_source_level() {
1340        let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
1341        assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
1342        assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
1343        assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
1344        assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
1345        assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
1346
1347        // 18 <= age shifted by +1 is 18 <= age + 1, i.e. 17 <= age.
1348        let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
1349        assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
1350
1351        let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
1352        assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
1353        assert_eq!(
1354            describe(&none, Mutation::Shift(2)),
1355            "`a >= b + 2` (without overflow)"
1356        );
1357        assert_eq!(
1358            describe(&none, Mutation::Shift(-1)),
1359            "`a >= b - 1` (without overflow)"
1360        );
1361        let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
1362        assert_eq!(describe(&lt, Mutation::Shift(1)), "`a <= b`");
1363
1364        let stmt = site_of("fn f(s: &mut S) { s.check(\n  1,\n  2); }");
1365        assert_eq!(
1366            describe(&stmt, Mutation::Delete),
1367            "delete `s.check( 1, 2);`"
1368        );
1369    }
1370
1371    /// The source-level form must mean the same as the planner's `Shift`.
1372    #[test]
1373    fn literal_shift_rendering_matches_shift_semantics() {
1374        use crate::plan::eval_mutated_d;
1375        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1376            for shift in [-2, -1, 1, 2] {
1377                for other in -5..=5i128 {
1378                    let k = 1i128;
1379                    // literal on the right: `x op k+shift`
1380                    assert_eq!(
1381                        op.eval_d(other - (k + shift)),
1382                        eval_mutated_d(op, Mutation::Shift(shift), other - k)
1383                    );
1384                    // literal on the left: `k-shift op x`
1385                    assert_eq!(
1386                        op.eval_d((k - shift) - other),
1387                        eval_mutated_d(op, Mutation::Shift(shift), k - other)
1388                    );
1389                }
1390            }
1391        }
1392        // And the operator flips used when neither side is a literal.
1393        for (op, shift, flipped) in [
1394            (CmpOp::Ge, 1, CmpOp::Gt),
1395            (CmpOp::Gt, -1, CmpOp::Ge),
1396            (CmpOp::Le, -1, CmpOp::Lt),
1397            (CmpOp::Lt, 1, CmpOp::Le),
1398        ] {
1399            for d in -3..=3 {
1400                assert_eq!(
1401                    flipped.eval_d(d),
1402                    eval_mutated_d(op, Mutation::Shift(shift), d)
1403                );
1404            }
1405        }
1406    }
1407
1408    #[test]
1409    fn boundary_finding_for_the_age_check() {
1410        let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
1411        let mut obs = Obs::of_d(-1);
1412        obs.merge(&Obs::of_d(2));
1413        let gap = InputGap::Boundary {
1414            min_shift: 0,
1415            max_shift: 2,
1416            missing: vec![0],
1417        };
1418        let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
1419        assert_eq!(
1420            finding,
1421            Finding::InputGap {
1422                at: Location {
1423                    file: "src/lib.rs".into(),
1424                    line: 1,
1425                    column: 26,
1426                    code: "age >= 18".into(),
1427                    ..Location::default()
1428                },
1429                survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
1430                survivor_count: 2,
1431                add_tests: vec!["`age` = 18 (the original gives true)".into()],
1432                observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
1433                verified: true,
1434            }
1435        );
1436        let report = Report {
1437            package: "p".into(),
1438            sites: 1,
1439            findings: vec![finding],
1440            ..Report::default()
1441        };
1442        let text = render_text(&report, false);
1443        assert!(text.contains("INPUT GAP  src/lib.rs:1:26"), "{text}");
1444        assert!(
1445            text.contains("passes every test as: `age >= 19`, `age >= 20`  [re-run: tests pass]"),
1446            "{text}"
1447        );
1448        assert!(
1449            text.contains("add a test with `age` = 18 (the original gives true)"),
1450            "{text}"
1451        );
1452        assert!(
1453            text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
1454            "{text}"
1455        );
1456        assert!(report.has_gaps());
1457    }
1458
1459    #[test]
1460    fn other_gap_kinds() {
1461        let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
1462        let mut obs = Obs::of_rel(crate::plan::Rel::Less);
1463        obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
1464        let gap = InputGap::EqualNeverObserved {
1465            flipped: CmpOp::Le,
1466            float_gap: None,
1467        };
1468        let Some(Finding::InputGap {
1469            survivors,
1470            add_tests,
1471            observed,
1472            ..
1473        }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
1474        else {
1475            panic!()
1476        };
1477        assert_eq!(survivors, ["`a <= b`"]);
1478        assert_eq!(
1479            add_tests,
1480            ["`a` equal to `b` (the original gives false, the mutant true)"]
1481        );
1482        assert_eq!(observed, None);
1483
1484        let Some(Finding::InputGap {
1485            survivors,
1486            add_tests,
1487            ..
1488        }) = input_gap_finding(
1489            "f.rs",
1490            &site,
1491            &InputGap::OneSided { always: true },
1492            &obs,
1493            false,
1494        )
1495        else {
1496            panic!()
1497        };
1498        assert_eq!(survivors, ["`true`"]);
1499        assert_eq!(add_tests, ["an input that makes `a < b` false"]);
1500
1501        assert_eq!(
1502            input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
1503            None
1504        );
1505    }
1506
1507    #[test]
1508    fn float_gap_finding() {
1509        let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
1510        let mut obs = Obs::of_f(-20.5);
1511        obs.merge(&Obs::of_f(9.5));
1512        let gap = InputGap::EqualNeverObserved {
1513            flipped: CmpOp::Ge,
1514            float_gap: obs.float_gap(),
1515        };
1516        let Some(Finding::InputGap {
1517            survivors,
1518            add_tests,
1519            observed,
1520            survivor_count,
1521            ..
1522        }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
1523        else {
1524            panic!()
1525        };
1526        assert_eq!(
1527            survivors,
1528            [
1529                "`celsius >= 30.5`",
1530                "`celsius > 35.25`",
1531                "`celsius > 20.25`"
1532            ]
1533        );
1534        assert_eq!(survivor_count, 3);
1535        assert_eq!(
1536            add_tests,
1537            ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
1538        );
1539        assert_eq!(
1540            observed.as_deref(),
1541            Some(
1542                "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
1543            )
1544        );
1545
1546        let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
1547        assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
1548        let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
1549        assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
1550        assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
1551        let finding = input_gap_finding(
1552            "f.rs",
1553            &none,
1554            &InputGap::EqualNeverObserved {
1555                flipped: CmpOp::Le,
1556                float_gap: Some((-1.0, 2.0)),
1557            },
1558            &obs,
1559            false,
1560        );
1561        let Some(Finding::InputGap { observed, .. }) = finding else {
1562            panic!()
1563        };
1564        assert_eq!(
1565            observed.as_deref(),
1566            Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
1567        );
1568
1569        assert_eq!(float_literal("30.5"), Some(30.5));
1570        assert_eq!(float_literal("-1e3"), Some(-1000.0));
1571        assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
1572        assert_eq!(float_literal("limit"), None);
1573        assert_eq!(float_literal("x1"), None);
1574        assert_eq!(float_literal("1x"), None);
1575        assert_eq!(float_literal("-x"), None);
1576        assert_eq!(float_literal("-2.5"), Some(-2.5));
1577        assert_eq!(float_literal("e"), None);
1578        // Nothing is rounded away: a tiny shift stays visible.
1579        assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
1580        assert_eq!(show_float(1e-10), "1e-10");
1581        assert_eq!(show_float(10.0), "10.0");
1582        assert_eq!(show_float(35.25), "35.25");
1583        // A shift that does not change the literal is not listed as a mutant.
1584        let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
1585        let tiny = InputGap::EqualNeverObserved {
1586            flipped: CmpOp::Ge,
1587            float_gap: Some((-2e-300, 2e-300)),
1588        };
1589        let Some(Finding::InputGap { survivors, .. }) =
1590            input_gap_finding("f.rs", &big, &tiny, &obs, true)
1591        else {
1592            panic!()
1593        };
1594        assert_eq!(survivors, ["`x >= 1e300`"]);
1595    }
1596
1597    #[test]
1598    fn logic_and_arithmetic_findings() {
1599        let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
1600        assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
1601        assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
1602        assert_eq!(
1603            describe(&or_site(), Mutation::LogicDropRhs),
1604            "`a || { b; false }`"
1605        );
1606        assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
1607        let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
1608        assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
1609        let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
1610            Some(Finding::InputGap {
1611                survivors,
1612                add_tests,
1613                ..
1614            }) => (survivors[0].clone(), add_tests[0].clone()),
1615            _ => panic!(),
1616        };
1617        assert_eq!(
1618            advice(&and, LogicGap::RhsNeverDecides),
1619            (
1620                "`a && { b; true }`".into(),
1621                "a case where `a` is true and `b` is false".into()
1622            )
1623        );
1624        assert_eq!(
1625            advice(&and, LogicGap::LhsNeverDecides),
1626            ("`{ a; b }`".into(), "a case where `a` is false".into())
1627        );
1628        assert_eq!(
1629            advice(&or, LogicGap::RhsNeverDecides),
1630            (
1631                "`a || { b; false }`".into(),
1632                "a case where `a` is false and `b` is true".into()
1633            )
1634        );
1635        assert_eq!(
1636            advice(&or, LogicGap::LhsNeverDecides),
1637            ("`{ a; b }`".into(), "a case where `a` is true".into())
1638        );
1639        assert_eq!(
1640            logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
1641            None
1642        );
1643        assert_eq!(
1644            arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
1645            None
1646        );
1647
1648        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
1649        assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
1650        let Some(Finding::InputGap {
1651            survivors,
1652            add_tests,
1653            ..
1654        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
1655        else {
1656            panic!()
1657        };
1658        assert_eq!(
1659            (survivors[0].as_str(), add_tests[0].as_str()),
1660            ("`total - fee`", "`fee` other than 0")
1661        );
1662        let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
1663        let Some(Finding::InputGap {
1664            survivors,
1665            add_tests,
1666            ..
1667        }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
1668        else {
1669            panic!()
1670        };
1671        assert_eq!(survivors[0], "`n / scale`");
1672        assert_eq!(
1673            add_tests[0],
1674            "operands for which `n * scale` and `n / scale` differ"
1675        );
1676        let assign = Site {
1677            kind: assign_kind(),
1678            ..add.clone()
1679        };
1680        assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
1681        let Some(Finding::InputGap { add_tests, .. }) =
1682            arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
1683        else {
1684            panic!()
1685        };
1686        assert_eq!(add_tests[0], "`fee` other than 0");
1687        let shift = Site {
1688            kind: SiteKind::Arith {
1689                op: ArithOp::Shl,
1690                assign: true,
1691                lhs: "bits".into(),
1692                rhs: "n".into(),
1693                gap: (0, 0),
1694            },
1695            ..assign.clone()
1696        };
1697        assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
1698        let Some(Finding::InputGap { add_tests, .. }) =
1699            arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
1700        else {
1701            panic!()
1702        };
1703        assert_eq!(
1704            add_tests[0],
1705            "operands for which `bits <<= n` and `bits >>= n` differ"
1706        );
1707
1708        let not = Site {
1709            kind: SiteKind::Not {
1710                bang: (0, 1),
1711                operand: "is_ready(x)".into(),
1712            },
1713            ..assign.clone()
1714        };
1715        assert_eq!(describe(&not, Mutation::DropNot), "`is_ready(x)`");
1716        let ret = Site {
1717            kind: SiteKind::Return {
1718                name: "is_ready".into(),
1719                option: None,
1720                sole_expr: None,
1721            },
1722            ..assign.clone()
1723        };
1724        assert_eq!(
1725            describe(&ret, Mutation::Const(true)),
1726            "`is_ready` returning `true`"
1727        );
1728        let Some(Finding::InputGap {
1729            survivors,
1730            add_tests,
1731            ..
1732        }) = return_gap_finding("f.rs", &ret, false, true)
1733        else {
1734            panic!()
1735        };
1736        assert_eq!(survivors[0], "`is_ready` returning `false`");
1737        assert_eq!(add_tests[0], "a case where `is_ready` returns true");
1738        assert_eq!(return_gap_finding("f.rs", &not, false, true), None);
1739
1740        let find = Site {
1741            kind: SiteKind::Return {
1742                name: "find".into(),
1743                option: Some("Option<&str>".into()),
1744                sole_expr: None,
1745            },
1746            ..assign.clone()
1747        };
1748        assert_eq!(
1749            describe(&find, Mutation::Const(false)),
1750            "`find` returning `None`"
1751        );
1752        let Some(Finding::InputGap { add_tests, .. }) =
1753            return_gap_finding("f.rs", &find, false, true)
1754        else {
1755            panic!()
1756        };
1757        assert_eq!(add_tests[0], "a case where `find` returns `Some`");
1758        let range = Site {
1759            kind: SiteKind::Range {
1760                inclusive: false,
1761                lhs: "0".into(),
1762                rhs: "n".into(),
1763                gap: (0, 0),
1764            },
1765            ..assign.clone()
1766        };
1767        assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
1768        let closed = Site {
1769            kind: SiteKind::Range {
1770                inclusive: true,
1771                lhs: "1".into(),
1772                rhs: "n".into(),
1773                gap: (0, 0),
1774            },
1775            ..assign.clone()
1776        };
1777        assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
1778        let arm = Site {
1779            kind: SiteKind::Arm {
1780                pattern: "Kind::Update { key, .. }".into(),
1781                guard: crate::instrument::ArmGuard::None(0),
1782                removal: (0, 0),
1783            },
1784            ..assign.clone()
1785        };
1786        assert_eq!(
1787            describe(&arm, Mutation::Delete),
1788            "remove the arm `Kind::Update { key, .. } => ..`"
1789        );
1790
1791        let clamp = Site {
1792            kind: SiteKind::MinMax {
1793                max: true,
1794                receiver: "drift".into(),
1795                argument: "peak.get()".into(),
1796                call: (0, 0),
1797                close: (0, 0),
1798            },
1799            ..assign.clone()
1800        };
1801        assert_eq!(
1802            describe(&clamp, Mutation::MinMax),
1803            "`drift.min(peak.get())`"
1804        );
1805        let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
1806        else {
1807            panic!()
1808        };
1809        assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
1810        assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
1811
1812        let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
1813        assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
1814        assert_eq!(
1815            logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
1816            None
1817        );
1818    }
1819
1820    #[test]
1821    fn workspace_sarif_matches_the_individual_runs() {
1822        use serde_json::{Value, json};
1823
1824        let report = Report {
1825            package: "zebra".into(),
1826            analysis: Analysis {
1827                package_path: "crates/zebra/".into(),
1828                ..Analysis::default()
1829            },
1830            findings: vec![Finding::Survivor {
1831                at: Location {
1832                    file: r#"src/"é".rs"#.into(),
1833                    line: 4,
1834                    column: 1,
1835                    id: "zebra|4".into(),
1836                    ..Location::default()
1837                },
1838                survivors: vec!["delete".into()],
1839                witness: None,
1840            }],
1841            ..Report::default()
1842        };
1843        let empty = Report {
1844            package: "ant".into(),
1845            ..Report::default()
1846        };
1847        for reports in [
1848            &[][..],
1849            std::slice::from_ref(&report),
1850            &[report.clone(), empty],
1851        ] {
1852            let runs: Vec<_> = reports
1853                .iter()
1854                .map(|report| {
1855                    let mut single: Value = serde_json::from_str(&render_sarif(report)).unwrap();
1856                    let mut run = single["runs"][0].take();
1857                    assert!(run["properties"].get("package").is_none());
1858                    run["properties"]["package"] = json!(report.package);
1859                    // What a run of a workspace has beside that of a package alone.
1860                    run["automationDetails"] = json!({ "id": format!("tmt/{}/", report.package) });
1861                    run["invocations"] = json!([{ "executionSuccessful": true }]);
1862                    run
1863                })
1864                .collect();
1865            let old = json!({
1866                "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1867                "version": "2.1.0",
1868                "runs": runs,
1869            });
1870            let workspace: Value =
1871                serde_json::from_str(&format!("{:#}", workspace_sarif(reports, &[]))).unwrap();
1872            assert_eq!(workspace, old);
1873        }
1874    }
1875
1876    #[test]
1877    fn a_package_that_could_not_be_analysed_is_a_run_that_says_so() {
1878        use serde_json::Value;
1879
1880        let analysed = Report {
1881            package: "ant".into(),
1882            ..Report::default()
1883        };
1884        let failed = [(
1885            "bee".to_string(),
1886            "the tests of `bee` fail: \"quoted\"\n".to_string(),
1887        )];
1888        let document: Value = serde_json::from_str(&format!(
1889            "{:#}",
1890            workspace_sarif(std::slice::from_ref(&analysed), &failed)
1891        ))
1892        .unwrap();
1893        let runs = document["runs"].as_array().unwrap();
1894        assert_eq!(runs.len(), 2);
1895        // Each run is told from the others, and the one that failed is not a clean one.
1896        assert_eq!(runs[0]["automationDetails"]["id"], "tmt/ant/");
1897        assert_eq!(runs[0]["invocations"][0]["executionSuccessful"], true);
1898        assert_eq!(runs[1]["automationDetails"]["id"], "tmt/bee/");
1899        assert_eq!(runs[1]["invocations"][0]["executionSuccessful"], false);
1900        assert_eq!(
1901            runs[1]["invocations"][0]["toolExecutionNotifications"][0]["message"]["text"],
1902            failed[0].1
1903        );
1904        assert_eq!(runs[1]["results"].as_array().unwrap().len(), 0);
1905        assert_eq!(runs[1]["tool"], runs[0]["tool"]);
1906        assert_eq!(runs[1]["properties"]["package"], "bee");
1907        // Only failures: still a document, with nothing passed off as analysed.
1908        let document: Value =
1909            serde_json::from_str(&format!("{:#}", workspace_sarif(&[], &failed))).unwrap();
1910        assert_eq!(document["runs"].as_array().unwrap().len(), 1);
1911    }
1912
1913    #[test]
1914    fn a_path_is_written_as_a_uri() {
1915        assert_eq!(sarif_uri("", "src/lib.rs"), "src/lib.rs");
1916        assert_eq!(
1917            sarif_uri("crates/a-b_c/", "src/x~1.rs"),
1918            "crates/a-b_c/src/x~1.rs"
1919        );
1920        // What a URI gives a meaning of its own, or does not allow, is written as bytes.
1921        assert_eq!(
1922            sarif_uri("my crate/", "a#b%c?.rs"),
1923            "my%20crate/a%23b%25c%3F.rs"
1924        );
1925        assert_eq!(sarif_uri("", "src/é.rs"), "src/%C3%A9.rs");
1926        assert_eq!(sarif_uri("", r#"a\b"c.rs"#), "a%5Cb%22c.rs");
1927        let report = Report {
1928            analysis: Analysis {
1929                package_path: "my crate/".into(),
1930                ..Analysis::default()
1931            },
1932            findings: vec![Finding::Survivor {
1933                at: Location {
1934                    file: "src/a b.rs".into(),
1935                    line: 1,
1936                    column: 1,
1937                    ..Location::default()
1938                },
1939                survivors: vec![],
1940                witness: None,
1941            }],
1942            ..Report::default()
1943        };
1944        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
1945        assert_eq!(
1946            sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]
1947                ["uri"],
1948            "my%20crate/src/a%20b.rs"
1949        );
1950    }
1951
1952    #[test]
1953    fn findings_sort_by_path_and_position_in_input_order_for_ties() {
1954        let mut report = Report {
1955            findings: [
1956                ("z.rs", 1, 1, "1"),
1957                ("é.rs", 1, 1, "2"),
1958                ("a.rs", 2, 1, "3"),
1959                ("a.rs", 1, 3, "4"),
1960                ("a.rs", 1, 3, "5"),
1961                ("a.rs", 1, 1, "6"),
1962            ]
1963            .into_iter()
1964            .map(|(file, line, column, id)| Finding::Survivor {
1965                at: Location {
1966                    file: file.into(),
1967                    line,
1968                    column,
1969                    id: id.into(),
1970                    ..Location::default()
1971                },
1972                survivors: vec![],
1973                witness: None,
1974            })
1975            .collect(),
1976            ..Report::default()
1977        };
1978        report.sort_findings();
1979        let ids: Vec<_> = report
1980            .findings
1981            .iter()
1982            .map(|finding| finding.at().id.as_str())
1983            .collect();
1984        assert_eq!(ids, ["6", "4", "5", "3", "1", "2"]);
1985    }
1986
1987    #[test]
1988    fn collapsed_code_matches_the_previous_format() {
1989        // Pairwise combinations of character set, whitespace and normalized width.
1990        for (charset, spacing, width) in [
1991            ("ascii", "none", 17),
1992            ("ascii", "split", 100),
1993            ("ascii", "surrounded", 101),
1994            ("multibyte", "split", 101),
1995            ("ascii", "none", 4096),
1996            ("multibyte", "none", 97),
1997            ("multibyte", "surrounded", 0),
1998            ("multibyte", "surrounded", 17),
1999            ("multibyte", "surrounded", 4096),
2000            ("ascii", "split", 17),
2001            ("multibyte", "none", 100),
2002            ("multibyte", "none", 101),
2003            ("ascii", "surrounded", 97),
2004            ("ascii", "surrounded", 100),
2005            ("multibyte", "split", 97),
2006            ("ascii", "none", 0),
2007            ("multibyte", "split", 4096),
2008        ] {
2009            let glyph = if charset == "ascii" { "x" } else { "🦀" };
2010            let code = match spacing {
2011                "none" => glyph.repeat(width),
2012                "surrounded" => format!("\t{}\u{2003}\r\n", glyph.repeat(width)),
2013                _ => format!(
2014                    "{}\u{2003}\r\n {}",
2015                    glyph.repeat(width / 2),
2016                    glyph.repeat(width - width / 2 - 1),
2017                ),
2018            };
2019            let normalized = code.split_whitespace().collect::<Vec<_>>().join(" ");
2020            let expected = if normalized.chars().count() > 100 {
2021                format!("{}...", normalized.chars().take(97).collect::<String>())
2022            } else {
2023                normalized
2024            };
2025            assert_eq!(one_line(&code), expected, "{charset} {spacing} {width}");
2026        }
2027
2028        // The last visible character can itself be the space between two words.
2029        let code = format!("{}\n{}", "x".repeat(96), "y".repeat(4096));
2030        assert_eq!(one_line(&code), format!("{} ...", "x".repeat(96)));
2031        let code = format!("{}\n{}", "x".repeat(100), " ".repeat(4096));
2032        assert_eq!(one_line(&code), "x".repeat(100));
2033    }
2034
2035    #[test]
2036    fn long_code_is_shortened() {
2037        let exactly_100 = "x".repeat(100);
2038        assert_eq!(one_line(&exactly_100), exactly_100);
2039        let shortened = one_line(&"x".repeat(101));
2040        assert_eq!(shortened, format!("{}...", "x".repeat(97)));
2041        assert_eq!(one_line("a\n   b"), "a b");
2042    }
2043
2044    #[test]
2045    fn timeout_rechecks_are_in_the_json_only_when_there_were_any() {
2046        let none = serde_json::to_value(Report::default()).unwrap();
2047        assert!(none.get("timeout_rechecks").is_none(), "{none}");
2048        let report = Report {
2049            timeout_rechecks: TimeoutRechecks {
2050                first_pass: 3,
2051                confirmed: 1,
2052                recovered: 2,
2053                unconfirmed: 0,
2054            },
2055            ..Report::default()
2056        };
2057        assert_eq!(
2058            serde_json::to_value(&report).unwrap()["timeout_rechecks"],
2059            serde_json::json!({"first_pass": 3, "confirmed": 1, "recovered": 2, "unconfirmed": 0})
2060        );
2061    }
2062
2063    #[test]
2064    fn at_most_three_survivors_are_listed_nearest_first() {
2065        let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
2066        let obs = Obs::default();
2067        let survivors = |min_shift, max_shift| {
2068            let gap = InputGap::Boundary {
2069                min_shift,
2070                max_shift,
2071                missing: vec![0],
2072            };
2073            match input_gap_finding("f.rs", &site, &gap, &obs, false) {
2074                Some(Finding::InputGap {
2075                    survivors,
2076                    survivor_count,
2077                    ..
2078                }) => (survivors, survivor_count),
2079                _ => panic!(),
2080            }
2081        };
2082        assert_eq!(
2083            survivors(-9, 9),
2084            (
2085                vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
2086                18
2087            )
2088        );
2089        assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
2090        assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
2091        assert_eq!(
2092            survivors(-2, 0),
2093            (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
2094        );
2095    }
2096
2097    #[test]
2098    fn text_report_is_exact() {
2099        let at = Location {
2100            file: "src/lib.rs".into(),
2101            line: 3,
2102            column: 9,
2103            code: "a >= b".into(),
2104            ..Location::default()
2105        };
2106        let below = Location {
2107            file: "src/lib.rs".into(),
2108            line: 7,
2109            column: 5,
2110            code: "s.reset();".into(),
2111            ..Location::default()
2112        };
2113        let report = Report {
2114            package: "p".into(),
2115            sites: 2,
2116            mutants_run: 1,
2117            suppressed: 2,
2118            findings: vec![
2119                Finding::InputGap {
2120                    at: at.clone(),
2121                    survivors: vec!["`a > b`".into()],
2122                    survivor_count: 4,
2123                    add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
2124                    observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
2125                    verified: false,
2126                },
2127                Finding::InputGap {
2128                    at: at.clone(),
2129                    survivors: vec!["`true`".into()],
2130                    survivor_count: 1,
2131                    add_tests: vec![],
2132                    observed: None,
2133                    verified: true,
2134                },
2135                Finding::AssertionGap {
2136                    at: Location { column: 4, ..at },
2137                    survivors: vec!["`!(a >= b)`".into()],
2138                    tests: vec!["t".into()],
2139                    effects: vec![],
2140                    effects_of: None,
2141                    witness: None,
2142                },
2143                Finding::AssertionGap {
2144                    at: below,
2145                    survivors: vec!["delete `s.reset();`".into()],
2146                    tests: vec!["t".into()],
2147                    effects: vec![
2148                        "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
2149                    ],
2150                    effects_of: None,
2151                    witness: None,
2152                },
2153            ],
2154            ..Report::default()
2155        };
2156        // Findings on one line form one block; a new line starts a new block.
2157        assert_eq!(
2158            render_text(&report, false),
2159            "INPUT GAP  src/lib.rs:3:9\n    a >= b\n\
2160             \x20 passes every test as: `a > b` (+3 more)  [from the trace, not re-run]\n\
2161             \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
2162             \x20 add a test with `a` equal to `b` (the original gives true)\n\
2163             \x20 + INPUT GAP  column 9\n    a >= b\n\
2164             \x20 passes every test as: `true`  [re-run: tests pass]\n\
2165             \x20 + ASSERTION GAP  column 4\n    a >= b\n\
2166             \x20 passes every test as: `!(a >= b)`\n\
2167             \x20 these tests run the changed code and still pass: t\n\
2168             \x20 add an assertion on what this code is responsible for\n\
2169             \n\
2170             ASSERTION GAP  src/lib.rs:7:5\n    s.reset();\n\
2171             \x20 passes every test as: delete `s.reset();`\n\
2172             \x20 these tests run the changed code and still pass: t\n\
2173             \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
2174             \n\
2175             p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
2176        );
2177        assert_eq!(
2178            render_text(
2179                &Report {
2180                    package: "q".into(),
2181                    ..Report::default()
2182                },
2183                false
2184            ),
2185            "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
2186        );
2187
2188        let mut in_repository = report.clone();
2189        in_repository.analysis.package_path = "crates/p/".into();
2190        in_repository.analysis.since = Some("abc".into());
2191        if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
2192            at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
2193        }
2194        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
2195        assert_eq!(
2196            results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
2197            "assertion_gap|src/lib.rs|f|s.reset();|0"
2198        );
2199        assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
2200        assert_eq!(sarif["version"], "2.1.0");
2201        let results = sarif["runs"][0]["results"].as_array().unwrap();
2202        assert_eq!(results.len(), 4);
2203        assert_eq!(results[0]["ruleId"], "input-gap");
2204        assert_eq!(results[3]["ruleId"], "assertion-gap");
2205        let location = &results[3]["locations"][0]["physicalLocation"];
2206        assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
2207        assert_eq!(
2208            (
2209                &location["region"]["startLine"],
2210                &location["region"]["startColumn"]
2211            ),
2212            (&serde_json::json!(7), &serde_json::json!(5))
2213        );
2214        assert!(
2215            results[3]["message"]["text"]
2216                .as_str()
2217                .unwrap()
2218                .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
2219        );
2220        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
2221            .as_array()
2222            .unwrap();
2223        assert_eq!(rules.len(), 3);
2224    }
2225
2226    #[test]
2227    fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
2228        let survivor = Finding::Survivor {
2229            at: Location {
2230                file: "src/lib.rs".into(),
2231                line: 2,
2232                column: 1,
2233                code: "const fn limit() -> u8".into(),
2234                ..Location::default()
2235            },
2236            survivors: vec!["the body of `limit` replaced by `0`".into()],
2237            witness: None,
2238        };
2239        assert_eq!(survivor.kind(), "survivor");
2240        assert_eq!(survivor.at().line, 2);
2241        assert_eq!(survivor.survivors().len(), 1);
2242        let report = Report {
2243            package: "p".into(),
2244            findings: vec![survivor],
2245            ..Report::default()
2246        };
2247        // Neither of the two gaps: it is counted and named as what it is.
2248        assert_eq!(
2249            render_text(&report, false),
2250            "SURVIVOR  src/lib.rs:2:1\n    const fn limit() -> u8\n\
2251             \x20 passes every test as: the body of `limit` replaced by `0`\n\
2252             \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\
2253             \n\
2254             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"
2255        );
2256        let json = serde_json::to_value(&report).unwrap();
2257        assert_eq!(json["findings"][0]["kind"], "survivor");
2258        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
2259        assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
2260        assert!(report.has_gaps());
2261    }
2262
2263    #[test]
2264    fn non_literal_inputs_in_words() {
2265        assert_eq!(
2266            input_for("a", "b", LiteralSide::None, 0),
2267            "`a` equal to `b`"
2268        );
2269        assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
2270        assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
2271        assert_eq!(
2272            input_for("18", "age", LiteralSide::Lhs(18), -1),
2273            "`age` = 19"
2274        );
2275    }
2276
2277    #[test]
2278    fn text_report_sections() {
2279        let at = Location {
2280            file: "src/lib.rs".into(),
2281            line: 3,
2282            column: 9,
2283            code: "s.check()?;".into(),
2284            ..Location::default()
2285        };
2286        let report = Report {
2287            mutants: None,
2288            package: "p".into(),
2289            analysis: Analysis::default(),
2290            audit: None,
2291            evaluation: None,
2292            sites: 4,
2293            skipped_sites: 1,
2294            skipped: vec![],
2295            unviable_mutants: 2,
2296            mutants_not_built: 0,
2297            mutants_not_evaluated: 0,
2298            mutants_run: 3,
2299            mutants_killed: 2,
2300            mutants_timed_out: 0,
2301            timeout_rechecks: TimeoutRechecks::default(),
2302            suppressed: 0,
2303            findings: vec![Finding::AssertionGap {
2304                at: at.clone(),
2305                survivors: vec!["delete `s.check()?;`".into()],
2306                tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
2307                effects: vec![],
2308                effects_of: None,
2309                witness: None,
2310            }],
2311            unreached: vec![at.clone()],
2312            unstable: vec![at],
2313        };
2314        let text = render_text(&report, false);
2315        assert!(
2316            text.contains("ASSERTION GAP  src/lib.rs:3:9\n    s.check()?;"),
2317            "{text}"
2318        );
2319        assert!(text.contains("tests::t4 (+2 more)"), "{text}");
2320        assert!(text.contains("UNSTABLE  src/lib.rs:3:9"), "{text}");
2321        assert!(!text.contains("UNREACHED"), "{text}");
2322        assert!(
2323            text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
2324            "{text}"
2325        );
2326        assert!(
2327            text.contains(", 2 mutants left out (they do not compile)\n"),
2328            "{text}"
2329        );
2330        assert!(text.contains("--show-unreached"), "{text}");
2331        let listed = render_text(&report, true);
2332        assert!(listed.contains("UNREACHED  src/lib.rs:3:9"));
2333        assert!(!listed.contains("--show-unreached"), "{listed}");
2334        let one_more = Report {
2335            findings: vec![Finding::InputGap {
2336                at: report.unreached[0].clone(),
2337                survivors: vec!["`a`".into()],
2338                survivor_count: 2,
2339                add_tests: vec![],
2340                observed: None,
2341                verified: true,
2342            }],
2343            ..report.clone()
2344        };
2345        assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
2346        let nothing_unreached = Report {
2347            unreached: vec![],
2348            ..report.clone()
2349        };
2350        assert!(!render_text(&nothing_unreached, false).contains("--show-unreached"));
2351        assert!(!Report::default().has_gaps());
2352    }
2353    #[test]
2354    fn unstable_predictions_alone_are_something_to_act_on() {
2355        let at = Location {
2356            file: "src/lib.rs".into(),
2357            line: 1,
2358            column: 1,
2359            code: "a > b".into(),
2360            ..Location::default()
2361        };
2362        assert!(!Report::default().has_gaps());
2363        assert!(
2364            Report {
2365                unstable: vec![at],
2366                ..Report::default()
2367            }
2368            .has_gaps()
2369        );
2370    }
2371
2372    #[test]
2373    fn what_counts_as_a_float_literal() {
2374        assert_eq!(float_literal("30.5"), Some(30.5));
2375        assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
2376        assert_eq!(float_literal("-1e3"), Some(-1000.0));
2377        // These parse as floats too, and are not literals: a variable called `inf`, and
2378        // forms Rust does not accept.
2379        for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
2380            assert_eq!(float_literal(text), None, "{text}");
2381        }
2382    }
2383
2384    #[test]
2385    fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
2386        // At 2^53 the next float below is 1 away and the next above 2 away.
2387        let survivors_of = |source: &str| {
2388            let site = site_of(source);
2389            let mut obs = Obs::of_f(-4.0);
2390            obs.merge(&Obs::of_f(4.0));
2391            let gap = InputGap::EqualNeverObserved {
2392                flipped: CmpOp::Ge,
2393                float_gap: obs.float_gap(),
2394            };
2395            match input_gap_finding("f.rs", &site, &gap, &obs, true) {
2396                Some(Finding::InputGap {
2397                    survivors,
2398                    survivor_count,
2399                    ..
2400                }) => (survivors, survivor_count),
2401                _ => panic!(),
2402            }
2403        };
2404        // Shifts of +2 and -2 are proposed. Both move the literal.
2405        assert_eq!(
2406            survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
2407            (
2408                vec![
2409                    "`x >= 9007199254740992.0`".to_string(),
2410                    "`x > 9007199254740994.0`".to_string(),
2411                    "`x > 9007199254740990.0`".to_string(),
2412                ],
2413                3
2414            )
2415        );
2416        // At 2^54 only the step down is a different number, and on the left of the
2417        // comparison the literal moves the other way.
2418        assert_eq!(
2419            survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
2420            (
2421                vec![
2422                    "`x >= 18014398509481984.0`".to_string(),
2423                    "`x > 1.8014398509481982e16`".to_string(),
2424                ],
2425                2
2426            )
2427        );
2428        assert_eq!(
2429            survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
2430            (
2431                vec![
2432                    "`18014398509481984.0 >= x`".to_string(),
2433                    "`1.8014398509481982e16 > x`".to_string(),
2434                ],
2435                2
2436            )
2437        );
2438        // With the literal on the left, the nearest values are those of the other side.
2439        let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
2440        let mut obs = Obs::of_f(-1.0);
2441        obs.merge(&Obs::of_f(2.0));
2442        let gap = InputGap::EqualNeverObserved {
2443            flipped: CmpOp::Ge,
2444            float_gap: obs.float_gap(),
2445        };
2446        let Some(Finding::InputGap { observed, .. }) =
2447            input_gap_finding("f.rs", &site, &gap, &obs, true)
2448        else {
2449            panic!()
2450        };
2451        assert_eq!(
2452            observed.as_deref(),
2453            Some(
2454                "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
2455            )
2456        );
2457        // Far above, neither does.
2458        assert_eq!(
2459            survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
2460            (vec!["`x >= 1e30`".to_string()], 1)
2461        );
2462    }
2463
2464    #[test]
2465    fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
2466        let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
2467            at: Location {
2468                file: "src/lib.rs".into(),
2469                line: 1,
2470                column: 1,
2471                code: "a < b".into(),
2472                ..Location::default()
2473            },
2474            survivors: survivors.iter().map(|s| s.to_string()).collect(),
2475            tests: vec!["tests::t".into()],
2476            effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
2477            effects_of: effects_of.map(str::to_string),
2478            witness: None,
2479        };
2480        // Of several mutants one was followed: the report says which.
2481        let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")));
2482        assert_eq!(
2483            body[2..],
2484            [
2485                "followed one of them through the tests: `a <= b`",
2486                "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
2487            ]
2488        );
2489        // A single mutant needs no saying, and nothing is said where nothing is known.
2490        for single in [
2491            gap(&["`a <= b`"], Some("`a <= b`")),
2492            gap(&["`a <= b`", "`a == b`"], None),
2493        ] {
2494            let body = finding_body(&single);
2495            assert_eq!(body.len(), 3, "{body:?}");
2496            assert!(body[2].starts_with("with the mutant"), "{body:?}");
2497        }
2498    }
2499
2500    #[test]
2501    fn an_audit_is_said_in_the_summary() {
2502        let mut report = Report {
2503            package: "p".into(),
2504            audit: Some(Audit {
2505                sampled: 2,
2506                survivors: 7,
2507                ..Audit::default()
2508            }),
2509            ..Report::default()
2510        };
2511        let text = render_text(&report, false);
2512        assert!(
2513            text.ends_with(
2514                "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
2515                 audit: recorded once more, the tests did the same\n"
2516            ),
2517            "{text}"
2518        );
2519        let audit = report.audit.as_mut().unwrap();
2520        audit.disagreements.push(Location {
2521            file: "src/lib.rs".into(),
2522            line: 3,
2523            column: 5,
2524            code: "x > 5".into(),
2525            ..Location::default()
2526        });
2527        audit.trace_differences.push(TraceDifference {
2528            binary: "p".into(),
2529            records: 4,
2530        });
2531        let text = render_text(&report, false);
2532        assert!(
2533            text.ends_with(
2534                "all tests, 1 failed one they had not been run against\n\
2535                 \x20 src/lib.rs:3:5  x > 5\n\
2536                 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
2537            ),
2538            "{text}"
2539        );
2540        // Mutants built from the source are said only where some were, with what differs.
2541        assert!(!text.contains("built from the source"), "{text}");
2542        let audit = report.audit.as_mut().unwrap();
2543        audit.rebuilt = 1;
2544        audit.not_compared = 1;
2545        let text = render_text(&report, false);
2546        assert!(
2547            text.contains(
2548                "\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"
2549            ),
2550            "{text}"
2551        );
2552        let audit = report.audit.as_mut().unwrap();
2553        audit.rebuilt = 5;
2554        audit.compared = 4;
2555        audit.source_disagreements.push(SourceDisagreement {
2556            at: Location {
2557                file: "src/lib.rs".into(),
2558                line: 9,
2559                column: 14,
2560                code: "note(asked)".into(),
2561                ..Location::default()
2562            },
2563            mutant: "the guard `note(asked)` replaced by `true`".into(),
2564            as_probe: "passes".into(),
2565            built: "fails".into(),
2566        });
2567        let text = render_text(&report, false);
2568        assert!(
2569            text.contains(
2570                "\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\
2571                 \x20 src/lib.rs:9:14  the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
2572            ),
2573            "{text}"
2574        );
2575        assert!(!render_text(&Report::default(), false).contains("audit"));
2576    }
2577
2578    #[test]
2579    fn lists_and_counts_at_their_limits() {
2580        let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
2581        assert_eq!(list(&items, 3), "a, b, c");
2582        assert_eq!(list(&items, 2), "a, b (+1 more)");
2583        assert_eq!(list(&items, 1), "a (+2 more)");
2584        let one = Report {
2585            package: "p".into(),
2586            suppressed: 1,
2587            unviable_mutants: 1,
2588            ..Report::default()
2589        };
2590        assert!(
2591            render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
2592            "{}",
2593            render_text(&one, false)
2594        );
2595        assert!(!render_text(&Report::default(), false).contains("left out"));
2596        assert!(!render_text(&one, false).contains("--rebuild"));
2597        assert!(!render_text(&one, false).contains("not evaluated"));
2598        let at_top = Report {
2599            mutants_not_evaluated: 1,
2600            ..Report::default()
2601        };
2602        assert!(
2603            render_text(&at_top, false).ends_with(
2604                "\n(1 mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n"
2605            ),
2606            "{}",
2607            render_text(&at_top, false)
2608        );
2609        let quick = Report {
2610            mutants_not_built: 1,
2611            ..Report::default()
2612        };
2613        assert!(
2614            render_text(&quick, false)
2615                .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
2616            "{}",
2617            render_text(&quick, false)
2618        );
2619        let slow = Report {
2620            mutants_run: 5,
2621            mutants_killed: 4,
2622            mutants_timed_out: 2,
2623            ..Report::default()
2624        };
2625        assert!(
2626            render_text(&slow, false)
2627                .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
2628            "{}",
2629            render_text(&slow, false)
2630        );
2631        assert!(!render_text(&one, false).contains("time limit"));
2632        let once = Report {
2633            mutants_timed_out: 1,
2634            ..slow.clone()
2635        };
2636        assert!(
2637            render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
2638            "{}",
2639            render_text(&once, false)
2640        );
2641        assert!(
2642            render_text(&one, false).contains(", 1 findings suppressed"),
2643            "{}",
2644            render_text(&one, false)
2645        );
2646        assert!(!render_text(&Report::default(), false).contains("suppressed"));
2647    }
2648
2649    #[test]
2650    fn findings_are_put_in_reading_order() {
2651        let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
2652            at: Location {
2653                file: file.into(),
2654                line,
2655                column,
2656                code: "x".into(),
2657                ..Location::default()
2658            },
2659            survivors: vec![survivor.into()],
2660            tests: vec![],
2661            effects: vec![],
2662            effects_of: None,
2663            witness: None,
2664        };
2665        let mut report = Report {
2666            findings: vec![
2667                gap("src/b.rs", 1, 1, "b"),
2668                gap("src/a.rs", 9, 5, "statement"),
2669                gap("src/a.rs", 7, 2, "above it"),
2670                gap("src/a.rs", 9, 5, "its operator"),
2671                gap("src/a.rs", 9, 3, "left of both"),
2672            ],
2673            ..Report::default()
2674        };
2675        report.sort_findings();
2676        let order: Vec<&str> = report
2677            .findings
2678            .iter()
2679            .map(|f| match f {
2680                Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
2681                _ => panic!(),
2682            })
2683            .collect();
2684        // Findings at one position keep the order they were made in.
2685        assert_eq!(
2686            order,
2687            ["above it", "left of both", "statement", "its operator", "b"]
2688        );
2689    }
2690    #[test]
2691    fn second_replacements_guards_fields_and_bodies_in_words() {
2692        let all = |src: &str| discover(src, 0).unwrap().sites;
2693        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
2694        assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
2695        let Some(Finding::InputGap {
2696            survivors,
2697            add_tests,
2698            ..
2699        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
2700        else {
2701            panic!()
2702        };
2703        assert_eq!(survivors, ["`total * fee`"]);
2704        assert_eq!(
2705            add_tests,
2706            ["operands for which `total + fee` and `total * fee` differ"]
2707        );
2708        let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
2709        let arith: Vec<&Site> = sites
2710            .iter()
2711            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
2712            .collect();
2713        assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
2714        assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
2715        let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
2716        assert_eq!(
2717            arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
2718            None
2719        );
2720        // A shift has one replacement: no second finding.
2721        assert_eq!(
2722            arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
2723            None
2724        );
2725
2726        let sites = all("fn f(k: Option<i32>, base: O) -> O { \
2727             let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
2728        let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
2729        let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
2730        assert_eq!(
2731            describe(guard, Mutation::Const(true)),
2732            "the guard `n > 1` replaced by `true`"
2733        );
2734        assert_eq!(
2735            guard_gap_finding("f.rs", guard, false, true),
2736            Finding::InputGap {
2737                at: location("f.rs", guard),
2738                survivors: vec!["the guard `n > 1` replaced by `false`".into()],
2739                survivor_count: 1,
2740                add_tests: vec!["a case where the guard `n > 1` is true".into()],
2741                observed: None,
2742                verified: true,
2743            }
2744        );
2745        let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
2746        assert_eq!(describe(neg, Mutation::Delete), "`n`");
2747        let field = of(&|k| matches!(k, SiteKind::Field { .. }));
2748        assert_eq!(
2749            describe(field, Mutation::Delete),
2750            "without the field `depth: d` (it is then `(base).depth`)"
2751        );
2752        let body = of(&|k| matches!(k, SiteKind::Body { .. }));
2753        assert_eq!(
2754            describe(body, Mutation::Delete),
2755            "the body of `f` replaced by `Default::default()`"
2756        );
2757        assert_eq!(
2758            location("f.rs", body).code,
2759            "fn f(k: Option<i32>, base: O) -> O"
2760        );
2761    }
2762}