1use serde::Serialize;
5use std::path::PathBuf;
6
7use crate::instrument::{ArithOp, LiteralSide, Site, SiteKind};
8use crate::plan::{CmpOp, InputGap, LogicGap, Mutation, Obs};
9
10pub const SCHEMA_VERSION: u32 = 1;
12
13#[derive(Clone, Debug, Default, PartialEq, Serialize)]
14pub struct Location {
15 pub file: String,
16 pub line: usize,
17 pub column: usize,
18 pub code: String,
19 #[serde(skip_serializing_if = "String::is_empty")]
21 pub item: String,
22 #[serde(skip_serializing_if = "String::is_empty")]
24 pub id: String,
25}
26
27pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
32 format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
33}
34
35#[derive(Clone, Debug, PartialEq, Serialize)]
36#[serde(rename_all = "snake_case", tag = "kind")]
37pub enum Finding {
38 InputGap {
40 #[serde(flatten)]
41 at: Location,
42 survivors: Vec<String>,
44 survivor_count: u128,
46 add_tests: Vec<String>,
48 observed: Option<String>,
50 verified: bool,
52 },
53 AssertionGap {
55 #[serde(flatten)]
56 at: Location,
57 survivors: Vec<String>,
58 tests: Vec<String>,
60 effects: Vec<String>,
63 effects_of: Option<String>,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 witness: Option<VerifiedWitness>,
67 },
68 Survivor {
72 #[serde(flatten)]
73 at: Location,
74 survivors: Vec<String>,
75 #[serde(skip_serializing_if = "Option::is_none")]
76 witness: Option<VerifiedWitness>,
77 #[serde(skip_serializing_if = "Option::is_none")]
80 change_since: Option<String>,
81 #[serde(skip_serializing_if = "Option::is_none")]
83 advice: Option<String>,
84 },
85}
86
87#[derive(Clone, Debug, PartialEq, Serialize)]
88pub struct VerifiedWitness {
89 pub call: String,
90 pub original: String,
91 pub mutant: String,
92 pub assertion: String,
93 #[serde(skip_serializing_if = "Option::is_none")]
96 pub field: Option<String>,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 pub guidance: Option<String>,
99 #[serde(skip_serializing_if = "Option::is_none")]
100 pub individually_killed: Option<usize>,
101 #[serde(skip_serializing_if = "Option::is_none")]
104 pub in_test: Option<String>,
105 #[serde(skip_serializing_if = "Option::is_none")]
107 pub in_test_line: Option<usize>,
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub in_test_column: Option<usize>,
110}
111
112impl Finding {
113 pub fn at(&self) -> &Location {
114 let (Finding::InputGap { at, .. }
115 | Finding::AssertionGap { at, .. }
116 | Finding::Survivor { at, .. }) = self;
117 at
118 }
119
120 pub fn at_mut(&mut self) -> &mut Location {
121 let (Finding::InputGap { at, .. }
122 | Finding::AssertionGap { at, .. }
123 | Finding::Survivor { at, .. }) = self;
124 at
125 }
126
127 pub fn survivors(&self) -> &[String] {
128 let (Finding::InputGap { survivors, .. }
129 | Finding::AssertionGap { survivors, .. }
130 | Finding::Survivor { survivors, .. }) = self;
131 survivors
132 }
133
134 pub(crate) fn set_witness(&mut self, evidence: VerifiedWitness) {
135 match self {
136 Self::AssertionGap { witness, .. } | Self::Survivor { witness, .. } => {
137 if witness.is_none() {
138 *witness = Some(evidence);
139 }
140 }
141 Self::InputGap { .. } => {}
142 }
143 }
144
145 pub fn kind(&self) -> &'static str {
147 match self {
148 Finding::InputGap { .. } => "input_gap",
149 Finding::AssertionGap { .. } => "assertion_gap",
150 Finding::Survivor { .. } => "survivor",
151 }
152 }
153}
154
155#[derive(Clone, Debug, Default, PartialEq, Serialize)]
157pub struct CargoConfig {
158 pub features: Vec<String>,
159 pub all_features: bool,
160 pub no_default_features: bool,
161 pub locked: bool,
162}
163
164#[derive(Clone, Debug, Default, PartialEq, Serialize)]
166pub struct Nextest {
167 #[serde(skip_serializing_if = "Option::is_none")]
168 pub profile: Option<String>,
169}
170
171#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
172pub struct Shard {
173 pub index: usize,
174 pub count: usize,
175 pub round_robin: bool,
176}
177
178#[derive(Clone, Debug, Default, PartialEq, Serialize)]
179pub struct Analysis {
180 pub package_path: String,
182 pub since: Option<String>,
184 pub lines: Vec<String>,
186 #[serde(skip_serializing_if = "Vec::is_empty")]
188 pub exclude_files: Vec<String>,
189 pub tests_of: Vec<String>,
191 pub cargo: CargoConfig,
192 pub opt_level: Option<u8>,
193 #[serde(skip_serializing_if = "Option::is_none")]
194 pub timeout_seconds: Option<u64>,
195 #[serde(skip_serializing_if = "Option::is_none")]
196 pub baseline_timeout_seconds: Option<u64>,
197 #[serde(skip_serializing_if = "Option::is_none")]
198 pub baseline_jobs: Option<usize>,
199 pub timeout_recheck: &'static str,
200 #[serde(skip_serializing_if = "Option::is_none")]
201 pub wrapper_grace_seconds: Option<u64>,
202 pub rebuild: bool,
204 pub verified: bool,
206 pub doc_tests: bool,
207 #[serde(skip_serializing_if = "std::ops::Not::not")]
208 pub source_only: bool,
209 #[serde(skip_serializing_if = "std::ops::Not::not")]
210 pub literal_operators: bool,
211 #[serde(skip_serializing_if = "Option::is_none")]
212 pub shard: Option<Shard>,
213 #[serde(skip_serializing_if = "Option::is_none")]
214 pub nextest: Option<Nextest>,
215 #[serde(skip_serializing_if = "Vec::is_empty")]
216 pub error_values: Vec<String>,
217 #[serde(skip_serializing_if = "Option::is_none")]
218 pub test_selection: Option<TestSelection>,
219 #[serde(skip_serializing_if = "std::ops::Not::not")]
220 pub git_index: bool,
221 #[serde(skip_serializing_if = "Vec::is_empty")]
222 pub copy_fixtures: Vec<PathBuf>,
223 #[serde(skip_serializing_if = "Vec::is_empty")]
224 pub copy_fixture_excludes: Vec<PathBuf>,
225 #[serde(skip_serializing_if = "Vec::is_empty")]
226 pub output_fixtures: Vec<crate::output_fixture::Fixture>,
227 #[serde(skip_serializing_if = "Vec::is_empty")]
228 pub stage_external: Vec<crate::driver::StageExternal>,
229 #[serde(skip_serializing_if = "Option::is_none")]
230 pub checkpoint: Option<PathBuf>,
231}
232
233#[derive(Clone, Debug, Default, PartialEq, Serialize)]
234pub struct TestSelection {
235 pub build_scope: TestBuildScope,
236 pub wrapper: Option<String>,
237 pub tests: Vec<String>,
238}
239
240#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
241#[serde(rename_all = "snake_case")]
242pub enum TestBuildScope {
243 #[default]
244 PackageWide,
245 SelectedTargets,
246}
247
248fn serialize_path_lossy<S: serde::Serializer>(
249 path: &std::path::Path,
250 serializer: S,
251) -> Result<S::Ok, S::Error> {
252 serializer.serialize_str(&path.to_string_lossy())
253}
254
255#[derive(Clone, Debug, PartialEq, Serialize)]
257pub struct BaselineTimingEntry {
258 pub runner: String,
259 #[serde(skip_serializing_if = "Option::is_none")]
260 pub test: Option<String>,
261 pub elapsed_seconds: f64,
262}
263
264#[derive(Clone, Debug, PartialEq, Serialize)]
266pub struct BaselineTimeoutDiagnostic {
267 pub schema_version: u32,
268 pub package: String,
269 pub stage: &'static str,
270 pub runner: String,
271 #[serde(skip_serializing_if = "Option::is_none")]
272 pub test: Option<String>,
273 pub elapsed_seconds: f64,
274 pub budget_seconds: u64,
275 pub completed_baselines: usize,
276 pub total_baselines: usize,
277 pub partial_baseline: bool,
278 #[serde(serialize_with = "serialize_path_lossy")]
279 pub log: PathBuf,
280 #[serde(skip_serializing_if = "Vec::is_empty")]
281 pub lines: Vec<String>,
282 #[serde(skip_serializing_if = "Vec::is_empty")]
283 pub rerun_args: Vec<String>,
284 #[serde(skip_serializing_if = "Vec::is_empty")]
285 pub exclude_args: Vec<String>,
286 #[serde(skip_serializing_if = "Vec::is_empty")]
287 pub completed_timings: Vec<BaselineTimingEntry>,
288 #[serde(skip_serializing_if = "Vec::is_empty")]
289 pub log_summary: Vec<String>,
290}
291
292#[derive(Clone, Debug, PartialEq, Serialize)]
294pub struct BaselineFailureDiagnostic {
295 pub schema_version: u32,
296 pub package: String,
297 pub stage: &'static str,
298 pub runner: String,
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub test: Option<String>,
301 pub reason: &'static str,
302 pub elapsed_seconds: f64,
303 pub completed_baselines: usize,
304 pub total_baselines: usize,
305 #[serde(serialize_with = "serialize_path_lossy")]
306 pub log: PathBuf,
307 #[serde(skip_serializing_if = "Vec::is_empty")]
308 pub completed_timings: Vec<BaselineTimingEntry>,
309 #[serde(skip_serializing_if = "Vec::is_empty")]
310 pub log_summary: Vec<String>,
311}
312
313#[derive(Clone, Debug, PartialEq, Serialize)]
315pub struct BaselineErrorReport {
316 pub schema_version: u32,
317 pub package: String,
318 pub evaluation: Evaluation,
319 pub error: String,
320 #[serde(skip_serializing_if = "Option::is_none")]
321 pub wrapper_grace_outcomes: Option<WrapperGraceOutcomes>,
322 #[serde(skip_serializing_if = "Option::is_none")]
323 pub baseline_timeout: Option<BaselineTimeoutDiagnostic>,
324 #[serde(skip_serializing_if = "Option::is_none")]
325 pub baseline_failure: Option<BaselineFailureDiagnostic>,
326}
327
328#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
334pub struct WrapperGraceOutcomes {
335 pub exited: usize,
337 pub expired: usize,
339}
340
341#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
342#[serde(rename_all = "snake_case")]
343pub enum Evaluation {
344 NoSites,
345 NoMutantsExecuted,
346 Partial,
349 BaselineFailed,
351}
352
353#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
358pub struct SurvivorBreakdown {
359 pub reported: usize,
362 pub suppressed: usize,
364 pub redundant_constant: usize,
367 pub preexisting_unchanged: usize,
370 pub unchanged_not_compared: usize,
374 pub unconfirmed_gap: usize,
377}
378
379impl SurvivorBreakdown {
380 pub fn checked_total(&self) -> Option<usize> {
382 self.reported
383 .checked_add(self.suppressed)?
384 .checked_add(self.redundant_constant)?
385 .checked_add(self.preexisting_unchanged)?
386 .checked_add(self.unchanged_not_compared)?
387 .checked_add(self.unconfirmed_gap)
388 }
389
390 pub fn total(&self) -> usize {
392 self.reported
393 + self.suppressed
394 + self.redundant_constant
395 + self.preexisting_unchanged
396 + self.unchanged_not_compared
397 + self.unconfirmed_gap
398 }
399
400 pub fn unreported(&self) -> usize {
402 self.redundant_constant
403 + self.preexisting_unchanged
404 + self.unchanged_not_compared
405 + self.unconfirmed_gap
406 }
407}
408
409#[derive(Clone, Debug, Default, PartialEq, Serialize)]
410pub struct TimeoutRechecks {
411 pub first_pass: usize,
412 pub confirmed: usize,
413 pub recovered: usize,
414 pub unconfirmed: usize,
415}
416
417impl TimeoutRechecks {
418 fn is_empty(&self) -> bool {
419 self.first_pass == 0
420 }
421}
422
423#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
424#[serde(rename_all = "snake_case")]
425pub enum SkipReason {
426 ProbeCompileError,
427 ProbeReplacedBySourceRebuild,
428 RequiresSourceRebuild,
429 SourceNotBuilt,
430 UnparseableSource,
431}
432
433#[derive(Clone, Debug, PartialEq, Serialize)]
434pub struct SkippedSite {
435 #[serde(flatten)]
436 pub at: Location,
437 pub end_line: usize,
438 pub end_column: usize,
439 pub reason: SkipReason,
440 #[serde(skip_serializing_if = "Option::is_none")]
441 pub diagnostic: Option<String>,
442}
443
444impl SkippedSite {
445 pub(crate) fn new(
446 at: Location,
447 (end_line, end_column): (usize, usize),
448 reason: SkipReason,
449 diagnostic: Option<String>,
450 ) -> Self {
451 Self {
452 at,
453 end_line,
454 end_column,
455 reason,
456 diagnostic,
457 }
458 }
459}
460
461fn is_zero_usize(value: &usize) -> bool {
462 *value == 0
463}
464
465#[derive(Clone, Debug, Default, PartialEq, Serialize)]
467pub struct Audit {
468 pub sampled: usize,
470 pub survivors: usize,
472 #[serde(skip_serializing_if = "is_zero_usize")]
474 pub not_audited: usize,
475 pub disagreements: Vec<Location>,
478 pub trace_differences: Vec<TraceDifference>,
481 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
483 pub trace_rerun_incomplete: bool,
484 pub rebuilt: usize,
486 pub compared: usize,
488 pub not_compared: usize,
491 pub source_disagreements: Vec<SourceDisagreement>,
493}
494
495#[derive(Clone, Debug, Default, PartialEq, Serialize)]
497pub struct SourceDisagreement {
498 #[serde(flatten)]
499 pub at: Location,
500 pub mutant: String,
501 pub as_probe: String,
503 pub built: String,
504}
505
506#[derive(Clone, Debug, Default, PartialEq, Serialize)]
507pub struct TraceDifference {
508 pub binary: String,
509 pub records: usize,
510 #[serde(skip_serializing_if = "std::ops::Not::not")]
511 pub rerun_failed: bool,
512}
513
514#[derive(Clone, Debug, PartialEq, Serialize)]
516pub struct CandidateEdit {
517 pub file: String,
518 pub line: usize,
519 pub column: usize,
520 pub start: usize,
521 pub end: usize,
522 pub before: String,
523 pub replacement: String,
524}
525
526#[derive(Clone, Debug, PartialEq, Serialize)]
527pub struct Candidate {
528 pub what: String,
529 pub into: String,
530 pub requires_rebuild: bool,
531 pub edits: Vec<CandidateEdit>,
532}
533
534#[derive(Clone, Debug, PartialEq, Serialize)]
535pub struct Report {
536 pub schema_version: u32,
537 pub package: String,
538 #[serde(skip_serializing_if = "Option::is_none")]
539 pub mutants: Option<Vec<Candidate>>,
540 pub analysis: Analysis,
541 #[serde(skip_serializing_if = "Option::is_none")]
543 pub audit: Option<Audit>,
544 #[serde(skip_serializing_if = "Option::is_none")]
545 pub evaluation: Option<Evaluation>,
546 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
549 pub interrupted: bool,
550 pub sites: usize,
551 pub skipped_sites: usize,
553 #[serde(skip_serializing_if = "Vec::is_empty")]
554 pub skipped: Vec<SkippedSite>,
555 pub unviable_mutants: usize,
558 pub mutants_not_built: usize,
560 pub mutants_not_evaluated: usize,
563 pub mutants_not_compiled: usize,
566 pub mutants_run: usize,
567 pub mutants_killed: usize,
568 pub mutants_timed_out: usize,
571 pub mutants_survived: usize,
573 pub survivor_breakdown: SurvivorBreakdown,
575 #[serde(skip_serializing_if = "TimeoutRechecks::is_empty")]
576 pub timeout_rechecks: TimeoutRechecks,
577 #[serde(skip_serializing_if = "Option::is_none")]
579 pub wrapper_grace_outcomes: Option<WrapperGraceOutcomes>,
580 pub findings: Vec<Finding>,
581 pub suppressed: usize,
583 #[serde(skip_serializing_if = "Option::is_none")]
585 pub baseline: Option<PathBuf>,
586 #[serde(skip_serializing_if = "Vec::is_empty")]
589 pub unassessed_test_changes: Vec<String>,
590 pub unreached: Vec<Location>,
592 pub unstable: Vec<Location>,
594 #[serde(skip_serializing_if = "Vec::is_empty")]
597 pub weakened: Vec<Location>,
598}
599
600impl Default for Report {
601 fn default() -> Self {
602 Self {
603 schema_version: SCHEMA_VERSION,
604 package: String::new(),
605 mutants: None,
606 analysis: Analysis::default(),
607 audit: None,
608 evaluation: None,
609 interrupted: false,
610 sites: 0,
611 skipped_sites: 0,
612 skipped: Vec::new(),
613 unviable_mutants: 0,
614 mutants_not_built: 0,
615 mutants_not_evaluated: 0,
616 mutants_not_compiled: 0,
617 mutants_run: 0,
618 mutants_killed: 0,
619 mutants_timed_out: 0,
620 mutants_survived: 0,
621 survivor_breakdown: SurvivorBreakdown::default(),
622 timeout_rechecks: TimeoutRechecks::default(),
623 wrapper_grace_outcomes: None,
624 findings: Vec::new(),
625 suppressed: 0,
626 baseline: None,
627 unassessed_test_changes: Vec::new(),
628 unreached: Vec::new(),
629 unstable: Vec::new(),
630 weakened: Vec::new(),
631 }
632 }
633}
634
635impl Report {
636 pub(crate) fn record_evaluation(&mut self) {
637 self.evaluation = if self.mutants_run == 0 {
638 if !self.interrupted
639 && self.sites == 0
640 && self.skipped.is_empty()
641 && self.mutants_not_built == 0
642 && self.mutants_not_evaluated == 0
643 {
644 Some(Evaluation::NoSites)
645 } else {
646 Some(Evaluation::NoMutantsExecuted)
647 }
648 } else if self.interrupted
649 || self.mutants_not_built > 0
650 || self.mutants_not_evaluated > 0
651 || self.skipped_sites > 0
652 || self.timeout_rechecks.unconfirmed > 0
653 || self.survivor_breakdown.unchanged_not_compared > 0
654 || (self.analysis.source_only && self.mutants_timed_out > 0)
655 || self
656 .skipped
657 .iter()
658 .any(|entry| entry.reason == SkipReason::UnparseableSource)
659 {
660 Some(Evaluation::Partial)
661 } else {
662 None
663 };
664 }
665
666 pub fn counts_reconcile(&self) -> bool {
671 self.mutants_killed.checked_add(self.mutants_survived) == Some(self.mutants_run)
672 && self.mutants_timed_out <= self.mutants_killed
673 && self.survivor_breakdown.checked_total() == Some(self.mutants_survived)
674 }
675
676 pub fn sort_findings(&mut self) {
679 self.findings.sort_by(|a, b| {
680 let (a, b) = (a.at(), b.at());
681 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
682 });
683 }
684
685 pub fn has_gaps(&self) -> bool {
688 !self.findings.is_empty()
689 || !self.unstable.is_empty()
690 || self.audit.as_ref().is_some_and(|audit| {
691 !audit.disagreements.is_empty()
692 || !audit.source_disagreements.is_empty()
693 || !audit.trace_differences.is_empty()
694 })
695 }
696}
697
698pub fn location(file: &str, site: &Site) -> Location {
699 Location {
700 file: file.to_string(),
701 line: site.line,
702 column: site.column,
703 code: one_line(&site.text),
704 ..Location::default()
705 }
706}
707
708pub(crate) fn short_revision(revision: &str) -> &str {
710 let full = revision.len() >= 40 && revision.bytes().all(|byte| byte.is_ascii_hexdigit());
711 if full { &revision[..12] } else { revision }
712}
713
714pub(crate) fn one_line(code: &str) -> String {
715 const LIMIT: usize = 100;
716 const ELLIPSIS: &str = "...";
717 const PREFIX: usize = LIMIT - ELLIPSIS.len();
718
719 if code.len() <= 4 * LIMIT {
722 let mut words = code.split_whitespace();
723 let Some(first) = words.next() else {
724 return String::new();
725 };
726 let mut output = String::with_capacity(code.len());
727 output.push_str(first);
728 for word in words {
729 output.push(' ');
730 output.push_str(word);
731 }
732 if output.len() > LIMIT && output.chars().count() > LIMIT {
734 let cut = output.char_indices().nth(PREFIX).unwrap().0;
735 output.truncate(cut);
736 output.push_str(ELLIPSIS);
737 }
738 return output;
739 }
740
741 let mut output = String::with_capacity(LIMIT);
742 let mut width = 0;
743 let mut shortened_at = 0;
744 let mut separated = false;
745 for ch in code.chars() {
746 if ch.is_whitespace() {
747 separated = width != 0;
748 continue;
749 }
750 for ch in [separated.then_some(' '), Some(ch)].into_iter().flatten() {
751 if width == LIMIT {
752 output.truncate(shortened_at);
753 output.push_str(ELLIPSIS);
754 return output;
755 }
756 output.push(ch);
757 width += 1;
758 if width == PREFIX {
759 shortened_at = output.len();
760 }
761 }
762 separated = false;
763 }
764 output
765}
766
767fn float_literal(text: &str) -> Option<f64> {
769 let text = text.trim().replace('_', "");
770 let text = text
771 .strip_suffix("f32")
772 .or(text.strip_suffix("f64"))
773 .unwrap_or(&text);
774 let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
775 && text
776 .chars()
777 .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
778 if looks_numeric {
779 text.parse().ok()
780 } else {
781 None
782 }
783}
784
785fn show_float(v: f64) -> String {
788 format!("{v:?}")
789}
790
791pub fn describe(site: &Site, m: Mutation) -> String {
793 match &site.kind {
794 SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
795 SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
796 SiteKind::Guard { .. } => match m {
797 Mutation::Const(value) => {
798 format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
799 }
800 _ => format!("another guard than `{}`", one_line(&site.text)),
801 },
802 SiteKind::Field {
803 from_base: Some(from_base),
804 ..
805 } => format!(
806 "without the field `{}` (it is then `{from_base}`)",
807 one_line(&site.text)
808 ),
809 SiteKind::Field {
810 from_base: None, ..
811 } => format!("without the field `{}`", one_line(&site.text)),
812 SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
813 SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
814 SiteKind::Return { name, option, .. } => match (m, option) {
815 (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
816 (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
817 _ => format!("`{name}` returning something else"),
818 },
819 SiteKind::Range {
820 inclusive,
821 lhs,
822 rhs,
823 ..
824 } => {
825 let dots = if *inclusive { ".." } else { "..=" };
826 format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
827 }
828 SiteKind::RangeContains {
829 inclusive,
830 lhs,
831 rhs,
832 argument,
833 ..
834 } => {
835 let dots = if *inclusive { ".." } else { "..=" };
836 format!(
837 "`({}{dots}{}).contains({})`",
838 one_line(lhs),
839 one_line(rhs),
840 one_line(argument)
841 )
842 }
843 SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
844 SiteKind::MinMax {
845 max,
846 receiver,
847 argument,
848 ..
849 } => {
850 let other = if *max { "min" } else { "max" };
851 format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
852 }
853 SiteKind::SliceEnd {
854 first, receiver, ..
855 } => {
856 let other = if *first { "last" } else { "first" };
857 format!("`{}.{other}()`", one_line(receiver))
858 }
859 SiteKind::StrAffix {
860 receiver, pattern, ..
861 } => format!("`{}.contains({})`", one_line(receiver), one_line(pattern)),
862 SiteKind::StrReplace {
863 replace_all,
864 receiver,
865 from,
866 to,
867 ..
868 } => {
869 let (r, f, t) = (one_line(receiver), one_line(from), one_line(to));
870 if *replace_all {
871 format!("`{r}.replacen({f}, {t}, 1)`")
872 } else {
873 format!("`{r}.replace({f}, {t})`")
874 }
875 }
876 SiteKind::Clamp {
877 receiver,
878 low,
879 high,
880 ..
881 } => match m {
882 Mutation::ClampDropLower => format!("`{}.min({})`", one_line(receiver), one_line(high)),
883 _ => format!("`{}.max({})`", one_line(receiver), one_line(low)),
884 },
885 SiteKind::Rounding { op, receiver, .. } => {
886 let alt = match m {
887 Mutation::RoundAlt2 => op.alt2(),
888 _ => op.alt1(),
889 };
890 format!("`{}.{}()`", one_line(receiver), alt.name())
891 }
892 SiteKind::Quantifier {
893 all,
894 receiver,
895 predicate,
896 ..
897 } => {
898 let other = if *all { "any" } else { "all" };
899 format!("`{}.{other}({})`", one_line(receiver), one_line(predicate))
900 }
901 SiteKind::Position {
902 forward,
903 receiver,
904 predicate,
905 ..
906 } => {
907 let other = if *forward { "rposition" } else { "position" };
908 format!("`{}.{other}({})`", one_line(receiver), one_line(predicate))
909 }
910 SiteKind::SaturatingArith {
911 op,
912 receiver,
913 argument,
914 ..
915 } => format!(
916 "`{}.{}({})`",
917 one_line(receiver),
918 op.swapped().name(),
919 one_line(argument)
920 ),
921 SiteKind::StrTrim { op, receiver, .. } => {
922 let alt = match m {
923 Mutation::TrimAlt2 => op.alt2().unwrap_or_else(|| op.alt1()),
924 _ => op.alt1(),
925 };
926 format!("`{}.{}()`", one_line(receiver), alt.name())
927 }
928 SiteKind::StrCaseEq {
929 receiver, argument, ..
930 } => format!("`{} == {}`", one_line(receiver), one_line(argument)),
931 SiteKind::Abs { receiver, .. } => format!("`{}` (without `.abs()`)", one_line(receiver)),
932 SiteKind::IterLimit { take, receiver, .. } => {
933 if *take {
934 format!("`{}.take(usize::MAX)`", one_line(receiver))
935 } else {
936 format!("`{}.skip(0)`", one_line(receiver))
937 }
938 }
939 SiteKind::EndianSwap { op, receiver, .. } => {
940 format!("`{}.{}()`", one_line(receiver), op.swapped().name())
941 }
942 SiteKind::BitCount { op, receiver, .. } => {
943 format!("`{}.{}()`", one_line(receiver), op.swapped().name())
944 }
945 SiteKind::LoopCtrl { is_break } => {
946 if *is_break {
947 "`continue`".to_string()
948 } else {
949 "`break`".to_string()
950 }
951 }
952 SiteKind::LiteralSet {
953 receiver,
954 argument,
955 elements,
956 ..
957 } => match m {
958 Mutation::DropLiteralElem(idx) => {
959 if let Some((elem, _, _)) = elements.get(idx as usize) {
960 format!(
961 "without `{}` in `{}.contains({})`",
962 one_line(elem),
963 one_line(receiver),
964 one_line(argument)
965 )
966 } else {
967 format!(
968 "without a literal element in `{}.contains({})`",
969 one_line(receiver),
970 one_line(argument)
971 )
972 }
973 }
974 _ => format!(
975 "without a literal element in `{}.contains({})`",
976 one_line(receiver),
977 one_line(argument)
978 ),
979 },
980 SiteKind::Logic { and, lhs, rhs, .. } => {
981 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
982 match m {
983 Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
986 Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
987 Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
988 _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
989 }
990 }
991 SiteKind::Arith {
992 op,
993 assign,
994 lhs,
995 rhs,
996 ..
997 } => {
998 let eq = if *assign { "=" } else { "" };
999 let other = match m {
1000 Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
1001 _ => op.swapped(),
1002 };
1003 format!(
1004 "`{} {}{eq} {}`",
1005 one_line(lhs),
1006 other.symbol(),
1007 one_line(rhs)
1008 )
1009 }
1010 SiteKind::Cmp {
1011 op,
1012 lhs,
1013 rhs,
1014 literal,
1015 ..
1016 } => {
1017 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1018 let sym = op.symbol();
1019 match m {
1020 Mutation::Const(c) => format!("`{c}`"),
1021 Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
1022 Mutation::Shift(d) => {
1023 let display = literal_display_kind(&lhs, &rhs, *literal);
1024 match literal {
1025 LiteralSide::Rhs(k) => {
1026 format!("`{lhs} {sym} {}`", format_shifted_literal(k + d, display))
1027 }
1028 LiteralSide::Lhs(k) => {
1030 format!("`{} {sym} {rhs}`", format_shifted_literal(k - d, display))
1031 }
1032 LiteralSide::None => match (op, d) {
1033 (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
1034 (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
1035 (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
1036 (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
1037 (_, d) if d > 0 => {
1041 format!("`{lhs} {sym} {rhs} + {d}` (without overflow)")
1042 }
1043 (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
1044 },
1045 }
1046 }
1047 Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
1048 (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
1049 (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
1050 _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
1052 _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
1053 },
1054 _ => format!("`!({lhs} {sym} {rhs})`"),
1055 }
1056 }
1057 }
1058}
1059
1060#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1061enum LiteralDisplay {
1062 Int,
1063 Byte,
1064 Char,
1065}
1066
1067fn literal_display_kind(lhs: &str, rhs: &str, literal: LiteralSide) -> LiteralDisplay {
1068 let text = match literal {
1069 LiteralSide::Rhs(_) => rhs,
1070 LiteralSide::Lhs(_) => lhs,
1071 LiteralSide::None => return LiteralDisplay::Int,
1072 };
1073 let Ok(mut expr) = syn::parse_str::<syn::Expr>(text) else {
1074 return LiteralDisplay::Int;
1075 };
1076 loop {
1077 match expr {
1078 syn::Expr::Paren(inner) => expr = *inner.expr,
1079 syn::Expr::Group(inner) => expr = *inner.expr,
1080 _ => break,
1081 }
1082 }
1083 match expr {
1084 syn::Expr::Lit(syn::ExprLit {
1085 lit: syn::Lit::Byte(_),
1086 ..
1087 }) => LiteralDisplay::Byte,
1088 syn::Expr::Lit(syn::ExprLit {
1089 lit: syn::Lit::Char(_),
1090 ..
1091 }) => LiteralDisplay::Char,
1092 _ => LiteralDisplay::Int,
1093 }
1094}
1095
1096fn format_byte_lit(b: u8) -> String {
1097 match b {
1098 b'\'' => "b'\\''".to_string(),
1099 b'\\' => "b'\\\\'".to_string(),
1100 b'\n' => "b'\\n'".to_string(),
1101 b'\r' => "b'\\r'".to_string(),
1102 b'\t' => "b'\\t'".to_string(),
1103 b'\0' => "b'\\0'".to_string(),
1104 0x20..=0x7e => format!("b'{}'", b as char),
1105 _ => format!("b'\\x{b:02x}'"),
1106 }
1107}
1108
1109fn ord_to_char(ord: i128) -> Option<char> {
1110 let u = u32::try_from(ord).ok()?;
1111 let scalar = if u < 0xD800 {
1112 u
1113 } else if u <= 0x10_D7FF {
1114 u + 0x800
1115 } else {
1116 return None;
1117 };
1118 char::from_u32(scalar)
1119}
1120
1121fn format_shifted_literal(v: i128, display: LiteralDisplay) -> String {
1122 match display {
1123 LiteralDisplay::Byte => u8::try_from(v)
1124 .map(format_byte_lit)
1125 .unwrap_or_else(|_| v.to_string()),
1126 LiteralDisplay::Char => ord_to_char(v)
1127 .map(|c| format!("{c:?}"))
1128 .unwrap_or_else(|| v.to_string()),
1129 LiteralDisplay::Int => v.to_string(),
1130 }
1131}
1132
1133fn format_literal_value(v: i128, display: LiteralDisplay) -> String {
1134 match display {
1135 LiteralDisplay::Byte => u8::try_from(v)
1136 .map(|b| format!("{} ({b})", format_byte_lit(b)))
1137 .unwrap_or_else(|_| v.to_string()),
1138 LiteralDisplay::Char => ord_to_char(v)
1139 .map(|c| format!("{c:?} ({})", c as u32))
1140 .unwrap_or_else(|| v.to_string()),
1141 LiteralDisplay::Int => v.to_string(),
1142 }
1143}
1144
1145fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
1147 let display = literal_display_kind(lhs, rhs, literal);
1148 match (literal, d) {
1149 (LiteralSide::Rhs(k), d) => {
1150 format!("`{lhs}` = {}", format_literal_value(k + d, display))
1151 }
1152 (LiteralSide::Lhs(k), d) => {
1153 format!("`{rhs}` = {}", format_literal_value(k - d, display))
1154 }
1155 (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
1156 (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
1158 (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
1159 }
1160}
1161
1162fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
1163 if !obs.valued() {
1164 return None;
1165 }
1166 let display = literal_display_kind(lhs, rhs, literal);
1167 let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
1168 .into_iter()
1169 .flatten()
1170 .collect();
1171 let text = match literal {
1172 LiteralSide::Rhs(k) => {
1173 let values: Vec<String> = ds
1174 .iter()
1175 .map(|d| format_literal_value(k + d, display))
1176 .collect();
1177 format!("`{lhs}` = {}", values.join(", "))
1178 }
1179 LiteralSide::Lhs(k) => {
1180 let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
1181 values.sort();
1182 let values: Vec<String> = values
1183 .iter()
1184 .map(|v| format_literal_value(*v, display))
1185 .collect();
1186 format!("`{rhs}` = {}", values.join(", "))
1187 }
1188 LiteralSide::None => {
1189 let values: Vec<String> = ds.iter().map(i128::to_string).collect();
1190 format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
1191 }
1192 };
1193 Some(format!("nearest values the tests passed: {text}"))
1194}
1195
1196pub fn input_gap_finding(
1199 file: &str,
1200 site: &Site,
1201 gap: &InputGap,
1202 obs: &Obs,
1203 verified: bool,
1204) -> Option<Finding> {
1205 let SiteKind::Cmp {
1206 op,
1207 lhs,
1208 rhs,
1209 literal,
1210 ..
1211 } = &site.kind
1212 else {
1213 return None;
1214 };
1215 let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
1216 let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
1219 (None, Some(k)) => k + d != k,
1220 (Some(k), None) => k - d != k,
1221 _ => true,
1222 };
1223 let survivors: Vec<String> = gap
1224 .survivors()
1225 .into_iter()
1226 .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
1227 .map(|m| describe(site, m))
1228 .collect();
1229 let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
1230 let (survivor_count, add_tests) = match gap {
1231 InputGap::Unreached => return None,
1232 InputGap::OneSided { always } => (
1233 1,
1234 vec![format!(
1235 "an input that makes `{}` {}",
1236 one_line(&site.text),
1237 !always
1238 )],
1239 ),
1240 InputGap::EqualNeverObserved { flipped, float_gap } => {
1241 if let Some((lo, hi)) = float_gap {
1242 observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
1243 (None, Some(k)) => format!(
1244 "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
1245 show_float(k + lo),
1246 show_float(k + hi)
1247 ),
1248 (Some(k), None) => format!(
1249 "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
1250 show_float(k - hi),
1251 show_float(k - lo)
1252 ),
1253 _ => format!(
1254 "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
1255 show_float(*lo),
1256 show_float(*hi)
1257 ),
1258 });
1259 }
1260 (
1261 survivors.len() as u128,
1262 vec![format!(
1263 "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
1264 op.eval_d(0),
1265 flipped.eval_d(0)
1266 )],
1267 )
1268 }
1269 InputGap::Boundary {
1270 min_shift,
1271 max_shift,
1272 missing,
1273 same,
1274 } => {
1275 let add = missing
1276 .iter()
1277 .map(|d| {
1278 format!(
1279 "{} (the original gives {})",
1280 input_for(&lhs_text, &rhs_text, *literal, *d),
1281 op.eval_d(*d)
1282 )
1283 })
1284 .collect();
1285 (((max_shift - min_shift) - (same.1 - same.0)) as u128, add)
1288 }
1289 };
1290 Some(Finding::InputGap {
1291 at: location(file, site),
1292 survivors,
1293 survivor_count,
1294 add_tests,
1295 observed,
1296 verified,
1297 })
1298}
1299
1300pub fn logic_gap_finding(
1302 file: &str,
1303 site: &Site,
1304 gap: LogicGap,
1305 verified: bool,
1306) -> Option<Finding> {
1307 let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
1308 return None;
1309 };
1310 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1311 let (mutation, add) = match (gap, and) {
1312 (LogicGap::Unreached, _) => return None,
1313 (LogicGap::RhsNeverDecides, true) => (
1314 Mutation::LogicDropRhs,
1315 format!("a case where `{lhs}` is true and `{rhs}` is false"),
1316 ),
1317 (LogicGap::RhsNeverDecides, false) => (
1318 Mutation::LogicDropRhs,
1319 format!("a case where `{lhs}` is false and `{rhs}` is true"),
1320 ),
1321 (LogicGap::LhsNeverDecides, true) => (
1322 Mutation::LogicDropLhs,
1323 format!("a case where `{lhs}` is false"),
1324 ),
1325 (LogicGap::LhsNeverDecides, false) => (
1326 Mutation::LogicDropLhs,
1327 format!("a case where `{lhs}` is true"),
1328 ),
1329 };
1330 Some(Finding::InputGap {
1331 at: location(file, site),
1332 survivors: vec![describe(site, mutation)],
1333 survivor_count: 1,
1334 add_tests: vec![add],
1335 observed: None,
1336 verified,
1337 })
1338}
1339
1340pub fn slice_end_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1342 let SiteKind::SliceEnd { receiver, .. } = &site.kind else {
1343 return None;
1344 };
1345 Some(Finding::InputGap {
1346 at: location(file, site),
1347 survivors: vec![describe(site, Mutation::OtherEnd)],
1348 survivor_count: 1,
1349 add_tests: vec![format!(
1350 "`{}` with two or more elements, the first different from the last",
1351 one_line(receiver)
1352 )],
1353 observed: None,
1354 verified,
1355 })
1356}
1357
1358pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1360 let SiteKind::MinMax {
1361 receiver, argument, ..
1362 } = &site.kind
1363 else {
1364 return None;
1365 };
1366 Some(Finding::InputGap {
1367 at: location(file, site),
1368 survivors: vec![describe(site, Mutation::MinMax)],
1369 survivor_count: 1,
1370 add_tests: vec![format!(
1371 "`{}` different from `{}`",
1372 one_line(receiver),
1373 one_line(argument)
1374 )],
1375 observed: None,
1376 verified,
1377 })
1378}
1379
1380pub fn str_affix_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1383 let SiteKind::StrAffix {
1384 starts,
1385 receiver,
1386 pattern,
1387 ..
1388 } = &site.kind
1389 else {
1390 return None;
1391 };
1392 let where_else = if *starts { "start" } else { "end" };
1393 Some(Finding::InputGap {
1394 at: location(file, site),
1395 survivors: vec![describe(site, Mutation::StrContains)],
1396 survivor_count: 1,
1397 add_tests: vec![format!(
1398 "`{}` containing `{}` somewhere other than the {where_else}",
1399 one_line(receiver),
1400 one_line(pattern)
1401 )],
1402 observed: None,
1403 verified,
1404 })
1405}
1406
1407pub fn str_replace_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1409 let SiteKind::StrReplace { receiver, from, .. } = &site.kind else {
1410 return None;
1411 };
1412 Some(Finding::InputGap {
1413 at: location(file, site),
1414 survivors: vec![describe(site, Mutation::StrReplaceMultiplicity)],
1415 survivor_count: 1,
1416 add_tests: vec![format!(
1417 "`{}` containing `{}` more than once",
1418 one_line(receiver),
1419 one_line(from)
1420 )],
1421 observed: None,
1422 verified,
1423 })
1424}
1425
1426pub fn clamp_gap_finding(
1428 file: &str,
1429 site: &Site,
1430 mutation: Mutation,
1431 verified: bool,
1432) -> Option<Finding> {
1433 let SiteKind::Clamp {
1434 receiver,
1435 low,
1436 high,
1437 ..
1438 } = &site.kind
1439 else {
1440 return None;
1441 };
1442 let advice = if mutation == Mutation::ClampDropLower {
1443 format!(
1444 "`{}` below the lower clamp bound `{}`",
1445 one_line(receiver),
1446 one_line(low)
1447 )
1448 } else {
1449 format!(
1450 "`{}` above the upper clamp bound `{}`",
1451 one_line(receiver),
1452 one_line(high)
1453 )
1454 };
1455 Some(Finding::InputGap {
1456 at: location(file, site),
1457 survivors: vec![describe(site, mutation)],
1458 survivor_count: 1,
1459 add_tests: vec![advice],
1460 observed: None,
1461 verified,
1462 })
1463}
1464
1465pub fn rounding_gap_finding(
1467 file: &str,
1468 site: &Site,
1469 mutation: Mutation,
1470 verified: bool,
1471) -> Option<Finding> {
1472 let SiteKind::Rounding { op, receiver, .. } = &site.kind else {
1473 return None;
1474 };
1475 let alt = if mutation == Mutation::RoundAlt2 {
1476 op.alt2()
1477 } else {
1478 op.alt1()
1479 };
1480 Some(Finding::InputGap {
1481 at: location(file, site),
1482 survivors: vec![describe(site, mutation)],
1483 survivor_count: 1,
1484 add_tests: vec![format!(
1485 "`{}` that is {}",
1486 one_line(receiver),
1487 op.differs_for(alt)
1488 )],
1489 observed: None,
1490 verified,
1491 })
1492}
1493
1494pub fn saturating_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1497 let SiteKind::SaturatingArith {
1498 op,
1499 receiver,
1500 argument,
1501 ..
1502 } = &site.kind
1503 else {
1504 return None;
1505 };
1506 Some(Finding::InputGap {
1507 at: location(file, site),
1508 survivors: vec![describe(site, Mutation::SaturatingSwap)],
1509 survivor_count: 1,
1510 add_tests: vec![format!(
1511 "`{}` and `{}` where `{}` differs from `{}` ({})",
1512 one_line(receiver),
1513 one_line(argument),
1514 op.name(),
1515 op.swapped().name(),
1516 op.overflow_phrase()
1517 )],
1518 observed: None,
1519 verified,
1520 })
1521}
1522
1523pub fn str_trim_gap_finding(
1525 file: &str,
1526 site: &Site,
1527 mutation: Mutation,
1528 verified: bool,
1529) -> Option<Finding> {
1530 let SiteKind::StrTrim { op, receiver, .. } = &site.kind else {
1531 return None;
1532 };
1533 let alt = if mutation == Mutation::TrimAlt2 {
1534 op.alt2().unwrap_or_else(|| op.alt1())
1535 } else {
1536 op.alt1()
1537 };
1538 Some(Finding::InputGap {
1539 at: location(file, site),
1540 survivors: vec![describe(site, mutation)],
1541 survivor_count: 1,
1542 add_tests: vec![format!(
1543 "`{}` with {}",
1544 one_line(receiver),
1545 op.whitespace_phrase(alt)
1546 )],
1547 observed: None,
1548 verified,
1549 })
1550}
1551
1552pub fn str_case_eq_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1554 let SiteKind::StrCaseEq {
1555 receiver, argument, ..
1556 } = &site.kind
1557 else {
1558 return None;
1559 };
1560 Some(Finding::InputGap {
1561 at: location(file, site),
1562 survivors: vec![describe(site, Mutation::StrExactEq)],
1563 survivor_count: 1,
1564 add_tests: vec![format!(
1565 "`{}` and `{}` that match only when ignoring ASCII case",
1566 one_line(receiver),
1567 one_line(argument)
1568 )],
1569 observed: None,
1570 verified,
1571 })
1572}
1573
1574pub fn abs_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1576 let SiteKind::Abs { receiver, .. } = &site.kind else {
1577 return None;
1578 };
1579 Some(Finding::InputGap {
1580 at: location(file, site),
1581 survivors: vec![describe(site, Mutation::DropAbs)],
1582 survivor_count: 1,
1583 add_tests: vec![format!("negative `{}`", one_line(receiver))],
1584 observed: None,
1585 verified,
1586 })
1587}
1588
1589pub fn iter_limit_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1591 let SiteKind::IterLimit { take, count, .. } = &site.kind else {
1592 return None;
1593 };
1594 let advice = if *take {
1595 format!(
1596 "`{}` smaller than `usize::MAX` with more elements than `{}`",
1597 one_line(count),
1598 one_line(count)
1599 )
1600 } else {
1601 format!("non-zero `{}`", one_line(count))
1602 };
1603 Some(Finding::InputGap {
1604 at: location(file, site),
1605 survivors: vec![describe(site, Mutation::IterLimitDrop)],
1606 survivor_count: 1,
1607 add_tests: vec![advice],
1608 observed: None,
1609 verified,
1610 })
1611}
1612
1613pub fn endian_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1616 let SiteKind::EndianSwap { receiver, .. } = &site.kind else {
1617 return None;
1618 };
1619 Some(Finding::InputGap {
1620 at: location(file, site),
1621 survivors: vec![describe(site, Mutation::EndianSwap)],
1622 survivor_count: 1,
1623 add_tests: vec![format!(
1624 "`{}` with asymmetric bytes (e.g. `0x0102`)",
1625 one_line(receiver)
1626 )],
1627 observed: None,
1628 verified,
1629 })
1630}
1631
1632pub fn bit_count_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1635 let SiteKind::BitCount { op, receiver, .. } = &site.kind else {
1636 return None;
1637 };
1638 Some(Finding::InputGap {
1639 at: location(file, site),
1640 survivors: vec![describe(site, Mutation::BitCountSwap)],
1641 survivor_count: 1,
1642 add_tests: vec![format!(
1643 "`{}` where `{}` differs from `{}`",
1644 one_line(receiver),
1645 op.name(),
1646 op.swapped().name()
1647 )],
1648 observed: None,
1649 verified,
1650 })
1651}
1652
1653pub fn return_gap_finding(
1655 file: &str,
1656 site: &Site,
1657 always: bool,
1658 verified: bool,
1659) -> Option<Finding> {
1660 let SiteKind::Return { name, option, .. } = &site.kind else {
1661 return None;
1662 };
1663 let other = match (option, always) {
1664 (None, always) => format!("{}", !always),
1665 (Some(_), false) => "`Some`".to_string(),
1666 (Some(_), true) => "`None`".to_string(),
1667 };
1668 Some(Finding::InputGap {
1669 at: location(file, site),
1670 survivors: vec![describe(site, Mutation::Const(always))],
1671 survivor_count: 1,
1672 add_tests: vec![format!("a case where `{name}` returns {other}")],
1673 observed: None,
1674 verified,
1675 })
1676}
1677
1678pub fn range_contains_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1682 let SiteKind::RangeContains {
1683 lhs, rhs, argument, ..
1684 } = &site.kind
1685 else {
1686 return None;
1687 };
1688 Some(Finding::InputGap {
1689 at: location(file, site),
1690 survivors: vec![describe(site, Mutation::RangeEnd)],
1691 survivor_count: 1,
1692 add_tests: vec![format!(
1693 "a case where `{}` equals `{}` (with `{} <= {}`)",
1694 one_line(argument),
1695 one_line(rhs),
1696 one_line(lhs),
1697 one_line(rhs)
1698 )],
1699 observed: None,
1700 verified,
1701 })
1702}
1703
1704pub fn literal_set_gap_finding(
1707 file: &str,
1708 site: &Site,
1709 elem_idx: u8,
1710 verified: bool,
1711) -> Option<Finding> {
1712 let SiteKind::LiteralSet {
1713 argument, elements, ..
1714 } = &site.kind
1715 else {
1716 return None;
1717 };
1718 let (elem, _, _) = elements.get(elem_idx as usize)?;
1719 Some(Finding::InputGap {
1720 at: location(file, site),
1721 survivors: vec![describe(site, Mutation::DropLiteralElem(elem_idx))],
1722 survivor_count: 1,
1723 add_tests: vec![format!(
1724 "a case where `{}` matches `{}`",
1725 one_line(argument),
1726 one_line(elem)
1727 )],
1728 observed: None,
1729 verified,
1730 })
1731}
1732
1733pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
1735 Finding::InputGap {
1736 at: location(file, site),
1737 survivors: vec![describe(site, Mutation::Const(always))],
1738 survivor_count: 1,
1739 add_tests: vec![format!(
1740 "a case where the guard `{}` is {}",
1741 one_line(&site.text),
1742 !always
1743 )],
1744 observed: None,
1745 verified,
1746 }
1747}
1748
1749pub fn arith_gap_finding(
1752 file: &str,
1753 site: &Site,
1754 mutation: Mutation,
1755 verified: bool,
1756) -> Option<Finding> {
1757 let SiteKind::Arith {
1758 op,
1759 assign,
1760 lhs,
1761 rhs,
1762 ..
1763 } = &site.kind
1764 else {
1765 return None;
1766 };
1767 let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1768 let eq = if *assign { "=" } else { "" };
1769 let other = match mutation {
1770 Mutation::ArithSwap2 => op.second(*assign)?,
1771 _ => op.swapped(),
1772 };
1773 let add = match (op, other) {
1774 (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
1775 format!("`{rhs}` other than 0")
1776 }
1777 (ArithOp::BitOr, ArithOp::BitXor) | (ArithOp::BitXor, ArithOp::BitOr) => format!(
1778 "operands where `{lhs}` and `{rhs}` share at least one set bit (if their bits are disjoint by construction, `{}` and `{}` are equivalent)",
1779 op.symbol(),
1780 other.symbol()
1781 ),
1782 _ => format!(
1783 "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
1784 op.symbol(),
1785 other.symbol()
1786 ),
1787 };
1788 Some(Finding::InputGap {
1789 at: location(file, site),
1790 survivors: vec![describe(site, mutation)],
1791 survivor_count: 1,
1792 add_tests: vec![add],
1793 observed: None,
1794 verified,
1795 })
1796}
1797
1798pub fn render_sarif(report: &Report) -> String {
1800 serde_json::to_string_pretty(&sarif_document(vec![sarif_run(report)]))
1801 .expect("JSON values serialise")
1802}
1803
1804#[doc(hidden)]
1810pub fn workspace_sarif(reports: &[Report], failed: &[(String, String)]) -> impl std::fmt::Display {
1811 workspace_sarif_interrupted(reports, failed, false)
1812}
1813
1814#[doc(hidden)]
1817pub fn workspace_sarif_interrupted(
1818 reports: &[Report],
1819 failed: &[(String, String)],
1820 interrupted: bool,
1821) -> impl std::fmt::Display {
1822 let category = |package: &str| serde_json::json!({ "id": format!("tmt/{package}/") });
1823 let mut runs: Vec<serde_json::Value> = reports
1824 .iter()
1825 .map(|report| {
1826 let mut run = sarif_run(report);
1827 run["properties"]["package"] = serde_json::json!(report.package);
1828 run["automationDetails"] = category(&report.package);
1829 run["invocations"] =
1830 serde_json::json!([{ "executionSuccessful": !report.interrupted }]);
1831 run
1832 })
1833 .collect();
1834 for (package, error) in failed {
1835 runs.push(serde_json::json!({
1836 "tool": sarif_tool(),
1837 "automationDetails": category(package),
1838 "invocations": [{
1839 "executionSuccessful": false,
1840 "toolExecutionNotifications": [{
1841 "level": "error",
1842 "message": { "text": error },
1843 }],
1844 }],
1845 "properties": { "package": package },
1846 "results": [],
1847 }));
1848 }
1849 if interrupted && !reports.iter().any(|report| report.interrupted) {
1850 runs.push(serde_json::json!({
1851 "tool": sarif_tool(),
1852 "invocations": [{ "executionSuccessful": false }],
1853 "properties": { "interrupted": true },
1854 "results": [],
1855 }));
1856 }
1857 sarif_document(runs)
1858}
1859
1860fn sarif_uri(prefix: &str, file: &str) -> String {
1864 sarif_uri_for(prefix, file, cfg!(windows))
1865}
1866
1867fn sarif_uri_for(prefix: &str, file: &str, backslash_is_separator: bool) -> String {
1868 let mut uri = String::new();
1869 for byte in prefix.bytes().chain(file.bytes()) {
1870 let byte = if backslash_is_separator && byte == b'\\' {
1871 b'/'
1872 } else {
1873 byte
1874 };
1875 match byte {
1876 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1877 uri.push(byte as char)
1878 }
1879 _ => uri.push_str(&format!("%{byte:02X}")),
1880 }
1881 }
1882 uri
1883}
1884
1885fn sarif_tool() -> serde_json::Value {
1886 serde_json::json!({ "driver": {
1887 "name": "tmt",
1888 "rules": [
1889 { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
1890 { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
1891 { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } },
1892 { "id": "unstable-prediction", "shortDescription": { "text": "A predicted survivor failed when re-run; tests may be non-deterministic" } },
1893 { "id": "weakened-test", "shortDescription": { "text": "Tests since the base revision stopped catching a mutant in unchanged code" } },
1894 { "id": "audit-disagreement", "shortDescription": { "text": "Audit found a mismatch between selective/probe results and full/source execution" } }
1895 ]
1896 } })
1897}
1898
1899fn sarif_document(runs: Vec<serde_json::Value>) -> serde_json::Value {
1900 let mut document = serde_json::json!({
1901 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1902 "version": "2.1.0",
1903 });
1904 document["runs"] = serde_json::Value::Array(runs);
1905 document
1906}
1907
1908fn sarif_run(report: &Report) -> serde_json::Value {
1909 let prefix = report.analysis.package_path.as_str();
1910 let mut results: Vec<serde_json::Value> = report
1911 .findings
1912 .iter()
1913 .map(|finding| {
1914 let (kind, at) = finding_parts(finding);
1915 let rule = match kind {
1916 "INPUT GAP" => "input-gap",
1917 "ASSERTION GAP" => "assertion-gap",
1918 _ => "survivor",
1919 };
1920 let text = format!("`{}`: {}", at.code, finding_body(finding, false).join("; "));
1921 serde_json::json!({
1922 "ruleId": rule,
1923 "level": "warning",
1924 "message": { "text": text },
1925 "partialFingerprints": { "tmtFindingId/v2": at.id },
1927 "locations": [{
1928 "physicalLocation": {
1929 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1930 "region": { "startLine": at.line, "startColumn": at.column }
1931 }
1932 }]
1933 })
1934 })
1935 .collect();
1936 for at in &report.unstable {
1937 results.push(serde_json::json!({
1938 "ruleId": "unstable-prediction",
1939 "level": "error",
1940 "message": {
1941 "text": format!(
1942 "`{}`: trace predicted a survivor, but the re-run failed (tests may not be deterministic)",
1943 at.code
1944 )
1945 },
1946 "locations": [{
1947 "physicalLocation": {
1948 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1949 "region": { "startLine": at.line, "startColumn": at.column }
1950 }
1951 }]
1952 }));
1953 }
1954 for at in &report.weakened {
1955 results.push(serde_json::json!({
1956 "ruleId": "weakened-test",
1957 "level": "warning",
1958 "message": {
1959 "text": format!(
1960 "`{}`: mutant in unchanged code now survives after test changes",
1961 at.code
1962 )
1963 },
1964 "locations": [{
1965 "physicalLocation": {
1966 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1967 "region": { "startLine": at.line, "startColumn": at.column }
1968 }
1969 }]
1970 }));
1971 }
1972 if let Some(audit) = &report.audit {
1973 for at in &audit.disagreements {
1974 results.push(serde_json::json!({
1975 "ruleId": "audit-disagreement",
1976 "level": "error",
1977 "message": {
1978 "text": format!(
1979 "`{}`: survived selective tests, but failed when audited against all tests",
1980 at.code
1981 )
1982 },
1983 "locations": [{
1984 "physicalLocation": {
1985 "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1986 "region": { "startLine": at.line, "startColumn": at.column }
1987 }
1988 }]
1989 }));
1990 }
1991 for diff in &audit.source_disagreements {
1992 results.push(serde_json::json!({
1993 "ruleId": "audit-disagreement",
1994 "level": "error",
1995 "message": {
1996 "text": format!(
1997 "`{}` ({}): {} as a probe, {} built from source",
1998 diff.at.code, diff.mutant, diff.as_probe, diff.built
1999 )
2000 },
2001 "locations": [{
2002 "physicalLocation": {
2003 "artifactLocation": { "uri": sarif_uri(prefix, &diff.at.file) },
2004 "region": { "startLine": diff.at.line, "startColumn": diff.at.column }
2005 }
2006 }]
2007 }));
2008 }
2009 for diff in &audit.trace_differences {
2010 let text = if diff.rerun_failed && diff.records == 0 {
2011 format!(
2012 "audit trace re-run for `{}` did not pass (tests may not be deterministic)",
2013 diff.binary
2014 )
2015 } else if diff.rerun_failed {
2016 format!(
2017 "audit trace re-run for `{}` did not pass and differed in {} records",
2018 diff.binary, diff.records
2019 )
2020 } else {
2021 format!(
2022 "audit trace for `{}` differed between two runs ({} records)",
2023 diff.binary, diff.records
2024 )
2025 };
2026 results.push(serde_json::json!({
2027 "ruleId": "audit-disagreement",
2028 "level": "error",
2029 "message": { "text": text }
2030 }));
2031 }
2032 }
2033 let mut properties = serde_json::json!({
2034 "analysis": report.analysis,
2035 "evaluation": report.evaluation,
2036 "skipped": report.skipped,
2037 });
2038 if let Some(audit) = &report.audit {
2039 properties["audit"] = serde_json::json!(audit);
2040 }
2041 if report.interrupted {
2042 properties["interrupted"] = serde_json::json!(true);
2043 }
2044 let mut run = serde_json::json!({
2045 "tool": sarif_tool(),
2046 "properties": properties,
2048 });
2049 run["results"] = serde_json::Value::Array(results);
2050 run
2051}
2052
2053fn list(items: &[String], limit: usize) -> String {
2054 let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
2055 let more = items.len().saturating_sub(limit);
2056 if more > 0 {
2057 format!("{} (+{more} more)", shown.join(", "))
2058 } else {
2059 shown.join(", ")
2060 }
2061}
2062
2063fn finding_body(finding: &Finding, sanitize: bool) -> Vec<String> {
2067 let clean = |s: &str| {
2068 if sanitize {
2069 sanitize_inline(s)
2070 } else {
2071 s.to_string()
2072 }
2073 };
2074 let clean_list = |items: &[String]| {
2075 if sanitize {
2076 items
2077 .iter()
2078 .map(|s| sanitize_inline(s))
2079 .collect::<Vec<_>>()
2080 .join(", ")
2081 } else {
2082 items.join(", ")
2083 }
2084 };
2085 let mut lines = vec![];
2086 match finding {
2087 Finding::InputGap {
2088 survivors,
2089 survivor_count,
2090 add_tests,
2091 observed,
2092 verified,
2093 ..
2094 } => {
2095 let more = survivor_count.saturating_sub(survivors.len() as u128);
2096 let more = if more > 0 {
2097 format!(" (+{more} more)")
2098 } else {
2099 String::new()
2100 };
2101 let note = if *verified {
2102 "re-run: tests pass"
2103 } else {
2104 "from the trace, not re-run"
2105 };
2106 lines.push(format!(
2107 "passes every test as: {}{more} [{note}]",
2108 clean_list(survivors)
2109 ));
2110 lines.extend(observed.iter().map(|s| clean(s)));
2111 lines.extend(
2112 add_tests
2113 .iter()
2114 .map(|test| format!("add a test with {}", clean(test))),
2115 );
2116 }
2117 Finding::AssertionGap {
2118 survivors,
2119 tests,
2120 effects,
2121 effects_of,
2122 witness,
2123 ..
2124 } => {
2125 lines.push(format!("passes every test as: {}", clean_list(survivors)));
2126 let shown_tests: Vec<String> = tests.iter().map(|t| clean(t)).collect();
2127 lines.push(format!(
2128 "these tests run the changed code and still pass: {}",
2129 list(&shown_tests, 5)
2130 ));
2131 if effects.is_empty() {
2132 lines.push("add an assertion on what this code is responsible for".to_string());
2133 } else {
2134 if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
2137 lines.push(format!(
2138 "followed one of them through the tests: {}",
2139 clean(followed)
2140 ));
2141 }
2142 lines.extend(effects.iter().map(|s| clean(s)));
2143 }
2144 if let Some(witness) = witness {
2145 lines.extend(witness_lines(witness, sanitize));
2146 }
2147 }
2148 Finding::Survivor {
2149 survivors,
2150 change_since: Some(revision),
2151 ..
2152 } => {
2153 lines.push(format!("passes every test {}", clean_list(survivors)));
2154 lines.push(format!(
2155 "no test tells this change from the code as it was at {}: add one that fails without it",
2156 clean(short_revision(revision))
2157 ));
2158 }
2159 Finding::Survivor {
2160 survivors,
2161 witness,
2162 advice,
2163 ..
2164 } => {
2165 lines.push(format!("passes every test as: {}", clean_list(survivors)));
2166 if let Some(witness) = witness {
2167 lines.extend(witness_lines(witness, sanitize));
2168 } else if let Some(advice) = advice {
2169 lines.push(clean(advice));
2170 } else {
2171 lines.push(
2172 "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"
2173 .to_string(),
2174 );
2175 }
2176 }
2177 }
2178 lines
2179}
2180
2181fn witness_lines(witness: &VerifiedWitness, sanitize: bool) -> Vec<String> {
2182 let clean = |s: &str| {
2183 if sanitize {
2184 sanitize_inline(s)
2185 } else {
2186 s.to_string()
2187 }
2188 };
2189 let call = clean(&witness.call);
2190 let orig = clean(&witness.original);
2191 let mut_val = clean(&witness.mutant);
2192 let assertion = clean(&witness.assertion);
2193 if let Some(test) = &witness.in_test {
2194 let test = clean(test);
2195 let place = witness
2197 .in_test_line
2198 .zip(witness.in_test_column)
2199 .map(|(line, column)| format!("line {line}, column {column}"));
2200 let (on, of) = place.map_or_else(
2201 || (String::new(), "that call".to_string()),
2202 |place| (format!(" at {place}"), format!("the call at {place}")),
2203 );
2204 return vec![
2205 format!(
2206 "verified on `{call}` where `{test}` calls it{on}: original returned {orig}, mutant returned {mut_val}",
2207 ),
2208 format!("in `{test}`, compare the result of {of} with this value: `{assertion}`"),
2209 ];
2210 }
2211 let mut lines = vec![format!(
2212 "verified on `{call}`: original returned {orig}, mutant returned {mut_val}",
2213 )];
2214 if let Some(killed) = witness.individually_killed {
2215 lines.push(format!(
2216 "the selected tests detected all {killed} component changes in isolation"
2217 ));
2218 }
2219 lines.extend(witness.guidance.iter().map(|s| clean(s)));
2220 lines.push(format!("add a test with `{assertion}`"));
2221 lines
2222}
2223
2224fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
2225 match finding {
2226 Finding::InputGap { at, .. } => ("INPUT GAP", at),
2227 Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
2228 Finding::Survivor {
2229 at,
2230 change_since: Some(_),
2231 ..
2232 } => ("UNTESTED CHANGE", at),
2233 Finding::Survivor { at, .. } => ("SURVIVOR", at),
2234 }
2235}
2236
2237fn sanitize_terminal_text(text: &str, preserve_newlines: bool) -> String {
2243 fn consume_csi(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
2244 while let Some(&next) = chars.peek() {
2245 if (' '..='?').contains(&next) {
2246 chars.next();
2247 } else if ('@'..='~').contains(&next) {
2248 chars.next();
2249 break;
2250 } else {
2251 break;
2253 }
2254 }
2255 }
2256 fn consume_st_terminated(
2257 chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
2258 allow_bel: bool,
2259 ) {
2260 while let Some(next) = chars.next() {
2261 if (allow_bel && next == '\x07') || next == '\u{009c}' {
2262 break;
2263 }
2264 if next == '\x1b' && chars.peek() == Some(&'\\') {
2265 chars.next();
2266 break;
2267 }
2268 }
2269 }
2270 let mut out = String::with_capacity(text.len());
2271 let mut chars = text.chars().peekable();
2272 while let Some(ch) = chars.next() {
2273 if ch == '\x1b' {
2274 match chars.peek().copied() {
2275 Some('[') => {
2277 chars.next();
2278 consume_csi(&mut chars);
2279 }
2280 Some(']') => {
2282 chars.next();
2283 consume_st_terminated(&mut chars, true);
2284 }
2285 Some('P' | 'X' | '^' | '_') => {
2287 chars.next();
2288 consume_st_terminated(&mut chars, false);
2289 }
2290 Some(next) if (' '..='/').contains(&next) => {
2292 while let Some(&c) = chars.peek() {
2293 if (' '..='/').contains(&c) {
2294 chars.next();
2295 } else if ('0'..='~').contains(&c) {
2296 chars.next();
2297 break;
2298 } else {
2299 break;
2300 }
2301 }
2302 }
2303 Some(next) if ('0'..='~').contains(&next) => {
2305 chars.next();
2306 }
2307 _ => {}
2308 }
2309 continue;
2310 }
2311 if ch == '\u{009b}' {
2313 consume_csi(&mut chars);
2314 continue;
2315 }
2316 if ch == '\u{009d}' {
2317 consume_st_terminated(&mut chars, true);
2318 continue;
2319 }
2320 if matches!(ch, '\u{0090}' | '\u{0098}' | '\u{009e}' | '\u{009f}') {
2321 consume_st_terminated(&mut chars, false);
2322 continue;
2323 }
2324 if matches!(
2326 ch,
2327 '\u{061c}'
2328 | '\u{200e}'
2329 | '\u{200f}'
2330 | '\u{202a}'..='\u{202e}'
2331 | '\u{2066}'..='\u{2069}'
2332 ) {
2333 continue;
2334 }
2335 if ch == '\n' && preserve_newlines {
2336 out.push('\n');
2337 continue;
2338 }
2339 if matches!(ch, '\n' | '\r' | '\t') {
2340 out.push(' ');
2341 continue;
2342 }
2343 if ch.is_control() {
2344 continue;
2345 }
2346 out.push(ch);
2347 }
2348 out
2349}
2350
2351#[doc(hidden)]
2354pub fn sanitize_inline(text: &str) -> String {
2355 sanitize_terminal_text(text, false)
2356}
2357
2358#[doc(hidden)]
2360pub fn sanitize_terminal(text: &str) -> String {
2361 sanitize_terminal_text(text, true)
2362}
2363
2364pub fn render_text(report: &Report, show_unreached: bool) -> String {
2365 let mut out = String::new();
2366 let mut previous: Option<(&str, usize)> = None;
2367 for finding in &report.findings {
2368 let (kind, at) = finding_parts(finding);
2369 let same_line = previous == Some((at.file.as_str(), at.line));
2372 if same_line {
2373 out.push_str(&format!(
2374 " + {kind} column {}\n {}\n",
2375 at.column,
2376 sanitize_inline(&at.code)
2377 ));
2378 } else {
2379 if previous.is_some() {
2380 out.push('\n');
2381 }
2382 out.push_str(&format!(
2383 "{kind} {}:{}:{}\n {}\n",
2384 sanitize_inline(&at.file),
2385 at.line,
2386 at.column,
2387 sanitize_inline(&at.code)
2388 ));
2389 }
2390 for line in finding_body(finding, true) {
2391 out.push_str(&format!(" {line}\n"));
2392 }
2393 if report.weakened.iter().any(|before| {
2394 (before.file.as_str(), before.line, before.column)
2395 == (at.file.as_str(), at.line, at.column)
2396 }) {
2397 out.push_str(&format!(
2398 " the tests as they were at {} found this out: a change to the tests lets it through\n",
2399 sanitize_inline(short_revision(
2400 report.analysis.since.as_deref().unwrap_or("the revision")
2401 ))
2402 ));
2403 }
2404 previous = Some((at.file.as_str(), at.line));
2405 }
2406 if previous.is_some() {
2407 out.push('\n');
2408 }
2409 if show_unreached {
2410 for at in &report.unreached {
2411 out.push_str(&format!(
2412 "UNREACHED {}:{}:{}\n {}\n\n",
2413 sanitize_inline(&at.file),
2414 at.line,
2415 at.column,
2416 sanitize_inline(&at.code)
2417 ));
2418 }
2419 }
2420 for at in &report.unstable {
2421 out.push_str(&format!(
2422 "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",
2423 sanitize_inline(&at.file),
2424 at.line,
2425 at.column,
2426 sanitize_inline(&at.code)
2427 ));
2428 }
2429 let input = report
2430 .findings
2431 .iter()
2432 .filter(|f| matches!(f, Finding::InputGap { .. }))
2433 .count();
2434 let assertion = report
2435 .findings
2436 .iter()
2437 .filter(|f| matches!(f, Finding::AssertionGap { .. }))
2438 .count();
2439 let unexplained = report.findings.len() - input - assertion;
2440 let by_time_limit = if report.mutants_timed_out > 0 {
2442 format!(", {} of them by the time limit", report.mutants_timed_out)
2443 } else {
2444 String::new()
2445 };
2446 out.push_str(&format!(
2447 "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
2448 sanitize_inline(&report.package),
2449 report.sites,
2450 input,
2451 assertion,
2452 report.mutants_run,
2453 report.mutants_killed,
2454 report.unreached.len()
2455 ));
2456 if unexplained > 0 {
2457 out.push_str(&format!(
2458 ", {unexplained} survivors of mutants built on their own"
2459 ));
2460 }
2461 if !report.timeout_rechecks.is_empty() {
2462 let rechecks = &report.timeout_rechecks;
2463 out.push_str(&format!(
2464 ", {} parallel timeouts ({} confirmed, {} recovered, {} unconfirmed)",
2465 rechecks.first_pass, rechecks.confirmed, rechecks.recovered, rechecks.unconfirmed
2466 ));
2467 }
2468 if report.suppressed > 0 {
2469 out.push_str(&format!(", {} findings suppressed", report.suppressed));
2470 }
2471 if report.skipped_sites > 0 {
2472 out.push_str(&format!(
2473 ", {} sites skipped (probe did not compile)",
2474 report.skipped_sites
2475 ));
2476 }
2477 if report.unviable_mutants > 0 {
2478 out.push_str(&format!(
2479 ", {} mutants left out (they do not compile)",
2480 report.unviable_mutants
2481 ));
2482 }
2483 out.push('\n');
2484 if let Some(audit) = &report.audit {
2485 out.push_str(&format!(
2486 "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against",
2487 audit.sampled,
2488 audit.survivors,
2489 audit.disagreements.len()
2490 ));
2491 if audit.not_audited > 0 {
2492 out.push_str(&format!(", {} could not be judged", audit.not_audited));
2493 }
2494 out.push('\n');
2495 for at in &audit.disagreements {
2496 out.push_str(&format!(
2497 " {}:{}:{} {}\n",
2498 sanitize_inline(&at.file),
2499 at.line,
2500 at.column,
2501 sanitize_inline(&at.code)
2502 ));
2503 }
2504 if audit.rebuilt > 0 {
2505 out.push_str(&format!(
2506 "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",
2507 audit.rebuilt,
2508 audit.compared,
2509 audit.source_disagreements.len(),
2510 audit.not_compared
2511 ));
2512 }
2513 for differs in &audit.source_disagreements {
2514 out.push_str(&format!(
2515 " {}:{}:{} {}: {} as a probe, {} built\n",
2516 sanitize_inline(&differs.at.file),
2517 differs.at.line,
2518 differs.at.column,
2519 sanitize_inline(&differs.mutant),
2520 sanitize_inline(&differs.as_probe),
2521 sanitize_inline(&differs.built)
2522 ));
2523 }
2524 if audit.trace_rerun_incomplete {
2525 out.push_str("audit: trace rerun interrupted before completion\n");
2526 } else if audit.trace_differences.is_empty() {
2527 out.push_str("audit: recorded once more, the tests did the same\n");
2528 }
2529 for binary in &audit.trace_differences {
2530 let name = sanitize_inline(&binary.binary);
2531 if binary.rerun_failed && binary.records == 0 {
2532 out.push_str(&format!(
2533 "audit: recorded once more, `{name}` did not pass: its tests do not always do the same\n"
2534 ));
2535 } else if binary.rerun_failed {
2536 out.push_str(&format!(
2537 "audit: recorded once more, `{name}` did not pass and differs in {} records: its tests do not always do the same\n",
2538 binary.records
2539 ));
2540 } else {
2541 out.push_str(&format!(
2542 "audit: recorded once more, `{name}` differs in {} records: its tests do not always do the same\n",
2543 binary.records
2544 ));
2545 }
2546 }
2547 }
2548 if report.mutants_not_compiled > 0 {
2549 out.push_str(&format!(
2550 "({} 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",
2551 report.mutants_not_compiled
2552 ));
2553 }
2554 let not_evaluated = report
2555 .mutants_not_evaluated
2556 .saturating_sub(report.mutants_not_compiled);
2557 if not_evaluated > 0 {
2558 if report.interrupted {
2559 out.push_str(&format!(
2560 "({not_evaluated} mutants not evaluated: interrupted before completion)\n"
2561 ));
2562 } else {
2563 out.push_str(&format!(
2564 "({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"
2565 ));
2566 }
2567 } else if report.interrupted {
2568 out.push_str("(interrupted before completion: results above are partial)\n");
2569 }
2570 if report.mutants_not_built > 0 {
2571 out.push_str(&format!(
2572 "({} more mutants need a build of their own: --rebuild runs them)\n",
2573 report.mutants_not_built
2574 ));
2575 }
2576 if !report.skipped.is_empty() {
2577 out.push_str(&format!(
2578 "({} skipped entries with locations and reasons in --json)\n",
2579 report.skipped.len()
2580 ));
2581 }
2582 if report.survivor_breakdown.unreported() > 0 {
2583 let breakdown = &report.survivor_breakdown;
2584 let mut parts = vec![];
2585 if breakdown.redundant_constant > 0 {
2586 parts.push(format!(
2587 "{} redundant constant",
2588 breakdown.redundant_constant
2589 ));
2590 }
2591 if breakdown.preexisting_unchanged > 0 {
2592 parts.push(format!(
2593 "{} preexisting in unchanged code",
2594 breakdown.preexisting_unchanged
2595 ));
2596 }
2597 if breakdown.unchanged_not_compared > 0 {
2598 parts.push(format!(
2599 "{} in unchanged code (earlier tests could not be evaluated)",
2600 breakdown.unchanged_not_compared
2601 ));
2602 }
2603 if breakdown.unconfirmed_gap > 0 {
2604 parts.push(format!(
2605 "{} from unconfirmed gaps",
2606 breakdown.unconfirmed_gap
2607 ));
2608 }
2609 out.push_str(&format!(
2610 "({} surviving mutants not reported as findings: {})\n",
2611 breakdown.unreported(),
2612 parts.join(", ")
2613 ));
2614 }
2615 if report.suppressed > 0
2616 && let Some(baseline) = &report.baseline
2617 {
2618 out.push_str(&format!(
2619 "(baseline: {} for package `{}`)\n",
2620 sanitize_inline(&baseline.display().to_string()),
2621 sanitize_inline(&report.package)
2622 ));
2623 }
2624 if !report.unassessed_test_changes.is_empty() {
2625 let files: Vec<String> = report
2626 .unassessed_test_changes
2627 .iter()
2628 .map(|f| sanitize_inline(f))
2629 .collect();
2630 out.push_str(&format!(
2631 "(note: integration test changes in {} are not evaluated for test weakening under `--since`; run `cargo tmt -p {}` for a full package analysis)\n",
2632 files.join(", "),
2633 sanitize_inline(&report.package)
2634 ));
2635 }
2636 if report.evaluation == Some(Evaluation::Partial) {
2637 out.push_str("(partial evaluation: some mutants were not built or evaluated)\n");
2638 }
2639 if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
2640 if report.unreached.is_empty()
2641 && report.mutants_not_evaluated == 0
2642 && report.mutants_not_built == 0
2643 && (report.unviable_mutants > 0 || report.skipped_sites > 0)
2644 {
2645 out.push_str("No mutants executed. See any skipped entries in --json.\n");
2646 } else {
2647 out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
2648 }
2649 }
2650 if !show_unreached && !report.unreached.is_empty() {
2651 out.push_str("(--show-unreached lists the code no test executes)\n");
2652 }
2653 sanitize_terminal(&out)
2654}
2655
2656#[cfg(test)]
2657mod tests {
2658 use super::*;
2659 use crate::instrument::discover;
2660
2661 #[test]
2662 fn evaluation_distinguishes_no_sites_no_mutants_partial_and_completed_work() {
2663 let mut report = Report::default();
2664 report.record_evaluation();
2665 assert_eq!(report.evaluation, Some(Evaluation::NoSites));
2666 report.sites = 1;
2667 report.record_evaluation();
2668 assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
2669 assert!(render_text(&report, false).contains("No mutants executed."));
2670 assert!(render_text(&report, false).contains("--source-only"));
2671 report.unviable_mutants = 1;
2674 let unbuildable_text = render_text(&report, false);
2675 assert!(unbuildable_text.contains("No mutants executed."));
2676 assert!(
2677 !unbuildable_text.contains("--source-only"),
2678 "{unbuildable_text}"
2679 );
2680 report.mutants_not_evaluated = 1;
2682 assert!(render_text(&report, false).contains("--source-only"));
2683 report.mutants_not_evaluated = 0;
2684 report.mutants_not_built = 1;
2685 assert!(render_text(&report, false).contains("--source-only"));
2686 report.mutants_not_built = 0;
2687 report.unviable_mutants = 0;
2688 report.mutants_run = 1;
2689 report.mutants_killed = 1;
2690 report.record_evaluation();
2691 assert_eq!(report.evaluation, None);
2692 assert!(report.counts_reconcile());
2693 assert!(!render_text(&report, false).contains("No mutants executed."));
2694 assert!(!render_text(&report, false).contains("partial evaluation"));
2695
2696 report.mutants_not_built = 3;
2697 report.record_evaluation();
2698 assert_eq!(report.evaluation, Some(Evaluation::Partial));
2699 assert!(render_text(&report, false).contains("partial evaluation"));
2700 }
2701
2702 #[test]
2703 fn evaluation_pict_table() {
2704 let table = include_str!("../tests/data/report_evaluation.pict.tsv");
2705 let mut lines = table.lines();
2706 let header = lines.next().expect("header");
2707 assert_eq!(
2708 header,
2709 "sites\tmutants_run\tskipped_entries\tskipped_sites\tunparseable_source\tmutants_not_built\tmutants_not_evaluated\tunconfirmed_timeouts\tsource_only_timeout\thas_gaps\tsource_only"
2710 );
2711 let dummy = || Location {
2712 file: "src/lib.rs".into(),
2713 line: 1,
2714 column: 1,
2715 code: "x".into(),
2716 ..Location::default()
2717 };
2718 let mut rows = 0;
2719 for line in lines.filter(|line| !line.trim().is_empty()) {
2720 rows += 1;
2721 let cols: Vec<&str> = line.split('\t').collect();
2722 assert_eq!(cols.len(), 11, "row: {line}");
2723 let skipped = if cols[4] == "true" {
2724 vec![SkippedSite::new(
2725 dummy(),
2726 (1, 2),
2727 SkipReason::UnparseableSource,
2728 Some("parse error".into()),
2729 )]
2730 } else if cols[2] == "nonempty" {
2731 vec![SkippedSite::new(
2732 dummy(),
2733 (1, 2),
2734 SkipReason::ProbeReplacedBySourceRebuild,
2735 None,
2736 )]
2737 } else {
2738 vec![]
2739 };
2740 let source_only_timeout = cols[8] == "true";
2741 let mut report = Report {
2742 sites: usize::from(cols[0] == "nonzero"),
2743 mutants_run: usize::from(cols[1] == "nonzero"),
2744 mutants_killed: usize::from(cols[1] == "nonzero"),
2745 mutants_timed_out: usize::from(source_only_timeout),
2746 skipped,
2747 skipped_sites: usize::from(cols[3] == "nonzero"),
2748 mutants_not_built: usize::from(cols[5] == "nonzero"),
2749 mutants_not_evaluated: usize::from(cols[6] == "nonzero"),
2750 timeout_rechecks: TimeoutRechecks {
2751 first_pass: usize::from(cols[7] == "nonzero"),
2752 unconfirmed: usize::from(cols[7] == "nonzero"),
2753 ..TimeoutRechecks::default()
2754 },
2755 analysis: Analysis {
2756 source_only: cols[10] == "true",
2757 ..Analysis::default()
2758 },
2759 ..Report::default()
2760 };
2761 report.record_evaluation();
2762 let expected = match cols[1] {
2763 "zero" => {
2764 if cols[0] == "zero"
2765 && cols[2] == "empty"
2766 && cols[5] == "zero"
2767 && cols[6] == "zero"
2768 {
2769 Some(Evaluation::NoSites)
2770 } else {
2771 Some(Evaluation::NoMutantsExecuted)
2772 }
2773 }
2774 "nonzero" => {
2775 if cols[3] == "nonzero"
2776 || cols[4] == "true"
2777 || cols[5] == "nonzero"
2778 || cols[6] == "nonzero"
2779 || cols[7] == "nonzero"
2780 || source_only_timeout
2781 {
2782 Some(Evaluation::Partial)
2783 } else {
2784 None
2785 }
2786 }
2787 other => panic!("unexpected mutants_run value: {other}"),
2788 };
2789 assert_eq!(report.evaluation, expected, "row: {line}");
2790 assert!(report.counts_reconcile(), "row: {line}");
2791 let text = render_text(&report, false);
2792 assert_eq!(
2793 text.contains("partial evaluation"),
2794 expected == Some(Evaluation::Partial),
2795 "row: {line}\n{text}"
2796 );
2797 }
2798 assert!(rows >= 11, "expected PICT table rows, got {rows}");
2799 }
2800
2801 #[test]
2802 fn survivor_breakdown_reconciles_and_renders_unreported_reasons() {
2803 let mut report = Report {
2804 package: "demo".into(),
2805 sites: 5,
2806 mutants_run: 11,
2807 mutants_killed: 4,
2808 mutants_timed_out: 1,
2809 mutants_survived: 7,
2810 survivor_breakdown: SurvivorBreakdown {
2811 reported: 1,
2812 suppressed: 1,
2813 redundant_constant: 2,
2814 preexisting_unchanged: 1,
2815 unchanged_not_compared: 1,
2816 unconfirmed_gap: 1,
2817 },
2818 ..Report::default()
2819 };
2820 assert!(report.counts_reconcile());
2821 report.record_evaluation();
2822 assert_eq!(report.evaluation, Some(Evaluation::Partial));
2823 let text = render_text(&report, false);
2824 assert!(
2825 text.contains(
2826 "(5 surviving mutants not reported as findings: 2 redundant constant, 1 preexisting in unchanged code, 1 in unchanged code (earlier tests could not be evaluated), 1 from unconfirmed gaps)"
2827 ),
2828 "{text}"
2829 );
2830
2831 report.survivor_breakdown.reported = 0;
2832 assert!(!report.counts_reconcile());
2833 report.survivor_breakdown.reported = 1;
2834 report.mutants_timed_out = 5;
2835 assert!(!report.counts_reconcile());
2836
2837 let overflow = Report {
2839 mutants_run: 0,
2840 mutants_killed: 0,
2841 mutants_survived: 0,
2842 survivor_breakdown: SurvivorBreakdown {
2843 reported: usize::MAX,
2844 suppressed: 1,
2845 ..SurvivorBreakdown::default()
2846 },
2847 ..Report::default()
2848 };
2849 assert!(!overflow.counts_reconcile());
2850 }
2851
2852 fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
2853 sarif["runs"][0]["results"].as_array().unwrap()
2854 }
2855
2856 fn or_site() -> Site {
2857 site_of("fn f(a: bool, b: bool) -> bool { a || b }")
2858 }
2859
2860 fn assign_kind() -> SiteKind {
2861 SiteKind::Arith {
2862 op: ArithOp::Add,
2863 assign: true,
2864 lhs: "*total".into(),
2865 rhs: "fee".into(),
2866 gap: (0, 0),
2867 local_types: vec![],
2868 shadowed_prims: vec![],
2869 cast_probes: vec![],
2870 }
2871 }
2872
2873 fn site_of(src: &str) -> Site {
2874 discover(src, 0)
2875 .unwrap()
2876 .sites
2877 .into_iter()
2878 .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
2879 .unwrap()
2880 }
2881
2882 #[test]
2883 fn describes_mutants_at_source_level() {
2884 let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
2885 assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
2886 assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
2887 assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
2888 assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
2889 assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
2890
2891 let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
2893 assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
2894
2895 let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
2896 assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
2897 assert_eq!(
2898 describe(&none, Mutation::Shift(2)),
2899 "`a >= b + 2` (without overflow)"
2900 );
2901 assert_eq!(
2902 describe(&none, Mutation::Shift(-1)),
2903 "`a >= b - 1` (without overflow)"
2904 );
2905 let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
2906 assert_eq!(describe(<, Mutation::Shift(1)), "`a <= b`");
2907
2908 let stmt = site_of("fn f(s: &mut S) { s.check(\n 1,\n 2); }");
2909 assert_eq!(
2910 describe(&stmt, Mutation::Delete),
2911 "delete `s.check( 1, 2);`"
2912 );
2913 }
2914
2915 #[test]
2917 fn literal_shift_rendering_matches_shift_semantics() {
2918 use crate::plan::eval_mutated_d;
2919 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
2920 for shift in [-2, -1, 1, 2] {
2921 for other in -5..=5i128 {
2922 let k = 1i128;
2923 assert_eq!(
2925 op.eval_d(other - (k + shift)),
2926 eval_mutated_d(op, Mutation::Shift(shift), other - k)
2927 );
2928 assert_eq!(
2930 op.eval_d((k - shift) - other),
2931 eval_mutated_d(op, Mutation::Shift(shift), k - other)
2932 );
2933 }
2934 }
2935 }
2936 for (op, shift, flipped) in [
2938 (CmpOp::Ge, 1, CmpOp::Gt),
2939 (CmpOp::Gt, -1, CmpOp::Ge),
2940 (CmpOp::Le, -1, CmpOp::Lt),
2941 (CmpOp::Lt, 1, CmpOp::Le),
2942 ] {
2943 for d in -3..=3 {
2944 assert_eq!(
2945 flipped.eval_d(d),
2946 eval_mutated_d(op, Mutation::Shift(shift), d)
2947 );
2948 }
2949 }
2950 }
2951
2952 #[test]
2953 fn boundary_finding_for_the_age_check() {
2954 let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
2955 let mut obs = Obs::of_d(-1);
2956 obs.merge(&Obs::of_d(2));
2957 let gap = InputGap::Boundary {
2958 min_shift: 0,
2959 max_shift: 2,
2960 missing: vec![0],
2961 same: (0, 0),
2962 };
2963 let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
2964 assert_eq!(
2965 finding,
2966 Finding::InputGap {
2967 at: Location {
2968 file: "src/lib.rs".into(),
2969 line: 1,
2970 column: 26,
2971 code: "age >= 18".into(),
2972 ..Location::default()
2973 },
2974 survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
2975 survivor_count: 2,
2976 add_tests: vec!["`age` = 18 (the original gives true)".into()],
2977 observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
2978 verified: true,
2979 }
2980 );
2981 let report = Report {
2982 package: "p".into(),
2983 sites: 1,
2984 findings: vec![finding],
2985 ..Report::default()
2986 };
2987 let text = render_text(&report, false);
2988 assert!(text.contains("INPUT GAP src/lib.rs:1:26"), "{text}");
2989 assert!(
2990 text.contains("passes every test as: `age >= 19`, `age >= 20` [re-run: tests pass]"),
2991 "{text}"
2992 );
2993 assert!(
2994 text.contains("add a test with `age` = 18 (the original gives true)"),
2995 "{text}"
2996 );
2997 assert!(
2998 text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
2999 "{text}"
3000 );
3001 assert!(report.has_gaps());
3002 }
3003
3004 #[test]
3005 fn other_gap_kinds() {
3006 let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
3007 let mut obs = Obs::of_rel(crate::plan::Rel::Less);
3008 obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
3009 let gap = InputGap::EqualNeverObserved {
3010 flipped: CmpOp::Le,
3011 float_gap: None,
3012 };
3013 let Some(Finding::InputGap {
3014 survivors,
3015 add_tests,
3016 observed,
3017 ..
3018 }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
3019 else {
3020 panic!()
3021 };
3022 assert_eq!(survivors, ["`a <= b`"]);
3023 assert_eq!(
3024 add_tests,
3025 ["`a` equal to `b` (the original gives false, the mutant true)"]
3026 );
3027 assert_eq!(observed, None);
3028
3029 let Some(Finding::InputGap {
3030 survivors,
3031 add_tests,
3032 ..
3033 }) = input_gap_finding(
3034 "f.rs",
3035 &site,
3036 &InputGap::OneSided { always: true },
3037 &obs,
3038 false,
3039 )
3040 else {
3041 panic!()
3042 };
3043 assert_eq!(survivors, ["`true`"]);
3044 assert_eq!(add_tests, ["an input that makes `a < b` false"]);
3045
3046 assert_eq!(
3047 input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
3048 None
3049 );
3050 }
3051
3052 #[test]
3053 fn float_gap_finding() {
3054 let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
3055 let mut obs = Obs::of_f(-20.5);
3056 obs.merge(&Obs::of_f(9.5));
3057 let gap = InputGap::EqualNeverObserved {
3058 flipped: CmpOp::Ge,
3059 float_gap: obs.float_gap(),
3060 };
3061 let Some(Finding::InputGap {
3062 survivors,
3063 add_tests,
3064 observed,
3065 survivor_count,
3066 ..
3067 }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
3068 else {
3069 panic!()
3070 };
3071 assert_eq!(
3072 survivors,
3073 [
3074 "`celsius >= 30.5`",
3075 "`celsius > 35.25`",
3076 "`celsius > 20.25`"
3077 ]
3078 );
3079 assert_eq!(survivor_count, 3);
3080 assert_eq!(
3081 add_tests,
3082 ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
3083 );
3084 assert_eq!(
3085 observed.as_deref(),
3086 Some(
3087 "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
3088 )
3089 );
3090
3091 let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
3092 assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
3093 let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
3094 assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
3095 assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
3096 let finding = input_gap_finding(
3097 "f.rs",
3098 &none,
3099 &InputGap::EqualNeverObserved {
3100 flipped: CmpOp::Le,
3101 float_gap: Some((-1.0, 2.0)),
3102 },
3103 &obs,
3104 false,
3105 );
3106 let Some(Finding::InputGap { observed, .. }) = finding else {
3107 panic!()
3108 };
3109 assert_eq!(
3110 observed.as_deref(),
3111 Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
3112 );
3113
3114 assert_eq!(float_literal("30.5"), Some(30.5));
3115 assert_eq!(float_literal("-1e3"), Some(-1000.0));
3116 assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
3117 assert_eq!(float_literal("limit"), None);
3118 assert_eq!(float_literal("x1"), None);
3119 assert_eq!(float_literal("1x"), None);
3120 assert_eq!(float_literal("-x"), None);
3121 assert_eq!(float_literal("-2.5"), Some(-2.5));
3122 assert_eq!(float_literal("e"), None);
3123 assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
3125 assert_eq!(show_float(1e-10), "1e-10");
3126 assert_eq!(show_float(10.0), "10.0");
3127 assert_eq!(show_float(35.25), "35.25");
3128 let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
3130 let tiny = InputGap::EqualNeverObserved {
3131 flipped: CmpOp::Ge,
3132 float_gap: Some((-2e-300, 2e-300)),
3133 };
3134 let Some(Finding::InputGap { survivors, .. }) =
3135 input_gap_finding("f.rs", &big, &tiny, &obs, true)
3136 else {
3137 panic!()
3138 };
3139 assert_eq!(survivors, ["`x >= 1e300`"]);
3140 }
3141
3142 #[test]
3143 fn logic_and_arithmetic_findings() {
3144 let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
3145 assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
3146 assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
3147 assert_eq!(
3148 describe(&or_site(), Mutation::LogicDropRhs),
3149 "`a || { b; false }`"
3150 );
3151 assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
3152 let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
3153 assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
3154 let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
3155 Some(Finding::InputGap {
3156 survivors,
3157 add_tests,
3158 ..
3159 }) => (survivors[0].clone(), add_tests[0].clone()),
3160 _ => panic!(),
3161 };
3162 assert_eq!(
3163 advice(&and, LogicGap::RhsNeverDecides),
3164 (
3165 "`a && { b; true }`".into(),
3166 "a case where `a` is true and `b` is false".into()
3167 )
3168 );
3169 assert_eq!(
3170 advice(&and, LogicGap::LhsNeverDecides),
3171 ("`{ a; b }`".into(), "a case where `a` is false".into())
3172 );
3173 assert_eq!(
3174 advice(&or, LogicGap::RhsNeverDecides),
3175 (
3176 "`a || { b; false }`".into(),
3177 "a case where `a` is false and `b` is true".into()
3178 )
3179 );
3180 assert_eq!(
3181 advice(&or, LogicGap::LhsNeverDecides),
3182 ("`{ a; b }`".into(), "a case where `a` is true".into())
3183 );
3184 assert_eq!(
3185 logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
3186 None
3187 );
3188 assert_eq!(
3189 arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
3190 None
3191 );
3192
3193 let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
3194 assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
3195 let Some(Finding::InputGap {
3196 survivors,
3197 add_tests,
3198 ..
3199 }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
3200 else {
3201 panic!()
3202 };
3203 assert_eq!(
3204 (survivors[0].as_str(), add_tests[0].as_str()),
3205 ("`total - fee`", "`fee` other than 0")
3206 );
3207 let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
3208 let Some(Finding::InputGap {
3209 survivors,
3210 add_tests,
3211 ..
3212 }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
3213 else {
3214 panic!()
3215 };
3216 assert_eq!(survivors[0], "`n / scale`");
3217 assert_eq!(
3218 add_tests[0],
3219 "operands for which `n * scale` and `n / scale` differ"
3220 );
3221 let assign = Site {
3222 kind: assign_kind(),
3223 ..add.clone()
3224 };
3225 assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
3226 let Some(Finding::InputGap { add_tests, .. }) =
3227 arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
3228 else {
3229 panic!()
3230 };
3231 assert_eq!(add_tests[0], "`fee` other than 0");
3232 let shift = Site {
3233 kind: SiteKind::Arith {
3234 op: ArithOp::Shl,
3235 assign: true,
3236 lhs: "bits".into(),
3237 rhs: "n".into(),
3238 gap: (0, 0),
3239 local_types: vec![],
3240 shadowed_prims: vec![],
3241 cast_probes: vec![],
3242 },
3243 ..assign.clone()
3244 };
3245 assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
3246 let Some(Finding::InputGap { add_tests, .. }) =
3247 arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
3248 else {
3249 panic!()
3250 };
3251 assert_eq!(
3252 add_tests[0],
3253 "operands for which `bits <<= n` and `bits >>= n` differ"
3254 );
3255
3256 let not = Site {
3257 kind: SiteKind::Not {
3258 bang: (0, 1),
3259 operand: "is_ready(x)".into(),
3260 needs_space: false,
3261 },
3262 ..assign.clone()
3263 };
3264 assert_eq!(describe(¬, Mutation::DropNot), "`is_ready(x)`");
3265 let ret = Site {
3266 kind: SiteKind::Return {
3267 name: "is_ready".into(),
3268 option: None,
3269 sole_expr: None,
3270 },
3271 ..assign.clone()
3272 };
3273 assert_eq!(
3274 describe(&ret, Mutation::Const(true)),
3275 "`is_ready` returning `true`"
3276 );
3277 let Some(Finding::InputGap {
3278 survivors,
3279 add_tests,
3280 ..
3281 }) = return_gap_finding("f.rs", &ret, false, true)
3282 else {
3283 panic!()
3284 };
3285 assert_eq!(survivors[0], "`is_ready` returning `false`");
3286 assert_eq!(add_tests[0], "a case where `is_ready` returns true");
3287 assert_eq!(return_gap_finding("f.rs", ¬, false, true), None);
3288
3289 let find = Site {
3290 kind: SiteKind::Return {
3291 name: "find".into(),
3292 option: Some("Option<&str>".into()),
3293 sole_expr: None,
3294 },
3295 ..assign.clone()
3296 };
3297 assert_eq!(
3298 describe(&find, Mutation::Const(false)),
3299 "`find` returning `None`"
3300 );
3301 let Some(Finding::InputGap { add_tests, .. }) =
3302 return_gap_finding("f.rs", &find, false, true)
3303 else {
3304 panic!()
3305 };
3306 assert_eq!(add_tests[0], "a case where `find` returns `Some`");
3307 let range = Site {
3308 kind: SiteKind::Range {
3309 inclusive: false,
3310 lhs: "0".into(),
3311 rhs: "n".into(),
3312 gap: (0, 0),
3313 index: None,
3314 },
3315 ..assign.clone()
3316 };
3317 assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
3318 let closed = Site {
3319 kind: SiteKind::Range {
3320 inclusive: true,
3321 lhs: "1".into(),
3322 rhs: "n".into(),
3323 gap: (0, 0),
3324 index: None,
3325 },
3326 ..assign.clone()
3327 };
3328 assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
3329 let arm = Site {
3330 kind: SiteKind::Arm {
3331 pattern: "Kind::Update { key, .. }".into(),
3332 guard: crate::instrument::ArmGuard::None(0),
3333 removal: (0, 0),
3334 },
3335 ..assign.clone()
3336 };
3337 assert_eq!(
3338 describe(&arm, Mutation::Delete),
3339 "remove the arm `Kind::Update { key, .. } => ..`"
3340 );
3341
3342 let clamp = Site {
3343 kind: SiteKind::MinMax {
3344 max: true,
3345 receiver: "drift".into(),
3346 argument: "peak.get()".into(),
3347 call: (0, 0),
3348 close: (0, 0),
3349 },
3350 ..assign.clone()
3351 };
3352 assert_eq!(
3353 describe(&clamp, Mutation::MinMax),
3354 "`drift.min(peak.get())`"
3355 );
3356 let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
3357 else {
3358 panic!()
3359 };
3360 assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
3361 assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
3362
3363 let end = Site {
3364 kind: SiteKind::SliceEnd {
3365 first: false,
3366 receiver: "self.items".into(),
3367 call: (0, 0),
3368 method: (0, 0),
3369 },
3370 ..assign.clone()
3371 };
3372 assert_eq!(describe(&end, Mutation::OtherEnd), "`self.items.first()`");
3373 let Some(Finding::InputGap { add_tests, .. }) = slice_end_gap_finding("f.rs", &end, true)
3374 else {
3375 panic!()
3376 };
3377 assert_eq!(
3378 add_tests[0],
3379 "`self.items` with two or more elements, the first different from the last"
3380 );
3381 assert_eq!(slice_end_gap_finding("f.rs", &clamp, true), None);
3382
3383 let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
3384 assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
3385 assert_eq!(
3386 logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
3387 None
3388 );
3389 }
3390
3391 #[test]
3392 fn workspace_sarif_matches_the_individual_runs() {
3393 use serde_json::{Value, json};
3394
3395 let report = Report {
3396 package: "zebra".into(),
3397 analysis: Analysis {
3398 package_path: "crates/zebra/".into(),
3399 ..Analysis::default()
3400 },
3401 findings: vec![Finding::Survivor {
3402 at: Location {
3403 file: r#"src/"é".rs"#.into(),
3404 line: 4,
3405 column: 1,
3406 id: "zebra|4".into(),
3407 ..Location::default()
3408 },
3409 survivors: vec!["delete".into()],
3410 witness: None,
3411 change_since: None,
3412 advice: None,
3413 }],
3414 ..Report::default()
3415 };
3416 let empty = Report {
3417 package: "ant".into(),
3418 ..Report::default()
3419 };
3420 for reports in [
3421 &[][..],
3422 std::slice::from_ref(&report),
3423 &[report.clone(), empty],
3424 ] {
3425 let runs: Vec<_> = reports
3426 .iter()
3427 .map(|report| {
3428 let mut single: Value = serde_json::from_str(&render_sarif(report)).unwrap();
3429 let mut run = single["runs"][0].take();
3430 assert!(run["properties"].get("package").is_none());
3431 run["properties"]["package"] = json!(report.package);
3432 run["automationDetails"] = json!({ "id": format!("tmt/{}/", report.package) });
3434 run["invocations"] = json!([{ "executionSuccessful": true }]);
3435 run
3436 })
3437 .collect();
3438 let old = json!({
3439 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
3440 "version": "2.1.0",
3441 "runs": runs,
3442 });
3443 let workspace: Value =
3444 serde_json::from_str(&format!("{:#}", workspace_sarif(reports, &[]))).unwrap();
3445 assert_eq!(workspace, old);
3446 }
3447 }
3448
3449 #[test]
3450 fn a_package_that_could_not_be_analysed_is_a_run_that_says_so() {
3451 use serde_json::Value;
3452
3453 let analysed = Report {
3454 package: "ant".into(),
3455 ..Report::default()
3456 };
3457 let failed = [(
3458 "bee".to_string(),
3459 "the tests of `bee` fail: \"quoted\"\n".to_string(),
3460 )];
3461 let document: Value = serde_json::from_str(&format!(
3462 "{:#}",
3463 workspace_sarif(std::slice::from_ref(&analysed), &failed)
3464 ))
3465 .unwrap();
3466 let runs = document["runs"].as_array().unwrap();
3467 assert_eq!(runs.len(), 2);
3468 assert_eq!(runs[0]["automationDetails"]["id"], "tmt/ant/");
3470 assert_eq!(runs[0]["invocations"][0]["executionSuccessful"], true);
3471 assert_eq!(runs[1]["automationDetails"]["id"], "tmt/bee/");
3472 assert_eq!(runs[1]["invocations"][0]["executionSuccessful"], false);
3473 assert_eq!(
3474 runs[1]["invocations"][0]["toolExecutionNotifications"][0]["message"]["text"],
3475 failed[0].1
3476 );
3477 assert_eq!(runs[1]["results"].as_array().unwrap().len(), 0);
3478 assert_eq!(runs[1]["tool"], runs[0]["tool"]);
3479 assert_eq!(runs[1]["properties"]["package"], "bee");
3480 let document: Value =
3482 serde_json::from_str(&format!("{:#}", workspace_sarif(&[], &failed))).unwrap();
3483 assert_eq!(document["runs"].as_array().unwrap().len(), 1);
3484 }
3485
3486 #[test]
3487 fn a_path_is_written_as_a_uri() {
3488 assert_eq!(sarif_uri("", "src/lib.rs"), "src/lib.rs");
3489 assert_eq!(
3490 sarif_uri("crates/a-b_c/", "src/x~1.rs"),
3491 "crates/a-b_c/src/x~1.rs"
3492 );
3493 assert_eq!(
3495 sarif_uri("my crate/", "a#b%c?.rs"),
3496 "my%20crate/a%23b%25c%3F.rs"
3497 );
3498 assert_eq!(sarif_uri("", "src/é.rs"), "src/%C3%A9.rs");
3499 assert_eq!(sarif_uri("", r#"a\b"c.rs"#), "a%5Cb%22c.rs");
3500 let report = Report {
3501 analysis: Analysis {
3502 package_path: "my crate/".into(),
3503 ..Analysis::default()
3504 },
3505 findings: vec![Finding::Survivor {
3506 at: Location {
3507 file: "src/a b.rs".into(),
3508 line: 1,
3509 column: 1,
3510 ..Location::default()
3511 },
3512 survivors: vec![],
3513 witness: None,
3514 change_since: None,
3515 advice: None,
3516 }],
3517 ..Report::default()
3518 };
3519 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3520 assert_eq!(
3521 sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]
3522 ["uri"],
3523 "my%20crate/src/a%20b.rs"
3524 );
3525 assert_eq!(sarif_uri_for("", r#"a\b"c.rs"#, false), "a%5Cb%22c.rs");
3526 assert_eq!(
3527 sarif_uri_for(r"crates\core\", r"src\lib.rs", true),
3528 "crates/core/src/lib.rs"
3529 );
3530 }
3531
3532 #[test]
3533 fn findings_sort_by_path_and_position_in_input_order_for_ties() {
3534 let mut report = Report {
3535 findings: [
3536 ("z.rs", 1, 1, "1"),
3537 ("é.rs", 1, 1, "2"),
3538 ("a.rs", 2, 1, "3"),
3539 ("a.rs", 1, 3, "4"),
3540 ("a.rs", 1, 3, "5"),
3541 ("a.rs", 1, 1, "6"),
3542 ]
3543 .into_iter()
3544 .map(|(file, line, column, id)| Finding::Survivor {
3545 at: Location {
3546 file: file.into(),
3547 line,
3548 column,
3549 id: id.into(),
3550 ..Location::default()
3551 },
3552 survivors: vec![],
3553 witness: None,
3554 change_since: None,
3555 advice: None,
3556 })
3557 .collect(),
3558 ..Report::default()
3559 };
3560 report.sort_findings();
3561 let ids: Vec<_> = report
3562 .findings
3563 .iter()
3564 .map(|finding| finding.at().id.as_str())
3565 .collect();
3566 assert_eq!(ids, ["6", "4", "5", "3", "1", "2"]);
3567 }
3568
3569 #[test]
3570 fn collapsed_code_matches_the_previous_format() {
3571 for (charset, spacing, width) in [
3573 ("ascii", "none", 17),
3574 ("ascii", "split", 100),
3575 ("ascii", "surrounded", 101),
3576 ("multibyte", "split", 101),
3577 ("ascii", "none", 4096),
3578 ("multibyte", "none", 97),
3579 ("multibyte", "surrounded", 0),
3580 ("multibyte", "surrounded", 17),
3581 ("multibyte", "surrounded", 4096),
3582 ("ascii", "split", 17),
3583 ("multibyte", "none", 100),
3584 ("multibyte", "none", 101),
3585 ("ascii", "surrounded", 97),
3586 ("ascii", "surrounded", 100),
3587 ("multibyte", "split", 97),
3588 ("ascii", "none", 0),
3589 ("multibyte", "split", 4096),
3590 ] {
3591 let glyph = if charset == "ascii" { "x" } else { "🦀" };
3592 let code = match spacing {
3593 "none" => glyph.repeat(width),
3594 "surrounded" => format!("\t{}\u{2003}\r\n", glyph.repeat(width)),
3595 _ => format!(
3596 "{}\u{2003}\r\n {}",
3597 glyph.repeat(width / 2),
3598 glyph.repeat(width - width / 2 - 1),
3599 ),
3600 };
3601 let normalized = code.split_whitespace().collect::<Vec<_>>().join(" ");
3602 let expected = if normalized.chars().count() > 100 {
3603 format!("{}...", normalized.chars().take(97).collect::<String>())
3604 } else {
3605 normalized
3606 };
3607 assert_eq!(one_line(&code), expected, "{charset} {spacing} {width}");
3608 }
3609
3610 let code = format!("{}\n{}", "x".repeat(96), "y".repeat(4096));
3612 assert_eq!(one_line(&code), format!("{} ...", "x".repeat(96)));
3613 let code = format!("{}\n{}", "x".repeat(100), " ".repeat(4096));
3614 assert_eq!(one_line(&code), "x".repeat(100));
3615 }
3616
3617 #[test]
3618 fn long_code_is_shortened() {
3619 let exactly_100 = "x".repeat(100);
3620 assert_eq!(one_line(&exactly_100), exactly_100);
3621 let shortened = one_line(&"x".repeat(101));
3622 assert_eq!(shortened, format!("{}...", "x".repeat(97)));
3623 assert_eq!(one_line("a\n b"), "a b");
3624 }
3625
3626 #[test]
3627 fn timeout_rechecks_are_in_the_json_only_when_there_were_any() {
3628 let none = serde_json::to_value(Report::default()).unwrap();
3629 assert!(none.get("timeout_rechecks").is_none(), "{none}");
3630 let report = Report {
3631 timeout_rechecks: TimeoutRechecks {
3632 first_pass: 3,
3633 confirmed: 1,
3634 recovered: 2,
3635 unconfirmed: 0,
3636 },
3637 ..Report::default()
3638 };
3639 assert_eq!(
3640 serde_json::to_value(&report).unwrap()["timeout_rechecks"],
3641 serde_json::json!({"first_pass": 3, "confirmed": 1, "recovered": 2, "unconfirmed": 0})
3642 );
3643 }
3644
3645 #[test]
3646 fn at_most_three_survivors_are_listed_nearest_first() {
3647 let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
3648 let obs = Obs::default();
3649 let survivors = |min_shift, max_shift| {
3650 let gap = InputGap::Boundary {
3651 min_shift,
3652 max_shift,
3653 missing: vec![0],
3654 same: (0, 0),
3655 };
3656 match input_gap_finding("f.rs", &site, &gap, &obs, false) {
3657 Some(Finding::InputGap {
3658 survivors,
3659 survivor_count,
3660 ..
3661 }) => (survivors, survivor_count),
3662 _ => panic!(),
3663 }
3664 };
3665 assert_eq!(
3666 survivors(-9, 9),
3667 (
3668 vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
3669 18
3670 )
3671 );
3672 assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
3673 assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
3674 assert_eq!(
3675 survivors(-2, 0),
3676 (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
3677 );
3678 }
3679
3680 #[test]
3681 fn text_report_is_exact() {
3682 let at = Location {
3683 file: "src/lib.rs".into(),
3684 line: 3,
3685 column: 9,
3686 code: "a >= b".into(),
3687 ..Location::default()
3688 };
3689 let below = Location {
3690 file: "src/lib.rs".into(),
3691 line: 7,
3692 column: 5,
3693 code: "s.reset();".into(),
3694 ..Location::default()
3695 };
3696 let report = Report {
3697 package: "p".into(),
3698 sites: 2,
3699 mutants_run: 1,
3700 suppressed: 2,
3701 findings: vec![
3702 Finding::InputGap {
3703 at: at.clone(),
3704 survivors: vec!["`a > b`".into()],
3705 survivor_count: 4,
3706 add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
3707 observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
3708 verified: false,
3709 },
3710 Finding::InputGap {
3711 at: at.clone(),
3712 survivors: vec!["`true`".into()],
3713 survivor_count: 1,
3714 add_tests: vec![],
3715 observed: None,
3716 verified: true,
3717 },
3718 Finding::AssertionGap {
3719 at: Location { column: 4, ..at },
3720 survivors: vec!["`!(a >= b)`".into()],
3721 tests: vec!["t".into()],
3722 effects: vec![],
3723 effects_of: None,
3724 witness: None,
3725 },
3726 Finding::AssertionGap {
3727 at: below,
3728 survivors: vec!["delete `s.reset();`".into()],
3729 tests: vec!["t".into()],
3730 effects: vec![
3731 "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
3732 ],
3733 effects_of: None,
3734 witness: None,
3735 },
3736 ],
3737 ..Report::default()
3738 };
3739 assert_eq!(
3741 render_text(&report, false),
3742 "INPUT GAP src/lib.rs:3:9\n a >= b\n\
3743 \x20 passes every test as: `a > b` (+3 more) [from the trace, not re-run]\n\
3744 \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
3745 \x20 add a test with `a` equal to `b` (the original gives true)\n\
3746 \x20 + INPUT GAP column 9\n a >= b\n\
3747 \x20 passes every test as: `true` [re-run: tests pass]\n\
3748 \x20 + ASSERTION GAP column 4\n a >= b\n\
3749 \x20 passes every test as: `!(a >= b)`\n\
3750 \x20 these tests run the changed code and still pass: t\n\
3751 \x20 add an assertion on what this code is responsible for\n\
3752 \n\
3753 ASSERTION GAP src/lib.rs:7:5\n s.reset();\n\
3754 \x20 passes every test as: delete `s.reset();`\n\
3755 \x20 these tests run the changed code and still pass: t\n\
3756 \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
3757 \n\
3758 p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
3759 );
3760 assert_eq!(
3761 render_text(
3762 &Report {
3763 package: "q".into(),
3764 ..Report::default()
3765 },
3766 false
3767 ),
3768 "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
3769 );
3770
3771 let mut in_repository = report.clone();
3772 in_repository.analysis.package_path = "crates/p/".into();
3773 in_repository.analysis.since = Some("abc".into());
3774 if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
3775 at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
3776 }
3777 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
3778 assert_eq!(
3779 results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
3780 "assertion_gap|src/lib.rs|f|s.reset();|0"
3781 );
3782 assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
3783 assert_eq!(sarif["version"], "2.1.0");
3784 let results = sarif["runs"][0]["results"].as_array().unwrap();
3785 assert_eq!(results.len(), 4);
3786 assert_eq!(results[0]["ruleId"], "input-gap");
3787 assert_eq!(results[3]["ruleId"], "assertion-gap");
3788 let location = &results[3]["locations"][0]["physicalLocation"];
3789 assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
3790 assert_eq!(
3791 (
3792 &location["region"]["startLine"],
3793 &location["region"]["startColumn"]
3794 ),
3795 (&serde_json::json!(7), &serde_json::json!(5))
3796 );
3797 assert!(
3798 results[3]["message"]["text"]
3799 .as_str()
3800 .unwrap()
3801 .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
3802 );
3803 let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
3804 .as_array()
3805 .unwrap();
3806 assert_eq!(rules.len(), 6);
3807 }
3808
3809 #[test]
3810 fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
3811 let survivor = Finding::Survivor {
3812 at: Location {
3813 file: "src/lib.rs".into(),
3814 line: 2,
3815 column: 1,
3816 code: "const fn limit() -> u8".into(),
3817 ..Location::default()
3818 },
3819 survivors: vec!["the body of `limit` replaced by `0`".into()],
3820 witness: None,
3821 change_since: None,
3822 advice: None,
3823 };
3824 assert_eq!(survivor.kind(), "survivor");
3825 assert_eq!(survivor.at().line, 2);
3826 assert_eq!(survivor.survivors().len(), 1);
3827 let report = Report {
3828 package: "p".into(),
3829 findings: vec![survivor],
3830 ..Report::default()
3831 };
3832 assert_eq!(
3834 render_text(&report, false),
3835 "SURVIVOR src/lib.rs:2:1\n const fn limit() -> u8\n\
3836 \x20 passes every test as: the body of `limit` replaced by `0`\n\
3837 \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\
3838 \n\
3839 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"
3840 );
3841 let json = serde_json::to_value(&report).unwrap();
3842 assert_eq!(json["findings"][0]["kind"], "survivor");
3843 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3844 assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
3845 assert!(report.has_gaps());
3846 }
3847
3848 #[test]
3849 fn non_literal_inputs_in_words() {
3850 assert_eq!(
3851 input_for("a", "b", LiteralSide::None, 0),
3852 "`a` equal to `b`"
3853 );
3854 assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
3855 assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
3856 assert_eq!(
3857 input_for("18", "age", LiteralSide::Lhs(18), -1),
3858 "`age` = 19"
3859 );
3860 }
3861
3862 #[test]
3863 fn text_report_sections() {
3864 let at = Location {
3865 file: "src/lib.rs".into(),
3866 line: 3,
3867 column: 9,
3868 code: "s.check()?;".into(),
3869 ..Location::default()
3870 };
3871 let report = Report {
3872 schema_version: SCHEMA_VERSION,
3873 mutants: None,
3874 package: "p".into(),
3875 analysis: Analysis::default(),
3876 audit: None,
3877 evaluation: None,
3878 interrupted: false,
3879 sites: 4,
3880 skipped_sites: 1,
3881 skipped: vec![],
3882 unviable_mutants: 2,
3883 mutants_not_built: 0,
3884 mutants_not_evaluated: 0,
3885 mutants_not_compiled: 0,
3886 mutants_run: 3,
3887 mutants_killed: 2,
3888 mutants_timed_out: 0,
3889 mutants_survived: 1,
3890 survivor_breakdown: SurvivorBreakdown {
3891 reported: 1,
3892 ..SurvivorBreakdown::default()
3893 },
3894 timeout_rechecks: TimeoutRechecks::default(),
3895 wrapper_grace_outcomes: None,
3896 suppressed: 0,
3897 baseline: None,
3898 unassessed_test_changes: vec![],
3899 findings: vec![Finding::AssertionGap {
3900 at: at.clone(),
3901 survivors: vec!["delete `s.check()?;`".into()],
3902 tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
3903 effects: vec![],
3904 effects_of: None,
3905 witness: None,
3906 }],
3907 unreached: vec![at.clone()],
3908 unstable: vec![at],
3909 weakened: vec![],
3910 };
3911 let text = render_text(&report, false);
3912 assert!(
3913 text.contains("ASSERTION GAP src/lib.rs:3:9\n s.check()?;"),
3914 "{text}"
3915 );
3916 assert!(text.contains("tests::t4 (+2 more)"), "{text}");
3917 assert!(text.contains("UNSTABLE src/lib.rs:3:9"), "{text}");
3918 assert!(!text.contains("UNREACHED"), "{text}");
3919 assert!(
3920 text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
3921 "{text}"
3922 );
3923 assert!(
3924 text.contains(", 2 mutants left out (they do not compile)\n"),
3925 "{text}"
3926 );
3927 assert!(text.contains("--show-unreached"), "{text}");
3928 let listed = render_text(&report, true);
3929 assert!(listed.contains("UNREACHED src/lib.rs:3:9"));
3930 assert!(!listed.contains("--show-unreached"), "{listed}");
3931 let one_more = Report {
3932 findings: vec![Finding::InputGap {
3933 at: report.unreached[0].clone(),
3934 survivors: vec!["`a`".into()],
3935 survivor_count: 2,
3936 add_tests: vec![],
3937 observed: None,
3938 verified: true,
3939 }],
3940 ..report.clone()
3941 };
3942 assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
3943 let nothing_unreached = Report {
3944 unreached: vec![],
3945 ..report.clone()
3946 };
3947 assert!(!render_text(¬hing_unreached, false).contains("--show-unreached"));
3948 assert!(!Report::default().has_gaps());
3949 }
3950 #[test]
3951 fn unstable_predictions_alone_are_something_to_act_on() {
3952 let at = Location {
3953 file: "src/lib.rs".into(),
3954 line: 1,
3955 column: 1,
3956 code: "a > b".into(),
3957 ..Location::default()
3958 };
3959 assert!(!Report::default().has_gaps());
3960 assert!(
3961 Report {
3962 unstable: vec![at],
3963 ..Report::default()
3964 }
3965 .has_gaps()
3966 );
3967 }
3968
3969 #[test]
3970 fn what_counts_as_a_float_literal() {
3971 assert_eq!(float_literal("30.5"), Some(30.5));
3972 assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
3973 assert_eq!(float_literal("-1e3"), Some(-1000.0));
3974 for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
3977 assert_eq!(float_literal(text), None, "{text}");
3978 }
3979 }
3980
3981 #[test]
3982 fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
3983 let survivors_of = |source: &str| {
3985 let site = site_of(source);
3986 let mut obs = Obs::of_f(-4.0);
3987 obs.merge(&Obs::of_f(4.0));
3988 let gap = InputGap::EqualNeverObserved {
3989 flipped: CmpOp::Ge,
3990 float_gap: obs.float_gap(),
3991 };
3992 match input_gap_finding("f.rs", &site, &gap, &obs, true) {
3993 Some(Finding::InputGap {
3994 survivors,
3995 survivor_count,
3996 ..
3997 }) => (survivors, survivor_count),
3998 _ => panic!(),
3999 }
4000 };
4001 assert_eq!(
4003 survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
4004 (
4005 vec![
4006 "`x >= 9007199254740992.0`".to_string(),
4007 "`x > 9007199254740994.0`".to_string(),
4008 "`x > 9007199254740990.0`".to_string(),
4009 ],
4010 3
4011 )
4012 );
4013 assert_eq!(
4016 survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
4017 (
4018 vec![
4019 "`x >= 18014398509481984.0`".to_string(),
4020 "`x > 1.8014398509481982e16`".to_string(),
4021 ],
4022 2
4023 )
4024 );
4025 assert_eq!(
4026 survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
4027 (
4028 vec![
4029 "`18014398509481984.0 >= x`".to_string(),
4030 "`1.8014398509481982e16 > x`".to_string(),
4031 ],
4032 2
4033 )
4034 );
4035 let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
4037 let mut obs = Obs::of_f(-1.0);
4038 obs.merge(&Obs::of_f(2.0));
4039 let gap = InputGap::EqualNeverObserved {
4040 flipped: CmpOp::Ge,
4041 float_gap: obs.float_gap(),
4042 };
4043 let Some(Finding::InputGap { observed, .. }) =
4044 input_gap_finding("f.rs", &site, &gap, &obs, true)
4045 else {
4046 panic!()
4047 };
4048 assert_eq!(
4049 observed.as_deref(),
4050 Some(
4051 "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
4052 )
4053 );
4054 assert_eq!(
4056 survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
4057 (vec!["`x >= 1e30`".to_string()], 1)
4058 );
4059 }
4060
4061 #[test]
4062 fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
4063 let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
4064 at: Location {
4065 file: "src/lib.rs".into(),
4066 line: 1,
4067 column: 1,
4068 code: "a < b".into(),
4069 ..Location::default()
4070 },
4071 survivors: survivors.iter().map(|s| s.to_string()).collect(),
4072 tests: vec!["tests::t".into()],
4073 effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
4074 effects_of: effects_of.map(str::to_string),
4075 witness: None,
4076 };
4077 let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")), false);
4079 assert_eq!(
4080 body[2..],
4081 [
4082 "followed one of them through the tests: `a <= b`",
4083 "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
4084 ]
4085 );
4086 for single in [
4088 gap(&["`a <= b`"], Some("`a <= b`")),
4089 gap(&["`a <= b`", "`a == b`"], None),
4090 ] {
4091 let body = finding_body(&single, false);
4092 assert_eq!(body.len(), 3, "{body:?}");
4093 assert!(body[2].starts_with("with the mutant"), "{body:?}");
4094 }
4095 }
4096
4097 #[test]
4098 fn an_audit_is_said_in_the_summary() {
4099 let mut report = Report {
4100 package: "p".into(),
4101 audit: Some(Audit {
4102 sampled: 2,
4103 survivors: 7,
4104 ..Audit::default()
4105 }),
4106 ..Report::default()
4107 };
4108 let text = render_text(&report, false);
4109 assert!(
4110 text.ends_with(
4111 "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
4112 audit: recorded once more, the tests did the same\n"
4113 ),
4114 "{text}"
4115 );
4116 let audit = report.audit.as_mut().unwrap();
4117 audit.disagreements.push(Location {
4118 file: "src/lib.rs".into(),
4119 line: 3,
4120 column: 5,
4121 code: "x > 5".into(),
4122 ..Location::default()
4123 });
4124 audit.trace_differences.push(TraceDifference {
4125 binary: "p".into(),
4126 records: 4,
4127 rerun_failed: false,
4128 });
4129 let text = render_text(&report, false);
4130 assert!(
4131 text.ends_with(
4132 "all tests, 1 failed one they had not been run against\n\
4133 \x20 src/lib.rs:3:5 x > 5\n\
4134 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
4135 ),
4136 "{text}"
4137 );
4138 assert!(!text.contains("built from the source"), "{text}");
4140 let audit = report.audit.as_mut().unwrap();
4141 audit.rebuilt = 1;
4142 audit.not_compared = 1;
4143 let text = render_text(&report, false);
4144 assert!(
4145 text.contains(
4146 "\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"
4147 ),
4148 "{text}"
4149 );
4150 let audit = report.audit.as_mut().unwrap();
4151 audit.rebuilt = 5;
4152 audit.compared = 4;
4153 audit.source_disagreements.push(SourceDisagreement {
4154 at: Location {
4155 file: "src/lib.rs".into(),
4156 line: 9,
4157 column: 14,
4158 code: "note(asked)".into(),
4159 ..Location::default()
4160 },
4161 mutant: "the guard `note(asked)` replaced by `true`".into(),
4162 as_probe: "passes".into(),
4163 built: "fails".into(),
4164 });
4165 let text = render_text(&report, false);
4166 assert!(
4167 text.contains(
4168 "\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\
4169 \x20 src/lib.rs:9:14 the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
4170 ),
4171 "{text}"
4172 );
4173 assert!(!render_text(&Report::default(), false).contains("audit"));
4174 }
4175
4176 #[test]
4177 fn lists_and_counts_at_their_limits() {
4178 let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
4179 assert_eq!(list(&items, 3), "a, b, c");
4180 assert_eq!(list(&items, 2), "a, b (+1 more)");
4181 assert_eq!(list(&items, 1), "a (+2 more)");
4182 let one = Report {
4183 package: "p".into(),
4184 suppressed: 1,
4185 unviable_mutants: 1,
4186 ..Report::default()
4187 };
4188 assert!(
4189 render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
4190 "{}",
4191 render_text(&one, false)
4192 );
4193 assert!(!render_text(&Report::default(), false).contains("left out"));
4194 assert!(!render_text(&one, false).contains("--rebuild"));
4195 assert!(!render_text(&one, false).contains("not evaluated"));
4196 let at_top = Report {
4197 mutants_not_evaluated: 1,
4198 ..Report::default()
4199 };
4200 assert!(
4201 render_text(&at_top, false).ends_with(
4202 "\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"
4203 ),
4204 "{}",
4205 render_text(&at_top, false)
4206 );
4207 let not_built = Report {
4209 mutants_not_evaluated: 5,
4210 mutants_not_compiled: 5,
4211 ..Report::default()
4212 };
4213 let text = render_text(¬_built, false);
4214 assert!(
4215 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"),
4216 "{text}"
4217 );
4218 assert!(!text.contains("largest value"), "{text}");
4219 let both = Report {
4220 mutants_not_evaluated: 7,
4221 mutants_not_compiled: 5,
4222 ..Report::default()
4223 };
4224 let text = render_text(&both, false);
4225 assert!(
4226 text.contains("(5 mutants not evaluated: their code"),
4227 "{text}"
4228 );
4229 assert!(
4230 text.contains("\n(2 mutants not evaluated: a range"),
4231 "{text}"
4232 );
4233 let quick = Report {
4234 mutants_not_built: 1,
4235 ..Report::default()
4236 };
4237 assert!(
4238 render_text(&quick, false)
4239 .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
4240 "{}",
4241 render_text(&quick, false)
4242 );
4243 let slow = Report {
4244 mutants_run: 5,
4245 mutants_killed: 4,
4246 mutants_timed_out: 2,
4247 ..Report::default()
4248 };
4249 assert!(
4250 render_text(&slow, false)
4251 .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
4252 "{}",
4253 render_text(&slow, false)
4254 );
4255 assert!(!render_text(&one, false).contains("time limit"));
4256 let once = Report {
4257 mutants_timed_out: 1,
4258 ..slow.clone()
4259 };
4260 assert!(
4261 render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
4262 "{}",
4263 render_text(&once, false)
4264 );
4265 assert!(
4266 render_text(&one, false).contains(", 1 findings suppressed"),
4267 "{}",
4268 render_text(&one, false)
4269 );
4270 assert!(!render_text(&Report::default(), false).contains("suppressed"));
4271 }
4272
4273 #[test]
4274 fn findings_are_put_in_reading_order() {
4275 let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
4276 at: Location {
4277 file: file.into(),
4278 line,
4279 column,
4280 code: "x".into(),
4281 ..Location::default()
4282 },
4283 survivors: vec![survivor.into()],
4284 tests: vec![],
4285 effects: vec![],
4286 effects_of: None,
4287 witness: None,
4288 };
4289 let mut report = Report {
4290 findings: vec![
4291 gap("src/b.rs", 1, 1, "b"),
4292 gap("src/a.rs", 9, 5, "statement"),
4293 gap("src/a.rs", 7, 2, "above it"),
4294 gap("src/a.rs", 9, 5, "its operator"),
4295 gap("src/a.rs", 9, 3, "left of both"),
4296 ],
4297 ..Report::default()
4298 };
4299 report.sort_findings();
4300 let order: Vec<&str> = report
4301 .findings
4302 .iter()
4303 .map(|f| match f {
4304 Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
4305 _ => panic!(),
4306 })
4307 .collect();
4308 assert_eq!(
4310 order,
4311 ["above it", "left of both", "statement", "its operator", "b"]
4312 );
4313 }
4314 #[test]
4315 fn second_replacements_guards_fields_and_bodies_in_words() {
4316 let all = |src: &str| discover(src, 0).unwrap().sites;
4317 let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
4318 assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
4319 let Some(Finding::InputGap {
4320 survivors,
4321 add_tests,
4322 ..
4323 }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
4324 else {
4325 panic!()
4326 };
4327 assert_eq!(survivors, ["`total * fee`"]);
4328 assert_eq!(
4329 add_tests,
4330 ["operands for which `total + fee` and `total * fee` differ"]
4331 );
4332 let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
4333 let arith: Vec<&Site> = sites
4334 .iter()
4335 .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
4336 .collect();
4337 assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
4338 assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
4339 let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
4340 assert_eq!(
4341 arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
4342 None
4343 );
4344 assert_eq!(
4346 arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
4347 None
4348 );
4349
4350 let sites = all("fn f(k: Option<i32>, base: O) -> O { \
4351 let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
4352 let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
4353 let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
4354 assert_eq!(
4355 describe(guard, Mutation::Const(true)),
4356 "the guard `n > 1` replaced by `true`"
4357 );
4358 assert_eq!(
4359 guard_gap_finding("f.rs", guard, false, true),
4360 Finding::InputGap {
4361 at: location("f.rs", guard),
4362 survivors: vec!["the guard `n > 1` replaced by `false`".into()],
4363 survivor_count: 1,
4364 add_tests: vec!["a case where the guard `n > 1` is true".into()],
4365 observed: None,
4366 verified: true,
4367 }
4368 );
4369 let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
4370 assert_eq!(describe(neg, Mutation::Delete), "`n`");
4371 let field = of(&|k| matches!(k, SiteKind::Field { .. }));
4372 assert_eq!(
4373 describe(field, Mutation::Delete),
4374 "without the field `depth: d` (it is then `(base).depth`)"
4375 );
4376 let body = of(&|k| matches!(k, SiteKind::Body { .. }));
4377 assert_eq!(
4378 describe(body, Mutation::Delete),
4379 "the body of `f` replaced by `Default::default()`"
4380 );
4381 assert_eq!(
4382 location("f.rs", body).code,
4383 "fn f(k: Option<i32>, base: O) -> O"
4384 );
4385 }
4386
4387 #[test]
4388 fn audit_reports_unjudged_all_tests_reruns_in_text_and_json() {
4389 let mut report = Report {
4390 package: "demo".into(),
4391 audit: Some(Audit {
4392 sampled: 3,
4393 survivors: 3,
4394 not_audited: 2,
4395 ..Audit::default()
4396 }),
4397 ..Report::default()
4398 };
4399 let text = render_text(&report, false);
4400 assert!(
4401 text.contains(
4402 "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"
4403 ),
4404 "{text}"
4405 );
4406 let value = serde_json::to_value(&report).unwrap();
4407 assert_eq!(value["audit"]["not_audited"], 2);
4408
4409 report.audit.as_mut().unwrap().not_audited = 0;
4410 let clean_text = render_text(&report, false);
4411 assert!(!clean_text.contains("could not be judged"), "{clean_text}");
4412 let clean_value = serde_json::to_value(&report).unwrap();
4413 assert!(clean_value["audit"].get("not_audited").is_none());
4414 }
4415
4416 #[test]
4417 fn sarif_emits_unstable_predictions() {
4418 let report = Report {
4419 package: "demo".into(),
4420 unstable: vec![Location {
4421 file: "src/lib.rs".into(),
4422 line: 12,
4423 column: 5,
4424 code: "age >= 18".into(),
4425 ..Location::default()
4426 }],
4427 ..Report::default()
4428 };
4429 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
4430 let results = sarif["runs"][0]["results"].as_array().unwrap();
4431 assert_eq!(results.len(), 1);
4432 assert_eq!(results[0]["ruleId"], "unstable-prediction");
4433 assert_eq!(results[0]["level"], "error");
4434 assert_eq!(
4435 results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
4436 "src/lib.rs"
4437 );
4438 }
4439
4440 #[test]
4441 fn sarif_emits_weakened_and_audit_disagreements_and_has_gaps() {
4442 let loc = Location {
4443 file: "src/lib.rs".into(),
4444 line: 20,
4445 column: 9,
4446 code: "x > 0".into(),
4447 ..Location::default()
4448 };
4449 let report = Report {
4450 package: "demo".into(),
4451 weakened: vec![loc.clone()],
4452 audit: Some(Audit {
4453 survivors: 1,
4454 sampled: 1,
4455 disagreements: vec![loc.clone()],
4456 not_audited: 0,
4457 rebuilt: 1,
4458 compared: 1,
4459 not_compared: 0,
4460 source_disagreements: vec![SourceDisagreement {
4461 at: loc,
4462 mutant: "`x >= 0`".into(),
4463 as_probe: "passes".into(),
4464 built: "fails".into(),
4465 }],
4466 trace_rerun_incomplete: false,
4467 trace_differences: vec![
4468 TraceDifference {
4469 binary: "unit".into(),
4470 records: 3,
4471 rerun_failed: false,
4472 },
4473 TraceDifference {
4474 binary: "flaky".into(),
4475 records: 0,
4476 rerun_failed: true,
4477 },
4478 TraceDifference {
4479 binary: "flaky-diff".into(),
4480 records: 2,
4481 rerun_failed: true,
4482 },
4483 ],
4484 }),
4485 ..Report::default()
4486 };
4487 assert!(report.has_gaps());
4488 let text = render_text(&report, false);
4489 assert!(
4490 text.contains("`flaky` did not pass: its tests do not always do the same"),
4491 "{text}"
4492 );
4493 assert!(
4494 text.contains(
4495 "`flaky-diff` did not pass and differs in 2 records: its tests do not always do the same"
4496 ),
4497 "{text}"
4498 );
4499 let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
4500 let results = sarif["runs"][0]["results"].as_array().unwrap();
4501 let rules: Vec<_> = results
4502 .iter()
4503 .map(|r| (r["ruleId"].as_str().unwrap(), r["level"].as_str().unwrap()))
4504 .collect();
4505 assert_eq!(
4506 rules,
4507 [
4508 ("weakened-test", "warning"),
4509 ("audit-disagreement", "error"),
4510 ("audit-disagreement", "error"),
4511 ("audit-disagreement", "error"),
4512 ("audit-disagreement", "error"),
4513 ("audit-disagreement", "error"),
4514 ]
4515 );
4516 assert!(
4517 results[4]["message"]["text"]
4518 .as_str()
4519 .unwrap()
4520 .contains("did not pass"),
4521 "{}",
4522 results[4]
4523 );
4524 assert!(
4525 results[5]["message"]["text"]
4526 .as_str()
4527 .unwrap()
4528 .contains("did not pass and differed in 2 records"),
4529 "{}",
4530 results[5]
4531 );
4532 assert!(sarif["runs"][0]["properties"].get("audit").is_some());
4533 }
4534
4535 #[test]
4536 fn render_text_sanitizes_terminal_escape_sequences_bidi_and_injected_newlines() {
4537 let report = Report {
4538 package: "pkg\x1b[31mred\x1b[0m\nFAKE".into(),
4539 sites: 1,
4540 findings: vec![Finding::AssertionGap {
4541 at: Location {
4542 file: "src/\x1b]52;c;evil\x07lib.rs".into(),
4543 line: 10,
4544 column: 5,
4545 code: "x\u{202e} == 1\r\nFAKE LINE".into(),
4546 ..Location::default()
4547 },
4548 survivors: vec!["`x \x1b[2J!= 1`".into()],
4549 tests: vec!["tests::\u{009b}31mspoof".into()],
4550 effects: vec![],
4551 effects_of: None,
4552 witness: None,
4553 }],
4554 ..Report::default()
4555 };
4556 assert_eq!(report.schema_version, SCHEMA_VERSION);
4557 let json: serde_json::Value = serde_json::to_value(&report).unwrap();
4558 assert_eq!(json["schema_version"], SCHEMA_VERSION);
4559 assert!(json["package"].as_str().unwrap().contains('\x1b'));
4561
4562 let text = render_text(&report, false);
4563 assert!(!text.contains('\x1b'), "{text:?}");
4564 assert!(!text.contains('\x07'), "{text:?}");
4565 assert!(!text.contains('\u{009b}'), "{text:?}");
4566 assert!(!text.contains('\u{202e}'), "{text:?}");
4567 assert!(!text.contains('\r'), "{text:?}");
4568 assert!(!text.lines().any(|l| l.starts_with("FAKE")), "{text:?}");
4570 assert!(text.contains("src/lib.rs:10:5"), "{text:?}");
4571 assert!(text.contains("pkgred FAKE:"), "{text:?}");
4572
4573 assert_eq!(sanitize_inline("a\u{009d}0;title\u{009c}b"), "ab");
4576 assert_eq!(sanitize_inline("a\u{0090}dcs-payload\u{009c}b"), "ab");
4577 assert_eq!(sanitize_inline("a\x1b]0;title\u{009c}b"), "ab");
4578 assert_eq!(sanitize_inline("a\x1b(Bb"), "ab");
4579 let report_unclosed = Report {
4580 package: "p".into(),
4581 sites: 1,
4582 findings: vec![Finding::AssertionGap {
4583 at: Location {
4584 file: "src/lib.rs".into(),
4585 line: 1,
4586 column: 1,
4587 code: "x == 1".into(),
4588 ..Location::default()
4589 },
4590 survivors: vec!["`a\x1b]0;unterminated".into(), "`b`".into()],
4591 tests: vec!["t".into()],
4592 effects: vec![],
4593 effects_of: None,
4594 witness: None,
4595 }],
4596 ..Report::default()
4597 };
4598 let unclosed_text = render_text(&report_unclosed, false);
4599 assert!(unclosed_text.contains("`a, `b`"), "{unclosed_text:?}");
4600 }
4601
4602 #[test]
4603 fn bitor_bitxor_input_gap_advice_mentions_shared_bits_and_disjoint_equivalence() {
4604 let found = crate::instrument::discover("fn f(a: u8, b: u8) -> u8 { a | b }", 0).unwrap();
4605 let site = found
4606 .sites
4607 .iter()
4608 .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
4609 .expect("arith site");
4610 let Some(Finding::InputGap { add_tests, .. }) =
4611 arith_gap_finding("src/lib.rs", site, Mutation::ArithSwap2, true)
4612 else {
4613 panic!("expected InputGap for | -> ^");
4614 };
4615 assert_eq!(add_tests.len(), 1);
4616 assert!(
4617 add_tests[0].contains("share at least one set bit")
4618 && add_tests[0].contains("disjoint by construction"),
4619 "{add_tests:?}"
4620 );
4621 }
4622
4623 #[test]
4624 fn byte_and_char_literal_nearest_values_match_pict_table() {
4625 let table = include_str!("../tests/data/literal-nearest.pict.tsv");
4626 let mut rows = 0;
4627 for line in table.lines().skip(1).filter(|l| !l.trim().is_empty()) {
4628 let cols: Vec<&str> = line.split('\t').collect();
4629 assert_eq!(cols.len(), 4, "unexpected row: {line}");
4630 let (lit_kind, lit_side, cmp_op, obs_kind) = (cols[0], cols[1], cols[2], cols[3]);
4631 let (lit_text, lit_val): (&str, Option<i128>) = match lit_kind {
4632 "byte_ascii" => ("b'A'", Some(65)),
4633 "byte_escape" => ("b'\\n'", Some(10)),
4634 "byte_non_ascii" => ("b'\\xfe'", Some(254)),
4635 "char_ascii" => ("'A'", Some(65)),
4636 "char_unicode" => ("'あ'", Some('あ' as u32 as i128)),
4637 "int" => ("65", Some(65)),
4638 "none" => ("other", None),
4639 other => panic!("unexpected LitKind: {other}"),
4640 };
4641 let (lhs, rhs, literal) = match (lit_val, lit_side) {
4642 (Some(k), "rhs") => ("tag", lit_text, LiteralSide::Rhs(k)),
4643 (Some(k), "lhs") => (lit_text, "tag", LiteralSide::Lhs(k)),
4644 (None, _) => ("tag", "other", LiteralSide::None),
4645 other => panic!("unexpected LitSide: {other:?}"),
4646 };
4647 let obs = match obs_kind {
4648 "pos_only" => Obs::of_d(46),
4649 "neg_only" => Obs::of_d(-1),
4650 "both_sides" => {
4651 let mut o = Obs::of_d(-2);
4652 o.merge(&Obs::of_d(1));
4653 o
4654 }
4655 "eq_only" => Obs::of_d(0),
4656 other => panic!("unexpected ObsKind: {other}"),
4657 };
4658 let observed = observed_values(lhs, rhs, literal, &obs).expect("valued obs");
4659 match lit_kind {
4660 "byte_ascii" => {
4661 if lit_side == "rhs" && obs_kind == "pos_only" {
4662 assert_eq!(
4663 observed,
4664 "nearest values the tests passed: `tag` = b'o' (111)"
4665 );
4666 } else {
4667 assert!(
4668 observed.contains("b'") && observed.contains('('),
4669 "{observed}"
4670 );
4671 }
4672 }
4673 "byte_escape" => {
4674 if lit_side == "rhs" && obs_kind == "eq_only" {
4675 assert_eq!(
4676 observed,
4677 "nearest values the tests passed: `tag` = b'\\n' (10)"
4678 );
4679 } else {
4680 assert!(
4681 observed.contains("b'") && observed.contains('('),
4682 "{observed}"
4683 );
4684 }
4685 }
4686 "byte_non_ascii" => {
4687 if lit_side == "rhs" && obs_kind == "pos_only" {
4688 assert_eq!(observed, "nearest values the tests passed: `tag` = 300");
4690 } else {
4691 assert!(observed.contains("b'\\x"), "{observed}");
4692 }
4693 }
4694 "char_ascii" => {
4695 if lit_side == "rhs" && obs_kind == "pos_only" {
4696 assert_eq!(
4697 observed,
4698 "nearest values the tests passed: `tag` = 'o' (111)"
4699 );
4700 } else {
4701 assert!(
4702 observed.contains('\'') && !observed.contains("b'"),
4703 "{observed}"
4704 );
4705 }
4706 }
4707 "char_unicode" => {
4708 assert!(
4709 observed.contains('\'') && !observed.contains("b'"),
4710 "{observed}"
4711 );
4712 }
4713 "int" => {
4714 assert!(!observed.contains('\''), "{observed}");
4715 }
4716 "none" => {
4717 assert!(observed.contains("`tag` - `other` = "), "{observed}");
4718 }
4719 _ => unreachable!(),
4720 }
4721
4722 if lit_kind == "byte_ascii" {
4724 let expected_input = "`tag` = b'A' (65)";
4725 assert_eq!(input_for(lhs, rhs, literal, 0), expected_input);
4726 if cmp_op != "eq" {
4727 let op_sym = if cmp_op == "ge" { ">=" } else { "<" };
4728 let expr = if lit_side == "rhs" {
4729 format!("tag {op_sym} b'A'")
4730 } else {
4731 format!("b'A' {op_sym} tag")
4732 };
4733 let site = site_of(&format!("fn f(tag: u8) -> bool {{ {expr} }}"));
4734 let expected = if lit_side == "rhs" {
4735 format!("`tag {op_sym} b'B'`")
4736 } else {
4737 format!("`b'@' {op_sym} tag`")
4738 };
4739 assert_eq!(describe(&site, Mutation::Shift(1)), expected);
4740 }
4741 }
4742 if lit_kind == "char_ascii" {
4743 let expected_input = "`tag` = 'A' (65)";
4744 assert_eq!(input_for(lhs, rhs, literal, 0), expected_input);
4745 if cmp_op != "eq" {
4746 let op_sym = if cmp_op == "ge" { ">=" } else { "<" };
4747 let expr = if lit_side == "rhs" {
4748 format!("tag {op_sym} 'A'")
4749 } else {
4750 format!("'A' {op_sym} tag")
4751 };
4752 let site = site_of(&format!("fn f(tag: char) -> bool {{ {expr} }}"));
4753 let expected = if lit_side == "rhs" {
4754 format!("`tag {op_sym} 'B'`")
4755 } else {
4756 format!("`'@' {op_sym} tag`")
4757 };
4758 assert_eq!(describe(&site, Mutation::Shift(1)), expected);
4759 }
4760 }
4761 rows += 1;
4762 }
4763 assert!(rows >= 25, "expected full PICT table, got {rows} rows");
4764
4765 assert_eq!(
4768 format_literal_value(0xd800, LiteralDisplay::Char),
4769 "'\\u{e000}' (57344)"
4770 );
4771 assert_eq!(
4772 format_literal_value(0x10_d800, LiteralDisplay::Char),
4773 "1103872"
4774 );
4775 }
4776}