cargo-tops 0.5.0

init / check / gate for the Rust-TOPS protocol. Orchestrates existing Cargo tools; does not replace them.
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
//! The survivors ledger: what `cargo mutants` left in `mutants.out/outcomes.json`.
//!
//! [`parse`] reads the file in the shape cargo-mutants [`PINNED`] writes and
//! refuses any other: a version it was not written for, a field it cannot
//! read, an outcome it does not know, or totals that disagree with the
//! outcomes. [`explain`] sorts the missed mutants into those a live
//! `layer: mutation` exemption covers (the rule of [`Exemption::covers`])
//! and those nothing covers. The gate passes the layer when the unexplained
//! count is at most `gates.mutation.unexplained_survivors_max`. Timeouts and
//! unviable mutants are counted and reported; they are not survivors.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]

use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use serde_json::{json, Value};

use crate::exemptions::Exemption;

/// Where cargo-mutants writes the run's outcomes, under the directory it ran in.
const OUTCOMES: &str = "mutants.out/outcomes.json";

/// What cargo-mutants 27.1.0 prints (to stderr) when the diff leaves nothing
/// to mutate, and then exits 0 without writing `mutants.out`: no Rust source
/// file changed, or the changed lines are in no function it mutates (a
/// comment, a test, a documentation or CI file). Recorded from real runs.
const NO_MUTANTS: [&str; 2] = ["Diff changes no Rust source files", "No mutants to filter"];

/// The cargo-mutants release whose `outcomes.json` this reads.
pub(crate) const PINNED: &str = "27.1.0";

/// One mutant the suite did not catch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Missed {
    /// The file, as cargo-mutants names it: relative to the workspace root.
    pub file: String,
    /// The function the mutant is in, `module::name` for a nested one.
    pub function: Option<String>,
    pub line: u64,
    /// cargo-mutants' own name for the mutant, such as
    /// `src/lib.rs:8:5: replace double -> i32 with 0`.
    pub name: String,
}

/// What a run found, by kind.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Outcomes {
    pub caught: usize,
    pub missed: Vec<Missed>,
    pub timeouts: usize,
    pub unviable: usize,
}

/// The missed mutants of a run, sorted by the records that cover them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Ledger {
    pub caught: usize,
    pub explained: Vec<Missed>,
    pub unexplained: Vec<Missed>,
    pub timeouts: usize,
    pub unviable: usize,
}

/// Remove the `outcomes.json` an earlier run left, so one found after
/// `cargo mutants` is the one it just wrote.
pub(crate) fn clear(dir: &Path) -> Result<()> {
    let path = dir.join(OUTCOMES);
    match fs::remove_file(&path) {
        Err(err) if err.kind() != std::io::ErrorKind::NotFound => {
            Err(err).with_context(|| format!("remove {}", path.display()))
        }
        _ => Ok(()),
    }
}

/// The outcomes `cargo mutants` just wrote under `dir`, after it ended with
/// `code` and printed `stderr`. Call [`clear`] before the run: a file that is
/// there afterwards is this run's. No file is the zero mutants of a diff with
/// nothing to mutate only when the run exited 0 and said so itself; any other
/// missing file is a failure.
pub(crate) fn read(dir: &Path, code: i32, stderr: &str) -> Result<Outcomes, String> {
    let text = match fs::read_to_string(dir.join(OUTCOMES)) {
        Ok(text) => text,
        Err(_) if code == 0 && says_no_mutants(stderr) => {
            return Ok(Outcomes::default());
        }
        Err(err) => {
            return Err(format!(
                "no {OUTCOMES} after cargo mutants exited {code}, and its output does not \
                 say it found no mutants: {err}"
            ));
        }
    };
    let found = parse(&text)?;
    check_exit(&found, code)?;
    Ok(found)
}

/// Whether a whole line of `stderr` is cargo-mutants' `INFO` line for a diff
/// with nothing to mutate (colour codes and surrounding space aside).
fn says_no_mutants(stderr: &str) -> bool {
    stderr.lines().any(|line| {
        let plain = without_colour(line);
        let text = plain.trim();
        NO_MUTANTS.iter().any(|said| {
            text.strip_prefix("INFO")
                .is_some_and(|rest| rest.trim() == *said)
        })
    })
}

/// `line` without ANSI colour sequences.
fn without_colour(line: &str) -> String {
    let mut plain = String::new();
    let mut chars = line.chars();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            // `ESC [ ... letter`
            for skipped in chars.by_ref() {
                if skipped.is_ascii_alphabetic() {
                    break;
                }
            }
        } else {
            plain.push(c);
        }
    }
    plain
}

/// The exit code and the file must agree: 2 says mutants were missed and 3
/// says some timed out.
fn check_exit(found: &Outcomes, code: i32) -> Result<(), String> {
    match code {
        2 if found.missed.is_empty() => Err(
            "cargo mutants exited 2 (mutants were missed) but outcomes.json lists no missed mutant"
                .to_string(),
        ),
        3 if found.timeouts == 0 => Err(
            "cargo mutants exited 3 (mutants timed out) but outcomes.json lists no timeout"
                .to_string(),
        ),
        _ => Ok(()),
    }
}

fn field<'v>(value: &'v Value, key: &str) -> Result<&'v Value, String> {
    value.get(key).ok_or_else(|| {
        format!("outcomes.json has no `{key}` where cargo-mutants {PINNED} writes one")
    })
}

fn count(value: &Value, key: &str) -> Result<usize, String> {
    field(value, key)?
        .as_u64()
        .and_then(|n| usize::try_from(n).ok())
        .ok_or_else(|| format!("outcomes.json `{key}` is not a count"))
}

/// The missed mutant a `Mutant` scenario describes.
fn missed(scenario: &Value) -> Result<Missed, String> {
    let mutant = field(scenario, "Mutant")?;
    let function = match field(mutant, "function")? {
        Value::Null => None,
        named => Some(
            field(named, "function_name")?
                .as_str()
                .ok_or("outcomes.json `function_name` is not a string")?
                .to_string(),
        ),
    };
    let line = field(field(field(mutant, "span")?, "start")?, "line")?
        .as_u64()
        .ok_or("outcomes.json span `line` is not a number")?;
    let text = |key: &str| -> Result<String, String> {
        Ok(field(mutant, key)?
            .as_str()
            .ok_or_else(|| format!("outcomes.json `{key}` is not a string"))?
            .to_string())
    };
    Ok(Missed {
        file: text("file")?,
        function,
        line,
        name: text("name")?,
    })
}

/// What one outcome says happened to its mutant.
#[derive(Clone, Copy)]
enum Kind {
    Caught,
    Missed,
    Timeout,
    Unviable,
}

/// The scenario and the summary of one outcome.
fn parts(outcome: &Value) -> Result<(&Value, &str), String> {
    let scenario = field(outcome, "scenario")?;
    let summary = field(outcome, "summary")?
        .as_str()
        .ok_or("outcomes.json `summary` is not a string")?;
    Ok((scenario, summary))
}

/// The baseline run is not a mutant: it must have succeeded.
fn baseline(summary: &str) -> Result<(), String> {
    match summary {
        "Success" => Ok(()),
        other => Err(format!("the baseline run ended as `{other}`")),
    }
}

fn kind(summary: &str) -> Result<Kind, String> {
    match summary {
        "CaughtMutant" => Ok(Kind::Caught),
        "MissedMutant" => Ok(Kind::Missed),
        "Timeout" => Ok(Kind::Timeout),
        "Unviable" => Ok(Kind::Unviable),
        other => Err(format!(
            "outcomes.json has an outcome `{other}` this gate does not know"
        )),
    }
}

impl Outcomes {
    fn add(&mut self, kind: Kind, scenario: &Value) -> Result<(), String> {
        match kind {
            Kind::Caught => self.caught += 1,
            Kind::Missed => self.missed.push(missed(scenario)?),
            Kind::Timeout => self.timeouts += 1,
            Kind::Unviable => self.unviable += 1,
        }
        Ok(())
    }
}

/// Add one outcome to `found`.
fn take(found: &mut Outcomes, outcome: &Value) -> Result<(), String> {
    let (scenario, summary) = parts(outcome)?;
    if scenario.as_str() == Some("Baseline") {
        return baseline(summary);
    }
    found.add(kind(summary)?, scenario)
}

/// Read `outcomes.json`. Any shape but the pinned one is an `Err` saying
/// what was not as expected, never a pass.
pub(crate) fn parse(text: &str) -> Result<Outcomes, String> {
    let doc: Value =
        serde_json::from_str(text).map_err(|err| format!("outcomes.json is not JSON: {err}"))?;
    let version = field(&doc, "cargo_mutants_version")?
        .as_str()
        .unwrap_or_default();
    if version != PINNED {
        return Err(format!(
            "outcomes.json is from cargo-mutants {version:?}; this gate reads {PINNED}"
        ));
    }
    let list = field(&doc, "outcomes")?
        .as_array()
        .ok_or("outcomes.json `outcomes` is not a list")?;
    let mut found = Outcomes::default();
    for outcome in list {
        take(&mut found, outcome)?;
    }
    let totals = [
        ("caught", found.caught),
        ("missed", found.missed.len()),
        ("timeout", found.timeouts),
        ("unviable", found.unviable),
        (
            "total_mutants",
            found.caught + found.missed.len() + found.timeouts + found.unviable,
        ),
    ];
    for (key, seen) in totals {
        let said = count(&doc, key)?;
        if said != seen {
            return Err(format!("outcomes.json says {said} {key} but lists {seen}"));
        }
    }
    Ok(found)
}

/// `file` relative to the crate root, given the crate's path under the
/// workspace root (`""` for a crate at the root).
fn relative<'f>(file: &'f str, crate_prefix: &str) -> &'f str {
    let prefix = crate_prefix.trim_matches('/');
    if prefix.is_empty() {
        return file;
    }
    file.strip_prefix(prefix)
        .and_then(|rest| rest.strip_prefix('/'))
        .unwrap_or(file)
}

/// Whether `record` explains a survivor in `function` of the file `rel`,
/// per function: a survivor inside a function is explained only by a record
/// whose `symbol` names that function and whose glob covers its file. A
/// survivor in no function (`function: null`: a `const` or `static`
/// initialiser, a type alias, a field type) is explained only by a record
/// with no symbol whose glob covers its file. No record explains every
/// survivor, so `unexplained_survivors_max` always decides.
fn explains(record: &Exemption, rel: &str, function: Option<&str>) -> bool {
    record.symbol.is_some() == function.is_some() && record.covers(rel, function)
}

/// Sort the missed mutants. `live` are the layer's records that have not
/// expired; `crate_prefix` is the crate's directory under the workspace root,
/// which the records' globs are relative to.
pub(crate) fn explain(found: &Outcomes, live: &[Exemption], crate_prefix: &str) -> Ledger {
    let (explained, unexplained) = found.missed.iter().cloned().partition(|mutant: &Missed| {
        let rel = relative(&mutant.file, crate_prefix);
        live.iter()
            .any(|record| explains(record, rel, mutant.function.as_deref()))
    });
    Ledger {
        caught: found.caught,
        explained,
        unexplained,
        timeouts: found.timeouts,
        unviable: found.unviable,
    }
}

impl Ledger {
    /// Whether the layer passes: at most `max` survivors nothing explains.
    pub(crate) fn passes(&self, max: i64) -> bool {
        i64::try_from(self.unexplained.len()).is_ok_and(|n| n <= max)
    }

    /// The problem that names each unexplained survivor, or `None` when the
    /// layer passes. Explained survivors are never named.
    pub(crate) fn problem(&self, max: i64) -> Option<String> {
        if self.passes(max) {
            return None;
        }
        let named: Vec<String> = self
            .unexplained
            .iter()
            .map(|mutant| mutant.name.clone())
            .collect();
        Some(format!(
            "mutation: {} unexplained survivor(s), above unexplained_survivors_max {max}: {}",
            named.len(),
            named.join("; ")
        ))
    }

    /// The numbers the mutation row's `judged` carries.
    pub(crate) fn to_json(&self, max: i64) -> Value {
        json!({
            "caught": self.caught,
            "missed": self.explained.len() + self.unexplained.len(),
            "explained": self.explained.len(),
            "unexplained": self.unexplained.len(),
            "timeouts": self.timeouts,
            "unviable": self.unviable,
            "unexplained_survivors_max": max,
        })
    }
}

#[cfg(test)]
#[expect(
    clippy::indexing_slicing,
    reason = "the tests edit and read JSON they built from the recorded fixture"
)]
mod tests {
    use super::{check_exit, clear, explain, parse, read, relative, Outcomes, PINNED};
    use crate::exemptions::Exemption;
    use serde_json::Value;
    use std::fs;

    /// A real run of cargo-mutants 27.1.0 over a small crate: 11 caught, 10
    /// missed (5 in `double`, 5 in `inner::triple`), 1 timeout, 1 unviable.
    type Edit = fn(&mut Value);

    const FIXTURE: &str = include_str!("../tests/fixtures/mutants-27.1.0/outcomes.json");

    fn record(path: &str, symbol: Option<&str>) -> Exemption {
        Exemption {
            path: path.to_string(),
            symbol: symbol.map(str::to_string),
            expires: "2099-01-01".to_string(),
        }
    }

    fn edited(change: impl FnOnce(&mut Value)) -> String {
        let mut doc: Value = serde_json::from_str(FIXTURE).expect("fixture is JSON");
        change(&mut doc);
        doc.to_string()
    }

    #[test]
    fn the_recorded_run_has_the_counts_cargo_mutants_reported() {
        let found = parse(FIXTURE).expect("the pinned shape parses");
        assert_eq!(found.caught, 11);
        assert_eq!(found.missed.len(), 10);
        assert_eq!(found.timeouts, 1);
        assert_eq!(found.unviable, 1);
        let first = found.missed.first().expect("a survivor");
        assert_eq!(first.file, "src/lib.rs");
        assert_eq!(first.function.as_deref(), Some("double"));
        assert_eq!(first.line, 8);
        assert_eq!(first.name, "src/lib.rs:8:5: replace double -> i32 with 0");
        let nested = found
            .missed
            .iter()
            .filter(|m| m.function.as_deref() == Some("inner::triple"))
            .count();
        assert_eq!(nested, 5);
    }

    #[test]
    fn another_release_is_refused_naming_both() {
        let text = edited(|doc| doc["cargo_mutants_version"] = "26.0.0".into());
        let err = parse(&text).expect_err("not the pinned release");
        assert!(err.contains("26.0.0") && err.contains(PINNED), "{err}");
        let text = edited(|doc| {
            doc.as_object_mut()
                .expect("object")
                .remove("cargo_mutants_version");
        });
        assert!(parse(&text).is_err());
    }

    #[test]
    fn an_unknown_shape_is_an_error_and_never_a_pass() {
        assert!(parse("").is_err());
        assert!(parse("[]").is_err());
        assert!(parse("{}").is_err());
        let cases: [(&str, Edit); 7] = [
            ("outcomes is not a list", |d| d["outcomes"] = "x".into()),
            ("an unknown summary", |d| {
                d["outcomes"][1]["summary"] = "Skipped".into()
            }),
            ("no scenario", |d| {
                d["outcomes"][1]
                    .as_object_mut()
                    .expect("object")
                    .remove("scenario");
            }),
            ("a baseline that failed", |d| {
                d["outcomes"][0]["summary"] = "Failure".into()
            }),
            ("no span", |d| {
                d["outcomes"][6]["scenario"]["Mutant"]
                    .as_object_mut()
                    .expect("object")
                    .remove("span");
            }),
            ("a missed total that disagrees", |d| d["missed"] = 3.into()),
            ("no caught total", |d| {
                d.as_object_mut().expect("object").remove("caught");
            }),
        ];
        for (what, change) in cases {
            let err = parse(&edited(change)).expect_err(what);
            assert!(!err.is_empty(), "{what}");
        }
    }

    #[test]
    fn a_missed_mutant_outside_a_function_has_no_function_name() {
        let text = edited(|doc| {
            let at = doc["outcomes"]
                .as_array()
                .expect("list")
                .iter()
                .position(|o| o["summary"] == "MissedMutant")
                .expect("a survivor");
            doc["outcomes"][at]["scenario"]["Mutant"]["function"] = Value::Null;
        });
        let found = parse(&text).expect("a null function is allowed");
        assert_eq!(found.missed.first().and_then(|m| m.function.clone()), None);
    }

    #[test]
    fn a_record_for_one_function_explains_only_its_survivors() {
        let found = parse(FIXTURE).expect("parses");
        let ledger = explain(&found, &[record("src/**", Some("double"))], "");
        assert_eq!(ledger.explained.len(), 5);
        assert_eq!(ledger.unexplained.len(), 5);
        assert!(ledger
            .unexplained
            .iter()
            .all(|m| m.function.as_deref() == Some("inner::triple")));
        assert!(!ledger.passes(0));
        assert!(ledger.passes(5));
        let problem = ledger.problem(0).expect("fails");
        assert!(
            problem.contains("5 unexplained") && problem.contains("inner::triple"),
            "{problem}"
        );
        assert!(!problem.contains(" double "), "{problem}");
    }

    #[test]
    fn a_symbol_matches_the_last_path_segment_and_a_symbol_free_record_explains_no_function() {
        let found = parse(FIXTURE).expect("parses");
        let nested = explain(&found, &[record("src/lib.rs", Some("triple"))], "");
        assert_eq!(nested.explained.len(), 5);
        let both = [
            record("src/lib.rs", Some("double")),
            record("src/lib.rs", Some("inner::triple")),
        ];
        assert!(explain(&found, &both, "").unexplained.is_empty());
        // No record explains every survivor: one with no symbol explains
        // none of those inside a function.
        let all = explain(&found, &[record("src/**", None)], "");
        assert_eq!(all.explained.len(), 0);
        assert_eq!(all.unexplained.len(), 10);
        assert!(!all.passes(0) && all.problem(0).is_some());
        let elsewhere = explain(&found, &[record("other/**", None)], "");
        assert_eq!(elsewhere.unexplained.len(), 10);
    }

    /// One record per function of the recorded run, over `path`.
    fn both(path: &str) -> [Exemption; 2] {
        [
            record(path, Some("double")),
            record(path, Some("inner::triple")),
        ]
    }

    #[test]
    fn globs_are_relative_to_the_crate_not_the_workspace() {
        let text = edited(|doc| {
            for outcome in doc["outcomes"].as_array_mut().expect("list") {
                if let Some(file) = outcome["scenario"]["Mutant"]["file"].as_str() {
                    let moved = format!("crates/sample/{file}");
                    outcome["scenario"]["Mutant"]["file"] = moved.into();
                }
            }
        });
        let found = parse(&text).expect("parses");
        // The record is relative to the crate: it names `src/lib.rs`, and the
        // workspace-relative file is `crates/sample/src/lib.rs`.
        let inside = both("src/lib.rs");
        assert_eq!(
            explain(&found, &inside, "crates/sample").explained.len(),
            10
        );
        assert_eq!(
            explain(&found, &inside, "crates/sample/").explained.len(),
            10
        );
        // A record that spells the workspace path matches only when no
        // prefix is stripped.
        let spelled = both("crates/sample/src/lib.rs");
        assert_eq!(explain(&found, &spelled, "").explained.len(), 10);
        assert_eq!(
            explain(&found, &spelled, "crates/sample").explained.len(),
            0
        );
        // A record for another crate's file explains nothing.
        let other = both("crates/other/src/lib.rs");
        assert_eq!(explain(&found, &other, "crates/sample").explained.len(), 0);
    }

    #[test]
    fn the_prefix_is_stripped_whole_segments_only() {
        assert_eq!(relative("crates/a/src/x.rs", "crates/a"), "src/x.rs");
        assert_eq!(
            relative("crates/ab/src/x.rs", "crates/a"),
            "crates/ab/src/x.rs"
        );
        assert_eq!(relative("src/x.rs", ""), "src/x.rs");
        assert_eq!(relative("src/x.rs", "/"), "src/x.rs");
    }

    #[test]
    fn the_judged_numbers_count_every_kind_and_the_max() {
        let found = parse(FIXTURE).expect("parses");
        let ledger = explain(&found, &[record("src/lib.rs", Some("double"))], "");
        let judged = ledger.to_json(2);
        assert_eq!(judged["caught"], 11);
        assert_eq!(judged["missed"], 10);
        assert_eq!(judged["explained"], 5);
        assert_eq!(judged["unexplained"], 5);
        assert_eq!(judged["timeouts"], 1);
        assert_eq!(judged["unviable"], 1);
        assert_eq!(judged["unexplained_survivors_max"], 2);
    }

    #[test]
    fn timeouts_and_unviable_mutants_are_not_survivors() {
        let only = Outcomes {
            caught: 0,
            missed: Vec::new(),
            timeouts: 4,
            unviable: 9,
        };
        let ledger = explain(&only, &[], "");
        assert!(ledger.passes(0) && ledger.problem(0).is_none());
        assert_eq!(ledger.timeouts, 4);
        assert_eq!(ledger.unviable, 9);
    }

    #[test]
    fn a_negative_max_is_never_met() {
        let ledger = explain(&Outcomes::default(), &[], "");
        assert!(!ledger.passes(-1));
    }

    /// The QA H4 shape, recorded in a workspace: `qa_h4_survivor_miss` has no
    /// test, so its two mutants survive, and `file` is relative to the
    /// workspace root, not to the crate.
    const PLANT: &str =
        include_str!("../tests/fixtures/mutants-27.1.0/plant-workspace/outcomes.json");

    #[test]
    fn the_h4_plant_has_two_survivors_in_a_crate_under_the_workspace() {
        let found = parse(PLANT).expect("parses");
        assert_eq!((found.caught, found.timeouts, found.unviable), (5, 0, 1));
        assert_eq!(found.missed.len(), 2);
        assert!(found
            .missed
            .iter()
            .all(|m| m.file == "crates/plant/src/qa_h4_plant.rs"
                && m.function.as_deref() == Some("qa_h4_survivor_miss")));
        let by_symbol = [record("src/qa_h4_plant.rs", Some("qa_h4_survivor_miss"))];
        assert_eq!(
            explain(&found, &by_symbol, "crates/plant").explained.len(),
            2
        );
        assert_eq!(explain(&found, &by_symbol, "").explained.len(), 2);
        let other = [record("src/qa_h4_plant.rs", Some("another"))];
        assert_eq!(explain(&found, &other, "crates/plant").unexplained.len(), 2);
        let wrong_file = [record("src/lib.rs", Some("qa_h4_survivor_miss"))];
        assert_eq!(
            explain(&found, &wrong_file, "crates/plant")
                .unexplained
                .len(),
            2
        );
    }

    fn scratch(name: &str) -> std::path::PathBuf {
        let dir =
            std::env::temp_dir().join(format!("cargo-tops-mutation-{name}-{}", std::process::id()));
        fs::remove_dir_all(&dir).ok();
        fs::create_dir_all(&dir).expect("mkdir");
        dir
    }

    #[test]
    fn an_outcomes_file_from_an_earlier_run_is_removed_and_none_is_nothing() {
        let dir = scratch("clear");
        assert!(clear(&dir).is_ok());
        fs::create_dir_all(dir.join("mutants.out")).expect("mkdir");
        let file = dir.join("mutants.out/outcomes.json");
        fs::write(&file, FIXTURE).expect("write");
        assert!(clear(&dir).is_ok());
        assert!(!file.exists());
        // A directory where the file should be cannot be removed as a file.
        fs::create_dir_all(file.join("inside")).expect("mkdir");
        let err = clear(&dir).expect_err("a directory is not a report");
        assert!(format!("{err:#}").contains("remove"), "{err:#}");
        fs::remove_dir_all(&dir).ok();
    }

    const NOTHING: &str = " INFO No mutants to filter\n";

    #[test]
    fn what_the_run_wrote_is_read_and_a_missing_file_is_an_error() {
        let dir = scratch("read");
        let err = read(&dir, 0, "").expect_err("no file");
        assert!(err.contains("mutants.out/outcomes.json"), "{err}");
        assert!(err.contains("exited 0"), "{err}");
        fs::create_dir_all(dir.join("mutants.out")).expect("mkdir");
        fs::write(dir.join("mutants.out/outcomes.json"), "not json").expect("write");
        assert!(read(&dir, 2, "")
            .expect_err("not json")
            .contains("not JSON"));
        fs::write(dir.join("mutants.out/outcomes.json"), FIXTURE).expect("write");
        assert_eq!(read(&dir, 2, "").expect("parses").missed.len(), 10);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn no_file_is_zero_mutants_only_for_exit_0_and_a_line_the_run_printed() {
        let dir = scratch("nothing");
        for line in super::NO_MUTANTS {
            let said = format!(" INFO {line}\n");
            assert_eq!(
                read(&dir, 0, &said).expect("zero mutants"),
                Outcomes::default()
            );
        }
        let said = format!("found 3 mutants\n{NOTHING}more\n");
        assert_eq!(
            read(&dir, 0, &said).expect("zero mutants"),
            Outcomes::default()
        );
        // With colour on, only the level is coloured.
        let coloured = "\u{1b}[32m INFO\u{1b}[0m No mutants to filter\n";
        assert_eq!(
            read(&dir, 0, coloured).expect("zero mutants"),
            Outcomes::default()
        );
        // Not a whole line of its own: the phrase inside another line is not it.
        for said in [
            "WARN path src/No mutants to filter.rs ignored\n",
            " INFO No mutants to filter.rs was skipped\n",
            " WARN No mutants to filter\n",
            "No mutants to filter\n",
            "",
            "Diff file is empty\n",
        ] {
            assert!(read(&dir, 0, said).is_err(), "{said:?}");
        }
        for code in [2, 3, 1] {
            assert!(read(&dir, code, NOTHING).is_err(), "exit {code}");
        }
        // A file that is there is read, whatever the run printed.
        fs::create_dir_all(dir.join("mutants.out")).expect("mkdir");
        fs::write(dir.join("mutants.out/outcomes.json"), FIXTURE).expect("write");
        assert_eq!(read(&dir, 0, NOTHING).expect("parses").caught, 11);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn the_exit_code_and_the_file_must_agree() {
        let found = parse(FIXTURE).expect("parses");
        assert!(check_exit(&found, 2).is_ok() && check_exit(&found, 3).is_ok());
        assert!(check_exit(&found, 0).is_ok());
        let none = Outcomes {
            missed: Vec::new(),
            timeouts: 0,
            ..found
        };
        let two = check_exit(&none, 2).expect_err("nothing missed");
        assert!(
            two.contains("exited 2") && two.contains("no missed"),
            "{two}"
        );
        let three = check_exit(&none, 3).expect_err("no timeout");
        assert!(
            three.contains("exited 3") && three.contains("no timeout"),
            "{three}"
        );
        // Missed but no timeout is fine for 2; a timeout but none missed for 3.
        let only_missed = Outcomes {
            timeouts: 0,
            ..found
        };
        assert!(check_exit(&only_missed, 2).is_ok());
        assert!(check_exit(&only_missed, 3).is_err());
        let only_timeout = Outcomes {
            missed: Vec::new(),
            ..found
        };
        assert!(check_exit(&only_timeout, 3).is_ok());
        assert!(check_exit(&only_timeout, 2).is_err());
    }

    #[test]
    fn the_total_must_be_there_and_agree() {
        let wrong = edited(|doc| doc["total_mutants"] = Value::from(999));
        let err = parse(&wrong).expect_err("999 is not 23");
        assert!(err.contains("says 999 total_mutants but lists 23"), "{err}");
        let gone = edited(|doc| {
            doc.as_object_mut().expect("object").remove("total_mutants");
        });
        assert!(parse(&gone)
            .expect_err("no total")
            .contains("total_mutants"));
    }

    const NULL_FUNCTION: &str =
        include_str!("../tests/fixtures/mutants-27.1.0/null-function/outcomes.json");

    #[test]
    fn a_survivor_in_no_function_takes_a_symbol_free_record_and_nothing_explains_them_all() {
        let found = parse(NULL_FUNCTION).expect("parses");
        assert_eq!(found.missed.len(), 12);
        assert_eq!(
            found.missed.iter().filter(|m| m.function.is_none()).count(),
            7
        );
        let count = |records: &[Exemption]| explain(&found, records, "").explained.len();
        // A symbol explains the function it names: 5 in `get`, none outside.
        assert_eq!(count(&[record("src/lib.rs", Some("get"))]), 5);
        assert_eq!(count(&[record("src/lib.rs", Some("no_such_fn"))]), 0);
        // No symbol: the 7 in no function, in the files the glob covers.
        for path in ["src/lib.rs", "src/**", "**", "*", "**/*.rs"] {
            assert_eq!(count(&[record(path, None)]), 7, "{path}");
        }
        assert_eq!(count(&[record("other/**", None)]), 0);
        // Both kinds of record: every survivor, each counted once.
        let both = [
            record("src/lib.rs", Some("get")),
            record("src/lib.rs", None),
        ];
        assert_eq!(count(&both), 12);
        // A symbol with a whole-tree path still names only its function.
        assert_eq!(count(&[record("**", Some("get"))]), 5);
        // In the recorded run every survivor is in a function: a symbol-free
        // record explains none, whatever its glob, so the max decides.
        let in_functions = parse(FIXTURE).expect("parses");
        for path in ["**", "/**", "*", "*.rs", "src/**", ".", "src/lib.rs"] {
            let ledger = explain(&in_functions, &[record(path, None)], "");
            assert_eq!(ledger.explained.len(), 0, "{path}");
            assert!(!ledger.passes(0), "{path}");
        }
    }

    #[test]
    fn a_survivor_is_named_once_by_its_own_name() {
        let found = parse(FIXTURE).expect("parses");
        let ledger = explain(&found, &[], "");
        let problem = ledger.problem(0).expect("fails");
        let first = &found.missed[0];
        assert_eq!(problem.matches(&first.name).count(), 1, "{problem}");
        assert!(!problem.contains(&format!("{}:{} {}", first.file, first.line, first.name)));
    }
}