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