1use std::collections::BTreeMap;
4use std::fmt::Write as _;
5
6use fallow_engine::module_graph::ExportTestReach;
7use fallow_engine::mutation::{MutantDisposition, MutationPlan, PlannedMutant, PruneReason};
8use fallow_output::{
9 MutantEquivalenceHint, MutantLocation, MutantResult, MutantStatus, MutantTestReach,
10 MutationBaselineFailure, MutationCompletion, MutationFunctionResult, MutationIncompleteReason,
11 MutationPlanCountsOutput, MutationPlanDisposition, MutationPlanFile, MutationPlanMutant,
12 MutationReport, MutationRunIssue, MutationSkippedFile, MutationStatusCounts,
13 SAMPLED_OUT_REASON, SKIPPED_TESTS_CODE, TestReachClass,
14};
15use fallow_types::envelope::ToolVersion;
16use rustc_hash::FxHashSet;
17
18use super::scheduler::ScheduleOutcome;
19use crate::ProgrammaticError;
20
21pub fn kebab<T: serde::Serialize>(value: &T) -> String {
23 serde_json::to_value(value)
24 .ok()
25 .and_then(|value| value.as_str().map(str::to_owned))
26 .unwrap_or_default()
27}
28
29pub fn tool_version() -> ToolVersion {
30 ToolVersion(env!("CARGO_PKG_VERSION").to_owned())
31}
32
33fn location(mutant: &PlannedMutant) -> MutantLocation {
34 MutantLocation {
35 mutant_id: mutant.mutant.id.as_str().to_owned(),
36 file: mutant.file.clone(),
37 line: mutant.mutant.line,
38 column: mutant.mutant.column + 1,
39 span: mutant.mutant.span,
40 operator: mutant.mutant.operator.as_str().to_owned(),
41 function: mutant
42 .function
43 .as_ref()
44 .and_then(|function| function.name.clone()),
45 function_line: mutant.function.as_ref().map(|function| function.line),
46 rank: mutant.rank,
47 change: Some(fallow_output::MutantChange {
48 from: mutant.mutant.change.from.to_owned(),
49 to: mutant.mutant.change.to.to_owned(),
50 }),
51 }
52}
53
54pub const NO_TARGET_COVERAGE: &str = "no-target-coverage";
56
57fn prune_reason(mutant: &PlannedMutant) -> Option<String> {
58 match mutant.disposition {
59 MutantDisposition::Pruned(reason) => Some(kebab::<PruneReason>(&reason)),
60 _ => None,
61 }
62}
63
64fn pending_reason(mutant: &PlannedMutant) -> Option<String> {
66 (mutant.disposition == MutantDisposition::SampledOut).then(|| SAMPLED_OUT_REASON.to_owned())
67}
68
69fn test_reach(mutant: &PlannedMutant) -> Option<MutantTestReach> {
71 let reach = mutant.test_reach.as_ref()?;
72 Some(MutantTestReach {
73 reach: match reach.reach {
74 ExportTestReach::Direct => TestReachClass::Direct,
75 ExportTestReach::Transitive => TestReachClass::Transitive,
76 ExportTestReach::MockedOnly => TestReachClass::MockedOnly,
77 ExportTestReach::None => TestReachClass::None,
78 ExportTestReach::NoneFile => TestReachClass::NoneFile,
79 },
80 export_name: reach.export_name.clone(),
81 tests: reach.tests.clone(),
82 mocked_targets: reach.mocked_targets.clone(),
83 })
84}
85
86pub fn skipped_files(plan: &MutationPlan) -> Vec<MutationSkippedFile> {
88 plan.skipped_files
89 .iter()
90 .map(|file| MutationSkippedFile {
91 path: file.path.clone(),
92 reason: kebab(&file.reason),
93 })
94 .collect()
95}
96
97pub fn unmatched_paths(plan: &MutationPlan) -> Vec<String> {
99 plan.unmatched_paths
100 .iter()
101 .map(|entry| entry.path.clone())
102 .collect()
103}
104
105pub fn plan_mutants(plan: &MutationPlan) -> Vec<MutationPlanMutant> {
107 plan.mutants
108 .iter()
109 .map(|mutant| MutationPlanMutant {
110 location: location(mutant),
111 disposition: match mutant.disposition {
112 MutantDisposition::Planned => MutationPlanDisposition::Planned,
113 MutantDisposition::Pending | MutantDisposition::SampledOut => {
114 MutationPlanDisposition::Pending
115 }
116 MutantDisposition::NoCoverage => MutationPlanDisposition::NoCoverage,
117 MutantDisposition::Pruned(_) => MutationPlanDisposition::Pruned,
118 },
119 prune_reason: prune_reason(mutant),
120 pending_reason: pending_reason(mutant),
121 test_reach: (mutant.disposition == MutantDisposition::NoCoverage)
122 .then(|| test_reach(mutant))
123 .flatten(),
124 })
125 .collect()
126}
127
128pub const fn plan_counts(plan: &MutationPlan) -> MutationPlanCountsOutput {
130 MutationPlanCountsOutput {
131 total: plan.counts.total,
132 planned: plan.counts.planned,
133 pending: plan.counts.pending + plan.counts.sampled_out,
134 sampled_out: plan.counts.sampled_out,
135 no_coverage: plan.counts.no_coverage,
136 pruned_dead_code: plan.counts.pruned.dead_code,
137 pruned_generated: plan.counts.pruned.generated,
138 pruned_side_effect_sink: plan.counts.pruned.side_effect_sink,
139 pruned_framework_config: plan.counts.pruned.framework_config,
140 pruned_build_tool_only: plan.counts.pruned.build_tool_only,
141 }
142}
143
144pub fn plan_files(plan: &MutationPlan) -> Vec<MutationPlanFile> {
146 plan.files
147 .iter()
148 .map(|file| MutationPlanFile {
149 path: file.path.clone(),
150 source_sha256: file.source_sha256.clone(),
151 static_test_files: file.static_test_files.clone(),
152 })
153 .collect()
154}
155
156pub fn mutant_results(plan: &MutationPlan, outcome: Option<&ScheduleOutcome>) -> Vec<MutantResult> {
165 plan.mutants
166 .iter()
167 .map(|mutant| {
168 let mut result = mutant_result(mutant, outcome);
169 if result.status == MutantStatus::NoCoverage {
170 result.test_reach = test_reach(mutant);
171 }
172 if result.status == MutantStatus::Survived && mutant.constant_parameter {
173 result.equivalence_hint = Some(MutantEquivalenceHint::ConstantParameter);
174 }
175 result
176 })
177 .collect()
178}
179
180fn mutant_result(mutant: &PlannedMutant, outcome: Option<&ScheduleOutcome>) -> MutantResult {
181 let base = MutantResult {
182 location: location(mutant),
183 status: MutantStatus::Pending,
184 prune_reason: prune_reason(mutant),
185 pending_reason: pending_reason(mutant),
186 killing_tests: Vec::new(),
187 kill_matrix_complete: false,
188 killed_by: None,
189 covering_tests: Vec::new(),
190 static_mutant: false,
191 duration_ms: None,
192 test_reach: None,
193 retried: false,
194 attempts: Vec::new(),
195 cached: false,
196 resumed: false,
197 carried: false,
198 type_error_codes: Vec::new(),
199 equivalence_hint: None,
200 witness: None,
201 };
202 let scheduled = outcome.and_then(|outcome| outcome.results.get(mutant.mutant.id.as_str()));
203 match (mutant.disposition, scheduled) {
204 (MutantDisposition::Pruned(_), _) => MutantResult {
205 status: MutantStatus::Pruned,
206 ..base
207 },
208 (
209 MutantDisposition::Planned
210 | MutantDisposition::Pending
211 | MutantDisposition::SampledOut
212 | MutantDisposition::NoCoverage,
213 Some(result),
214 ) => MutantResult {
215 status: result.status,
216 pending_reason: None,
217 killing_tests: result.killing_tests.clone(),
218 kill_matrix_complete: result.kill_matrix_complete,
219 killed_by: result.killed_by.clone(),
220 covering_tests: result.covering_tests.clone(),
221 static_mutant: result.static_mutant,
222 duration_ms: result.duration_ms,
223 retried: result.retried,
224 attempts: result.attempts.clone(),
225 cached: result.cached,
226 resumed: result.resumed,
227 prune_reason: (result.status == MutantStatus::Pruned)
229 .then(|| NO_TARGET_COVERAGE.to_owned()),
230 ..base
231 },
232 (MutantDisposition::NoCoverage, None) => MutantResult {
233 status: MutantStatus::NoCoverage,
234 ..base
235 },
236 (
237 MutantDisposition::Planned | MutantDisposition::Pending | MutantDisposition::SampledOut,
238 _,
239 ) => base,
240 }
241}
242
243type FunctionKey = (String, Option<u32>, Option<(u32, u32)>);
246
247pub fn function_results(
250 plan: &MutationPlan,
251 results: &[MutantResult],
252) -> Vec<MutationFunctionResult> {
253 let mut groups: BTreeMap<FunctionKey, MutationFunctionResult> = BTreeMap::new();
254 for (mutant, result) in plan.mutants.iter().zip(results) {
255 let function = mutant.function.as_ref();
256 let key = (
257 mutant.file.clone(),
258 function.map(|function| function.line),
259 function.map(|function| function.span),
260 );
261 let group = groups.entry(key).or_insert_with(|| MutationFunctionResult {
262 file: mutant.file.clone(),
263 name: function.and_then(|function| function.name.clone()),
264 line: function.map(|function| function.line),
265 end_line: function.map(|function| function.end_line),
266 in_diff: function.is_some_and(|function| function.in_diff),
267 cyclomatic: function.and_then(|function| function.cyclomatic),
268 counts: MutationStatusCounts::default(),
269 score: None,
270 survived: Vec::new(),
271 });
272 group.counts.add(result.status);
273 if result.status == MutantStatus::Survived {
274 group.survived.push(result.location.mutant_id.clone());
275 }
276 }
277 groups
278 .into_values()
279 .map(|mut group| {
280 group.score = group.counts.score();
281 group
282 })
283 .collect()
284}
285
286pub struct CompletionFacts<'a> {
288 pub plan: &'a MutationPlan,
289 pub results: &'a [MutantResult],
290 pub baseline_failures: &'a [MutationBaselineFailure],
291 pub worktree_changed: bool,
292 pub worktree_unchecked: bool,
294 pub unretried: bool,
296 pub unloaded_paths: &'a [String],
298 pub undiscovered_test_files: &'a [String],
300 pub typecheck_failed: bool,
302 pub promoted: &'a [String],
305}
306
307pub fn completion(facts: &CompletionFacts<'_>) -> MutationCompletion {
310 let mut reasons = Vec::new();
311 if facts
312 .results
313 .iter()
314 .any(|result| result.status == MutantStatus::RuntimeError)
315 {
316 reasons.push(MutationIncompleteReason::RuntimeError);
317 }
318 let promoted: FxHashSet<&str> = facts.promoted.iter().map(String::as_str).collect();
319 let mut limit_pending = false;
320 let mut sampled_pending = false;
321 let mut budget_pending = false;
322 for (mutant, result) in facts.plan.mutants.iter().zip(facts.results) {
323 if result.status != MutantStatus::Pending {
324 continue;
325 }
326 if is_scheduled(mutant, &promoted) {
327 budget_pending = true;
328 } else if mutant.disposition == MutantDisposition::Pending {
329 limit_pending = true;
330 } else if mutant.disposition == MutantDisposition::SampledOut {
331 sampled_pending = true;
332 }
333 }
334 if limit_pending {
335 reasons.push(MutationIncompleteReason::MutantLimit);
336 }
337 if sampled_pending {
338 reasons.push(MutationIncompleteReason::SampledOut);
339 }
340 if budget_pending || facts.unretried {
341 reasons.push(MutationIncompleteReason::TimeBudget);
342 }
343 if !facts.plan.skipped_files.is_empty() {
344 reasons.push(MutationIncompleteReason::SkippedFiles);
345 }
346 if has_unloaded_reached_file(facts.plan, facts.unloaded_paths, &promoted) {
347 reasons.push(MutationIncompleteReason::UnloadedFiles);
348 }
349 if !facts.undiscovered_test_files.is_empty() {
350 reasons.push(MutationIncompleteReason::TestFilesNotDiscovered);
351 }
352 if !facts.baseline_failures.is_empty() {
353 reasons.push(MutationIncompleteReason::BaselineFailure);
354 }
355 if facts.worktree_changed {
356 reasons.push(MutationIncompleteReason::WorktreeChanged);
357 }
358 if facts.worktree_unchecked {
359 reasons.push(MutationIncompleteReason::WorktreeUnchecked);
360 }
361 if facts.typecheck_failed {
362 reasons.push(MutationIncompleteReason::TypecheckFailed);
363 }
364 MutationCompletion::from_reasons(reasons)
365}
366
367fn is_scheduled(mutant: &PlannedMutant, promoted: &FxHashSet<&str>) -> bool {
371 match mutant.disposition {
372 MutantDisposition::Planned => true,
373 MutantDisposition::Pending => promoted.contains(mutant.mutant.id.as_str()),
374 MutantDisposition::SampledOut
375 | MutantDisposition::NoCoverage
376 | MutantDisposition::Pruned(_) => false,
377 }
378}
379
380fn has_unloaded_reached_file(
385 plan: &MutationPlan,
386 unloaded_paths: &[String],
387 promoted: &FxHashSet<&str>,
388) -> bool {
389 if unloaded_paths.is_empty() {
390 return false;
391 }
392 let unloaded: FxHashSet<&str> = unloaded_paths.iter().map(String::as_str).collect();
393 plan.files.iter().any(|file| {
394 unloaded.contains(file.path.as_str())
395 && !file.static_test_files.is_empty()
396 && plan
397 .mutants
398 .iter()
399 .any(|mutant| mutant.file == file.path && is_scheduled(mutant, promoted))
400 })
401}
402
403#[must_use]
418pub fn baseline_blocked_run_error(report: &MutationReport) -> Option<ProgrammaticError> {
419 let counts = &report.summary.counts;
420 if has_test_result(counts) || counts.pending > 0 {
421 return None;
422 }
423 let first = report.baseline_failures.first()?;
424 let name = first
425 .test_id
426 .as_deref()
427 .or(first.file.as_deref())
428 .unwrap_or("a test file");
429 let mut message = format!(
430 "no mutant has a test result, because the test suite fails with no active mutant: {name}"
431 );
432 if let Some(line) = first.message.as_deref().and_then(first_message_line) {
433 message.push_str(": ");
434 message.push_str(line);
435 }
436 let others = report.baseline_failures.len() - 1;
437 if others > 0 {
438 let noun = if others == 1 { "failure" } else { "failures" };
439 let _ = write!(
440 message,
441 " ({others} more {noun}, see `baseline_failures` in the JSON report)"
442 );
443 }
444 Some(
445 ProgrammaticError::new(message, 2)
446 .with_code("FALLOW_MUTATION_BASELINE_FAILED")
447 .with_help(
448 "read the error of each failed test in `baseline_failures[].message` of the JSON report, make the tests pass with the runner directly, then run fallow mutation again",
449 ),
450 )
451}
452
453const fn has_test_result(counts: &MutationStatusCounts) -> bool {
456 counts.killed + counts.timeout + counts.survived + counts.flaky + counts.not_killed_by_target
457 > 0
458}
459
460fn first_message_line(message: &str) -> Option<&str> {
462 message.lines().map(str::trim).find(|line| !line.is_empty())
463}
464
465pub fn baseline_failures(outcome: Option<&ScheduleOutcome>) -> Vec<MutationBaselineFailure> {
467 outcome
468 .map(|outcome| {
469 outcome
470 .baseline_failures
471 .iter()
472 .map(|failure| MutationBaselineFailure {
473 file: failure.file.clone(),
474 test_id: failure.test_id.clone(),
475 message: failure.message.clone(),
476 mutant_ids: failure.mutant_ids.clone(),
477 })
478 .collect()
479 })
480 .unwrap_or_default()
481}
482
483const MAX_SKIPPED_TESTS_SHOWN: usize = 10;
485
486pub fn skipped_tests_issue(plan: &MutationPlan) -> Option<MutationRunIssue> {
490 let tests = &plan.skipped_tests;
491 if tests.is_empty() {
492 return None;
493 }
494 let shown: Vec<String> = tests
495 .iter()
496 .take(MAX_SKIPPED_TESTS_SHOWN)
497 .map(|test| match &test.name {
498 Some(name) => format!("{}:{} ({name})", test.file, test.line),
499 None => format!("{}:{}", test.file, test.line),
500 })
501 .collect();
502 let tail = match tests.len().saturating_sub(MAX_SKIPPED_TESTS_SHOWN) {
503 0 => String::new(),
504 more => format!(" and {more} more"),
505 };
506 let (noun, verb) = if tests.len() == 1 {
507 ("test", "is")
508 } else {
509 ("tests", "are")
510 };
511 Some(MutationRunIssue {
512 code: SKIPPED_TESTS_CODE.to_owned(),
513 message: format!(
514 "{} {noun} {verb} skipped or todo: {}{tail}. A skipped test checks nothing, so it cannot kill a mutant. Run each test or remove it.",
515 tests.len(),
516 shown.join(", ")
517 ),
518 mutant_id: None,
519 stderr_tail: None,
520 })
521}
522
523pub fn issues(outcome: Option<&ScheduleOutcome>) -> Vec<MutationRunIssue> {
525 outcome
526 .map(|outcome| {
527 outcome
528 .issues
529 .iter()
530 .map(|issue| MutationRunIssue {
531 code: issue.code.to_owned(),
532 message: issue.message.clone(),
533 mutant_id: issue.mutant_id.clone(),
534 stderr_tail: issue.stderr_tail.clone(),
535 })
536 .collect()
537 })
538 .unwrap_or_default()
539}
540
541#[cfg(test)]
542mod tests {
543 use super::super::scheduler::{MutantOutcome, ScheduleTimings};
544 use super::*;
545 use fallow_engine::mutation::{
546 FunctionFacts, Mutant, MutantChange, MutantId, MutationPlanCounts, Operator, PlannedFile,
547 PruneCounts, SkipReason, SkippedFile,
548 };
549 use fallow_output::MutationCompletionStatus;
550 use rustc_hash::FxHashMap;
551
552 fn function(name: &str, line: u32) -> FunctionFacts {
553 FunctionFacts {
554 name: Some(name.to_owned()),
555 span: (line * 100, line * 100 + 50),
556 line,
557 end_line: line + 3,
558 cyclomatic: Some(2),
559 in_diff: true,
560 }
561 }
562
563 fn planned(
564 id: &str,
565 rank: Option<u32>,
566 disposition: MutantDisposition,
567 function: Option<FunctionFacts>,
568 ) -> PlannedMutant {
569 PlannedMutant {
570 mutant: Mutant {
571 id: MutantId(id.to_owned()),
572 operator: Operator::ArithmeticOperator,
573 span: (10, 15),
574 line: 2,
575 column: 9,
576 original: "a + b".to_owned(),
577 replacement: "a - b".to_owned(),
578 enclosing_function: None,
579 change: MutantChange::new("+", "-"),
580 },
581 file: "src/a.ts".to_owned(),
582 rank,
583 disposition,
584 function,
585 constant_parameter: false,
586 test_reach: Some(fallow_engine::mutation::MutantTestReach {
587 reach: ExportTestReach::MockedOnly,
588 export_name: Some("add".to_owned()),
589 tests: vec!["test/a.test.ts".to_owned()],
590 export_test_files: Vec::new(),
591 mocked_targets: vec!["src/a.ts".to_owned()],
592 }),
593 }
594 }
595
596 fn plan(mutants: Vec<PlannedMutant>, pending: usize) -> MutationPlan {
597 MutationPlan {
598 files: vec![PlannedFile {
599 path: "src/a.ts".to_owned(),
600 source_sha256: "ab".repeat(32),
601 instrumented_code: "SECRET SOURCE".to_owned(),
602 static_test_files: vec!["test/a.test.ts".to_owned()],
603 }],
604 counts: MutationPlanCounts {
605 total: mutants.len(),
606 pending,
607 pruned: PruneCounts::default(),
608 ..MutationPlanCounts::default()
609 },
610 mutants,
611 test_files: vec!["test/a.test.ts".to_owned()],
612 reach_files: Vec::new(),
613 test_file_reach: BTreeMap::new(),
614 support_files: Vec::new(),
615 no_test_files: false,
616 framework_config_checked: false,
617 skipped_files: Vec::new(),
618 unmatched_paths: Vec::new(),
619 skipped_tests: Vec::new(),
620 }
621 }
622
623 fn outcome(results: &[(&str, MutantStatus)]) -> ScheduleOutcome {
624 ScheduleOutcome {
625 test_files: FxHashMap::default(),
626 duplicate_test_ids: Vec::new(),
627 ready: None,
628 results: results
629 .iter()
630 .map(|(id, status)| {
631 (
632 (*id).to_owned(),
633 MutantOutcome {
634 status: *status,
635 killing_tests: Vec::new(),
636 kill_matrix_complete: false,
637 killed_by: (*status == MutantStatus::Killed)
638 .then(|| "test/a.test.ts::t1".to_owned()),
639 covering_tests: vec!["test/a.test.ts::t1".to_owned()],
640 static_mutant: false,
641 duration_ms: Some(4),
642 retried: matches!(
643 *status,
644 MutantStatus::Survived | MutantStatus::Timeout
645 ),
646 attempts: Vec::new(),
647 cached: false,
648 resumed: false,
649 },
650 )
651 })
652 .collect::<FxHashMap<_, _>>(),
653 baseline_failures: Vec::new(),
654 unloaded_paths: Vec::new(),
655 undiscovered_test_files: Vec::new(),
656 issues: Vec::new(),
657 unretried: Vec::new(),
658 timings: ScheduleTimings::default(),
659 workers: 1,
660 cache_keys: FxHashMap::default(),
661 promoted: Vec::new(),
662 targets: Vec::new(),
663 }
664 }
665
666 #[test]
667 fn a_pending_mutant_that_the_dry_run_never_hit_is_no_coverage() {
668 let plan = plan(
669 vec![
670 planned("m1", Some(1), MutantDisposition::Planned, None),
671 planned("m2", Some(2), MutantDisposition::Pending, None),
672 planned("m3", Some(3), MutantDisposition::Pending, None),
673 ],
674 2,
675 );
676 let mut outcome = outcome(&[
677 ("m1", MutantStatus::Killed),
678 ("m3", MutantStatus::NoCoverage),
679 ]);
680 if let Some(result) = outcome.results.get_mut("m3") {
681 result.covering_tests.clear();
682 }
683 let results = mutant_results(&plan, Some(&outcome));
684 let statuses: Vec<MutantStatus> = results.iter().map(|result| result.status).collect();
685 assert_eq!(
686 statuses,
687 vec![
688 MutantStatus::Killed,
689 MutantStatus::Pending,
690 MutantStatus::NoCoverage,
691 ]
692 );
693 let summary = fallow_output::MutationSummary::from_results(&results);
694 assert_eq!(summary.coverage, Some(2.0 / 3.0));
695 }
696
697 #[test]
698 fn a_mutant_that_no_target_covers_is_pruned_and_leaves_score_and_coverage() {
699 let plan = plan(
700 vec![
701 planned("m1", Some(1), MutantDisposition::Planned, None),
702 planned("m2", Some(2), MutantDisposition::Planned, None),
703 ],
704 2,
705 );
706 let outcome = outcome(&[("m1", MutantStatus::Killed), ("m2", MutantStatus::Pruned)]);
707 let results = mutant_results(&plan, Some(&outcome));
708 assert_eq!(results[0].prune_reason, None);
709 assert_eq!(results[1].status, MutantStatus::Pruned);
710 assert_eq!(results[1].prune_reason.as_deref(), Some(NO_TARGET_COVERAGE));
711 let summary = fallow_output::MutationSummary::from_results(&results);
712 assert_eq!(summary.score, Some(1.0));
713 assert_eq!(summary.coverage, Some(1.0));
714 }
715
716 #[test]
717 fn a_promoted_pending_mutant_reports_its_run_and_the_limit_cuts_nothing() {
718 let plan = plan(
719 vec![
720 planned("m1", Some(1), MutantDisposition::Planned, None),
721 planned("m2", Some(2), MutantDisposition::Pending, None),
722 planned("m3", Some(3), MutantDisposition::Pending, None),
723 ],
724 2,
725 );
726 let reasons = |m2: MutantStatus| {
727 let mut outcome = outcome(&[
728 ("m1", MutantStatus::NoCoverage),
729 ("m2", m2),
730 ("m3", MutantStatus::NoCoverage),
731 ]);
732 outcome.promoted = vec!["m2".to_owned()];
733 let results = mutant_results(&plan, Some(&outcome));
734 let statuses: Vec<MutantStatus> = results.iter().map(|result| result.status).collect();
735 assert_eq!(
736 statuses,
737 vec![MutantStatus::NoCoverage, m2, MutantStatus::NoCoverage]
738 );
739 completion(&CompletionFacts {
740 plan: &plan,
741 results: &results,
742 baseline_failures: &[],
743 worktree_changed: false,
744 worktree_unchecked: false,
745 unretried: false,
746 unloaded_paths: &[],
747 undiscovered_test_files: &[],
748 typecheck_failed: false,
749 promoted: &outcome.promoted,
750 })
751 .reasons
752 };
753 assert_eq!(
754 reasons(MutantStatus::Killed),
755 Vec::<MutationIncompleteReason>::new(),
756 "each covered mutant ran, so the limit cut nothing"
757 );
758 assert_eq!(
759 reasons(MutantStatus::Pending),
760 vec![MutationIncompleteReason::TimeBudget],
761 "a promoted mutant that did not run before the deadline is a time budget miss"
762 );
763 }
764
765 #[test]
766 fn only_a_no_coverage_mutant_carries_its_test_reach() {
767 let plan = plan(
768 vec![
769 planned("m1", Some(1), MutantDisposition::Planned, None),
770 planned("m2", Some(2), MutantDisposition::Pending, None),
771 planned("m3", None, MutantDisposition::NoCoverage, None),
772 planned("m4", Some(3), MutantDisposition::Pending, None),
773 ],
774 2,
775 );
776 let mut outcome = outcome(&[
777 ("m1", MutantStatus::Killed),
778 ("m2", MutantStatus::NoCoverage),
779 ]);
780 if let Some(result) = outcome.results.get_mut("m2") {
781 result.covering_tests.clear();
782 }
783 let reach = |results: &[MutantResult]| -> Vec<(MutantStatus, Option<TestReachClass>)> {
784 results
785 .iter()
786 .map(|result| {
787 (
788 result.status,
789 result.test_reach.as_ref().map(|reach| reach.reach),
790 )
791 })
792 .collect()
793 };
794 let results = mutant_results(&plan, Some(&outcome));
795 let mocked = Some(TestReachClass::MockedOnly);
796 assert_eq!(
797 reach(&results),
798 vec![
799 (MutantStatus::Killed, None),
800 (MutantStatus::NoCoverage, mocked),
801 (MutantStatus::NoCoverage, mocked),
802 (MutantStatus::Pending, None),
803 ]
804 );
805 let entry = results[2].test_reach.as_ref().expect("a test reach");
806 assert_eq!(entry.export_name.as_deref(), Some("add"));
807 assert_eq!(entry.mocked_targets, vec!["src/a.ts"]);
808 let value = serde_json::to_value(&results[2]).expect("serializes");
809 assert_eq!(value["test_reach"]["reach"], "mocked-only");
810 assert!(serde_json::to_value(&results[0]).expect("serializes")["test_reach"].is_null());
811
812 let entries = plan_mutants(&plan);
813 let plan_reach: Vec<Option<TestReachClass>> = entries
814 .iter()
815 .map(|entry| entry.test_reach.as_ref().map(|reach| reach.reach))
816 .collect();
817 assert_eq!(plan_reach, vec![None, None, mocked, None]);
818 }
819
820 #[test]
821 fn plan_dispositions_and_schedule_outcomes_merge_into_one_status_each() {
822 let plan = plan(
823 vec![
824 planned(
825 "m1",
826 Some(1),
827 MutantDisposition::Planned,
828 Some(function("add", 1)),
829 ),
830 planned(
831 "m2",
832 Some(2),
833 MutantDisposition::Planned,
834 Some(function("add", 1)),
835 ),
836 planned("m3", Some(3), MutantDisposition::Planned, None),
837 planned("m4", Some(4), MutantDisposition::Pending, None),
838 planned(
839 "m5",
840 None,
841 MutantDisposition::NoCoverage,
842 Some(function("sub", 9)),
843 ),
844 planned(
845 "m6",
846 None,
847 MutantDisposition::Pruned(PruneReason::SideEffectSink),
848 Some(function("sub", 9)),
849 ),
850 ],
851 1,
852 );
853 let outcome = outcome(&[("m1", MutantStatus::Killed), ("m2", MutantStatus::Survived)]);
854 let results = mutant_results(&plan, Some(&outcome));
855 let statuses: Vec<MutantStatus> = results.iter().map(|result| result.status).collect();
856 assert_eq!(
857 statuses,
858 vec![
859 MutantStatus::Killed,
860 MutantStatus::Survived,
861 MutantStatus::Pending,
862 MutantStatus::Pending,
863 MutantStatus::NoCoverage,
864 MutantStatus::Pruned,
865 ]
866 );
867 assert_eq!(results[0].killed_by.as_deref(), Some("test/a.test.ts::t1"));
868 assert_eq!(results[0].location.column, 10, "the column is 1-based");
869 assert_eq!(results[5].prune_reason.as_deref(), Some("side-effect-sink"));
870 assert_eq!(
871 results
872 .iter()
873 .map(|result| result.retried)
874 .collect::<Vec<_>>(),
875 vec![false, true, false, false, false, false],
876 "only the retried survivor carries the flag"
877 );
878
879 let summary = fallow_output::MutationSummary::from_results(&results);
880 assert_eq!(summary.counts.total, 6);
881 assert_eq!(
882 summary.score,
883 Some(0.5),
884 "killed / (killed + survived); no_coverage stays out"
885 );
886 assert_eq!(
887 summary.coverage,
888 Some(0.8),
889 "covered / (covered + no_coverage); the pending mutants count as covered"
890 );
891
892 let completion = completion(&CompletionFacts {
893 plan: &plan,
894 results: &results,
895 baseline_failures: &[],
896 worktree_changed: false,
897 worktree_unchecked: false,
898 unretried: false,
899 unloaded_paths: &[],
900 undiscovered_test_files: &[],
901 typecheck_failed: false,
902 promoted: &[],
903 });
904 assert_eq!(
905 completion.reasons,
906 vec![
907 MutationIncompleteReason::MutantLimit,
908 MutationIncompleteReason::TimeBudget
909 ],
910 "m3 is planned with no outcome, m4 is after the limit"
911 );
912 }
913
914 #[test]
915 fn skipped_tests_make_one_warning_with_file_line_and_name_and_no_completion_change() {
916 use fallow_engine::mutation::{SkipKind, SkippedTest};
917 let skipped = |line, kind, name: Option<&str>| SkippedTest {
918 file: "src/a.test.ts".to_owned(),
919 line,
920 kind,
921 name: name.map(str::to_owned),
922 };
923 let mut plan = plan(Vec::new(), 0);
924 assert!(skipped_tests_issue(&plan).is_none());
925 plan.skipped_tests = vec![skipped(5, SkipKind::Skip, Some("adds negatives"))];
926 let issue = skipped_tests_issue(&plan).expect("one warning");
927 assert_eq!(issue.code, "skipped-tests");
928 assert_eq!(
929 issue.message,
930 "1 test is skipped or todo: src/a.test.ts:5 (adds negatives). A skipped test checks nothing, so it cannot kill a mutant. Run each test or remove it."
931 );
932 plan.skipped_tests = (1..=12)
933 .map(|line| skipped(line, SkipKind::Todo, None))
934 .collect();
935 let issue = skipped_tests_issue(&plan).expect("one warning");
936 assert!(
937 issue
938 .message
939 .starts_with("12 tests are skipped or todo: src/a.test.ts:1, "),
940 "{}",
941 issue.message
942 );
943 assert!(issue.message.contains(" and 2 more. "), "{}", issue.message);
944 }
945
946 #[test]
947 fn a_sampled_out_mutant_is_pending_with_a_reason_and_makes_the_run_partial() {
948 let mut plan = plan(
949 vec![
950 planned("m1", Some(1), MutantDisposition::Planned, None),
951 planned("m2", None, MutantDisposition::SampledOut, None),
952 ],
953 0,
954 );
955 plan.counts.sampled_out = 1;
956 let outcome = outcome(&[("m1", MutantStatus::Killed)]);
957 let results = mutant_results(&plan, Some(&outcome));
958 assert_eq!(results[1].status, MutantStatus::Pending);
959 assert_eq!(results[1].pending_reason.as_deref(), Some("sampled-out"));
960 assert_eq!(results[0].pending_reason, None);
961 let summary = fallow_output::MutationSummary::from_results(&results);
962 assert_eq!(summary.counts.pending, 1);
963 assert_eq!(summary.sampled_out, 1);
964 let counts = plan_counts(&plan);
965 assert_eq!((counts.pending, counts.sampled_out), (1, 1));
966 let entries = plan_mutants(&plan);
967 assert_eq!(entries[1].disposition, MutationPlanDisposition::Pending);
968 assert_eq!(entries[1].pending_reason.as_deref(), Some("sampled-out"));
969 let completion = completion(&CompletionFacts {
970 plan: &plan,
971 results: &results,
972 baseline_failures: &[],
973 worktree_changed: false,
974 worktree_unchecked: false,
975 unretried: false,
976 unloaded_paths: &[],
977 undiscovered_test_files: &[],
978 typecheck_failed: false,
979 promoted: &[],
980 });
981 assert_eq!(
982 completion.reasons,
983 vec![MutationIncompleteReason::SampledOut]
984 );
985 }
986
987 #[test]
988 fn a_sampled_out_mutant_that_no_test_covers_is_no_coverage_without_a_reason() {
989 let plan = plan(
990 vec![planned("m1", None, MutantDisposition::SampledOut, None)],
991 0,
992 );
993 let outcome = outcome(&[("m1", MutantStatus::NoCoverage)]);
994 let results = mutant_results(&plan, Some(&outcome));
995 assert_eq!(results[0].status, MutantStatus::NoCoverage);
996 assert_eq!(results[0].pending_reason, None);
997 }
998
999 #[test]
1000 fn functions_roll_up_by_file_and_span_with_their_survivors() {
1001 let plan = plan(
1002 vec![
1003 planned(
1004 "m1",
1005 Some(1),
1006 MutantDisposition::Planned,
1007 Some(function("add", 1)),
1008 ),
1009 planned(
1010 "m2",
1011 Some(2),
1012 MutantDisposition::Planned,
1013 Some(function("add", 1)),
1014 ),
1015 planned("m3", Some(3), MutantDisposition::Planned, None),
1016 planned(
1017 "m4",
1018 Some(4),
1019 MutantDisposition::Planned,
1020 Some(function("sub", 9)),
1021 ),
1022 ],
1023 0,
1024 );
1025 let outcome = outcome(&[
1026 ("m1", MutantStatus::Killed),
1027 ("m2", MutantStatus::Survived),
1028 ("m3", MutantStatus::Timeout),
1029 ("m4", MutantStatus::Survived),
1030 ]);
1031 let results = mutant_results(&plan, Some(&outcome));
1032 let functions = function_results(&plan, &results);
1033 type Shape<'a> = (
1034 Option<&'a str>,
1035 Option<u32>,
1036 usize,
1037 Option<f64>,
1038 Vec<&'a str>,
1039 );
1040 let shape: Vec<Shape<'_>> = functions
1041 .iter()
1042 .map(|function| {
1043 (
1044 function.name.as_deref(),
1045 function.line,
1046 function.counts.total,
1047 function.score,
1048 function.survived.iter().map(String::as_str).collect(),
1049 )
1050 })
1051 .collect();
1052 assert_eq!(
1053 shape,
1054 vec![
1055 (None, None, 1, Some(1.0), vec![]),
1056 (Some("add"), Some(1), 2, Some(0.5), vec!["m2"]),
1057 (Some("sub"), Some(9), 1, Some(0.0), vec!["m4"]),
1058 ]
1059 );
1060 assert!(functions[1].in_diff);
1061 assert_eq!(functions[1].end_line, Some(4));
1062 assert_eq!(
1063 completion(&CompletionFacts {
1064 plan: &plan,
1065 results: &results,
1066 baseline_failures: &[],
1067 worktree_changed: false,
1068 worktree_unchecked: false,
1069 unretried: false,
1070 unloaded_paths: &[],
1071 undiscovered_test_files: &[],
1072 typecheck_failed: false,
1073 promoted: &[],
1074 })
1075 .reasons,
1076 Vec::<MutationIncompleteReason>::new()
1077 );
1078 }
1079
1080 #[test]
1081 fn runtime_errors_skipped_files_baseline_failures_and_worktree_changes_make_a_run_partial() {
1082 let mut plan = plan(
1083 vec![planned("m1", Some(1), MutantDisposition::Planned, None)],
1084 0,
1085 );
1086 plan.skipped_files.push(SkippedFile {
1087 path: "src/big.ts".to_owned(),
1088 reason: SkipReason::NotAnalyzed,
1089 });
1090 let outcome = outcome(&[("m1", MutantStatus::RuntimeError)]);
1091 let results = mutant_results(&plan, Some(&outcome));
1092 let failure = MutationBaselineFailure {
1093 file: Some("test/a.test.ts".to_owned()),
1094 test_id: None,
1095 message: Some("boom".to_owned()),
1096 mutant_ids: Vec::new(),
1097 };
1098 let completion = completion(&CompletionFacts {
1099 plan: &plan,
1100 results: &results,
1101 baseline_failures: &[failure],
1102 worktree_changed: true,
1103 worktree_unchecked: false,
1104 unretried: false,
1105 unloaded_paths: &[],
1106 undiscovered_test_files: &[],
1107 typecheck_failed: false,
1108 promoted: &[],
1109 });
1110 assert_eq!(
1111 completion.reasons,
1112 vec![
1113 MutationIncompleteReason::RuntimeError,
1114 MutationIncompleteReason::SkippedFiles,
1115 MutationIncompleteReason::BaselineFailure,
1116 MutationIncompleteReason::WorktreeChanged,
1117 ]
1118 );
1119 assert_eq!(skipped_files(&plan)[0].reason, "not-analyzed");
1120 }
1121
1122 #[test]
1123 fn an_unretried_mutant_and_an_unchecked_worktree_make_a_run_partial() {
1124 let plan = plan(
1125 vec![planned("m1", Some(1), MutantDisposition::Planned, None)],
1126 0,
1127 );
1128 let outcome = outcome(&[("m1", MutantStatus::Survived)]);
1129 let results = mutant_results(&plan, Some(&outcome));
1130 let completion = completion(&CompletionFacts {
1131 plan: &plan,
1132 results: &results,
1133 baseline_failures: &[],
1134 worktree_changed: false,
1135 worktree_unchecked: true,
1136 unretried: true,
1137 unloaded_paths: &[],
1138 undiscovered_test_files: &[],
1139 typecheck_failed: false,
1140 promoted: &[],
1141 });
1142 assert_eq!(
1143 completion.reasons,
1144 vec![
1145 MutationIncompleteReason::TimeBudget,
1146 MutationIncompleteReason::WorktreeUnchecked,
1147 ]
1148 );
1149 }
1150
1151 #[test]
1152 fn an_unloaded_file_that_a_dry_run_test_reaches_makes_a_run_partial() {
1153 let mut plan = plan(
1154 vec![planned("m1", Some(1), MutantDisposition::Planned, None)],
1155 0,
1156 );
1157 plan.files.push(PlannedFile {
1158 path: "src/b.ts".to_owned(),
1159 source_sha256: "cd".repeat(32),
1160 instrumented_code: String::new(),
1161 static_test_files: Vec::new(),
1162 });
1163 let results = mutant_results(&plan, Some(&outcome(&[("m1", MutantStatus::NoCoverage)])));
1164 let reasons = |unloaded: &[String]| {
1165 completion(&CompletionFacts {
1166 plan: &plan,
1167 results: &results,
1168 baseline_failures: &[],
1169 worktree_changed: false,
1170 worktree_unchecked: false,
1171 unretried: false,
1172 unloaded_paths: unloaded,
1173 undiscovered_test_files: &[],
1174 typecheck_failed: false,
1175 promoted: &[],
1176 })
1177 .reasons
1178 };
1179 assert_eq!(
1180 reasons(&["src/a.ts".to_owned()]),
1181 vec![MutationIncompleteReason::UnloadedFiles],
1182 "a static test reaches src/a.ts, so the runner had to load it"
1183 );
1184 assert_eq!(
1185 reasons(&["src/b.ts".to_owned()]),
1186 Vec::new(),
1187 "no static test reaches src/b.ts, so it is a fact, not a fault"
1188 );
1189 }
1190
1191 #[test]
1192 fn a_static_test_file_that_the_runner_does_not_list_makes_a_run_partial() {
1193 let plan = plan(
1194 vec![planned("m1", Some(1), MutantDisposition::Planned, None)],
1195 0,
1196 );
1197 let results = mutant_results(&plan, Some(&outcome(&[("m1", MutantStatus::Survived)])));
1198 let completion_with = |undiscovered: &[String]| {
1199 completion(&CompletionFacts {
1200 plan: &plan,
1201 results: &results,
1202 baseline_failures: &[],
1203 worktree_changed: false,
1204 worktree_unchecked: false,
1205 unretried: false,
1206 unloaded_paths: &[],
1207 undiscovered_test_files: undiscovered,
1208 typecheck_failed: false,
1209 promoted: &[],
1210 })
1211 };
1212 let partial = completion_with(&["test/integration.test.ts".to_owned()]);
1213 assert_eq!(partial.status, MutationCompletionStatus::Partial);
1214 assert_eq!(
1215 partial.reasons,
1216 vec![MutationIncompleteReason::TestFilesNotDiscovered],
1217 "a test that never ran can kill the survivor, so the survivor list is not conclusive"
1218 );
1219 assert_eq!(
1220 completion_with(&[]).status,
1221 MutationCompletionStatus::Complete
1222 );
1223 }
1224
1225 #[test]
1226 fn a_static_map_miss_takes_the_schedule_outcome() {
1227 let plan = plan(
1228 vec![
1229 planned("m1", None, MutantDisposition::NoCoverage, None),
1230 planned("m2", None, MutantDisposition::NoCoverage, None),
1231 ],
1232 0,
1233 );
1234 let results = mutant_results(&plan, Some(&outcome(&[("m1", MutantStatus::Killed)])));
1235 assert_eq!(results[0].status, MutantStatus::Killed);
1236 assert_eq!(results[0].killed_by.as_deref(), Some("test/a.test.ts::t1"));
1237 assert_eq!(results[1].status, MutantStatus::NoCoverage);
1238 }
1239
1240 #[test]
1241 fn a_cached_result_is_marked_in_the_report_and_counts_like_a_run() {
1242 let plan = plan(
1243 vec![
1244 planned("m1", Some(1), MutantDisposition::Planned, None),
1245 planned("m2", Some(2), MutantDisposition::Planned, None),
1246 ],
1247 0,
1248 );
1249 let mut outcome = outcome(&[("m1", MutantStatus::Killed), ("m2", MutantStatus::Survived)]);
1250 if let Some(result) = outcome.results.get_mut("m1") {
1251 result.cached = true;
1252 }
1253 let results = mutant_results(&plan, Some(&outcome));
1254 assert!(results[0].cached);
1255 assert!(!results[1].cached);
1256 assert_eq!(
1257 fallow_output::MutationSummary::from_results(&results).score,
1258 Some(0.5)
1259 );
1260 }
1261
1262 #[test]
1263 fn plan_output_parts_carry_no_source_text() {
1264 let plan = plan(
1265 vec![planned(
1266 "m1",
1267 Some(1),
1268 MutantDisposition::Pruned(PruneReason::FrameworkConfig),
1269 None,
1270 )],
1271 0,
1272 );
1273 let files = serde_json::to_string(&plan_files(&plan)).expect("json");
1274 let mutants = serde_json::to_string(&plan_mutants(&plan)).expect("json");
1275 assert!(
1276 mutants.contains(r#""change":{"from":"+","to":"-"}"#),
1277 "{mutants}"
1278 );
1279 for text in [&files, &mutants] {
1280 assert!(!text.contains("SECRET SOURCE"));
1281 assert!(!text.contains("a + b"));
1282 assert!(!text.contains("a - b"));
1283 }
1284 assert!(mutants.contains(r#""disposition":"pruned""#), "{mutants}");
1285 assert!(
1286 mutants.contains(r#""prune_reason":"framework-config""#),
1287 "{mutants}"
1288 );
1289 assert!(files.contains("test/a.test.ts"), "{files}");
1290 }
1291
1292 #[test]
1293 fn the_build_tool_only_count_is_absent_when_zero() {
1294 let mut plan = plan(
1295 vec![planned(
1296 "m1",
1297 Some(1),
1298 MutantDisposition::Pruned(PruneReason::BuildToolOnly),
1299 None,
1300 )],
1301 0,
1302 );
1303 let mutants = serde_json::to_string(&plan_mutants(&plan)).expect("json");
1304 assert!(
1305 mutants.contains(r#""prune_reason":"build-tool-only""#),
1306 "{mutants}"
1307 );
1308 let without = serde_json::to_string(&plan_counts(&plan)).expect("json");
1309 assert!(!without.contains("pruned_build_tool_only"), "{without}");
1310 plan.counts.pruned.build_tool_only = 1;
1311 let with = serde_json::to_string(&plan_counts(&plan)).expect("json");
1312 assert!(with.contains(r#""pruned_build_tool_only":1"#), "{with}");
1313 }
1314
1315 #[test]
1316 fn results_carry_the_change_without_project_text() {
1317 let mut logical = planned("m1", Some(1), MutantDisposition::Planned, None);
1318 logical.mutant.operator = Operator::LogicalOperator;
1319 logical.mutant.original = "??".to_owned();
1320 logical.mutant.replacement = "&&".to_owned();
1321 logical.mutant.change = MutantChange::new("??", "&&");
1322 let mut string = planned("m2", Some(2), MutantDisposition::Planned, None);
1323 string.mutant.operator = Operator::StringLiteral;
1324 string.mutant.original = "\"SECRET SOURCE\"".to_owned();
1325 string.mutant.replacement = "\"\"".to_owned();
1326 string.mutant.change = MutantChange::new(MutantChange::STRING, "\"\"");
1327 let plan = plan(vec![logical, string], 2);
1328 let value = serde_json::to_value(mutant_results(&plan, None)).expect("json");
1329 assert_eq!(
1330 value[0]["change"],
1331 serde_json::json!({"from": "??", "to": "&&"})
1332 );
1333 assert_eq!(
1334 value[1]["change"],
1335 serde_json::json!({"from": "<string>", "to": "\"\""})
1336 );
1337 assert!(!value.to_string().contains("SECRET SOURCE"), "{value}");
1338 }
1339}