supercov 4.29.14

Coverage, security and code quality for coding agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! `supercov runs <run-id> mutants --format jsonl`: every mutant asked
//! about, one JSON object per line, each as `mutants --json` lists it. A
//! reply holds a page, about 128 mutants under its 64 KB limit, and a large
//! app's run has tens of thousands.
//!
//! `--format markdown`: the mutants the tests leave alive as a table for a
//! pull request's comment, `--diff` the change's, capped at
//! `MARKDOWN_ROWS` with the command that lists the rest. Once a strong pass
//! ran, the mutation score and the verdicts too, and the survivors.
//!
//! `--format stryker`: StrykerJS's `mutation.json` (the mutation testing
//! report schema), and `--format pit`: PIT's `mutations.xml`, for the tools
//! that read those (`mutation_report`).

use std::{io::Write, path::PathBuf, process::ExitCode};

/// Everything one page holds: the export asks for all of it at once.
const ALL: &str = "1000000000";

pub fn command(arguments: &[String]) -> ExitCode {
    let mut passed = Vec::new();
    let mut output = None;
    let mut format = None;
    // Dispatch sends `<run> mutants ... --format ...` here: never nothing.
    let mut index = 0;
    loop {
        match arguments[index].as_str() {
            "--format" => {
                index += 1;
                format = arguments.get(index).cloned();
            }
            "--output" => {
                index += 1;
                output = arguments.get(index).map(PathBuf::from);
            }
            // Pages and the JSON envelope are the export's to choose.
            "--offset" | "--limit" => index += 1,
            "--json" => {}
            other => passed.push(other.to_owned()),
        }
        index += 1;
        if index >= arguments.len() {
            break;
        }
    }
    let format = match format.as_deref() {
        Some(format @ ("jsonl" | "markdown" | "stryker" | "pit")) => format.to_owned(),
        _ => {
            eprintln!("[supercov] mutants --format takes jsonl, markdown, stryker or pit");
            return ExitCode::from(2);
        }
    };
    let markdown = format == "markdown";
    // Dispatch sends `<run> mutants ...` here.
    let run = passed[0].clone();
    let mut mutants_arguments = passed[2..].to_vec();
    mutants_arguments.extend(["--json", "--limit", ALL].map(str::to_owned));
    let (request, _) =
        match super::public_query::coverage_request(run, "mutants", &mutants_arguments, true) {
            Ok(request) => request,
            Err(error) => {
                eprintln!("[supercov] {}", error.error.message);
                return ExitCode::from(2);
            }
        };
    let root = match std::env::current_dir() {
        Ok(root) => root,
        Err(error) => {
            eprintln!("[supercov] could not resolve the current directory: {error}");
            return ExitCode::from(2);
        }
    };
    // The query's data itself, not its reply, which stops at 64 KB.
    let (output_data, _) = match super::execute_coverage_query(&root, &request, None) {
        Ok(output) => output,
        Err(failure) => {
            eprintln!("[supercov] {}", failure.error.message);
            return ExitCode::from(2);
        }
    };
    let data = output_data
        .data
        .mutants()
        .expect("a mutants request is answered with mutants");
    if let Some(note) = &data.note {
        eprintln!("[supercov] {note}");
    }
    let mut lines = String::new();
    if markdown {
        lines = self::markdown(&request, data);
    } else if format == "stryker" {
        lines = stryker(&root, data);
    } else if format == "pit" {
        lines = supercov_engine::mutation_report::pit_xml(data);
    } else {
        for mutant in &data.mutants {
            lines.push_str(&serde_json::to_string(mutant).expect("a mutant is plain data"));
            lines.push('\n');
        }
    }
    let written = match output {
        Some(path) => {
            if let Err(error) = supercov_engine::fault_fs::write(&path, &lines) {
                eprintln!("[supercov] {}: {error}", path.display());
                return ExitCode::from(2);
            }
            if markdown {
                eprintln!("[supercov] wrote the mutants' table to {}", path.display());
            } else if format != "jsonl" {
                eprintln!(
                    "[supercov] wrote {} mutant(s) as a {format} report to {}",
                    data.mutants.len(),
                    path.display()
                );
            } else {
                eprintln!(
                    "[supercov] wrote {} mutant(s) to {}",
                    data.mutants.len(),
                    path.display()
                );
            }
            ExitCode::SUCCESS
        }
        None => printed(&mut std::io::stdout().lock(), &lines),
    };
    if written != ExitCode::SUCCESS {
        return written;
    }
    // As the query: a mutant said to be unkillable that StrykerJS killed.
    if let Some(stryker) = &data.stryker
        && stryker.soundness_violations.total > 0
    {
        eprintln!(
            "[supercov] {} soundness violation(s): mutants not infected or not reached here that StrykerJS killed",
            stryker.soundness_violations.total
        );
        return ExitCode::from(1);
    }
    if let Some(gate) = crate::human_query::gate_failure(data) {
        eprintln!("[supercov] {gate}");
        return ExitCode::from(1);
    }
    ExitCode::SUCCESS
}

/// The most mutants a markdown table lists.
const MARKDOWN_ROWS: usize = 25;

/// Text for a markdown table's cell: one line, its pipes escaped.
fn cell(text: &str) -> String {
    text.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace('|', "\\|")
}

/// Code as a markdown code span, whatever backticks it holds.
fn code(text: &str) -> String {
    let longest = text
        .split(|character| character != '`')
        .map(str::len)
        .max()
        .unwrap_or(0);
    let fence = "`".repeat(longest + 1);
    let padded = if text.starts_with('`') || text.ends_with('`') {
        format!(" {text} ")
    } else {
        text.to_owned()
    };
    cell(&format!("{fence}{padded}{fence}"))
}

/// The mutants as StrykerJS's `mutation.json`, each file with its source as
/// the checkout holds it; a file it cannot read is left out and said so.
fn stryker(
    root: &std::path::Path,
    data: &supercov_engine::mutants_query::CoverageMutantsData,
) -> String {
    let mut sources = std::collections::BTreeMap::new();
    for mutant in &data.mutants {
        if !sources.contains_key(&mutant.file)
            && let Ok(text) = supercov_engine::fault_fs::read_to_string(root.join(&mutant.file))
        {
            sources.insert(mutant.file.clone(), text);
        }
    }
    let (report, missing) = supercov_engine::mutation_report::stryker_report(data, &sources);
    for file in missing {
        eprintln!("[supercov] {file} could not be read: its mutants are left out of the report");
    }
    let mut text = serde_json::to_string_pretty(&report).expect("a report is plain data");
    text.push('\n');
    text
}

/// The mutants the tests leave alive, or those `--status` asked for, as a
/// pull request's comment: one line of counts and a table. Once a strong
/// pass gave verdicts, the line has the mutation score and the verdicts, and
/// the table the survivors with their verdicts.
pub(crate) fn markdown(
    request: &supercov_engine::indexed_query::IndexedQueryRequest,
    data: &supercov_engine::mutants_query::CoverageMutantsData,
) -> String {
    use supercov_engine::coverage_index::MutantStatus;
    use supercov_engine::mutation_report::{self as report, Outcome};
    let summary = &data.summary;
    let strong = data.mutants.iter().any(|mutant| mutant.strong.is_some());
    // `--status survived` and the other verdicts pick by strong verdict.
    let asked_verdicts = &request.mutants.strong_statuses;
    let asked_statuses = !request.mutants.statuses.is_empty() || !asked_verdicts.is_empty();
    let wanted = if asked_statuses {
        request.mutants.statuses.clone()
    } else {
        vec![MutantStatus::NotInfected, MutantStatus::NotReached]
    };
    let mut rows = data
        .mutants
        .iter()
        .filter(|mutant| {
            if !asked_verdicts.is_empty() {
                report::verdict(mutant)
                    .is_some_and(|verdict| asked_verdicts.contains(&verdict.status))
            } else if strong && !asked_statuses {
                report::alive(mutant)
            } else {
                wanted.contains(&mutant.status)
            }
        })
        .collect::<Vec<_>>();
    // What the tests leave alive first, as `--diff` lists them: once a
    // strong pass ran, what survived it first.
    rows.sort_by_key(|mutant| {
        let verdict = match report::outcome(mutant) {
            Outcome::Survived => 0,
            Outcome::NoCoverage => 1,
            _ => 2,
        };
        (
            verdict,
            wanted.iter().position(|status| *status == mutant.status),
        )
    });
    let score = summary
        .weak_score
        .map_or_else(|| "—".to_owned(), |score| format!("{:.1}%", score * 100.0));
    let mut counts = MutantStatus::ALL
        .into_iter()
        .filter(|status| summary.status.of(*status) > 0)
        .map(|status| {
            format!(
                "{} {}",
                summary.status.of(status),
                status.name().replace('-', " ")
            )
        })
        .collect::<Vec<_>>()
        .join(" · ");
    if strong {
        let tally = report::Tally::of(&data.mutants);
        let verdicts = [
            (tally.strong.killed, "killed"),
            (tally.strong.timeout, "timed out"),
            (tally.strong.survived, "survived"),
            (tally.strong.no_coverage, "no coverage"),
            (tally.strong.unviable, "unviable"),
            (tally.strong.error, "error"),
            (tally.strong.not_run, "not run (no driver)"),
            (tally.strong.survived_so_far, "survived so far"),
            (tally.strong.pending, "no strong verdict"),
        ]
        .into_iter()
        .filter(|(count, _)| *count > 0)
        .map(|(count, name)| format!("{count} {name}"))
        .collect::<Vec<_>>()
        .join(" · ");
        // The score with what it is over: a score of a few mutants is not
        // the run's, and no score says why.
        let strong = &tally.strong;
        let basis = strong.killed + strong.timeout + strong.survived + strong.no_coverage;
        let mutation = match tally.mutation_score {
            Some(score) => format!(
                "Mutation score **{:.1}%** (of {basis} of {})",
                score * 100.0,
                plural(tally.mutants, "mutant")
            ),
            None => {
                "No mutation score: no mutant was killed, timed out, survived or left uncovered"
                    .to_owned()
            }
        };
        counts = format!("{counts}\n\n{mutation} · {verdicts}");
    }
    let mut text = String::new();
    match &data.diff {
        Some(diff) => {
            text.push_str("### Mutants on this change\n\n");
            text.push_str(&format!(
                "**{}** on {} of {} changed lines since `{}` (from `{}`): weak score **{score}**{}{counts}\n",
                plural(summary.mutants, "mutant"),
                diff.lines_with_mutants,
                diff.changed_lines,
                diff.base,
                diff.merge_base.chars().take(12).collect::<String>(),
                if counts.is_empty() { "" } else { " · " },
            ));
            text.push_str(&unrun_lines(&diff.unrun_lines));
        }
        None => {
            text.push_str("### Mutants\n\n");
            text.push_str(&format!(
                "**{}**: weak score **{score}**{}{counts}\n",
                plural(summary.mutants, "mutant"),
                if counts.is_empty() { "" } else { " · " },
            ));
        }
    }
    let names = if !asked_verdicts.is_empty() {
        asked_verdicts
            .iter()
            .map(|status| status.replace('-', " "))
            .collect::<Vec<_>>()
            .join(" or ")
    } else if strong && !asked_statuses {
        "left alive by the tests".to_owned()
    } else {
        wanted
            .iter()
            .map(|status| status.name().replace('-', " "))
            .collect::<Vec<_>>()
            .join(" or ")
    };
    // What only changes a log line is set aside, folded: a reader triages
    // the rest first.
    let (logged, rows): (Vec<_>, Vec<_>) = rows.into_iter().partition(|mutant| mutant.log_only);
    // Those a first tier of candidates let live, apart: no verdict yet.
    let so_far = data
        .mutants
        .iter()
        .filter(|mutant| report::outcome(mutant) == Outcome::SurvivedSoFar)
        .collect::<Vec<_>>();
    let weak_status = |mutant: &supercov_engine::mutants_query::MutantEntry| {
        format!(
            "{}{}",
            mutant.status.name().replace('-', " "),
            mutant
                .weak
                .untestable
                .map_or_else(String::new, |kind| format!(" ({} boundary)", kind.name()))
        )
    };
    let place = |mutant: &supercov_engine::mutants_query::MutantEntry| {
        code(&format!(
            "{}:{}:{}",
            mutant.file, mutant.span.start[0], mutant.span.start[1]
        ))
    };
    // How many of the run's tests ran its line: none is code no test runs.
    let ran = |mutant: &supercov_engine::mutants_query::MutantEntry| {
        mutant
            .line_tests
            .map_or_else(|| "—".to_owned(), |tests| tests.to_string())
    };
    let table = |rows: &[&supercov_engine::mutants_query::MutantEntry]| {
        let mut table = String::new();
        if strong {
            table.push_str(
                "\n| Where | Mutant | Weak | Strong | Tests on its line | Why |\n| --- | --- | --- | --- | --- | --- |\n",
            );
            table.extend(rows.iter().take(MARKDOWN_ROWS).map(|mutant| {
                let outcome = report::outcome(mutant);
                format!(
                    "| {} | {} | {} | {} | {} | {} |\n",
                    place(mutant),
                    code(&report::change(mutant)),
                    cell(&weak_status(mutant)),
                    cell(match outcome {
                        Outcome::Pending => "—",
                        other => other.name(),
                    }),
                    ran(mutant),
                    cell(&report::why(mutant, true)),
                )
            }));
        } else {
            table.push_str(
                "\n| Where | Mutant | Status | Tests on its line | Why |\n| --- | --- | --- | --- | --- |\n",
            );
            table.extend(rows.iter().take(MARKDOWN_ROWS).map(|mutant| {
                format!(
                    "| {} | {} | {} | {} | {} |\n",
                    place(mutant),
                    code(&report::change(mutant)),
                    cell(&weak_status(mutant)),
                    ran(mutant),
                    cell(&mutant.weak.reason),
                )
            }));
        }
        table
    };
    // A folded table, with how many it leaves out.
    let folded = |summary: String, rows: &[&supercov_engine::mutants_query::MutantEntry]| {
        let mut folded = format!("\n<details><summary>{summary}</summary>\n{}", table(rows));
        if rows.len() > MARKDOWN_ROWS {
            folded.push_str(&format!("\n_…and {} more_\n", rows.len() - MARKDOWN_ROWS));
        }
        folded.push_str("\n</details>\n");
        folded
    };
    if rows.is_empty() {
        // Nothing the tests leave alive, in the words a comment's reader uses.
        let said = if asked_statuses || strong {
            format!("No mutant is {names}.")
        } else {
            "No mutant is left alive: none is not infected or not reached.".to_owned()
        };
        text.push_str(&format!(
            "\n{said}{}\n",
            if logged.is_empty() {
                ""
            } else {
                " Those below change only what is logged."
            }
        ));
    } else {
        text.push_str(&table(&rows));
        if rows.len() > MARKDOWN_ROWS {
            let mut asked = request.clone();
            if !strong {
                asked.mutants.statuses = wanted.clone();
            }
            text.push_str(&format!(
                "\n_…and {} more: `{}`_\n",
                rows.len() - MARKDOWN_ROWS,
                crate::human_query::mutants_command(&asked, data, data.file.as_deref())
            ));
        }
    }
    if !logged.is_empty() {
        text.push_str(&folded(
            format!(
                "{} more that {} only what is logged: wholly in a logging call's arguments, or in what makes a logger",
                logged.len(),
                if logged.len() == 1 { "changes" } else { "change" },
            ),
            &logged,
        ));
    }
    if !so_far.is_empty() {
        text.push_str(&folded(
            format!(
                "{} survived so far: each lived through a first tier of the tests that ran it, and the rest have not run with it yet; not survivors, and not in the score",
                plural(so_far.len(), "mutant"),
            ),
            &so_far,
        ));
    }
    text
}

/// The changed lines of code no test of the run ran, file by file, as runs
/// of lines; nothing where every one ran.
fn unrun_lines(unrun: &std::collections::BTreeMap<String, Vec<u32>>) -> String {
    if unrun.is_empty() {
        return String::new();
    }
    let total = unrun.values().map(Vec::len).sum::<usize>();
    let mut text = format!(
        "\n**{} no test ran**, which no mutant on them can tell apart:\n\n",
        plural(total, "changed line")
    );
    unrun.iter().take(MARKDOWN_ROWS).for_each(|(file, lines)| {
        // Each run of consecutive lines as `a–b`.
        let runs = lines
            .iter()
            .fold(Vec::<(u32, u32)>::new(), |mut runs, line| {
                match runs.last_mut() {
                    Some((_, end)) if *end + 1 == *line => *end = *line,
                    _ => runs.push((*line, *line)),
                }
                runs
            })
            .into_iter()
            .map(|(start, end)| {
                if start == end {
                    start.to_string()
                } else {
                    format!("{start}–{end}")
                }
            })
            .collect::<Vec<_>>()
            .join(", ");
        text.push_str(&format!("- {}: {runs}\n", code(file)));
    });
    if unrun.len() > MARKDOWN_ROWS {
        text.push_str(&format!(
            "- _…and {}_\n",
            plural(unrun.len() - MARKDOWN_ROWS, "more file")
        ));
    }
    text
}

fn plural(count: usize, noun: &str) -> String {
    format!("{count} {noun}{}", if count == 1 { "" } else { "s" })
}

/// The mutants written to standard output, `out`.
fn printed(out: &mut dyn Write, lines: &str) -> ExitCode {
    if let Err(error) = out.write_all(lines.as_bytes()).and_then(|()| out.flush()) {
        // A reader that stopped early, as `head` does, needs no word.
        if error.kind() != std::io::ErrorKind::BrokenPipe {
            eprintln!("[supercov] could not write the mutants to standard output: {error}");
        }
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A standard output whose every write fails with this kind of error.
    struct Failing(std::io::ErrorKind);

    impl Write for Failing {
        fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
            Err(self.0.into())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    fn request() -> supercov_engine::indexed_query::IndexedQueryRequest {
        supercov_engine::indexed_query::IndexedQueryRequest {
            run_id: "run_1".into(),
            filter: "all".into(),
            command: "coverage.mutants".into(),
            metric: supercov_engine::coverage_query::MinimizeMetric::All,
            kind: None,
            runner: None,
            file: None,
            line: None,
            more_lines: Vec::new(),
            selector: None,
            sort: None,
            valid: None,
            test_exit_code: None,
            stale: None,
            stale_reasons: None,
            offset: 0,
            limit: 20,
            target: None,
            max_states: None,
            group: None,
            depth: None,
            gained_only: false,
            tags: Vec::new(),
            titles: Vec::new(),
            test_files: Vec::new(),
            mutants: Default::default(),
        }
    }

    fn data(
        mutants: Vec<supercov_engine::mutants_query::MutantEntry>,
    ) -> supercov_engine::mutants_query::CoverageMutantsData {
        use supercov_engine::coverage_index::MutantCounts;
        use supercov_engine::mutants_query::{CoverageMutantsData, MutantLevels, MutantsSummary};
        let mut counts = MutantCounts::default();
        mutants.iter().for_each(|mutant| counts.add(mutant.status));
        CoverageMutantsData {
            run: "run_1".into(),
            mutant_set: Some("stryker-js@10.1.1".into()),
            levels: MutantLevels {
                weak: true,
                strong: true,
            },
            file: None,
            line: None,
            summary: MutantsSummary::of(counts, 0),
            note: None,
            mutants,
            stryker: None,
            files: Vec::new(),
            diff: None,
            fail_on: None,
        }
    }

    fn mutant(
        line: u32,
        status: supercov_engine::coverage_index::MutantStatus,
        strong: Option<serde_json::Value>,
    ) -> supercov_engine::mutants_query::MutantEntry {
        use supercov_engine::mutants_query::{MutantEntry, MutantSpan, WeakResult};
        MutantEntry {
            log_only: false,
            line_tests: None,
            id: format!("src/a.py:{line}:3-{line}:9:ArithmeticOperator:-"),
            file: "src/a.py".into(),
            span: MutantSpan {
                start: [line, 3],
                end: [line, 9],
            },
            mutator: "ArithmeticOperator".into(),
            original: "a + b".into(),
            replacement: "a - b".into(),
            changed: None,
            status,
            weak: WeakResult {
                reach: "reached",
                infection: Some(status.name()),
                code: "c".into(),
                reason: "weak reason".into(),
                proxy: false,
                rule: None,
                untestable: None,
                untestable_reason: None,
            },
            strong,
            stryker: None,
        }
    }

    /// Once a strong pass ran, the table is of the survivors, with both
    /// levels, the mutation score and each verdict counted.
    #[test]
    fn a_strong_pass_s_survivors_are_the_table_with_their_verdicts() {
        use serde_json::json;
        use supercov_engine::coverage_index::MutantStatus::*;
        let mut mutants = (1..=28)
            .map(|line| {
                mutant(
                    line,
                    Infected,
                    Some(json!({"status": "survived", "tests": 2})),
                )
            })
            .collect::<Vec<_>>();
        mutants.push(mutant(
            29,
            NotReached,
            Some(json!({"status": "no-coverage"})),
        ));
        mutants.push(mutant(30, NotInfected, None));
        mutants.push(mutant(
            31,
            Infected,
            Some(json!({"status": "killed", "killedBy": "t"})),
        ));
        mutants.push(mutant(32, Infected, Some(json!({"status": "timeout"}))));
        mutants.push(mutant(33, Infected, Some(json!({"status": "unviable"}))));
        mutants.push(mutant(34, Infected, Some(json!({"status": "error"}))));
        mutants.push(mutant(
            35,
            Infected,
            Some(json!({"status": "error", "reason": "no strong mutation driver for python yet"})),
        ));
        mutants.push(mutant(36, Infected, None));
        let text = markdown(&request(), &data(mutants.clone()));
        assert!(
            text.contains("\n\nMutation score **6.5%** (of 31 of 36 mutants) · 1 killed · 1 timed out · 28 survived · 1 no coverage · 1 unviable · 1 error · 1 not run (no driver) · 2 no strong verdict\n"),
            "{text}"
        );
        assert!(
            text.contains("| Where | Mutant | Weak | Strong | Tests on its line | Why |"),
            "{text}"
        );
        assert!(
            text.contains("| `src/a.py:1:3` | `a + b → a - b` | infected | survived | — | every test that reached it passed with it in place (2 tests ran) |"),
            "{text}"
        );
        assert_eq!(text.matches("| `src/a.py:").count(), 25, "{text}");
        // The rest of the survivors: two survived, the uncovered and the not infected.
        assert!(
            text.contains("_…and 5 more: `supercov runs 'run_1' mutants`_"),
            "{text}"
        );
        // Asked by weak status: those, with their verdicts.
        let mut asked = request();
        asked.mutants.statuses = vec![NotInfected];
        let text = markdown(&asked, &data(mutants.clone()));
        assert!(
            text.contains(
                "| `src/a.py:30:3` | `a + b → a - b` | not infected | — | — | weak reason |"
            ),
            "{text}"
        );
        assert_eq!(text.matches("| `src/a.py:").count(), 1, "{text}");
        // Asked by verdict: those alone, and a verdict none has said so.
        let mut survived = request();
        survived.mutants.strong_statuses = vec!["survived".into()];
        let text = markdown(&survived, &data(mutants.clone()));
        assert_eq!(text.matches(" | survived | ").count(), 25, "{text}");
        assert!(!text.contains("| no-coverage |"), "{text}");
        let mut none = request();
        none.mutants.strong_statuses = vec!["no-coverage".into(), "killed".into()];
        let text = markdown(
            &none,
            &data(vec![mutant(
                1,
                Infected,
                Some(json!({"status": "survived"})),
            )]),
        );
        assert!(
            text.ends_with("\nNo mutant is no coverage or killed.\n"),
            "{text}"
        );
        // Nothing left alive.
        let text = markdown(
            &request(),
            &data(vec![mutant(1, Infected, Some(json!({"status": "killed"})))]),
        );
        assert!(
            text.contains("Mutation score **100.0%** (of 1 of 1 mutant) · 1 killed\n"),
            "{text}"
        );
        assert!(
            text.ends_with("\nNo mutant is left alive by the tests.\n"),
            "{text}"
        );
        // Verdicts and none counted: no score.
        let text = markdown(
            &request(),
            &data(vec![mutant(1, Infected, Some(json!({"status": "error"})))]),
        );
        assert!(text.contains("No mutation score: no mutant was killed, timed out, survived or left uncovered · 1 error\n"), "{text}");
    }

    /// What a pull request's comment needs: the survivors with how many
    /// tests ran each one's line, those that change only a log line folded
    /// apart, those a first tier let live apart, and the changed lines no
    /// test ran.
    #[test]
    fn a_comment_folds_log_lines_and_open_mutants_and_names_unrun_lines() {
        use serde_json::json;
        use supercov_engine::coverage_index::MutantStatus::*;
        let survivor = |line: u32| {
            mutant(
                line,
                Infected,
                Some(json!({"status": "survived", "tests": 3})),
            )
        };
        let mut ran = survivor(1);
        ran.line_tests = Some(7);
        let mut mutants = vec![ran];
        for line in 2..=28 {
            let mut logged = survivor(line);
            logged.log_only = true;
            mutants.push(logged);
        }
        mutants.push(mutant(
            40,
            Infected,
            Some(json!({"status": "survived-so-far", "tests": 32})),
        ));
        let mut changed = data(mutants);
        let unrun = (0..27)
            .map(|file| (format!("src/f{file:02}.ts"), vec![3, 4, 5, 9]))
            .collect();
        changed.diff = Some(supercov_engine::mutants_query::DiffSummary {
            base: "origin/main".into(),
            merge_base: "0123456789abcdef".into(),
            commit: None,
            changed_lines: 120,
            lines_with_mutants: 29,
            unrun_lines: unrun,
        });
        let text = markdown(&request(), &changed);
        for expected in [
            " · 28 survived · 1 survived so far\n",
            "\n**108 changed lines no test ran**, which no mutant on them can tell apart:\n\n- `src/f00.ts`: 3–5, 9\n",
            "- `src/f24.ts`: 3–5, 9\n- _…and 2 more files_\n",
            "| `src/a.py:1:3` | `a + b → a - b` | infected | survived | 7 | every test that reached it passed with it in place (3 tests ran) |\n",
            "\n<details><summary>27 more that change only what is logged: wholly in a logging call's arguments, or in what makes a logger</summary>\n",
            "\n_…and 2 more_\n\n</details>\n",
            "<details><summary>1 mutant survived so far: each lived through a first tier of the tests that ran it, and the rest have not run with it yet; not survivors, and not in the score</summary>\n",
            "| `src/a.py:40:3` | `a + b → a - b` | infected | survived-so-far | — | survived so far: 32 tests passed with it in place, and the rest of its candidates have not run with it yet |\n\n</details>\n",
        ] {
            assert!(text.contains(expected), "{expected} in {text}");
        }
        assert!(!text.contains("src/f25.ts"), "{text}");
        // Every survivor only logs: the sentence says so, and the fold holds them.
        let mut logged = survivor(1);
        logged.log_only = true;
        let text = markdown(&request(), &data(vec![logged]));
        assert!(
            text.contains("\nNo mutant is left alive by the tests. Those below change only what is logged.\n\n<details><summary>1 more that changes only what is logged"),
            "{text}"
        );
        // A weak table counts the tests too.
        let mut weak = mutant(2, NotInfected, None);
        weak.line_tests = Some(0);
        let text = markdown(&request(), &data(vec![weak]));
        assert!(
            text.contains("| Where | Mutant | Status | Tests on its line | Why |\n| --- | --- | --- | --- | --- |\n| `src/a.py:2:3` | `a + b → a - b` | not infected | 0 | weak reason |"),
            "{text}"
        );
        // Every changed line ran: nothing said of them; a few files are all
        // named.
        assert_eq!(unrun_lines(&Default::default()), "");
        assert_eq!(
            unrun_lines(&std::collections::BTreeMap::from([(
                "src/a.ts".to_owned(),
                vec![7]
            )])),
            "\n**1 changed line no test ran**, which no mutant on them can tell apart:\n\n- `src/a.ts`: 7\n"
        );
        // No pass and nothing left alive; asked by status and none has it.
        let killed = data(vec![mutant(3, Infected, None)]);
        let text = markdown(&request(), &killed);
        assert!(
            text.ends_with("\nNo mutant is left alive: none is not infected or not reached.\n"),
            "{text}"
        );
        let mut asked = request();
        asked.mutants.statuses = vec![NotReached];
        let text = markdown(&asked, &killed);
        assert!(text.ends_with("\nNo mutant is not reached.\n"), "{text}");
    }

    #[test]
    fn mutants_that_cannot_be_printed_end_the_export_with_two() {
        // A reader that stopped early, and a standard output that failed.
        for kind in [
            std::io::ErrorKind::BrokenPipe,
            std::io::ErrorKind::StorageFull,
        ] {
            assert_eq!(printed(&mut Failing(kind), "{}\n"), ExitCode::from(2));
        }
        let mut written = Vec::new();
        assert_eq!(printed(&mut written, "{}\n"), ExitCode::SUCCESS);
        assert_eq!(written, b"{}\n");
    }
}