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 #[serde(skip_serializing_if = "Option::is_none")]
63 witness: Option<VerifiedWitness>,
64 },
65 Survivor {
69 #[serde(flatten)]
70 at: Location,
71 survivors: Vec<String>,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 witness: Option<VerifiedWitness>,
74 #[serde(skip_serializing_if = "Option::is_none")]
77 change_since: Option<String>,
78 #[serde(skip_serializing_if = "Option::is_none")]
80 advice: Option<String>,
81 },
82}
83
84#[derive(Clone, Debug, PartialEq, Serialize)]
85pub struct VerifiedWitness {
86 pub call: String,
87 pub original: String,
88 pub mutant: String,
89 pub assertion: String,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub guidance: Option<String>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub individually_killed: Option<usize>,
94 #[serde(skip_serializing_if = "Option::is_none")]
97 pub in_test: Option<String>,
98 #[serde(skip_serializing_if = "Option::is_none")]
100 pub in_test_line: Option<usize>,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 pub in_test_column: Option<usize>,
103}
104
105impl Finding {
106 pub fn at(&self) -> &Location {
107 let (Finding::InputGap { at, .. }
108 | Finding::AssertionGap { at, .. }
109 | Finding::Survivor { at, .. }) = self;
110 at
111 }
112
113 pub fn at_mut(&mut self) -> &mut Location {
114 let (Finding::InputGap { at, .. }
115 | Finding::AssertionGap { at, .. }
116 | Finding::Survivor { at, .. }) = self;
117 at
118 }
119
120 pub fn survivors(&self) -> &[String] {
121 let (Finding::InputGap { survivors, .. }
122 | Finding::AssertionGap { survivors, .. }
123 | Finding::Survivor { survivors, .. }) = self;
124 survivors
125 }
126
127 pub(crate) fn set_witness(&mut self, evidence: VerifiedWitness) {
128 match self {
129 Self::AssertionGap { witness, .. } | Self::Survivor { witness, .. } => {
130 if witness.is_none() {
131 *witness = Some(evidence);
132 }
133 }
134 Self::InputGap { .. } => {}
135 }
136 }
137
138 pub fn kind(&self) -> &'static str {
140 match self {
141 Finding::InputGap { .. } => "input_gap",
142 Finding::AssertionGap { .. } => "assertion_gap",
143 Finding::Survivor { .. } => "survivor",
144 }
145 }
146}
147
148#[derive(Clone, Debug, Default, PartialEq, Serialize)]
150pub struct CargoConfig {
151 pub features: Vec<String>,
152 pub all_features: bool,
153 pub no_default_features: bool,
154 pub locked: bool,
155}
156
157#[derive(Clone, Debug, Default, PartialEq, Serialize)]
159pub struct Nextest {
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub profile: Option<String>,
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
165pub struct Shard {
166 pub index: usize,
167 pub count: usize,
168 pub round_robin: bool,
169}
170
171#[derive(Clone, Debug, Default, PartialEq, Serialize)]
172pub struct Analysis {
173 pub package_path: String,
175 pub since: Option<String>,
177 pub lines: Vec<String>,
179 pub tests_of: Vec<String>,
181 pub cargo: CargoConfig,
182 pub opt_level: Option<u8>,
183 #[serde(skip_serializing_if = "Option::is_none")]
184 pub timeout_seconds: Option<u64>,
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub baseline_jobs: Option<usize>,
187 pub timeout_recheck: &'static str,
188 #[serde(skip_serializing_if = "Option::is_none")]
189 pub wrapper_grace_seconds: Option<u64>,
190 pub rebuild: bool,
192 pub verified: bool,
194 pub doc_tests: bool,
195 #[serde(skip_serializing_if = "std::ops::Not::not")]
196 pub source_only: bool,
197 #[serde(skip_serializing_if = "std::ops::Not::not")]
198 pub literal_operators: bool,
199 #[serde(skip_serializing_if = "Option::is_none")]
200 pub shard: Option<Shard>,
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub nextest: Option<Nextest>,
203 #[serde(skip_serializing_if = "Vec::is_empty")]
204 pub error_values: Vec<String>,
205 #[serde(skip_serializing_if = "Option::is_none")]
206 pub test_selection: Option<TestSelection>,
207 #[serde(skip_serializing_if = "std::ops::Not::not")]
208 pub git_index: bool,
209 #[serde(skip_serializing_if = "Vec::is_empty")]
210 pub copy_fixtures: Vec<PathBuf>,
211 #[serde(skip_serializing_if = "Vec::is_empty")]
212 pub copy_fixture_excludes: Vec<PathBuf>,
213 #[serde(skip_serializing_if = "Vec::is_empty")]
214 pub output_fixtures: Vec<crate::output_fixture::Fixture>,
215 #[serde(skip_serializing_if = "Option::is_none")]
216 pub checkpoint: Option<PathBuf>,
217}
218
219#[derive(Clone, Debug, Default, PartialEq, Serialize)]
220pub struct TestSelection {
221 pub build_scope: TestBuildScope,
222 pub wrapper: Option<String>,
223 pub tests: Vec<String>,
224}
225
226#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
227#[serde(rename_all = "snake_case")]
228pub enum TestBuildScope {
229 #[default]
230 PackageWide,
231 SelectedTargets,
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
235#[serde(rename_all = "snake_case")]
236pub enum Evaluation {
237 NoSites,
238 NoMutantsExecuted,
239}
240
241#[derive(Clone, Debug, Default, PartialEq, Serialize)]
242pub struct TimeoutRechecks {
243 pub first_pass: usize,
244 pub confirmed: usize,
245 pub recovered: usize,
246 pub unconfirmed: usize,
247}
248
249impl TimeoutRechecks {
250 fn is_empty(&self) -> bool {
251 self.first_pass == 0
252 }
253}
254
255#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
256#[serde(rename_all = "snake_case")]
257pub enum SkipReason {
258 ProbeCompileError,
259 ProbeReplacedBySourceRebuild,
260 RequiresSourceRebuild,
261 SourceNotBuilt,
262 UnparseableSource,
263}
264
265#[derive(Clone, Debug, PartialEq, Serialize)]
266pub struct SkippedSite {
267 #[serde(flatten)]
268 pub at: Location,
269 pub end_line: usize,
270 pub end_column: usize,
271 pub reason: SkipReason,
272 #[serde(skip_serializing_if = "Option::is_none")]
273 pub diagnostic: Option<String>,
274}
275
276impl SkippedSite {
277 pub(crate) fn new(
278 at: Location,
279 (end_line, end_column): (usize, usize),
280 reason: SkipReason,
281 diagnostic: Option<String>,
282 ) -> Self {
283 Self {
284 at,
285 end_line,
286 end_column,
287 reason,
288 diagnostic,
289 }
290 }
291}
292
293fn is_zero_usize(value: &usize) -> bool {
294 *value == 0
295}
296
297#[derive(Clone, Debug, Default, PartialEq, Serialize)]
299pub struct Audit {
300 pub sampled: usize,
302 pub survivors: usize,
304 #[serde(skip_serializing_if = "is_zero_usize")]
306 pub not_audited: usize,
307 pub disagreements: Vec<Location>,
310 pub trace_differences: Vec<TraceDifference>,
313 pub rebuilt: usize,
315 pub compared: usize,
317 pub not_compared: usize,
320 pub source_disagreements: Vec<SourceDisagreement>,
322}
323
324#[derive(Clone, Debug, Default, PartialEq, Serialize)]
326pub struct SourceDisagreement {
327 #[serde(flatten)]
328 pub at: Location,
329 pub mutant: String,
330 pub as_probe: String,
332 pub built: String,
333}
334
335#[derive(Clone, Debug, Default, PartialEq, Serialize)]
336pub struct TraceDifference {
337 pub binary: String,
338 pub records: usize,
339 #[serde(skip_serializing_if = "std::ops::Not::not")]
340 pub rerun_failed: bool,
341}
342
343#[derive(Clone, Debug, PartialEq, Serialize)]
345pub struct CandidateEdit {
346 pub file: String,
347 pub line: usize,
348 pub column: usize,
349 pub start: usize,
350 pub end: usize,
351 pub before: String,
352 pub replacement: String,
353}
354
355#[derive(Clone, Debug, PartialEq, Serialize)]
356pub struct Candidate {
357 pub what: String,
358 pub into: String,
359 pub requires_rebuild: bool,
360 pub edits: Vec<CandidateEdit>,
361}
362
363#[derive(Clone, Debug, Default, PartialEq, Serialize)]
364pub struct Report {
365 pub package: String,
366 #[serde(skip_serializing_if = "Option::is_none")]
367 pub mutants: Option<Vec<Candidate>>,
368 pub analysis: Analysis,
369 #[serde(skip_serializing_if = "Option::is_none")]
371 pub audit: Option<Audit>,
372 #[serde(skip_serializing_if = "Option::is_none")]
373 pub evaluation: Option<Evaluation>,
374 pub sites: usize,
375 pub skipped_sites: usize,
377 #[serde(skip_serializing_if = "Vec::is_empty")]
378 pub skipped: Vec<SkippedSite>,
379 pub unviable_mutants: usize,
382 pub mutants_not_built: usize,
384 pub mutants_not_evaluated: usize,
387 pub mutants_not_compiled: usize,
390 pub mutants_run: usize,
391 pub mutants_killed: usize,
392 pub mutants_timed_out: usize,
394 #[serde(skip_serializing_if = "TimeoutRechecks::is_empty")]
395 pub timeout_rechecks: TimeoutRechecks,
396 pub findings: Vec<Finding>,
397 pub suppressed: usize,
399 pub unreached: Vec<Location>,
401 pub unstable: Vec<Location>,
403 #[serde(skip_serializing_if = "Vec::is_empty")]
406 pub weakened: Vec<Location>,
407}
408
409impl Report {
410 pub(crate) fn record_evaluation(&mut self) {
411 self.evaluation = match (self.sites, self.mutants_run, self.skipped.is_empty()) {
412 (_, 1.., _) => None,
413 (0, 0, true) => Some(Evaluation::NoSites),
414 _ => Some(Evaluation::NoMutantsExecuted),
415 };
416 }
417
418 pub fn sort_findings(&mut self) {
421 self.findings.sort_by(|a, b| {
422 let (a, b) = (a.at(), b.at());
423 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
424 });
425 }
426
427 pub fn has_gaps(&self) -> bool {
430 !self.findings.is_empty()
431 || !self.unstable.is_empty()
432 || self.audit.as_ref().is_some_and(|audit| {
433 !audit.disagreements.is_empty()
434 || !audit.source_disagreements.is_empty()
435 || !audit.trace_differences.is_empty()
436 })
437 }
438}
439
440pub fn location(file: &str, site: &Site) -> Location {
441 Location {
442 file: file.to_string(),
443 line: site.line,
444 column: site.column,
445 code: one_line(&site.text),
446 ..Location::default()
447 }
448}
449
450pub(crate) fn short_revision(revision: &str) -> &str {
452 let full = revision.len() >= 40 && revision.bytes().all(|byte| byte.is_ascii_hexdigit());
453 if full { &revision[..12] } else { revision }
454}
455
456pub(crate) fn one_line(code: &str) -> String {
457 const LIMIT: usize = 100;
458 const ELLIPSIS: &str = "...";
459 const PREFIX: usize = LIMIT - ELLIPSIS.len();
460
461 if code.len() <= 4 * LIMIT {
464 let mut words = code.split_whitespace();
465 let Some(first) = words.next() else {
466 return String::new();
467 };
468 let mut output = String::with_capacity(code.len());
469 output.push_str(first);
470 for word in words {
471 output.push(' ');
472 output.push_str(word);
473 }
474 if output.len() > LIMIT && output.chars().count() > LIMIT {
476 let cut = output.char_indices().nth(PREFIX).unwrap().0;
477 output.truncate(cut);
478 output.push_str(ELLIPSIS);
479 }
480 return output;
481 }
482
483 let mut output = String::with_capacity(LIMIT);
484 let mut width = 0;
485 let mut shortened_at = 0;
486 let mut separated = false;
487 for ch in code.chars() {
488 if ch.is_whitespace() {
489 separated = width != 0;
490 continue;
491 }
492 for ch in [separated.then_some(' '), Some(ch)].into_iter().flatten() {
493 if width == LIMIT {
494 output.truncate(shortened_at);
495 output.push_str(ELLIPSIS);
496 return output;
497 }
498 output.push(ch);
499 width += 1;
500 if width == PREFIX {
501 shortened_at = output.len();
502 }
503 }
504 separated = false;
505 }
506 output
507}
508
509fn float_literal(text: &str) -> Option<f64> {
511 let text = text.trim().replace('_', "");
512 let text = text
513 .strip_suffix("f32")
514 .or(text.strip_suffix("f64"))
515 .unwrap_or(&text);
516 let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
517 && text
518 .chars()
519 .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
520 if looks_numeric {
521 text.parse().ok()
522 } else {
523 None
524 }
525}
526
527fn show_float(v: f64) -> String {
530 format!("{v:?}")
531}
532
533pub fn describe(site: &Site, m: Mutation) -> String {
535 match &site.kind {
536 SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
537 SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
538 SiteKind::Guard { .. } => match m {
539 Mutation::Const(value) => {
540 format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
541 }
542 _ => format!("another guard than `{}`", one_line(&site.text)),
543 },
544 SiteKind::Field {
545 from_base: Some(from_base),
546 ..
547 } => format!(
548 "without the field `{}` (it is then `{from_base}`)",
549 one_line(&site.text)
550 ),
551 SiteKind::Field {
552 from_base: None, ..
553 } => format!("without the field `{}`", one_line(&site.text)),
554 SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
555 SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
556 SiteKind::Return { name, option, .. } => match (m, option) {
557 (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
558 (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
559 _ => format!("`{name}` returning something else"),
560 },
561 SiteKind::Range {
562 inclusive,
563 lhs,
564 rhs,
565 ..
566 } => {
567 let dots = if *inclusive { ".." } else { "..=" };
568 format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
569 }
570 SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
571 SiteKind::MinMax {
572 max,
573 receiver,
574 argument,
575 ..
576 } => {
577 let other = if *max { "min" } else { "max" };
578 format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
579 }
580 SiteKind::SliceEnd {
581 first, receiver, ..
582 } => {
583 let other = if *first { "last" } else { "first" };
584 format!("`{}.{other}()`", one_line(receiver))
585 }
586 SiteKind::Logic { and, lhs, rhs, .. } => {
587 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
588 match m {
589 Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
592 Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
593 Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
594 _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
595 }
596 }
597 SiteKind::Arith {
598 op,
599 assign,
600 lhs,
601 rhs,
602 ..
603 } => {
604 let eq = if *assign { "=" } else { "" };
605 let other = match m {
606 Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
607 _ => op.swapped(),
608 };
609 format!(
610 "`{} {}{eq} {}`",
611 one_line(lhs),
612 other.symbol(),
613 one_line(rhs)
614 )
615 }
616 SiteKind::Cmp {
617 op,
618 lhs,
619 rhs,
620 literal,
621 ..
622 } => {
623 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
624 let sym = op.symbol();
625 match m {
626 Mutation::Const(c) => format!("`{c}`"),
627 Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
628 Mutation::Shift(d) => match literal {
629 LiteralSide::Rhs(k) => format!("`{lhs} {sym} {}`", k + d),
630 LiteralSide::Lhs(k) => format!("`{} {sym} {rhs}`", k - d),
632 LiteralSide::None => match (op, d) {
633 (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
634 (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
635 (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
636 (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
637 (_, d) if d > 0 => format!("`{lhs} {sym} {rhs} + {d}` (without overflow)"),
641 (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
642 },
643 },
644 Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
645 (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
646 (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
647 _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
649 _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
650 },
651 _ => format!("`!({lhs} {sym} {rhs})`"),
652 }
653 }
654 }
655}
656
657fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
659 match (literal, d) {
660 (LiteralSide::Rhs(k), d) => format!("`{lhs}` = {}", k + d),
661 (LiteralSide::Lhs(k), d) => format!("`{rhs}` = {}", k - d),
662 (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
663 (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
665 (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
666 }
667}
668
669fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
670 if !obs.valued() {
671 return None;
672 }
673 let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
674 .into_iter()
675 .flatten()
676 .collect();
677 let text = match literal {
678 LiteralSide::Rhs(k) => {
679 let values: Vec<String> = ds.iter().map(|d| (k + d).to_string()).collect();
680 format!("`{lhs}` = {}", values.join(", "))
681 }
682 LiteralSide::Lhs(k) => {
683 let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
684 values.sort();
685 let values: Vec<String> = values.iter().map(i128::to_string).collect();
686 format!("`{rhs}` = {}", values.join(", "))
687 }
688 LiteralSide::None => {
689 let values: Vec<String> = ds.iter().map(i128::to_string).collect();
690 format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
691 }
692 };
693 Some(format!("nearest values the tests passed: {text}"))
694}
695
696pub fn input_gap_finding(
699 file: &str,
700 site: &Site,
701 gap: &InputGap,
702 obs: &Obs,
703 verified: bool,
704) -> Option<Finding> {
705 let SiteKind::Cmp {
706 op,
707 lhs,
708 rhs,
709 literal,
710 ..
711 } = &site.kind
712 else {
713 return None;
714 };
715 let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
716 let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
719 (None, Some(k)) => k + d != k,
720 (Some(k), None) => k - d != k,
721 _ => true,
722 };
723 let survivors: Vec<String> = gap
724 .survivors()
725 .into_iter()
726 .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
727 .map(|m| describe(site, m))
728 .collect();
729 let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
730 let (survivor_count, add_tests) = match gap {
731 InputGap::Unreached => return None,
732 InputGap::OneSided { always } => (
733 1,
734 vec![format!(
735 "an input that makes `{}` {}",
736 one_line(&site.text),
737 !always
738 )],
739 ),
740 InputGap::EqualNeverObserved { flipped, float_gap } => {
741 if let Some((lo, hi)) = float_gap {
742 observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
743 (None, Some(k)) => format!(
744 "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
745 show_float(k + lo),
746 show_float(k + hi)
747 ),
748 (Some(k), None) => format!(
749 "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
750 show_float(k - hi),
751 show_float(k - lo)
752 ),
753 _ => format!(
754 "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
755 show_float(*lo),
756 show_float(*hi)
757 ),
758 });
759 }
760 (
761 survivors.len() as u128,
762 vec![format!(
763 "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
764 op.eval_d(0),
765 flipped.eval_d(0)
766 )],
767 )
768 }
769 InputGap::Boundary {
770 min_shift,
771 max_shift,
772 missing,
773 same,
774 } => {
775 let add = missing
776 .iter()
777 .map(|d| {
778 format!(
779 "{} (the original gives {})",
780 input_for(&lhs_text, &rhs_text, *literal, *d),
781 op.eval_d(*d)
782 )
783 })
784 .collect();
785 (((max_shift - min_shift) - (same.1 - same.0)) as u128, add)
788 }
789 };
790 Some(Finding::InputGap {
791 at: location(file, site),
792 survivors,
793 survivor_count,
794 add_tests,
795 observed,
796 verified,
797 })
798}
799
800pub fn logic_gap_finding(
802 file: &str,
803 site: &Site,
804 gap: LogicGap,
805 verified: bool,
806) -> Option<Finding> {
807 let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
808 return None;
809 };
810 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
811 let (mutation, add) = match (gap, and) {
812 (LogicGap::Unreached, _) => return None,
813 (LogicGap::RhsNeverDecides, true) => (
814 Mutation::LogicDropRhs,
815 format!("a case where `{lhs}` is true and `{rhs}` is false"),
816 ),
817 (LogicGap::RhsNeverDecides, false) => (
818 Mutation::LogicDropRhs,
819 format!("a case where `{lhs}` is false and `{rhs}` is true"),
820 ),
821 (LogicGap::LhsNeverDecides, true) => (
822 Mutation::LogicDropLhs,
823 format!("a case where `{lhs}` is false"),
824 ),
825 (LogicGap::LhsNeverDecides, false) => (
826 Mutation::LogicDropLhs,
827 format!("a case where `{lhs}` is true"),
828 ),
829 };
830 Some(Finding::InputGap {
831 at: location(file, site),
832 survivors: vec![describe(site, mutation)],
833 survivor_count: 1,
834 add_tests: vec![add],
835 observed: None,
836 verified,
837 })
838}
839
840pub fn slice_end_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
842 let SiteKind::SliceEnd { receiver, .. } = &site.kind else {
843 return None;
844 };
845 Some(Finding::InputGap {
846 at: location(file, site),
847 survivors: vec![describe(site, Mutation::OtherEnd)],
848 survivor_count: 1,
849 add_tests: vec![format!(
850 "`{}` with two or more elements, the first different from the last",
851 one_line(receiver)
852 )],
853 observed: None,
854 verified,
855 })
856}
857
858pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
860 let SiteKind::MinMax {
861 receiver, argument, ..
862 } = &site.kind
863 else {
864 return None;
865 };
866 Some(Finding::InputGap {
867 at: location(file, site),
868 survivors: vec![describe(site, Mutation::MinMax)],
869 survivor_count: 1,
870 add_tests: vec![format!(
871 "`{}` different from `{}`",
872 one_line(receiver),
873 one_line(argument)
874 )],
875 observed: None,
876 verified,
877 })
878}
879
880pub fn return_gap_finding(
882 file: &str,
883 site: &Site,
884 always: bool,
885 verified: bool,
886) -> Option<Finding> {
887 let SiteKind::Return { name, option, .. } = &site.kind else {
888 return None;
889 };
890 let other = match (option, always) {
891 (None, always) => format!("{}", !always),
892 (Some(_), false) => "`Some`".to_string(),
893 (Some(_), true) => "`None`".to_string(),
894 };
895 Some(Finding::InputGap {
896 at: location(file, site),
897 survivors: vec![describe(site, Mutation::Const(always))],
898 survivor_count: 1,
899 add_tests: vec![format!("a case where `{name}` returns {other}")],
900 observed: None,
901 verified,
902 })
903}
904
905pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
907 Finding::InputGap {
908 at: location(file, site),
909 survivors: vec![describe(site, Mutation::Const(always))],
910 survivor_count: 1,
911 add_tests: vec![format!(
912 "a case where the guard `{}` is {}",
913 one_line(&site.text),
914 !always
915 )],
916 observed: None,
917 verified,
918 }
919}
920
921pub fn arith_gap_finding(
924 file: &str,
925 site: &Site,
926 mutation: Mutation,
927 verified: bool,
928) -> Option<Finding> {
929 let SiteKind::Arith {
930 op,
931 assign,
932 lhs,
933 rhs,
934 ..
935 } = &site.kind
936 else {
937 return None;
938 };
939 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
940 let eq = if *assign { "=" } else { "" };
941 let other = match mutation {
942 Mutation::ArithSwap2 => op.second(*assign)?,
943 _ => op.swapped(),
944 };
945 let add = match (op, other) {
946 (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
947 format!("`{rhs}` other than 0")
948 }
949 _ => format!(
950 "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
951 op.symbol(),
952 other.symbol()
953 ),
954 };
955 Some(Finding::InputGap {
956 at: location(file, site),
957 survivors: vec![describe(site, mutation)],
958 survivor_count: 1,
959 add_tests: vec![add],
960 observed: None,
961 verified,
962 })
963}
964
965pub fn render_sarif(report: &Report) -> String {
967 serde_json::to_string_pretty(&sarif_document(vec![sarif_run(report)]))
968 .expect("JSON values serialise")
969}
970
971#[doc(hidden)]
977pub fn workspace_sarif(reports: &[Report], failed: &[(String, String)]) -> impl std::fmt::Display {
978 let category = |package: &str| serde_json::json!({ "id": format!("tmt/{package}/") });
979 let mut runs: Vec<serde_json::Value> = reports
980 .iter()
981 .map(|report| {
982 let mut run = sarif_run(report);
983 run["properties"]["package"] = serde_json::json!(report.package);
984 run["automationDetails"] = category(&report.package);
985 run["invocations"] = serde_json::json!([{ "executionSuccessful": true }]);
986 run
987 })
988 .collect();
989 for (package, error) in failed {
990 runs.push(serde_json::json!({
991 "tool": sarif_tool(),
992 "automationDetails": category(package),
993 "invocations": [{
994 "executionSuccessful": false,
995 "toolExecutionNotifications": [{
996 "level": "error",
997 "message": { "text": error },
998 }],
999 }],
1000 "properties": { "package": package },
1001 "results": [],
1002 }));
1003 }
1004 sarif_document(runs)
1005}
1006
1007fn sarif_uri(prefix: &str, file: &str) -> String {
1011 sarif_uri_for(prefix, file, cfg!(windows))
1012}
1013
1014fn sarif_uri_for(prefix: &str, file: &str, backslash_is_separator: bool) -> String {
1015 let mut uri = String::new();
1016 for byte in prefix.bytes().chain(file.bytes()) {
1017 let byte = if backslash_is_separator && byte == b'\\' {
1018 b'/'
1019 } else {
1020 byte
1021 };
1022 match byte {
1023 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1024 uri.push(byte as char)
1025 }
1026 _ => uri.push_str(&format!("%{byte:02X}")),
1027 }
1028 }
1029 uri
1030}
1031
1032fn sarif_tool() -> serde_json::Value {
1033 serde_json::json!({ "driver": {
1034 "name": "tmt",
1035 "rules": [
1036 { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
1037 { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
1038 { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } },
1039 { "id": "unstable-prediction", "shortDescription": { "text": "A predicted survivor failed when re-run; tests may be non-deterministic" } },
1040 { "id": "weakened-test", "shortDescription": { "text": "Tests since the base revision stopped catching a mutant in unchanged code" } },
1041 { "id": "audit-disagreement", "shortDescription": { "text": "Audit found a mismatch between selective/probe results and full/source execution" } }
1042 ]
1043 } })
1044}
1045
1046fn sarif_document(runs: Vec<serde_json::Value>) -> serde_json::Value {
1047 let mut document = serde_json::json!({
1048 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1049 "version": "2.1.0",
1050 });
1051 document["runs"] = serde_json::Value::Array(runs);
1052 document
1053}
1054
1055fn sarif_run(report: &Report) -> serde_json::Value {
1056 let prefix = report.analysis.package_path.as_str();
1057 let mut results: Vec<serde_json::Value> = report
1058 .findings
1059 .iter()
1060 .map(|finding| {
1061 let (kind, at) = finding_parts(finding);
1062 let rule = match kind {
1063 "INPUT GAP" => "input-gap",
1064 "ASSERTION GAP" => "assertion-gap",
1065 _ => "survivor",
1066 };
1067 let text = format!("`{}`: {}", at.code, finding_body(finding).join("; "));
1068 serde_json::json!({
1069 "ruleId": rule,
1070 "level": "warning",
1071 "message": { "text": text },
1072 "partialFingerprints": { "tmtFindingId/v2": at.id },
1074 "locations": [{
1075 "physicalLocation": {
1076 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1077 "region": { "startLine": at.line, "startColumn": at.column }
1078 }
1079 }]
1080 })
1081 })
1082 .collect();
1083 for at in &report.unstable {
1084 results.push(serde_json::json!({
1085 "ruleId": "unstable-prediction",
1086 "level": "error",
1087 "message": {
1088 "text": format!(
1089 "`{}`: trace predicted a survivor, but the re-run failed (tests may not be deterministic)",
1090 at.code
1091 )
1092 },
1093 "locations": [{
1094 "physicalLocation": {
1095 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1096 "region": { "startLine": at.line, "startColumn": at.column }
1097 }
1098 }]
1099 }));
1100 }
1101 for at in &report.weakened {
1102 results.push(serde_json::json!({
1103 "ruleId": "weakened-test",
1104 "level": "warning",
1105 "message": {
1106 "text": format!(
1107 "`{}`: mutant in unchanged code now survives after test changes",
1108 at.code
1109 )
1110 },
1111 "locations": [{
1112 "physicalLocation": {
1113 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1114 "region": { "startLine": at.line, "startColumn": at.column }
1115 }
1116 }]
1117 }));
1118 }
1119 if let Some(audit) = &report.audit {
1120 for at in &audit.disagreements {
1121 results.push(serde_json::json!({
1122 "ruleId": "audit-disagreement",
1123 "level": "error",
1124 "message": {
1125 "text": format!(
1126 "`{}`: survived selective tests, but failed when audited against all tests",
1127 at.code
1128 )
1129 },
1130 "locations": [{
1131 "physicalLocation": {
1132 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1133 "region": { "startLine": at.line, "startColumn": at.column }
1134 }
1135 }]
1136 }));
1137 }
1138 for diff in &audit.source_disagreements {
1139 results.push(serde_json::json!({
1140 "ruleId": "audit-disagreement",
1141 "level": "error",
1142 "message": {
1143 "text": format!(
1144 "`{}` ({}): {} as a probe, {} built from source",
1145 diff.at.code, diff.mutant, diff.as_probe, diff.built
1146 )
1147 },
1148 "locations": [{
1149 "physicalLocation": {
1150 "artifactLocation": { "uri": sarif_uri(prefix, &diff.at.file) },
1151 "region": { "startLine": diff.at.line, "startColumn": diff.at.column }
1152 }
1153 }]
1154 }));
1155 }
1156 for diff in &audit.trace_differences {
1157 let text = if diff.rerun_failed && diff.records == 0 {
1158 format!(
1159 "audit trace re-run for `{}` did not pass (tests may not be deterministic)",
1160 diff.binary
1161 )
1162 } else if diff.rerun_failed {
1163 format!(
1164 "audit trace re-run for `{}` did not pass and differed in {} records",
1165 diff.binary, diff.records
1166 )
1167 } else {
1168 format!(
1169 "audit trace for `{}` differed between two runs ({} records)",
1170 diff.binary, diff.records
1171 )
1172 };
1173 results.push(serde_json::json!({
1174 "ruleId": "audit-disagreement",
1175 "level": "error",
1176 "message": { "text": text }
1177 }));
1178 }
1179 }
1180 let mut properties = serde_json::json!({
1181 "analysis": report.analysis,
1182 "evaluation": report.evaluation,
1183 "skipped": report.skipped,
1184 });
1185 if let Some(audit) = &report.audit {
1186 properties["audit"] = serde_json::json!(audit);
1187 }
1188 let mut run = serde_json::json!({
1189 "tool": sarif_tool(),
1190 "properties": properties,
1192 });
1193 run["results"] = serde_json::Value::Array(results);
1194 run
1195}
1196
1197fn list(items: &[String], limit: usize) -> String {
1198 let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
1199 let more = items.len().saturating_sub(limit);
1200 if more > 0 {
1201 format!("{} (+{more} more)", shown.join(", "))
1202 } else {
1203 shown.join(", ")
1204 }
1205}
1206
1207fn finding_body(finding: &Finding) -> Vec<String> {
1209 let mut lines = vec![];
1210 match finding {
1211 Finding::InputGap {
1212 survivors,
1213 survivor_count,
1214 add_tests,
1215 observed,
1216 verified,
1217 ..
1218 } => {
1219 let more = survivor_count.saturating_sub(survivors.len() as u128);
1220 let more = if more > 0 {
1221 format!(" (+{more} more)")
1222 } else {
1223 String::new()
1224 };
1225 let note = if *verified {
1226 "re-run: tests pass"
1227 } else {
1228 "from the trace, not re-run"
1229 };
1230 lines.push(format!(
1231 "passes every test as: {}{more} [{note}]",
1232 survivors.join(", ")
1233 ));
1234 lines.extend(observed.iter().cloned());
1235 lines.extend(
1236 add_tests
1237 .iter()
1238 .map(|test| format!("add a test with {test}")),
1239 );
1240 }
1241 Finding::AssertionGap {
1242 survivors,
1243 tests,
1244 effects,
1245 effects_of,
1246 witness,
1247 ..
1248 } => {
1249 lines.push(format!("passes every test as: {}", survivors.join(", ")));
1250 lines.push(format!(
1251 "these tests run the changed code and still pass: {}",
1252 list(tests, 5)
1253 ));
1254 if effects.is_empty() {
1255 lines.push("add an assertion on what this code is responsible for".to_string());
1256 } else {
1257 if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
1260 lines.push(format!(
1261 "followed one of them through the tests: {followed}"
1262 ));
1263 }
1264 lines.extend(effects.iter().cloned());
1265 }
1266 if let Some(witness) = witness {
1267 lines.extend(witness_lines(witness));
1268 }
1269 }
1270 Finding::Survivor {
1271 survivors,
1272 change_since: Some(revision),
1273 ..
1274 } => {
1275 lines.push(format!("passes every test {}", survivors.join(", ")));
1276 lines.push(format!(
1277 "no test tells this change from the code as it was at {}: add one that fails without it",
1278 short_revision(revision)
1279 ));
1280 }
1281 Finding::Survivor {
1282 survivors,
1283 witness,
1284 advice,
1285 ..
1286 } => {
1287 lines.push(format!("passes every test as: {}", survivors.join(", ")));
1288 if let Some(witness) = witness {
1289 lines.extend(witness_lines(witness));
1290 } else if let Some(advice) = advice {
1291 lines.push(advice.clone());
1292 } else {
1293 lines.push(
1294 "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"
1295 .to_string(),
1296 );
1297 }
1298 }
1299 }
1300 lines
1301}
1302
1303fn witness_lines(witness: &VerifiedWitness) -> Vec<String> {
1304 if let Some(test) = &witness.in_test {
1305 let place = witness
1307 .in_test_line
1308 .zip(witness.in_test_column)
1309 .map(|(line, column)| format!("line {line}, column {column}"));
1310 let (on, of) = place.map_or_else(
1311 || (String::new(), "that call".to_string()),
1312 |place| (format!(" at {place}"), format!("the call at {place}")),
1313 );
1314 return vec![
1315 format!(
1316 "verified on `{}` where `{test}` calls it{on}: original returned {}, mutant returned {}",
1317 witness.call, witness.original, witness.mutant,
1318 ),
1319 format!(
1320 "in `{test}`, compare the result of {of} with this value: `{}`",
1321 witness.assertion
1322 ),
1323 ];
1324 }
1325 let mut lines = vec![format!(
1326 "verified on `{}`: original returned {}, mutant returned {}",
1327 witness.call, witness.original, witness.mutant,
1328 )];
1329 if let Some(killed) = witness.individually_killed {
1330 lines.push(format!(
1331 "the selected tests detected all {killed} component changes in isolation"
1332 ));
1333 }
1334 lines.extend(witness.guidance.iter().cloned());
1335 lines.push(format!("add a test with `{}`", witness.assertion));
1336 lines
1337}
1338
1339fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
1340 match finding {
1341 Finding::InputGap { at, .. } => ("INPUT GAP", at),
1342 Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
1343 Finding::Survivor {
1344 at,
1345 change_since: Some(_),
1346 ..
1347 } => ("UNTESTED CHANGE", at),
1348 Finding::Survivor { at, .. } => ("SURVIVOR", at),
1349 }
1350}
1351
1352pub fn render_text(report: &Report, show_unreached: bool) -> String {
1353 let mut out = String::new();
1354 let mut previous: Option<(&str, usize)> = None;
1355 for finding in &report.findings {
1356 let (kind, at) = finding_parts(finding);
1357 let same_line = previous == Some((at.file.as_str(), at.line));
1360 if same_line {
1361 out.push_str(&format!(
1362 " + {kind} column {}\n {}\n",
1363 at.column, at.code
1364 ));
1365 } else {
1366 if previous.is_some() {
1367 out.push('\n');
1368 }
1369 out.push_str(&format!(
1370 "{kind} {}:{}:{}\n {}\n",
1371 at.file, at.line, at.column, at.code
1372 ));
1373 }
1374 for line in finding_body(finding) {
1375 out.push_str(&format!(" {line}\n"));
1376 }
1377 if report.weakened.iter().any(|before| {
1378 (before.file.as_str(), before.line, before.column)
1379 == (at.file.as_str(), at.line, at.column)
1380 }) {
1381 out.push_str(&format!(
1382 " the tests as they were at {} found this out: a change to the tests lets it through\n",
1383 short_revision(report.analysis.since.as_deref().unwrap_or("the revision"))
1384 ));
1385 }
1386 previous = Some((at.file.as_str(), at.line));
1387 }
1388 if previous.is_some() {
1389 out.push('\n');
1390 }
1391 if show_unreached {
1392 for at in &report.unreached {
1393 out.push_str(&format!(
1394 "UNREACHED {}:{}:{}\n {}\n\n",
1395 at.file, at.line, at.column, at.code
1396 ));
1397 }
1398 }
1399 for at in &report.unstable {
1400 out.push_str(&format!(
1401 "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",
1402 at.file, at.line, at.column, at.code
1403 ));
1404 }
1405 let input = report
1406 .findings
1407 .iter()
1408 .filter(|f| matches!(f, Finding::InputGap { .. }))
1409 .count();
1410 let assertion = report
1411 .findings
1412 .iter()
1413 .filter(|f| matches!(f, Finding::AssertionGap { .. }))
1414 .count();
1415 let unexplained = report.findings.len() - input - assertion;
1416 let by_time_limit = if report.mutants_timed_out > 0 {
1418 format!(", {} of them by the time limit", report.mutants_timed_out)
1419 } else {
1420 String::new()
1421 };
1422 out.push_str(&format!(
1423 "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
1424 report.package,
1425 report.sites,
1426 input,
1427 assertion,
1428 report.mutants_run,
1429 report.mutants_killed,
1430 report.unreached.len()
1431 ));
1432 if unexplained > 0 {
1433 out.push_str(&format!(
1434 ", {unexplained} survivors of mutants built on their own"
1435 ));
1436 }
1437 if !report.timeout_rechecks.is_empty() {
1438 let rechecks = &report.timeout_rechecks;
1439 out.push_str(&format!(
1440 ", {} parallel timeouts ({} confirmed, {} recovered, {} unconfirmed)",
1441 rechecks.first_pass, rechecks.confirmed, rechecks.recovered, rechecks.unconfirmed
1442 ));
1443 }
1444 if report.suppressed > 0 {
1445 out.push_str(&format!(", {} findings suppressed", report.suppressed));
1446 }
1447 if report.skipped_sites > 0 {
1448 out.push_str(&format!(
1449 ", {} sites skipped (probe did not compile)",
1450 report.skipped_sites
1451 ));
1452 }
1453 if report.unviable_mutants > 0 {
1454 out.push_str(&format!(
1455 ", {} mutants left out (they do not compile)",
1456 report.unviable_mutants
1457 ));
1458 }
1459 out.push('\n');
1460 if let Some(audit) = &report.audit {
1461 out.push_str(&format!(
1462 "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against",
1463 audit.sampled,
1464 audit.survivors,
1465 audit.disagreements.len()
1466 ));
1467 if audit.not_audited > 0 {
1468 out.push_str(&format!(", {} could not be judged", audit.not_audited));
1469 }
1470 out.push('\n');
1471 for at in &audit.disagreements {
1472 out.push_str(&format!(
1473 " {}:{}:{} {}\n",
1474 at.file, at.line, at.column, at.code
1475 ));
1476 }
1477 if audit.rebuilt > 0 {
1478 out.push_str(&format!(
1479 "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",
1480 audit.rebuilt,
1481 audit.compared,
1482 audit.source_disagreements.len(),
1483 audit.not_compared
1484 ));
1485 }
1486 for differs in &audit.source_disagreements {
1487 out.push_str(&format!(
1488 " {}:{}:{} {}: {} as a probe, {} built\n",
1489 differs.at.file,
1490 differs.at.line,
1491 differs.at.column,
1492 differs.mutant,
1493 differs.as_probe,
1494 differs.built
1495 ));
1496 }
1497 if audit.trace_differences.is_empty() {
1498 out.push_str("audit: recorded once more, the tests did the same\n");
1499 }
1500 for binary in &audit.trace_differences {
1501 if binary.rerun_failed && binary.records == 0 {
1502 out.push_str(&format!(
1503 "audit: recorded once more, `{}` did not pass: its tests do not always do the same\n",
1504 binary.binary
1505 ));
1506 } else if binary.rerun_failed {
1507 out.push_str(&format!(
1508 "audit: recorded once more, `{}` did not pass and differs in {} records: its tests do not always do the same\n",
1509 binary.binary, binary.records
1510 ));
1511 } else {
1512 out.push_str(&format!(
1513 "audit: recorded once more, `{}` differs in {} records: its tests do not always do the same\n",
1514 binary.binary, binary.records
1515 ));
1516 }
1517 }
1518 }
1519 if report.mutants_not_compiled > 0 {
1520 out.push_str(&format!(
1521 "({} mutants not evaluated: their code is not part of this build (a `cfg` or a feature that is off, or a file of another target); other --features may build it)\n",
1522 report.mutants_not_compiled
1523 ));
1524 }
1525 let not_evaluated = report
1526 .mutants_not_evaluated
1527 .saturating_sub(report.mutants_not_compiled);
1528 if not_evaluated > 0 {
1529 out.push_str(&format!(
1530 "({not_evaluated} mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it, or a run that could not be judged)\n"
1531 ));
1532 }
1533 if report.mutants_not_built > 0 {
1534 out.push_str(&format!(
1535 "({} more mutants need a build of their own: --rebuild runs them)\n",
1536 report.mutants_not_built
1537 ));
1538 }
1539 if !report.skipped.is_empty() {
1540 out.push_str(&format!(
1541 "({} skipped entries with locations and reasons in --json)\n",
1542 report.skipped.len()
1543 ));
1544 }
1545 if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
1546 out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
1547 }
1548 if !show_unreached && !report.unreached.is_empty() {
1549 out.push_str("(--show-unreached lists the code no test executes)\n");
1550 }
1551 out
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556 use super::*;
1557 use crate::instrument::discover;
1558
1559 #[test]
1560 fn evaluation_distinguishes_no_sites_no_mutants_and_completed_work() {
1561 let mut report = Report::default();
1562 report.record_evaluation();
1563 assert_eq!(report.evaluation, Some(Evaluation::NoSites));
1564 report.sites = 1;
1565 report.record_evaluation();
1566 assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
1567 assert!(render_text(&report, false).contains("No mutants executed."));
1568 report.mutants_run = 1;
1569 report.record_evaluation();
1570 assert_eq!(report.evaluation, None);
1571 assert!(!render_text(&report, false).contains("No mutants executed."));
1572 }
1573
1574 fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
1575 sarif["runs"][0]["results"].as_array().unwrap()
1576 }
1577
1578 fn or_site() -> Site {
1579 site_of("fn f(a: bool, b: bool) -> bool { a || b }")
1580 }
1581
1582 fn assign_kind() -> SiteKind {
1583 SiteKind::Arith {
1584 op: ArithOp::Add,
1585 assign: true,
1586 lhs: "*total".into(),
1587 rhs: "fee".into(),
1588 gap: (0, 0),
1589 }
1590 }
1591
1592 fn site_of(src: &str) -> Site {
1593 discover(src, 0)
1594 .unwrap()
1595 .sites
1596 .into_iter()
1597 .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
1598 .unwrap()
1599 }
1600
1601 #[test]
1602 fn describes_mutants_at_source_level() {
1603 let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
1604 assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
1605 assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
1606 assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
1607 assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
1608 assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
1609
1610 let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
1612 assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
1613
1614 let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
1615 assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
1616 assert_eq!(
1617 describe(&none, Mutation::Shift(2)),
1618 "`a >= b + 2` (without overflow)"
1619 );
1620 assert_eq!(
1621 describe(&none, Mutation::Shift(-1)),
1622 "`a >= b - 1` (without overflow)"
1623 );
1624 let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
1625 assert_eq!(describe(<, Mutation::Shift(1)), "`a <= b`");
1626
1627 let stmt = site_of("fn f(s: &mut S) { s.check(\n 1,\n 2); }");
1628 assert_eq!(
1629 describe(&stmt, Mutation::Delete),
1630 "delete `s.check( 1, 2);`"
1631 );
1632 }
1633
1634 #[test]
1636 fn literal_shift_rendering_matches_shift_semantics() {
1637 use crate::plan::eval_mutated_d;
1638 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1639 for shift in [-2, -1, 1, 2] {
1640 for other in -5..=5i128 {
1641 let k = 1i128;
1642 assert_eq!(
1644 op.eval_d(other - (k + shift)),
1645 eval_mutated_d(op, Mutation::Shift(shift), other - k)
1646 );
1647 assert_eq!(
1649 op.eval_d((k - shift) - other),
1650 eval_mutated_d(op, Mutation::Shift(shift), k - other)
1651 );
1652 }
1653 }
1654 }
1655 for (op, shift, flipped) in [
1657 (CmpOp::Ge, 1, CmpOp::Gt),
1658 (CmpOp::Gt, -1, CmpOp::Ge),
1659 (CmpOp::Le, -1, CmpOp::Lt),
1660 (CmpOp::Lt, 1, CmpOp::Le),
1661 ] {
1662 for d in -3..=3 {
1663 assert_eq!(
1664 flipped.eval_d(d),
1665 eval_mutated_d(op, Mutation::Shift(shift), d)
1666 );
1667 }
1668 }
1669 }
1670
1671 #[test]
1672 fn boundary_finding_for_the_age_check() {
1673 let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
1674 let mut obs = Obs::of_d(-1);
1675 obs.merge(&Obs::of_d(2));
1676 let gap = InputGap::Boundary {
1677 min_shift: 0,
1678 max_shift: 2,
1679 missing: vec![0],
1680 same: (0, 0),
1681 };
1682 let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
1683 assert_eq!(
1684 finding,
1685 Finding::InputGap {
1686 at: Location {
1687 file: "src/lib.rs".into(),
1688 line: 1,
1689 column: 26,
1690 code: "age >= 18".into(),
1691 ..Location::default()
1692 },
1693 survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
1694 survivor_count: 2,
1695 add_tests: vec!["`age` = 18 (the original gives true)".into()],
1696 observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
1697 verified: true,
1698 }
1699 );
1700 let report = Report {
1701 package: "p".into(),
1702 sites: 1,
1703 findings: vec![finding],
1704 ..Report::default()
1705 };
1706 let text = render_text(&report, false);
1707 assert!(text.contains("INPUT GAP src/lib.rs:1:26"), "{text}");
1708 assert!(
1709 text.contains("passes every test as: `age >= 19`, `age >= 20` [re-run: tests pass]"),
1710 "{text}"
1711 );
1712 assert!(
1713 text.contains("add a test with `age` = 18 (the original gives true)"),
1714 "{text}"
1715 );
1716 assert!(
1717 text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
1718 "{text}"
1719 );
1720 assert!(report.has_gaps());
1721 }
1722
1723 #[test]
1724 fn other_gap_kinds() {
1725 let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
1726 let mut obs = Obs::of_rel(crate::plan::Rel::Less);
1727 obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
1728 let gap = InputGap::EqualNeverObserved {
1729 flipped: CmpOp::Le,
1730 float_gap: None,
1731 };
1732 let Some(Finding::InputGap {
1733 survivors,
1734 add_tests,
1735 observed,
1736 ..
1737 }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
1738 else {
1739 panic!()
1740 };
1741 assert_eq!(survivors, ["`a <= b`"]);
1742 assert_eq!(
1743 add_tests,
1744 ["`a` equal to `b` (the original gives false, the mutant true)"]
1745 );
1746 assert_eq!(observed, None);
1747
1748 let Some(Finding::InputGap {
1749 survivors,
1750 add_tests,
1751 ..
1752 }) = input_gap_finding(
1753 "f.rs",
1754 &site,
1755 &InputGap::OneSided { always: true },
1756 &obs,
1757 false,
1758 )
1759 else {
1760 panic!()
1761 };
1762 assert_eq!(survivors, ["`true`"]);
1763 assert_eq!(add_tests, ["an input that makes `a < b` false"]);
1764
1765 assert_eq!(
1766 input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
1767 None
1768 );
1769 }
1770
1771 #[test]
1772 fn float_gap_finding() {
1773 let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
1774 let mut obs = Obs::of_f(-20.5);
1775 obs.merge(&Obs::of_f(9.5));
1776 let gap = InputGap::EqualNeverObserved {
1777 flipped: CmpOp::Ge,
1778 float_gap: obs.float_gap(),
1779 };
1780 let Some(Finding::InputGap {
1781 survivors,
1782 add_tests,
1783 observed,
1784 survivor_count,
1785 ..
1786 }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
1787 else {
1788 panic!()
1789 };
1790 assert_eq!(
1791 survivors,
1792 [
1793 "`celsius >= 30.5`",
1794 "`celsius > 35.25`",
1795 "`celsius > 20.25`"
1796 ]
1797 );
1798 assert_eq!(survivor_count, 3);
1799 assert_eq!(
1800 add_tests,
1801 ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
1802 );
1803 assert_eq!(
1804 observed.as_deref(),
1805 Some(
1806 "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
1807 )
1808 );
1809
1810 let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
1811 assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
1812 let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
1813 assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
1814 assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
1815 let finding = input_gap_finding(
1816 "f.rs",
1817 &none,
1818 &InputGap::EqualNeverObserved {
1819 flipped: CmpOp::Le,
1820 float_gap: Some((-1.0, 2.0)),
1821 },
1822 &obs,
1823 false,
1824 );
1825 let Some(Finding::InputGap { observed, .. }) = finding else {
1826 panic!()
1827 };
1828 assert_eq!(
1829 observed.as_deref(),
1830 Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
1831 );
1832
1833 assert_eq!(float_literal("30.5"), Some(30.5));
1834 assert_eq!(float_literal("-1e3"), Some(-1000.0));
1835 assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
1836 assert_eq!(float_literal("limit"), None);
1837 assert_eq!(float_literal("x1"), None);
1838 assert_eq!(float_literal("1x"), None);
1839 assert_eq!(float_literal("-x"), None);
1840 assert_eq!(float_literal("-2.5"), Some(-2.5));
1841 assert_eq!(float_literal("e"), None);
1842 assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
1844 assert_eq!(show_float(1e-10), "1e-10");
1845 assert_eq!(show_float(10.0), "10.0");
1846 assert_eq!(show_float(35.25), "35.25");
1847 let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
1849 let tiny = InputGap::EqualNeverObserved {
1850 flipped: CmpOp::Ge,
1851 float_gap: Some((-2e-300, 2e-300)),
1852 };
1853 let Some(Finding::InputGap { survivors, .. }) =
1854 input_gap_finding("f.rs", &big, &tiny, &obs, true)
1855 else {
1856 panic!()
1857 };
1858 assert_eq!(survivors, ["`x >= 1e300`"]);
1859 }
1860
1861 #[test]
1862 fn logic_and_arithmetic_findings() {
1863 let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
1864 assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
1865 assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
1866 assert_eq!(
1867 describe(&or_site(), Mutation::LogicDropRhs),
1868 "`a || { b; false }`"
1869 );
1870 assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
1871 let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
1872 assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
1873 let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
1874 Some(Finding::InputGap {
1875 survivors,
1876 add_tests,
1877 ..
1878 }) => (survivors[0].clone(), add_tests[0].clone()),
1879 _ => panic!(),
1880 };
1881 assert_eq!(
1882 advice(&and, LogicGap::RhsNeverDecides),
1883 (
1884 "`a && { b; true }`".into(),
1885 "a case where `a` is true and `b` is false".into()
1886 )
1887 );
1888 assert_eq!(
1889 advice(&and, LogicGap::LhsNeverDecides),
1890 ("`{ a; b }`".into(), "a case where `a` is false".into())
1891 );
1892 assert_eq!(
1893 advice(&or, LogicGap::RhsNeverDecides),
1894 (
1895 "`a || { b; false }`".into(),
1896 "a case where `a` is false and `b` is true".into()
1897 )
1898 );
1899 assert_eq!(
1900 advice(&or, LogicGap::LhsNeverDecides),
1901 ("`{ a; b }`".into(), "a case where `a` is true".into())
1902 );
1903 assert_eq!(
1904 logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
1905 None
1906 );
1907 assert_eq!(
1908 arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
1909 None
1910 );
1911
1912 let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
1913 assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
1914 let Some(Finding::InputGap {
1915 survivors,
1916 add_tests,
1917 ..
1918 }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
1919 else {
1920 panic!()
1921 };
1922 assert_eq!(
1923 (survivors[0].as_str(), add_tests[0].as_str()),
1924 ("`total - fee`", "`fee` other than 0")
1925 );
1926 let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
1927 let Some(Finding::InputGap {
1928 survivors,
1929 add_tests,
1930 ..
1931 }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
1932 else {
1933 panic!()
1934 };
1935 assert_eq!(survivors[0], "`n / scale`");
1936 assert_eq!(
1937 add_tests[0],
1938 "operands for which `n * scale` and `n / scale` differ"
1939 );
1940 let assign = Site {
1941 kind: assign_kind(),
1942 ..add.clone()
1943 };
1944 assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
1945 let Some(Finding::InputGap { add_tests, .. }) =
1946 arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
1947 else {
1948 panic!()
1949 };
1950 assert_eq!(add_tests[0], "`fee` other than 0");
1951 let shift = Site {
1952 kind: SiteKind::Arith {
1953 op: ArithOp::Shl,
1954 assign: true,
1955 lhs: "bits".into(),
1956 rhs: "n".into(),
1957 gap: (0, 0),
1958 },
1959 ..assign.clone()
1960 };
1961 assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
1962 let Some(Finding::InputGap { add_tests, .. }) =
1963 arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
1964 else {
1965 panic!()
1966 };
1967 assert_eq!(
1968 add_tests[0],
1969 "operands for which `bits <<= n` and `bits >>= n` differ"
1970 );
1971
1972 let not = Site {
1973 kind: SiteKind::Not {
1974 bang: (0, 1),
1975 operand: "is_ready(x)".into(),
1976 needs_space: false,
1977 },
1978 ..assign.clone()
1979 };
1980 assert_eq!(describe(¬, Mutation::DropNot), "`is_ready(x)`");
1981 let ret = Site {
1982 kind: SiteKind::Return {
1983 name: "is_ready".into(),
1984 option: None,
1985 sole_expr: None,
1986 },
1987 ..assign.clone()
1988 };
1989 assert_eq!(
1990 describe(&ret, Mutation::Const(true)),
1991 "`is_ready` returning `true`"
1992 );
1993 let Some(Finding::InputGap {
1994 survivors,
1995 add_tests,
1996 ..
1997 }) = return_gap_finding("f.rs", &ret, false, true)
1998 else {
1999 panic!()
2000 };
2001 assert_eq!(survivors[0], "`is_ready` returning `false`");
2002 assert_eq!(add_tests[0], "a case where `is_ready` returns true");
2003 assert_eq!(return_gap_finding("f.rs", ¬, false, true), None);
2004
2005 let find = Site {
2006 kind: SiteKind::Return {
2007 name: "find".into(),
2008 option: Some("Option<&str>".into()),
2009 sole_expr: None,
2010 },
2011 ..assign.clone()
2012 };
2013 assert_eq!(
2014 describe(&find, Mutation::Const(false)),
2015 "`find` returning `None`"
2016 );
2017 let Some(Finding::InputGap { add_tests, .. }) =
2018 return_gap_finding("f.rs", &find, false, true)
2019 else {
2020 panic!()
2021 };
2022 assert_eq!(add_tests[0], "a case where `find` returns `Some`");
2023 let range = Site {
2024 kind: SiteKind::Range {
2025 inclusive: false,
2026 lhs: "0".into(),
2027 rhs: "n".into(),
2028 gap: (0, 0),
2029 },
2030 ..assign.clone()
2031 };
2032 assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
2033 let closed = Site {
2034 kind: SiteKind::Range {
2035 inclusive: true,
2036 lhs: "1".into(),
2037 rhs: "n".into(),
2038 gap: (0, 0),
2039 },
2040 ..assign.clone()
2041 };
2042 assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
2043 let arm = Site {
2044 kind: SiteKind::Arm {
2045 pattern: "Kind::Update { key, .. }".into(),
2046 guard: crate::instrument::ArmGuard::None(0),
2047 removal: (0, 0),
2048 },
2049 ..assign.clone()
2050 };
2051 assert_eq!(
2052 describe(&arm, Mutation::Delete),
2053 "remove the arm `Kind::Update { key, .. } => ..`"
2054 );
2055
2056 let clamp = Site {
2057 kind: SiteKind::MinMax {
2058 max: true,
2059 receiver: "drift".into(),
2060 argument: "peak.get()".into(),
2061 call: (0, 0),
2062 close: (0, 0),
2063 },
2064 ..assign.clone()
2065 };
2066 assert_eq!(
2067 describe(&clamp, Mutation::MinMax),
2068 "`drift.min(peak.get())`"
2069 );
2070 let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
2071 else {
2072 panic!()
2073 };
2074 assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
2075 assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
2076
2077 let end = Site {
2078 kind: SiteKind::SliceEnd {
2079 first: false,
2080 receiver: "self.items".into(),
2081 call: (0, 0),
2082 method: (0, 0),
2083 },
2084 ..assign.clone()
2085 };
2086 assert_eq!(describe(&end, Mutation::OtherEnd), "`self.items.first()`");
2087 let Some(Finding::InputGap { add_tests, .. }) = slice_end_gap_finding("f.rs", &end, true)
2088 else {
2089 panic!()
2090 };
2091 assert_eq!(
2092 add_tests[0],
2093 "`self.items` with two or more elements, the first different from the last"
2094 );
2095 assert_eq!(slice_end_gap_finding("f.rs", &clamp, true), None);
2096
2097 let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
2098 assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
2099 assert_eq!(
2100 logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
2101 None
2102 );
2103 }
2104
2105 #[test]
2106 fn workspace_sarif_matches_the_individual_runs() {
2107 use serde_json::{Value, json};
2108
2109 let report = Report {
2110 package: "zebra".into(),
2111 analysis: Analysis {
2112 package_path: "crates/zebra/".into(),
2113 ..Analysis::default()
2114 },
2115 findings: vec![Finding::Survivor {
2116 at: Location {
2117 file: r#"src/"é".rs"#.into(),
2118 line: 4,
2119 column: 1,
2120 id: "zebra|4".into(),
2121 ..Location::default()
2122 },
2123 survivors: vec!["delete".into()],
2124 witness: None,
2125 change_since: None,
2126 advice: None,
2127 }],
2128 ..Report::default()
2129 };
2130 let empty = Report {
2131 package: "ant".into(),
2132 ..Report::default()
2133 };
2134 for reports in [
2135 &[][..],
2136 std::slice::from_ref(&report),
2137 &[report.clone(), empty],
2138 ] {
2139 let runs: Vec<_> = reports
2140 .iter()
2141 .map(|report| {
2142 let mut single: Value = serde_json::from_str(&render_sarif(report)).unwrap();
2143 let mut run = single["runs"][0].take();
2144 assert!(run["properties"].get("package").is_none());
2145 run["properties"]["package"] = json!(report.package);
2146 run["automationDetails"] = json!({ "id": format!("tmt/{}/", report.package) });
2148 run["invocations"] = json!([{ "executionSuccessful": true }]);
2149 run
2150 })
2151 .collect();
2152 let old = json!({
2153 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2154 "version": "2.1.0",
2155 "runs": runs,
2156 });
2157 let workspace: Value =
2158 serde_json::from_str(&format!("{:#}", workspace_sarif(reports, &[]))).unwrap();
2159 assert_eq!(workspace, old);
2160 }
2161 }
2162
2163 #[test]
2164 fn a_package_that_could_not_be_analysed_is_a_run_that_says_so() {
2165 use serde_json::Value;
2166
2167 let analysed = Report {
2168 package: "ant".into(),
2169 ..Report::default()
2170 };
2171 let failed = [(
2172 "bee".to_string(),
2173 "the tests of `bee` fail: \"quoted\"\n".to_string(),
2174 )];
2175 let document: Value = serde_json::from_str(&format!(
2176 "{:#}",
2177 workspace_sarif(std::slice::from_ref(&analysed), &failed)
2178 ))
2179 .unwrap();
2180 let runs = document["runs"].as_array().unwrap();
2181 assert_eq!(runs.len(), 2);
2182 assert_eq!(runs[0]["automationDetails"]["id"], "tmt/ant/");
2184 assert_eq!(runs[0]["invocations"][0]["executionSuccessful"], true);
2185 assert_eq!(runs[1]["automationDetails"]["id"], "tmt/bee/");
2186 assert_eq!(runs[1]["invocations"][0]["executionSuccessful"], false);
2187 assert_eq!(
2188 runs[1]["invocations"][0]["toolExecutionNotifications"][0]["message"]["text"],
2189 failed[0].1
2190 );
2191 assert_eq!(runs[1]["results"].as_array().unwrap().len(), 0);
2192 assert_eq!(runs[1]["tool"], runs[0]["tool"]);
2193 assert_eq!(runs[1]["properties"]["package"], "bee");
2194 let document: Value =
2196 serde_json::from_str(&format!("{:#}", workspace_sarif(&[], &failed))).unwrap();
2197 assert_eq!(document["runs"].as_array().unwrap().len(), 1);
2198 }
2199
2200 #[test]
2201 fn a_path_is_written_as_a_uri() {
2202 assert_eq!(sarif_uri("", "src/lib.rs"), "src/lib.rs");
2203 assert_eq!(
2204 sarif_uri("crates/a-b_c/", "src/x~1.rs"),
2205 "crates/a-b_c/src/x~1.rs"
2206 );
2207 assert_eq!(
2209 sarif_uri("my crate/", "a#b%c?.rs"),
2210 "my%20crate/a%23b%25c%3F.rs"
2211 );
2212 assert_eq!(sarif_uri("", "src/é.rs"), "src/%C3%A9.rs");
2213 assert_eq!(sarif_uri("", r#"a\b"c.rs"#), "a%5Cb%22c.rs");
2214 let report = Report {
2215 analysis: Analysis {
2216 package_path: "my crate/".into(),
2217 ..Analysis::default()
2218 },
2219 findings: vec![Finding::Survivor {
2220 at: Location {
2221 file: "src/a b.rs".into(),
2222 line: 1,
2223 column: 1,
2224 ..Location::default()
2225 },
2226 survivors: vec![],
2227 witness: None,
2228 change_since: None,
2229 advice: None,
2230 }],
2231 ..Report::default()
2232 };
2233 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
2234 assert_eq!(
2235 sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]
2236 ["uri"],
2237 "my%20crate/src/a%20b.rs"
2238 );
2239 assert_eq!(sarif_uri_for("", r#"a\b"c.rs"#, false), "a%5Cb%22c.rs");
2240 assert_eq!(
2241 sarif_uri_for(r"crates\core\", r"src\lib.rs", true),
2242 "crates/core/src/lib.rs"
2243 );
2244 }
2245
2246 #[test]
2247 fn findings_sort_by_path_and_position_in_input_order_for_ties() {
2248 let mut report = Report {
2249 findings: [
2250 ("z.rs", 1, 1, "1"),
2251 ("é.rs", 1, 1, "2"),
2252 ("a.rs", 2, 1, "3"),
2253 ("a.rs", 1, 3, "4"),
2254 ("a.rs", 1, 3, "5"),
2255 ("a.rs", 1, 1, "6"),
2256 ]
2257 .into_iter()
2258 .map(|(file, line, column, id)| Finding::Survivor {
2259 at: Location {
2260 file: file.into(),
2261 line,
2262 column,
2263 id: id.into(),
2264 ..Location::default()
2265 },
2266 survivors: vec![],
2267 witness: None,
2268 change_since: None,
2269 advice: None,
2270 })
2271 .collect(),
2272 ..Report::default()
2273 };
2274 report.sort_findings();
2275 let ids: Vec<_> = report
2276 .findings
2277 .iter()
2278 .map(|finding| finding.at().id.as_str())
2279 .collect();
2280 assert_eq!(ids, ["6", "4", "5", "3", "1", "2"]);
2281 }
2282
2283 #[test]
2284 fn collapsed_code_matches_the_previous_format() {
2285 for (charset, spacing, width) in [
2287 ("ascii", "none", 17),
2288 ("ascii", "split", 100),
2289 ("ascii", "surrounded", 101),
2290 ("multibyte", "split", 101),
2291 ("ascii", "none", 4096),
2292 ("multibyte", "none", 97),
2293 ("multibyte", "surrounded", 0),
2294 ("multibyte", "surrounded", 17),
2295 ("multibyte", "surrounded", 4096),
2296 ("ascii", "split", 17),
2297 ("multibyte", "none", 100),
2298 ("multibyte", "none", 101),
2299 ("ascii", "surrounded", 97),
2300 ("ascii", "surrounded", 100),
2301 ("multibyte", "split", 97),
2302 ("ascii", "none", 0),
2303 ("multibyte", "split", 4096),
2304 ] {
2305 let glyph = if charset == "ascii" { "x" } else { "🦀" };
2306 let code = match spacing {
2307 "none" => glyph.repeat(width),
2308 "surrounded" => format!("\t{}\u{2003}\r\n", glyph.repeat(width)),
2309 _ => format!(
2310 "{}\u{2003}\r\n {}",
2311 glyph.repeat(width / 2),
2312 glyph.repeat(width - width / 2 - 1),
2313 ),
2314 };
2315 let normalized = code.split_whitespace().collect::<Vec<_>>().join(" ");
2316 let expected = if normalized.chars().count() > 100 {
2317 format!("{}...", normalized.chars().take(97).collect::<String>())
2318 } else {
2319 normalized
2320 };
2321 assert_eq!(one_line(&code), expected, "{charset} {spacing} {width}");
2322 }
2323
2324 let code = format!("{}\n{}", "x".repeat(96), "y".repeat(4096));
2326 assert_eq!(one_line(&code), format!("{} ...", "x".repeat(96)));
2327 let code = format!("{}\n{}", "x".repeat(100), " ".repeat(4096));
2328 assert_eq!(one_line(&code), "x".repeat(100));
2329 }
2330
2331 #[test]
2332 fn long_code_is_shortened() {
2333 let exactly_100 = "x".repeat(100);
2334 assert_eq!(one_line(&exactly_100), exactly_100);
2335 let shortened = one_line(&"x".repeat(101));
2336 assert_eq!(shortened, format!("{}...", "x".repeat(97)));
2337 assert_eq!(one_line("a\n b"), "a b");
2338 }
2339
2340 #[test]
2341 fn timeout_rechecks_are_in_the_json_only_when_there_were_any() {
2342 let none = serde_json::to_value(Report::default()).unwrap();
2343 assert!(none.get("timeout_rechecks").is_none(), "{none}");
2344 let report = Report {
2345 timeout_rechecks: TimeoutRechecks {
2346 first_pass: 3,
2347 confirmed: 1,
2348 recovered: 2,
2349 unconfirmed: 0,
2350 },
2351 ..Report::default()
2352 };
2353 assert_eq!(
2354 serde_json::to_value(&report).unwrap()["timeout_rechecks"],
2355 serde_json::json!({"first_pass": 3, "confirmed": 1, "recovered": 2, "unconfirmed": 0})
2356 );
2357 }
2358
2359 #[test]
2360 fn at_most_three_survivors_are_listed_nearest_first() {
2361 let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
2362 let obs = Obs::default();
2363 let survivors = |min_shift, max_shift| {
2364 let gap = InputGap::Boundary {
2365 min_shift,
2366 max_shift,
2367 missing: vec![0],
2368 same: (0, 0),
2369 };
2370 match input_gap_finding("f.rs", &site, &gap, &obs, false) {
2371 Some(Finding::InputGap {
2372 survivors,
2373 survivor_count,
2374 ..
2375 }) => (survivors, survivor_count),
2376 _ => panic!(),
2377 }
2378 };
2379 assert_eq!(
2380 survivors(-9, 9),
2381 (
2382 vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
2383 18
2384 )
2385 );
2386 assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
2387 assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
2388 assert_eq!(
2389 survivors(-2, 0),
2390 (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
2391 );
2392 }
2393
2394 #[test]
2395 fn text_report_is_exact() {
2396 let at = Location {
2397 file: "src/lib.rs".into(),
2398 line: 3,
2399 column: 9,
2400 code: "a >= b".into(),
2401 ..Location::default()
2402 };
2403 let below = Location {
2404 file: "src/lib.rs".into(),
2405 line: 7,
2406 column: 5,
2407 code: "s.reset();".into(),
2408 ..Location::default()
2409 };
2410 let report = Report {
2411 package: "p".into(),
2412 sites: 2,
2413 mutants_run: 1,
2414 suppressed: 2,
2415 findings: vec![
2416 Finding::InputGap {
2417 at: at.clone(),
2418 survivors: vec!["`a > b`".into()],
2419 survivor_count: 4,
2420 add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
2421 observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
2422 verified: false,
2423 },
2424 Finding::InputGap {
2425 at: at.clone(),
2426 survivors: vec!["`true`".into()],
2427 survivor_count: 1,
2428 add_tests: vec![],
2429 observed: None,
2430 verified: true,
2431 },
2432 Finding::AssertionGap {
2433 at: Location { column: 4, ..at },
2434 survivors: vec!["`!(a >= b)`".into()],
2435 tests: vec!["t".into()],
2436 effects: vec![],
2437 effects_of: None,
2438 witness: None,
2439 },
2440 Finding::AssertionGap {
2441 at: below,
2442 survivors: vec!["delete `s.reset();`".into()],
2443 tests: vec!["t".into()],
2444 effects: vec![
2445 "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
2446 ],
2447 effects_of: None,
2448 witness: None,
2449 },
2450 ],
2451 ..Report::default()
2452 };
2453 assert_eq!(
2455 render_text(&report, false),
2456 "INPUT GAP src/lib.rs:3:9\n a >= b\n\
2457 \x20 passes every test as: `a > b` (+3 more) [from the trace, not re-run]\n\
2458 \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
2459 \x20 add a test with `a` equal to `b` (the original gives true)\n\
2460 \x20 + INPUT GAP column 9\n a >= b\n\
2461 \x20 passes every test as: `true` [re-run: tests pass]\n\
2462 \x20 + ASSERTION GAP column 4\n a >= b\n\
2463 \x20 passes every test as: `!(a >= b)`\n\
2464 \x20 these tests run the changed code and still pass: t\n\
2465 \x20 add an assertion on what this code is responsible for\n\
2466 \n\
2467 ASSERTION GAP src/lib.rs:7:5\n s.reset();\n\
2468 \x20 passes every test as: delete `s.reset();`\n\
2469 \x20 these tests run the changed code and still pass: t\n\
2470 \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
2471 \n\
2472 p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
2473 );
2474 assert_eq!(
2475 render_text(
2476 &Report {
2477 package: "q".into(),
2478 ..Report::default()
2479 },
2480 false
2481 ),
2482 "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
2483 );
2484
2485 let mut in_repository = report.clone();
2486 in_repository.analysis.package_path = "crates/p/".into();
2487 in_repository.analysis.since = Some("abc".into());
2488 if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
2489 at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
2490 }
2491 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
2492 assert_eq!(
2493 results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
2494 "assertion_gap|src/lib.rs|f|s.reset();|0"
2495 );
2496 assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
2497 assert_eq!(sarif["version"], "2.1.0");
2498 let results = sarif["runs"][0]["results"].as_array().unwrap();
2499 assert_eq!(results.len(), 4);
2500 assert_eq!(results[0]["ruleId"], "input-gap");
2501 assert_eq!(results[3]["ruleId"], "assertion-gap");
2502 let location = &results[3]["locations"][0]["physicalLocation"];
2503 assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
2504 assert_eq!(
2505 (
2506 &location["region"]["startLine"],
2507 &location["region"]["startColumn"]
2508 ),
2509 (&serde_json::json!(7), &serde_json::json!(5))
2510 );
2511 assert!(
2512 results[3]["message"]["text"]
2513 .as_str()
2514 .unwrap()
2515 .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
2516 );
2517 let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
2518 .as_array()
2519 .unwrap();
2520 assert_eq!(rules.len(), 6);
2521 }
2522
2523 #[test]
2524 fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
2525 let survivor = Finding::Survivor {
2526 at: Location {
2527 file: "src/lib.rs".into(),
2528 line: 2,
2529 column: 1,
2530 code: "const fn limit() -> u8".into(),
2531 ..Location::default()
2532 },
2533 survivors: vec!["the body of `limit` replaced by `0`".into()],
2534 witness: None,
2535 change_since: None,
2536 advice: None,
2537 };
2538 assert_eq!(survivor.kind(), "survivor");
2539 assert_eq!(survivor.at().line, 2);
2540 assert_eq!(survivor.survivors().len(), 1);
2541 let report = Report {
2542 package: "p".into(),
2543 findings: vec![survivor],
2544 ..Report::default()
2545 };
2546 assert_eq!(
2548 render_text(&report, false),
2549 "SURVIVOR src/lib.rs:2:1\n const fn limit() -> u8\n\
2550 \x20 passes every test as: the body of `limit` replaced by `0`\n\
2551 \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\
2552 \n\
2553 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"
2554 );
2555 let json = serde_json::to_value(&report).unwrap();
2556 assert_eq!(json["findings"][0]["kind"], "survivor");
2557 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
2558 assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
2559 assert!(report.has_gaps());
2560 }
2561
2562 #[test]
2563 fn non_literal_inputs_in_words() {
2564 assert_eq!(
2565 input_for("a", "b", LiteralSide::None, 0),
2566 "`a` equal to `b`"
2567 );
2568 assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
2569 assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
2570 assert_eq!(
2571 input_for("18", "age", LiteralSide::Lhs(18), -1),
2572 "`age` = 19"
2573 );
2574 }
2575
2576 #[test]
2577 fn text_report_sections() {
2578 let at = Location {
2579 file: "src/lib.rs".into(),
2580 line: 3,
2581 column: 9,
2582 code: "s.check()?;".into(),
2583 ..Location::default()
2584 };
2585 let report = Report {
2586 mutants: None,
2587 package: "p".into(),
2588 analysis: Analysis::default(),
2589 audit: None,
2590 evaluation: None,
2591 sites: 4,
2592 skipped_sites: 1,
2593 skipped: vec![],
2594 unviable_mutants: 2,
2595 mutants_not_built: 0,
2596 mutants_not_evaluated: 0,
2597 mutants_not_compiled: 0,
2598 mutants_run: 3,
2599 mutants_killed: 2,
2600 mutants_timed_out: 0,
2601 timeout_rechecks: TimeoutRechecks::default(),
2602 suppressed: 0,
2603 findings: vec![Finding::AssertionGap {
2604 at: at.clone(),
2605 survivors: vec!["delete `s.check()?;`".into()],
2606 tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
2607 effects: vec![],
2608 effects_of: None,
2609 witness: None,
2610 }],
2611 unreached: vec![at.clone()],
2612 unstable: vec![at],
2613 weakened: vec![],
2614 };
2615 let text = render_text(&report, false);
2616 assert!(
2617 text.contains("ASSERTION GAP src/lib.rs:3:9\n s.check()?;"),
2618 "{text}"
2619 );
2620 assert!(text.contains("tests::t4 (+2 more)"), "{text}");
2621 assert!(text.contains("UNSTABLE src/lib.rs:3:9"), "{text}");
2622 assert!(!text.contains("UNREACHED"), "{text}");
2623 assert!(
2624 text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
2625 "{text}"
2626 );
2627 assert!(
2628 text.contains(", 2 mutants left out (they do not compile)\n"),
2629 "{text}"
2630 );
2631 assert!(text.contains("--show-unreached"), "{text}");
2632 let listed = render_text(&report, true);
2633 assert!(listed.contains("UNREACHED src/lib.rs:3:9"));
2634 assert!(!listed.contains("--show-unreached"), "{listed}");
2635 let one_more = Report {
2636 findings: vec![Finding::InputGap {
2637 at: report.unreached[0].clone(),
2638 survivors: vec!["`a`".into()],
2639 survivor_count: 2,
2640 add_tests: vec![],
2641 observed: None,
2642 verified: true,
2643 }],
2644 ..report.clone()
2645 };
2646 assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
2647 let nothing_unreached = Report {
2648 unreached: vec![],
2649 ..report.clone()
2650 };
2651 assert!(!render_text(¬hing_unreached, false).contains("--show-unreached"));
2652 assert!(!Report::default().has_gaps());
2653 }
2654 #[test]
2655 fn unstable_predictions_alone_are_something_to_act_on() {
2656 let at = Location {
2657 file: "src/lib.rs".into(),
2658 line: 1,
2659 column: 1,
2660 code: "a > b".into(),
2661 ..Location::default()
2662 };
2663 assert!(!Report::default().has_gaps());
2664 assert!(
2665 Report {
2666 unstable: vec![at],
2667 ..Report::default()
2668 }
2669 .has_gaps()
2670 );
2671 }
2672
2673 #[test]
2674 fn what_counts_as_a_float_literal() {
2675 assert_eq!(float_literal("30.5"), Some(30.5));
2676 assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
2677 assert_eq!(float_literal("-1e3"), Some(-1000.0));
2678 for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
2681 assert_eq!(float_literal(text), None, "{text}");
2682 }
2683 }
2684
2685 #[test]
2686 fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
2687 let survivors_of = |source: &str| {
2689 let site = site_of(source);
2690 let mut obs = Obs::of_f(-4.0);
2691 obs.merge(&Obs::of_f(4.0));
2692 let gap = InputGap::EqualNeverObserved {
2693 flipped: CmpOp::Ge,
2694 float_gap: obs.float_gap(),
2695 };
2696 match input_gap_finding("f.rs", &site, &gap, &obs, true) {
2697 Some(Finding::InputGap {
2698 survivors,
2699 survivor_count,
2700 ..
2701 }) => (survivors, survivor_count),
2702 _ => panic!(),
2703 }
2704 };
2705 assert_eq!(
2707 survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
2708 (
2709 vec![
2710 "`x >= 9007199254740992.0`".to_string(),
2711 "`x > 9007199254740994.0`".to_string(),
2712 "`x > 9007199254740990.0`".to_string(),
2713 ],
2714 3
2715 )
2716 );
2717 assert_eq!(
2720 survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
2721 (
2722 vec![
2723 "`x >= 18014398509481984.0`".to_string(),
2724 "`x > 1.8014398509481982e16`".to_string(),
2725 ],
2726 2
2727 )
2728 );
2729 assert_eq!(
2730 survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
2731 (
2732 vec![
2733 "`18014398509481984.0 >= x`".to_string(),
2734 "`1.8014398509481982e16 > x`".to_string(),
2735 ],
2736 2
2737 )
2738 );
2739 let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
2741 let mut obs = Obs::of_f(-1.0);
2742 obs.merge(&Obs::of_f(2.0));
2743 let gap = InputGap::EqualNeverObserved {
2744 flipped: CmpOp::Ge,
2745 float_gap: obs.float_gap(),
2746 };
2747 let Some(Finding::InputGap { observed, .. }) =
2748 input_gap_finding("f.rs", &site, &gap, &obs, true)
2749 else {
2750 panic!()
2751 };
2752 assert_eq!(
2753 observed.as_deref(),
2754 Some(
2755 "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
2756 )
2757 );
2758 assert_eq!(
2760 survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
2761 (vec!["`x >= 1e30`".to_string()], 1)
2762 );
2763 }
2764
2765 #[test]
2766 fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
2767 let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
2768 at: Location {
2769 file: "src/lib.rs".into(),
2770 line: 1,
2771 column: 1,
2772 code: "a < b".into(),
2773 ..Location::default()
2774 },
2775 survivors: survivors.iter().map(|s| s.to_string()).collect(),
2776 tests: vec!["tests::t".into()],
2777 effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
2778 effects_of: effects_of.map(str::to_string),
2779 witness: None,
2780 };
2781 let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")));
2783 assert_eq!(
2784 body[2..],
2785 [
2786 "followed one of them through the tests: `a <= b`",
2787 "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
2788 ]
2789 );
2790 for single in [
2792 gap(&["`a <= b`"], Some("`a <= b`")),
2793 gap(&["`a <= b`", "`a == b`"], None),
2794 ] {
2795 let body = finding_body(&single);
2796 assert_eq!(body.len(), 3, "{body:?}");
2797 assert!(body[2].starts_with("with the mutant"), "{body:?}");
2798 }
2799 }
2800
2801 #[test]
2802 fn an_audit_is_said_in_the_summary() {
2803 let mut report = Report {
2804 package: "p".into(),
2805 audit: Some(Audit {
2806 sampled: 2,
2807 survivors: 7,
2808 ..Audit::default()
2809 }),
2810 ..Report::default()
2811 };
2812 let text = render_text(&report, false);
2813 assert!(
2814 text.ends_with(
2815 "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
2816 audit: recorded once more, the tests did the same\n"
2817 ),
2818 "{text}"
2819 );
2820 let audit = report.audit.as_mut().unwrap();
2821 audit.disagreements.push(Location {
2822 file: "src/lib.rs".into(),
2823 line: 3,
2824 column: 5,
2825 code: "x > 5".into(),
2826 ..Location::default()
2827 });
2828 audit.trace_differences.push(TraceDifference {
2829 binary: "p".into(),
2830 records: 4,
2831 rerun_failed: false,
2832 });
2833 let text = render_text(&report, false);
2834 assert!(
2835 text.ends_with(
2836 "all tests, 1 failed one they had not been run against\n\
2837 \x20 src/lib.rs:3:5 x > 5\n\
2838 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
2839 ),
2840 "{text}"
2841 );
2842 assert!(!text.contains("built from the source"), "{text}");
2844 let audit = report.audit.as_mut().unwrap();
2845 audit.rebuilt = 1;
2846 audit.not_compared = 1;
2847 let text = render_text(&report, false);
2848 assert!(
2849 text.contains(
2850 "\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"
2851 ),
2852 "{text}"
2853 );
2854 let audit = report.audit.as_mut().unwrap();
2855 audit.rebuilt = 5;
2856 audit.compared = 4;
2857 audit.source_disagreements.push(SourceDisagreement {
2858 at: Location {
2859 file: "src/lib.rs".into(),
2860 line: 9,
2861 column: 14,
2862 code: "note(asked)".into(),
2863 ..Location::default()
2864 },
2865 mutant: "the guard `note(asked)` replaced by `true`".into(),
2866 as_probe: "passes".into(),
2867 built: "fails".into(),
2868 });
2869 let text = render_text(&report, false);
2870 assert!(
2871 text.contains(
2872 "\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\
2873 \x20 src/lib.rs:9:14 the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
2874 ),
2875 "{text}"
2876 );
2877 assert!(!render_text(&Report::default(), false).contains("audit"));
2878 }
2879
2880 #[test]
2881 fn lists_and_counts_at_their_limits() {
2882 let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
2883 assert_eq!(list(&items, 3), "a, b, c");
2884 assert_eq!(list(&items, 2), "a, b (+1 more)");
2885 assert_eq!(list(&items, 1), "a (+2 more)");
2886 let one = Report {
2887 package: "p".into(),
2888 suppressed: 1,
2889 unviable_mutants: 1,
2890 ..Report::default()
2891 };
2892 assert!(
2893 render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
2894 "{}",
2895 render_text(&one, false)
2896 );
2897 assert!(!render_text(&Report::default(), false).contains("left out"));
2898 assert!(!render_text(&one, false).contains("--rebuild"));
2899 assert!(!render_text(&one, false).contains("not evaluated"));
2900 let at_top = Report {
2901 mutants_not_evaluated: 1,
2902 ..Report::default()
2903 };
2904 assert!(
2905 render_text(&at_top, false).ends_with(
2906 "\n(1 mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it, or a run that could not be judged)\n"
2907 ),
2908 "{}",
2909 render_text(&at_top, false)
2910 );
2911 let not_built = Report {
2913 mutants_not_evaluated: 5,
2914 mutants_not_compiled: 5,
2915 ..Report::default()
2916 };
2917 let text = render_text(¬_built, false);
2918 assert!(
2919 text.ends_with("\n(5 mutants not evaluated: their code is not part of this build (a `cfg` or a feature that is off, or a file of another target); other --features may build it)\n"),
2920 "{text}"
2921 );
2922 assert!(!text.contains("largest value"), "{text}");
2923 let both = Report {
2924 mutants_not_evaluated: 7,
2925 mutants_not_compiled: 5,
2926 ..Report::default()
2927 };
2928 let text = render_text(&both, false);
2929 assert!(
2930 text.contains("(5 mutants not evaluated: their code"),
2931 "{text}"
2932 );
2933 assert!(
2934 text.contains("\n(2 mutants not evaluated: a range"),
2935 "{text}"
2936 );
2937 let quick = Report {
2938 mutants_not_built: 1,
2939 ..Report::default()
2940 };
2941 assert!(
2942 render_text(&quick, false)
2943 .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
2944 "{}",
2945 render_text(&quick, false)
2946 );
2947 let slow = Report {
2948 mutants_run: 5,
2949 mutants_killed: 4,
2950 mutants_timed_out: 2,
2951 ..Report::default()
2952 };
2953 assert!(
2954 render_text(&slow, false)
2955 .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
2956 "{}",
2957 render_text(&slow, false)
2958 );
2959 assert!(!render_text(&one, false).contains("time limit"));
2960 let once = Report {
2961 mutants_timed_out: 1,
2962 ..slow.clone()
2963 };
2964 assert!(
2965 render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
2966 "{}",
2967 render_text(&once, false)
2968 );
2969 assert!(
2970 render_text(&one, false).contains(", 1 findings suppressed"),
2971 "{}",
2972 render_text(&one, false)
2973 );
2974 assert!(!render_text(&Report::default(), false).contains("suppressed"));
2975 }
2976
2977 #[test]
2978 fn findings_are_put_in_reading_order() {
2979 let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
2980 at: Location {
2981 file: file.into(),
2982 line,
2983 column,
2984 code: "x".into(),
2985 ..Location::default()
2986 },
2987 survivors: vec![survivor.into()],
2988 tests: vec![],
2989 effects: vec![],
2990 effects_of: None,
2991 witness: None,
2992 };
2993 let mut report = Report {
2994 findings: vec![
2995 gap("src/b.rs", 1, 1, "b"),
2996 gap("src/a.rs", 9, 5, "statement"),
2997 gap("src/a.rs", 7, 2, "above it"),
2998 gap("src/a.rs", 9, 5, "its operator"),
2999 gap("src/a.rs", 9, 3, "left of both"),
3000 ],
3001 ..Report::default()
3002 };
3003 report.sort_findings();
3004 let order: Vec<&str> = report
3005 .findings
3006 .iter()
3007 .map(|f| match f {
3008 Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
3009 _ => panic!(),
3010 })
3011 .collect();
3012 assert_eq!(
3014 order,
3015 ["above it", "left of both", "statement", "its operator", "b"]
3016 );
3017 }
3018 #[test]
3019 fn second_replacements_guards_fields_and_bodies_in_words() {
3020 let all = |src: &str| discover(src, 0).unwrap().sites;
3021 let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
3022 assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
3023 let Some(Finding::InputGap {
3024 survivors,
3025 add_tests,
3026 ..
3027 }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
3028 else {
3029 panic!()
3030 };
3031 assert_eq!(survivors, ["`total * fee`"]);
3032 assert_eq!(
3033 add_tests,
3034 ["operands for which `total + fee` and `total * fee` differ"]
3035 );
3036 let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
3037 let arith: Vec<&Site> = sites
3038 .iter()
3039 .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
3040 .collect();
3041 assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
3042 assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
3043 let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
3044 assert_eq!(
3045 arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
3046 None
3047 );
3048 assert_eq!(
3050 arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
3051 None
3052 );
3053
3054 let sites = all("fn f(k: Option<i32>, base: O) -> O { \
3055 let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
3056 let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
3057 let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
3058 assert_eq!(
3059 describe(guard, Mutation::Const(true)),
3060 "the guard `n > 1` replaced by `true`"
3061 );
3062 assert_eq!(
3063 guard_gap_finding("f.rs", guard, false, true),
3064 Finding::InputGap {
3065 at: location("f.rs", guard),
3066 survivors: vec!["the guard `n > 1` replaced by `false`".into()],
3067 survivor_count: 1,
3068 add_tests: vec!["a case where the guard `n > 1` is true".into()],
3069 observed: None,
3070 verified: true,
3071 }
3072 );
3073 let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
3074 assert_eq!(describe(neg, Mutation::Delete), "`n`");
3075 let field = of(&|k| matches!(k, SiteKind::Field { .. }));
3076 assert_eq!(
3077 describe(field, Mutation::Delete),
3078 "without the field `depth: d` (it is then `(base).depth`)"
3079 );
3080 let body = of(&|k| matches!(k, SiteKind::Body { .. }));
3081 assert_eq!(
3082 describe(body, Mutation::Delete),
3083 "the body of `f` replaced by `Default::default()`"
3084 );
3085 assert_eq!(
3086 location("f.rs", body).code,
3087 "fn f(k: Option<i32>, base: O) -> O"
3088 );
3089 }
3090
3091 #[test]
3092 fn audit_reports_unjudged_all_tests_reruns_in_text_and_json() {
3093 let mut report = Report {
3094 package: "demo".into(),
3095 audit: Some(Audit {
3096 sampled: 3,
3097 survivors: 3,
3098 not_audited: 2,
3099 ..Audit::default()
3100 }),
3101 ..Report::default()
3102 };
3103 let text = render_text(&report, false);
3104 assert!(
3105 text.contains(
3106 "audit: 3 of 3 surviving mutants run against all tests, 0 failed one they had not been run against, 2 could not be judged\n"
3107 ),
3108 "{text}"
3109 );
3110 let value = serde_json::to_value(&report).unwrap();
3111 assert_eq!(value["audit"]["not_audited"], 2);
3112
3113 report.audit.as_mut().unwrap().not_audited = 0;
3114 let clean_text = render_text(&report, false);
3115 assert!(!clean_text.contains("could not be judged"), "{clean_text}");
3116 let clean_value = serde_json::to_value(&report).unwrap();
3117 assert!(clean_value["audit"].get("not_audited").is_none());
3118 }
3119
3120 #[test]
3121 fn sarif_emits_unstable_predictions() {
3122 let report = Report {
3123 package: "demo".into(),
3124 unstable: vec![Location {
3125 file: "src/lib.rs".into(),
3126 line: 12,
3127 column: 5,
3128 code: "age >= 18".into(),
3129 ..Location::default()
3130 }],
3131 ..Report::default()
3132 };
3133 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3134 let results = sarif["runs"][0]["results"].as_array().unwrap();
3135 assert_eq!(results.len(), 1);
3136 assert_eq!(results[0]["ruleId"], "unstable-prediction");
3137 assert_eq!(results[0]["level"], "error");
3138 assert_eq!(
3139 results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
3140 "src/lib.rs"
3141 );
3142 }
3143
3144 #[test]
3145 fn sarif_emits_weakened_and_audit_disagreements_and_has_gaps() {
3146 let loc = Location {
3147 file: "src/lib.rs".into(),
3148 line: 20,
3149 column: 9,
3150 code: "x > 0".into(),
3151 ..Location::default()
3152 };
3153 let report = Report {
3154 package: "demo".into(),
3155 weakened: vec![loc.clone()],
3156 audit: Some(Audit {
3157 survivors: 1,
3158 sampled: 1,
3159 disagreements: vec![loc.clone()],
3160 not_audited: 0,
3161 rebuilt: 1,
3162 compared: 1,
3163 not_compared: 0,
3164 source_disagreements: vec![SourceDisagreement {
3165 at: loc,
3166 mutant: "`x >= 0`".into(),
3167 as_probe: "passes".into(),
3168 built: "fails".into(),
3169 }],
3170 trace_differences: vec![
3171 TraceDifference {
3172 binary: "unit".into(),
3173 records: 3,
3174 rerun_failed: false,
3175 },
3176 TraceDifference {
3177 binary: "flaky".into(),
3178 records: 0,
3179 rerun_failed: true,
3180 },
3181 TraceDifference {
3182 binary: "flaky-diff".into(),
3183 records: 2,
3184 rerun_failed: true,
3185 },
3186 ],
3187 }),
3188 ..Report::default()
3189 };
3190 assert!(report.has_gaps());
3191 let text = render_text(&report, false);
3192 assert!(
3193 text.contains("`flaky` did not pass: its tests do not always do the same"),
3194 "{text}"
3195 );
3196 assert!(
3197 text.contains(
3198 "`flaky-diff` did not pass and differs in 2 records: its tests do not always do the same"
3199 ),
3200 "{text}"
3201 );
3202 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3203 let results = sarif["runs"][0]["results"].as_array().unwrap();
3204 let rules: Vec<_> = results
3205 .iter()
3206 .map(|r| (r["ruleId"].as_str().unwrap(), r["level"].as_str().unwrap()))
3207 .collect();
3208 assert_eq!(
3209 rules,
3210 [
3211 ("weakened-test", "warning"),
3212 ("audit-disagreement", "error"),
3213 ("audit-disagreement", "error"),
3214 ("audit-disagreement", "error"),
3215 ("audit-disagreement", "error"),
3216 ("audit-disagreement", "error"),
3217 ]
3218 );
3219 assert!(
3220 results[4]["message"]["text"]
3221 .as_str()
3222 .unwrap()
3223 .contains("did not pass"),
3224 "{}",
3225 results[4]
3226 );
3227 assert!(
3228 results[5]["message"]["text"]
3229 .as_str()
3230 .unwrap()
3231 .contains("did not pass and differed in 2 records"),
3232 "{}",
3233 results[5]
3234 );
3235 assert!(sarif["runs"][0]["properties"].get("audit").is_some());
3236 }
3237}