paperboy 0.7.0

A Rust TUI API tester
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! The JUnit XML export: a report as a test suite, for CI.
//!
//! Every CI system on the planet — GitHub Actions, GitLab, Jenkins, Buildkite,
//! Azure — knows how to read JUnit XML and will draw the failures in its own
//! UI, annotate the pull request, and keep the history of which case has been
//! flaky. None of them will do any of that for a CSV. So this is not a sixth
//! way to render the same table: it is what makes a post-deploy PaperTrail run
//! a *test result* rather than an artefact someone has to open.
//!
//! The mapping follows JUnit's own distinction rather than inventing one, since
//! every consumer already shades the two differently:
//!
//! - **`<error>`** — the request itself went wrong (refused connection, an
//!   unexpected status, a failed `[Asserts]` entry). In JUnit's vocabulary that
//!   is an exception: the test could not deliver a verdict.
//! - **`<failure>`** — the request answered, and the answer was wrong against
//!   the report's ground truth (`TRUTH "…"`, the `Correct` column). That is an
//!   assertion that did not hold, which is what a failure is.
//! - **`<skipped>`** — a dry run. Nothing was sent, so every case is skipped
//!   rather than passed; a preview that reported a green suite would be the
//!   same lie the report file used to tell (see [`super::model::ReportResult`]).
//!
//! A case gets **one** of those, in that order of seniority: a row whose
//! request failed is an `<error>` even if its ground truth also came out
//! wrong, because the wrong answer is a consequence of the failure and the
//! stricter JUnit schemas allow a case only one outcome. The demoted verdict
//! is not lost — it is written into the case's `<system-out>`.
//!
//! A row with neither is a pass. Note what that means for a report with no
//! `TRUTH` column and a service that answers: every case passes, which is
//! exactly right — that report is a smoke test, and the requests were fine.

use super::compare::CORRECT_COLUMN;
use super::flow::Header;
use super::model::{OutputColumn, ReportResult, ReportRow, Verdict};
use super::writer::ReportWriter;
use std::collections::{HashMap, HashSet};

/// How much of a cell's text goes into `<system-out>`. A report can carry a
/// whole response body per row; a CI viewer that has to page through a megabyte
/// of JSON to find the one line that matters is no better than no context at
/// all, and the full value is in the `-o` report next to it.
const MAX_CELL: usize = 1000;

/// Writes a report as JUnit XML: one `<testsuite>`, one `<testcase>` per row.
pub struct JunitWriter;

impl ReportWriter for JunitWriter {
    fn write(&self, result: &ReportResult, header: &Header) -> Result<Vec<u8>, String> {
        let columns = result.resolved_columns(header);
        let suite = suite_name(header);
        let mut cases: Vec<Case> = result
            .rows
            .iter()
            .enumerate()
            .map(|(r, row)| Case::of(r, row, result, &columns))
            .collect();

        // Run errors that no row is responsible for: an empty glob, a producer
        // that failed before any row existed, a `CLEANUP` that broke after the
        // last row was emitted. Without this they would vanish — and a report
        // that produced no rows *because* something was wrong would be a green
        // suite of zero tests, which is the most dangerous shape a CI result
        // can take.
        //
        // Ownership is structural (`ReportRow::errors`), never a comparison of
        // the formatted text: the row's `…Error` cell and the run's error list
        // are worded differently, so matching on the sentence reported every
        // failed row twice — once as itself and once as an unexplained run
        // error.
        //
        // A dry run owns nothing, whatever its rows hold. Every projected case
        // is emitted `<skipped>`, and a skipped case carries no `<error>` — so
        // an error a row "explains" is an error the document never states. A
        // preview really can fail: resolution, `USING` and producer expansion
        // all happen before a request would be sent, so `REPORT REQUEST ghost`
        // records a row error on a run that sends nothing. Letting the row
        // claim it filed the one fault a preview exists to find under a green
        // skip, which is the worst shape a CI result can take.
        let explained =
            |e: &String| !result.dry_run && result.rows.iter().any(|row| row.errors.contains(e));
        let unexplained: Vec<&String> = result.errors.iter().filter(|e| !explained(e)).collect();

        // What a reader needs to know about the run that isn't about any one
        // case: the caveats the other formats carry as banners, plus the
        // teardown warnings and the steps that never ran.
        let mut notes: Vec<String> = Vec::new();
        if result.dry_run {
            notes.push("DRY RUN: no requests were sent — these cases are projected".to_string());
        }
        if let Some(p) = &result.partial {
            notes.push(format!(
                "PARTIAL: the run was stopped — {} of {} rows ran",
                p.rows_completed, p.rows_planned
            ));
        }
        notes.extend(result.skipped.iter().map(|s| format!("skipped: {s}")));
        notes.extend(result.warnings.iter().map(|w| format!("warning: {w}")));

        // The run-level case exists when there is something to say that belongs
        // to no row. It carries the notes as well as the orphan errors because
        // a suite-level `<system-err>` is legal but *invisible* in GitLab,
        // which reads those elements only under a `<testcase>` — and "the run
        // was stopped half way" is not a caveat a CI reader can afford to miss.
        let run_case = (!unexplained.is_empty() || !notes.is_empty()).then(|| Case {
            name: suite.clone(),
            errors: unexplained.iter().map(|e| (*e).clone()).collect(),
            failures: Vec::new(),
            context: notes.iter().map(|n| (String::new(), n.clone())).collect(),
            seconds: 0.0,
            disc: String::new(),
        });

        // Named alongside the rows, not after them. The run case takes the
        // suite's own name, which a row keyed the same way collides with — and
        // a first-wins consumer then keeps whichever came first and drops the
        // other, hiding either that row's failure or the run-level error that
        // explains an empty suite.
        let run_index = run_case.is_some().then_some(cases.len());
        cases.extend(run_case);
        disambiguate(&mut cases);

        // The run case is never a projection: it is *about* the run rather
        // than a case the run would have produced, so a dry run must not count
        // it among the skipped, and its note is the thing it exists to carry.
        let projected = |i: usize| result.dry_run && Some(i) != run_index;

        // Counted off the status each case is actually *emitted* with, so the
        // totals can never describe a document other than this one: a dry run
        // writes `<skipped>` and nothing else, and a case demoted from failure
        // to error is counted once, as an error.
        let tests = cases.len();
        let (mut failures, mut errors, mut skipped) = (0, 0, 0);
        for (i, c) in cases.iter().enumerate() {
            match c.status(projected(i)) {
                Status::Skipped => skipped += 1,
                Status::Error => errors += 1,
                Status::Failure => failures += 1,
                Status::Passed => {}
            }
        }
        let time = positive(cases.iter().map(|c| c.seconds).sum());

        let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        out.push_str(&format!(
            "<testsuites name=\"{}\" tests=\"{tests}\" failures=\"{failures}\" \
             errors=\"{errors}\" skipped=\"{skipped}\" time=\"{time:.3}\">\n",
            esc(&suite)
        ));
        out.push_str(&format!(
            "  <testsuite name=\"{}\" tests=\"{tests}\" failures=\"{failures}\" \
             errors=\"{errors}\" skipped=\"{skipped}\" time=\"{time:.3}\">\n",
            esc(&suite)
        ));

        for (i, case) in cases.iter().enumerate() {
            push_case(&mut out, case, &suite, projected(i));
        }

        // Kept as well as on the run case, for the consumers that do read it.
        if !notes.is_empty() {
            out.push_str(&format!(
                "    <system-err>{}</system-err>\n",
                esc(&notes.join("\n"))
            ));
        }

        out.push_str("  </testsuite>\n</testsuites>\n");
        Ok(out.into_bytes())
    }
}

/// What a case is reported as. One per case: the stricter JUnit schemas
/// (Ant/Windy Road) allow a `<testcase>` only one of these, and a case counted
/// in two totals makes every consumer's arithmetic disagree with the document.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    Skipped,
    Error,
    Failure,
    Passed,
}

/// One row, reduced to what JUnit needs to say about it.
struct Case {
    name: String,
    /// The run errors this row is responsible for, taken from
    /// [`ReportRow::errors`] — structural ownership recorded where the failure
    /// happened, rather than re-derived here from an `…Error` cell that a
    /// declared field or a `HIDE(Error)` may have removed.
    errors: Vec<String>,
    /// Ground-truth verdicts that came out wrong, as `column: expected … got …`.
    failures: Vec<String>,
    /// Name/value pairs for `<system-out>`; an empty name writes the value
    /// alone (the run case's notes, which are sentences rather than cells).
    context: Vec<(String, String)>,
    /// Wall time for the row, in seconds.
    seconds: f64,
    /// What tells this case apart from another of the same name, where
    /// anything does. Empty otherwise, and only ever read when there is a
    /// collision to resolve.
    disc: String,
}

impl Case {
    fn of(r: usize, row: &ReportRow, result: &ReportResult, columns: &[OutputColumn]) -> Self {
        let errors = row.errors.clone();

        let mut failures = Vec::new();
        for col in columns.iter().filter(|c| c.truth.is_some()) {
            if result.verdicts.get(&(r, col.header.clone())) == Some(&Verdict::Incorrect) {
                let expected = result
                    .truths
                    .get(&(r, col.header.clone()))
                    .cloned()
                    .unwrap_or_default();
                let got = col.value(row, &result.no_match_marker);
                failures.push(format!(
                    "{}: expected {expected:?}, got {got:?}",
                    col.header
                ));
            }
        }
        // The row can also be rolled up as wrong without this writer being able
        // to name the column that did it — a snapshot row, or a result built by
        // something other than a live run. A vague failure beats a lost one.
        if failures.is_empty()
            && row.cells.get(CORRECT_COLUMN).map(String::as_str)
                == Some(Verdict::Incorrect.as_str())
        {
            failures.push("the row's answer did not match its ground truth".to_string());
        }

        // Only the *totals*: `…Time` under its own name, plus whatever a field
        // aliased the `Time` intrinsic to (recorded per run, since the alias is
        // the user's name and says nothing about what it holds). Adding the
        // setup/wait/download slices as well would count the same milliseconds
        // two or three times over.
        //
        // And a request is only allowed to spend its total once, which is why
        // the totals are collected per *step* before they are added up. Nothing
        // stops a flow naming the same intrinsic twice — `[Reports]` with both
        // `took = Time` and `elapsed = Time`, or an alias beside the plain
        // `Time` column — and every one of those columns holds the very same
        // milliseconds. Summing the columns made a case that reported its
        // duration twice appear to have taken twice as long, which is worse
        // than not reporting it at all: it is a plausible number.
        let mut totals: Vec<(&str, f64)> = Vec::new();
        for (k, v) in &row.cells {
            let is_total =
                k.as_str() == "Time" || k.ends_with(".Time") || result.duration_columns.contains(k);
            if !is_total {
                continue;
            }
            // A duration that is negative, infinite or NaN is not a duration;
            // JUnit's `time` is a plain non-negative number and some consumers
            // reject the document outright over one.
            let Ok(n) = v.trim().parse::<f64>() else {
                continue;
            };
            if !n.is_finite() || n < 0.0 {
                continue;
            }
            // Cells are keyed `<step>.<field>`; a bare `Time` belongs to no
            // named step and stands alone.
            let step = k.rsplit_once('.').map(|(s, _)| s).unwrap_or("");
            match totals.iter_mut().find(|(s, _)| *s == step) {
                // Equal in every case the interpreter can produce — they are
                // the same `duration_ms` read twice. The larger is taken rather
                // than the first so a hand-built or imported result, where they
                // might not be, still reports a duration no shorter than the
                // longest thing the step is known to have done.
                Some((_, seen)) => *seen = seen.max(n),
                None => totals.push((step, n)),
            }
        }
        let ms: f64 = totals.iter().map(|(_, n)| n).sum();

        let context = columns
            .iter()
            .map(|c| {
                (
                    c.header.clone(),
                    truncate(&c.value(row, &result.no_match_marker)),
                )
            })
            .filter(|(_, v)| !v.is_empty())
            .collect();

        Self {
            name: case_name(r, row),
            errors,
            failures,
            context,
            seconds: positive(ms / 1000.0),
            disc: discriminator(row),
        }
    }

    /// The one status this case is reported with. A failed request outranks a
    /// wrong answer: the answer was wrong *because* the request was, and a case
    /// that claimed both would be counted twice and rejected by the stricter
    /// schemas.
    fn status(&self, dry_run: bool) -> Status {
        if dry_run {
            Status::Skipped
        } else if !self.errors.is_empty() {
            Status::Error
        } else if !self.failures.is_empty() {
            Status::Failure
        } else {
            Status::Passed
        }
    }
}

/// What distinguishes a row from another with the same key.
///
/// The two ways a key legitimately repeats are the two things read here: the
/// same key under two comparison clauses (both clauses drop their environment
/// axis from the key, which is what lets a baseline and its candidate meet),
/// and the same key against two `ENVS` targets. Naming the case after the one
/// that differs says *why* there are two, and keeps the case's identity across
/// runs — an ordinal moves the moment a row is added above it, which breaks
/// every CI history that tracks a case over time.
///
/// Empty when the row offers nothing, leaving [`disambiguate`] its ordinal.
/// The path is deliberately not used: it is a run-time coordinate of loop node
/// and iteration indices, which reads as noise and is empty for snapshot rows
/// anyway.
fn discriminator(row: &ReportRow) -> String {
    let parts: Vec<&str> = [row.target.as_deref(), row.comparison.as_deref()]
        .into_iter()
        .flatten()
        .filter(|p| !p.is_empty())
        .collect();
    parts.join(" ")
}

/// Make every case name unique within the suite — as the *consumer* sees it.
///
/// A row *key* can legitimately repeat — two manifest lines with the same
/// values, the same key under two comparison clauses — while `row.path` is
/// guaranteed unique. CI consumers key a case on `(classname, name)` and
/// GitLab, for one, keeps only the first of a duplicated pair: a colliding name
/// does not merely read badly, it silently *hides* the second row's failure.
///
/// Two names collide when they *arrive* the same way, not when they are the
/// same Rust string. The name goes out as an XML attribute, and every parser
/// normalises one before anyone compares it: a tab or a newline inside becomes
/// a space (XML 1.0 §3.3.3), and `esc` has already mapped the characters XML
/// cannot carry at all to a space too. So the decision is made on [`seen_as`],
/// the form that reaches the reader.
///
/// The discriminator is the row's path where it has one, since that keeps a
/// case's identity stable across runs and so keeps a CI history joined up; a
/// plain ordinal otherwise. Either way the result is checked against every
/// other final name and retried until it is free — `#1` is itself a name a row
/// can already carry, and appending to a duplicate must not manufacture a
/// fresh one.
fn disambiguate(cases: &mut [Case]) {
    let mut counts: HashMap<String, usize> = HashMap::new();
    for c in cases.iter() {
        *counts.entry(seen_as(&c.name)).or_default() += 1;
    }
    // The names that keep what they have, and are therefore spoken for.
    let mut taken: HashSet<String> = counts
        .iter()
        .filter(|(_, n)| **n == 1)
        .map(|(name, _)| name.clone())
        .collect();
    if taken.len() == cases.len() {
        return;
    }
    let mut nth: HashMap<String, usize> = HashMap::new();
    for c in cases.iter_mut() {
        let canon = seen_as(&c.name);
        if counts[&canon] == 1 {
            continue;
        }
        let n = nth.entry(canon).or_default();
        let mut candidate = if c.disc.is_empty() {
            *n += 1;
            format!("{} #{n}", c.name)
        } else {
            format!("{} #{}", c.name, c.disc)
        };
        while !taken.insert(seen_as(&candidate)) {
            *n += 1;
            candidate = format!("{} #{n}", c.name);
        }
        c.name = candidate;
    }
}

/// A name as a consumer finally sees it.
///
/// Uniqueness has to be judged on this rather than on the original string:
/// `"a\tb"` and `"a b"` are different names here and the same name in every
/// parser, and so are a name carrying a NUL and the one carrying a space that
/// `esc` turns it into.
fn seen_as(name: &str) -> String {
    esc(name)
        .chars()
        .map(|c| {
            if matches!(c, '\t' | '\n' | '\r') {
                ' '
            } else {
                c
            }
        })
        .collect()
}

/// Turn a negative zero into a plain one.
///
/// Rust sums `f64` from an identity of `-0.0` (so that a sum of negative zeros
/// keeps its sign), which means a row carrying no `…Time` cell at all comes out
/// as `-0.0` and formats as `time="-0.000"`. Some JUnit parsers refuse a
/// negative duration outright, and every human who sees one stops to work out
/// what went backwards.
fn positive(v: f64) -> f64 {
    v + 0.0
}

/// A row's name in the suite: its **key** — the loop values that identify it
/// (`batch-07 / case-a`) — because that is the identity CI has to keep stable
/// between runs to track a case's history. The row's index would rename every
/// case the moment a manifest gained a line, which is exactly when a reader
/// most wants the history.
fn case_name(r: usize, row: &ReportRow) -> String {
    let mut name = row.key.join(" / ");
    if name.trim().is_empty() {
        name = format!("row {}", r + 1);
    }
    // An `ENVS` comparison runs the same key against several targets; without
    // the target they would be one case reported twice.
    match &row.target {
        Some(t) if !t.is_empty() => format!("{name} [{t}]"),
        _ => name,
    }
}

/// The suite's name: the report's `# name:`, else a constant — never the file
/// name, which is the one thing a CI job can already see.
fn suite_name(header: &Header) -> String {
    match header.get("name").map(str::trim) {
        Some(n) if !n.is_empty() => n.to_string(),
        _ => "PaperTrail report".to_string(),
    }
}

fn push_case(out: &mut String, case: &Case, suite: &str, dry_run: bool) {
    out.push_str(&format!(
        "    <testcase name=\"{}\" classname=\"{}\" time=\"{:.3}\"",
        esc(&case.name),
        esc(suite),
        case.seconds
    ));
    let status = case.status(dry_run);
    // `<system-out>` carries the row's cells, and (for a case demoted from
    // failure to error) the verdict that lost the tie — so nothing a reader
    // needs is dropped by the one-status rule.
    let mut out_lines: Vec<String> = Vec::new();
    if status == Status::Error {
        out_lines.extend(case.failures.iter().cloned());
    }
    // A skipped case still says what went wrong with it. The run case carries
    // these errors as the suite's `<error>`s (see the writer's `explained`),
    // so this is attribution rather than duplication: it is the only place the
    // document says *which row* a dry run's resolution failure belongs to.
    if status == Status::Skipped {
        out_lines.extend(case.errors.iter().cloned());
    }
    out_lines.extend(case.context.iter().map(|(k, v)| {
        if k.is_empty() {
            v.clone()
        } else {
            format!("{k}: {v}")
        }
    }));
    if status == Status::Passed && out_lines.is_empty() {
        out.push_str("/>\n");
        return;
    }
    out.push_str(">\n");
    // Element order follows the JUnit XSD's content model —
    // `skipped?, error*, failure*, system-out*, system-err*` — which the
    // stricter validators enforce.
    match status {
        Status::Skipped => {
            out.push_str("      <skipped message=\"dry run — no request was sent\"/>\n");
        }
        Status::Error => {
            for e in &case.errors {
                out.push_str(&format!(
                    "      <error message=\"{}\" type=\"request\">{}</error>\n",
                    esc(&first_line(e)),
                    esc(e)
                ));
            }
        }
        Status::Failure => {
            for f in &case.failures {
                out.push_str(&format!(
                    "      <failure message=\"{}\" type=\"truth\">{}</failure>\n",
                    esc(&first_line(f)),
                    esc(f)
                ));
            }
        }
        Status::Passed => {}
    }
    if !out_lines.is_empty() {
        out.push_str(&format!(
            "      <system-out>{}</system-out>\n",
            esc(&out_lines.join("\n"))
        ));
    }
    out.push_str("    </testcase>\n");
}

/// The first line of `s`, for an attribute: a `message` is rendered inline by
/// every consumer, and a response body pasted into one makes the suite
/// unreadable in all of them.
fn first_line(s: &str) -> String {
    truncate(s.lines().next().unwrap_or("").trim())
}

fn truncate(s: &str) -> String {
    if s.chars().count() <= MAX_CELL {
        return s.to_string();
    }
    let kept: String = s.chars().take(MAX_CELL).collect();
    format!("{kept}…")
}

/// XML-escape `s`, and replace every character XML 1.0 cannot represent.
///
/// A raw response body reaches this — a `\x00` from a binary payload, an
/// `0x1b` from an ANSI-coloured error, a `U+FFFF` from a fuzzer — and a single
/// one of them makes the whole file unparseable, which would take every *other*
/// failure in the suite down with it. The legal set is XML 1.0's `Char`
/// production: tab/LF/CR, `U+0020..=U+D7FF`, `U+E000..=U+FFFD`, and
/// `U+10000..=U+10FFFF`. (Surrogates cannot occur in a Rust `str`, so the gap
/// between D7FF and E000 is unreachable — it is written out anyway because the
/// rule, not the reachability, is what the next reader needs to see.)
fn esc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            '\t' | '\n' | '\r' => out.push(c),
            c if is_xml_char(c) => out.push(c),
            // Replaced rather than dropped: a body that is mostly control
            // bytes should still look like something went wrong with it.
            _ => out.push(' '),
        }
    }
    out
}

/// Whether `c` is legal in an XML 1.0 document at all (excluding the
/// tab/LF/CR handled by the caller).
fn is_xml_char(c: char) -> bool {
    let u = c as u32;
    (0x20..=0xD7FF).contains(&u)
        || (0xE000..=0xFFFD).contains(&u)
        || (0x10000..=0x10FFFF).contains(&u)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::model::{ReportResult, ReportRow};
    use std::collections::HashMap;

    fn row(key: &[&str], cells: &[(&str, &str)]) -> ReportRow {
        ReportRow {
            errors: Vec::new(),
            role: crate::report::model::RowRole::default(),
            cells: cells
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            vars: HashMap::new(),
            key: key.iter().map(|k| k.to_string()).collect(),
            path: Vec::new(),
            comparison: None,
            target: None,
        }
    }

    /// A row whose request failed. The errors are the run's own wording (what
    /// `ReportResult::errors` holds); the `…Error` cell is the report's, and
    /// the two are deliberately different — which is why ownership is carried
    /// structurally rather than matched on the text.
    fn failed_row(key: &[&str], cells: &[(&str, &str)], errors: &[&str]) -> ReportRow {
        ReportRow {
            errors: errors.iter().map(|e| e.to_string()).collect(),
            ..row(key, cells)
        }
    }

    fn xml(result: &ReportResult) -> String {
        String::from_utf8(JunitWriter.write(result, &Header::default()).unwrap()).unwrap()
    }

    /// The smoke-test shape: a request that came back broken is an `<error>`,
    /// and the suite counts it, so CI paints the step red and shows the reason.
    #[test]
    fn a_failed_request_is_an_error_case() {
        let res = ReportResult {
            column_order: vec!["Ping.HttpStatus".into(), "Ping.Error".into()],
            rows: vec![
                row(&["a"], &[("Ping.HttpStatus", "200"), ("Ping.Error", "")]),
                failed_row(
                    &["b"],
                    &[
                        ("Ping.HttpStatus", "500"),
                        ("Ping.Error", "Expected status 200 but got 500"),
                    ],
                    &["Ping: Expected status 200 but got 500"],
                ),
            ],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("tests=\"2\""), "{out}");
        assert!(out.contains("errors=\"1\""), "{out}");
        assert!(out.contains("failures=\"0\""), "{out}");
        assert!(
            out.contains("name=\"b\"") && out.contains("but got 500"),
            "the failing case is named by its key: {out}"
        );
    }

    /// A wrong *answer* is a `<failure>`, not an `<error>`: the request worked.
    /// Every CI viewer shades the two differently, and the difference is the
    /// one a reader acts on — "the service is down" versus "the model is worse".
    #[test]
    fn a_wrong_answer_is_a_failure_with_both_sides_of_the_comparison() {
        let mut res = ReportResult {
            column_order: vec!["Verdict".into()],
            rows: vec![row(&["doc-1"], &[("Verdict", "fake")])],
            column_truths: [("Verdict".to_string(), "real".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        res.verdicts
            .insert((0, "Verdict".into()), Verdict::Incorrect);
        res.truths.insert((0, "Verdict".into()), "real".into());
        let out = xml(&res);
        assert!(out.contains("failures=\"1\""), "{out}");
        assert!(out.contains("errors=\"0\""), "{out}");
        assert!(
            out.contains("expected \\\"real\\\"") || out.contains("expected &quot;real&quot;"),
            "the message carries what was expected: {out}"
        );
        assert!(
            out.contains("got &quot;fake&quot;"),
            "and what came back: {out}"
        );
    }

    /// A dry run is a suite of skipped cases. A preview that reported green
    /// would be the same lie the report file used to tell.
    #[test]
    fn a_dry_run_skips_every_case_rather_than_passing_it() {
        let res = ReportResult {
            column_order: vec!["Ping.HttpStatus".into()],
            rows: vec![row(&["a"], &[("Ping.HttpStatus", "")])],
            dry_run: true,
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("skipped=\"1\""), "{out}");
        assert!(out.contains("<skipped"), "{out}");
        assert!(out.contains("DRY RUN"), "the suite says why: {out}");
    }

    /// A preview can fail. Resolution, `USING` and producer expansion all
    /// happen before a request would be sent, so `REPORT REQUEST ghost` records
    /// an error on a run that sent nothing -- and the row that owns it is
    /// emitted `<skipped>`, which carries no `<error>` at all. Left to the row,
    /// the fault the preview exists to find would appear nowhere in the
    /// document: a clean green dry run of a broken report.
    #[test]
    fn a_dry_run_that_could_not_resolve_a_request_is_not_a_clean_skip() {
        let err = "request 'ghost' could not be resolved";
        let res = ReportResult {
            column_order: vec!["ghost.Error".into()],
            rows: vec![failed_row(
                &["a"],
                &[("ghost.Error", "unresolved request 'ghost'")],
                &[err],
            )],
            errors: vec![err.to_string()],
            dry_run: true,
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("errors=\"1\""), "the suite reports it: {out}");
        assert!(out.contains("<error"), "as an error element: {out}");
        // Compared escaped: the wording carries an apostrophe, and the
        // document is XML before it is prose.
        let quoted = esc(err);
        assert!(
            out.contains(&quoted),
            "quoting the run's own wording: {out}"
        );
        // The projected row is still a projection, and still says which row the
        // failure belongs to.
        assert!(out.contains("<skipped"), "{out}");
        assert!(out.contains("skipped=\"1\""), "{out}");
        assert!(
            out.matches(quoted.as_str()).count() >= 2,
            "the skipped case attributes it too: {out}"
        );
    }

    /// The dangerous shape: a run that produced no rows *because* something was
    /// wrong. An empty suite is a green suite in every CI system there is, so
    /// the run's own errors become a case of their own.
    #[test]
    fn a_run_error_that_belongs_to_no_row_still_fails_the_suite() {
        let res = ReportResult {
            errors: vec!["FILES \"cases/*.json\" matched nothing".into()],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("tests=\"1\""), "{out}");
        assert!(out.contains("errors=\"1\""), "{out}");
        assert!(out.contains("matched nothing"), "{out}");
    }

    /// A stopped run says so where a JUnit reader will see it, for the same
    /// reason every other format carries the caveat.
    #[test]
    fn a_partial_run_carries_its_caveat_on_the_suite() {
        let res = ReportResult {
            rows: vec![row(&["a"], &[("Ping.HttpStatus", "200")])],
            partial: Some(crate::report::model::Partial {
                rows_completed: 1,
                rows_planned: 9,
            }),
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("PARTIAL"), "{out}");
        assert!(out.contains("1 of 9"), "{out}");
    }

    /// One malformed byte in a response body must not cost the whole file: an
    /// unparseable suite takes every *other* failure down with it.
    #[test]
    fn control_characters_and_markup_cannot_break_the_document() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(
                &["<script>"],
                &[("Body", "a\u{0}b & <tag> \"quoted\"")],
            )],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(!out.contains('\u{0}'), "the NUL is gone: {out:?}");
        assert!(out.contains("&lt;script&gt;"), "{out}");
        assert!(out.contains("&amp;"), "{out}");
        assert!(!out.contains("<tag>"), "no raw markup from a body: {out}");
    }

    /// A row that carries no timing at all is not a row that took negative
    /// time. Rust's `f64` sum starts from `-0.0`, so this used to render
    /// `time="-0.000"` — a duration some JUnit parsers reject and every reader
    /// has to stop and think about.
    #[test]
    fn a_row_with_no_timing_takes_no_time_rather_than_negative_time() {
        let res = ReportResult {
            column_order: vec!["Ping.status".into()],
            rows: vec![row(&["a"], &[("Ping.status", "200")])],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(!out.contains("-0.000"), "no negative durations: {out}");
        assert!(out.contains("time=\"0.000\""), "{out}");
    }

    /// Every shape this writer can produce, parsed by a real XML parser.
    ///
    /// The assertions elsewhere in this module are substring checks, and a
    /// substring check cannot see the thing that matters most here: whether a
    /// CI system can read the file at all. One illegal character or one
    /// unbalanced element makes the whole suite unreadable — including every
    /// failure it was written to report.
    #[test]
    fn every_document_this_writer_produces_parses_as_xml() {
        let awkward = ReportResult {
            column_order: vec!["Body".into(), "Ping.Time".into()],
            rows: vec![
                // U+FFFE and U+FFFF are legal Rust `char`s and illegal XML;
                // a fuzzer, a bad encoding guess or a binary body produces
                // them, and one is enough to make the document unparseable.
                failed_row(
                    &["odd \u{fffe}\u{ffff}\u{0}\u{1b}"],
                    &[("Body", "]]> & <b> \"q\" '\u{7f}'"), ("Ping.Time", "12")],
                    &["Ping: broken \u{ffff} pipe"],
                ),
                row(&["dup"], &[("Body", "one")]),
                row(&["dup"], &[("Body", "two")]),
                row(&[], &[("Body", "")]),
            ],
            errors: vec!["FILES \"x\" matched <nothing>".into()],
            warnings: vec!["CLEANUP failed & kept going".into()],
            skipped: vec!["Teardown".into()],
            ..Default::default()
        };
        let header = Header {
            lines: vec![crate::report::flow::HeaderLine::Directive {
                key: "name".into(),
                value: "A & B <report>".into(),
            }],
        };

        for (what, result, head) in [
            ("awkward", awkward, header),
            ("empty", ReportResult::default(), Header::default()),
            (
                "dry run",
                ReportResult {
                    rows: vec![row(&["a"], &[("Ping.HttpStatus", "")])],
                    dry_run: true,
                    errors: vec!["never sent".into()],
                    ..Default::default()
                },
                Header::default(),
            ),
        ] {
            let doc = String::from_utf8(JunitWriter.write(&result, &head).unwrap()).unwrap();
            let mut reader = quick_xml::Reader::from_str(&doc);
            let mut depth = 0i32;
            loop {
                match reader.read_event() {
                    Ok(quick_xml::events::Event::Start(_)) => depth += 1,
                    Ok(quick_xml::events::Event::End(_)) => depth -= 1,
                    Ok(quick_xml::events::Event::Eof) => break,
                    Ok(_) => {}
                    Err(e) => panic!("the {what} document is not XML: {e}\n{doc}"),
                }
            }
            assert_eq!(
                depth, 0,
                "unbalanced elements in the {what} document:\n{doc}"
            );
            for illegal in ['\u{0}', '\u{1b}', '\u{fffe}', '\u{ffff}'] {
                assert!(
                    !doc.contains(illegal),
                    "{illegal:?} survived into the {what} document"
                );
            }
        }
    }

    /// Two rows can legitimately share a key — a manifest with a repeated line,
    /// the same key under two comparison clauses. CI consumers key a case on
    /// `(classname, name)`, and GitLab keeps only the first of a colliding
    /// pair: a duplicate name does not merely read badly, it *hides* the second
    /// row's failure, which is the one shape a CI report must never take.
    #[test]
    fn colliding_row_keys_become_separate_cases() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![
                row(&["same"], &[("Body", "first")]),
                failed_row(&["same"], &[("Body", "second")], &["Ping: down"]),
                row(&["other"], &[("Body", "third")]),
            ],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("name=\"same #1\""), "{out}");
        assert!(out.contains("name=\"same #2\""), "{out}");
        // The row that did not collide keeps the readable name that makes a
        // case history worth having.
        assert!(out.contains("name=\"other\""), "{out}");
        assert!(out.contains("errors=\"1\""), "{out}");
    }

    /// Every name in the document, as a consumer finally reads it: the
    /// attribute values, after the escaping and the attribute-value
    /// normalisation a parser applies. Uniqueness is only meaningful here.
    fn names(out: &str) -> Vec<String> {
        out.match_indices("<testcase name=\"")
            .map(|(i, m)| {
                let rest = &out[i + m.len()..];
                rest[..rest.find('"').unwrap()]
                    .chars()
                    .map(|c| {
                        if matches!(c, '\t' | '\n' | '\r') {
                            ' '
                        } else {
                            c
                        }
                    })
                    .collect()
            })
            .collect()
    }

    fn all_unique(out: &str) -> bool {
        let n = names(out);
        let mut sorted = n.clone();
        sorted.sort();
        sorted.dedup();
        sorted.len() == n.len()
    }

    /// Resolving a collision creates a name, and the name it creates is one a
    /// row can already be using: a manifest holding `same`, `same` and
    /// `same #1` produced `same #1` *twice*, which is the collision the
    /// renaming exists to prevent — now with the appearance of having been
    /// dealt with.
    #[test]
    fn a_name_invented_to_resolve_a_collision_cannot_make_another() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![
                row(&["same"], &[("Body", "first")]),
                row(&["same"], &[("Body", "second")]),
                row(&["same #1"], &[("Body", "third")]),
            ],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(all_unique(&out), "{out}");
        assert_eq!(names(&out).len(), 3, "{out}");
    }

    /// The run case is named after the suite, so a row keyed the same way
    /// collides with it — and a first-wins consumer then keeps one and drops
    /// the other, losing either that row's failure or the run-level error that
    /// explains why the suite is short. It is named with the rows for that
    /// reason, rather than appended once they are already unique among
    /// themselves.
    #[test]
    fn a_row_named_like_the_suite_cannot_swallow_the_runs_own_case() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&[&suite_name(&Header::default())], &[("Body", "a")])],
            errors: vec!["FILES \"cases/*.json\" matched nothing".into()],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(all_unique(&out), "{out}");
        assert!(out.contains("<error"), "the run error survives: {out}");
    }

    /// Two names that differ only in whitespace a parser erases are one name to
    /// the consumer: XML normalises a tab or a newline inside an attribute to a
    /// space, and `esc` has already turned the characters XML cannot carry at
    /// all into spaces. Comparing the Rust strings called these distinct and
    /// shipped a document in which they are not.
    #[test]
    fn names_that_only_a_parser_would_flatten_together_are_still_told_apart() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![
                row(&["a\tb"], &[("Body", "tab")]),
                row(&["a b"], &[("Body", "space")]),
                row(&["a\u{0}c"], &[("Body", "nul")]),
                row(&["a c"], &[("Body", "space too")]),
            ],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(all_unique(&out), "{out}");
    }

    /// Where the rows themselves say why there are two of them, the case is
    /// named for that rather than counted off. An ordinal moves as soon as a
    /// row is added above it, so a CI history that tracks a case over time
    /// follows the wrong one; the clause a row belongs to does not move.
    #[test]
    fn a_collision_is_named_for_what_actually_differs() {
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![
                ReportRow {
                    comparison: Some("nightly".into()),
                    ..row(&["same"], &[("Body", "a")])
                },
                ReportRow {
                    comparison: Some("release".into()),
                    ..row(&["same"], &[("Body", "b")])
                },
            ],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("name=\"same #nightly\""), "{out}");
        assert!(out.contains("name=\"same #release\""), "{out}");
    }

    /// A failed request is an error even when the report does not *show* the
    /// error: `HIDE(Error)`, or a `# columns:` directive, or a declared field
    /// list that never asked for one. Ownership is recorded where the failure
    /// happened, not re-read from a cell that may not exist.
    #[test]
    fn a_hidden_error_column_still_fails_its_case() {
        let res = ReportResult {
            column_order: vec!["Ping.HttpStatus".into()],
            rows: vec![failed_row(
                &["a"],
                &[("Ping.HttpStatus", "500")],
                &["Ping: Expected status 200 but got 500"],
            )],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("errors=\"1\""), "{out}");
        assert!(out.contains("but got 500"), "{out}");
        // Exactly one case, and exactly one error in it: the run's own copy of
        // the same failure must not be reported a second time as an orphan.
        assert_eq!(out.matches("<testcase").count(), 1, "{out}");
        assert_eq!(out.matches("<error").count(), 1, "{out}");
    }

    /// A run error that a row owns is that row's, and nobody else's. Before
    /// ownership was structural this was matched on the formatted text — which
    /// never matched, so every failed row was reported twice: once as itself
    /// and once as an unexplained run error.
    #[test]
    fn a_rows_error_is_not_also_reported_against_the_run() {
        let res = ReportResult {
            column_order: vec!["Ping.HttpStatus".into()],
            rows: vec![failed_row(
                &["a"],
                &[("Ping.HttpStatus", "500")],
                &["Ping: connection refused".to_string().as_str()],
            )],
            errors: vec!["Ping: connection refused".into()],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("tests=\"1\""), "one case, not two: {out}");
        assert!(out.contains("errors=\"1\""), "{out}");
    }

    /// A row whose request failed *and* whose answer was wrong is one case with
    /// one status. The stricter JUnit schemas allow a case only one outcome,
    /// and a case counted in two totals makes every consumer's arithmetic
    /// disagree with the document it is reading.
    #[test]
    fn a_failed_request_outranks_its_wrong_answer() {
        let mut res = ReportResult {
            column_order: vec!["Ping.status".into()],
            rows: vec![failed_row(
                &["a"],
                &[
                    ("Ping.status", "500"),
                    (crate::report::compare::CORRECT_COLUMN, "incorrect"),
                ],
                &["Ping: Expected status 200 but got 500"],
            )],
            ..Default::default()
        };
        res.verdicts
            .insert((0, "Ping.status".into()), Verdict::Incorrect);
        let out = xml(&res);
        assert!(out.contains("errors=\"1\""), "{out}");
        assert!(out.contains("failures=\"0\""), "{out}");
        assert_eq!(out.matches("<failure").count(), 0, "one status only: {out}");
        // The demoted verdict is not lost, only moved.
        assert!(out.contains("<system-out>"), "{out}");
    }

    /// The `Time` intrinsic under a user's own name. The field alias is
    /// recorded per run because the name says nothing about what it holds —
    /// and a case with no `time` is a case a CI viewer cannot chart.
    #[test]
    fn a_renamed_time_field_is_still_the_cases_duration() {
        let res = ReportResult {
            column_order: vec!["Ping.took".into()],
            rows: vec![row(&["a"], &[("Ping.took", "2500")])],
            duration_columns: ["Ping.took".to_string()].into_iter().collect(),
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("time=\"2.500\""), "{out}");
    }

    /// A step can only spend its total once. Nothing stops a flow naming the
    /// `Time` intrinsic twice for the same request — under its own name and
    /// under an alias, or under two aliases — and every one of those columns
    /// holds the same milliseconds. Adding them made a case appear to have
    /// taken as many times as long as it was reported, which is a worse failure
    /// than a missing duration because the number looks plausible.
    #[test]
    fn a_request_whose_time_is_reported_twice_did_not_take_twice_as_long() {
        let res = ReportResult {
            column_order: vec![
                "Ping.Time".into(),
                "Ping.took".into(),
                "Ping.elapsed".into(),
            ],
            rows: vec![row(
                &["a"],
                &[
                    ("Ping.Time", "2500"),
                    ("Ping.took", "2500"),
                    ("Ping.elapsed", "2500"),
                ],
            )],
            duration_columns: ["Ping.took".to_string(), "Ping.elapsed".to_string()]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        let out = xml(&res);
        assert!(
            out.contains("time=\"2.500\""),
            "one request, one duration: {out}"
        );
    }

    /// The other half of the same rule: two *different* requests each spend
    /// their own time, and a row that made two calls took as long as both.
    #[test]
    fn two_requests_in_a_row_each_spend_their_own_time() {
        let res = ReportResult {
            column_order: vec!["Ping.Time".into(), "Pong.took".into()],
            rows: vec![row(&["a"], &[("Ping.Time", "1500"), ("Pong.took", "500")])],
            duration_columns: ["Pong.took".to_string()].into_iter().collect(),
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("time=\"2.000\""), "{out}");
    }

    /// `time` is a plain non-negative number in the format, and some consumers
    /// reject the whole document over one that is not. A report can hold
    /// anything in a cell — a marker, a stale value, whatever a capture
    /// produced — so the writer reads only what is actually a duration.
    #[test]
    fn a_nonsense_timing_is_no_timing() {
        let res = ReportResult {
            column_order: vec!["A.Time".into(), "B.Time".into(), "C.Time".into()],
            rows: vec![row(
                &["a"],
                &[("A.Time", "-5"), ("B.Time", "NaN"), ("C.Time", "—")],
            )],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("time=\"0.000\""), "{out}");
        assert!(
            !out.contains("NaN") || !out.contains("time=\"NaN\""),
            "{out}"
        );
    }

    /// The `ENVS` shape: one key run against several targets is several cases,
    /// and a target name is as free-form as anything else a user types.
    #[test]
    fn comparison_targets_separate_the_cases_they_belong_to() {
        let mut staging = row(&["a"], &[("Ping.status", "200")]);
        staging.target = Some("staging <1>".into());
        let mut prod = row(&["a"], &[("Ping.status", "500")]);
        prod.target = Some("prod & co".into());
        let res = ReportResult {
            column_order: vec!["Ping.status".into()],
            rows: vec![staging, prod],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("name=\"a [staging &lt;1&gt;]\""), "{out}");
        assert!(out.contains("name=\"a [prod &amp; co]\""), "{out}");
    }

    /// A cell is truncated by characters, not by bytes: slicing a multibyte
    /// character in half produces a `String` that is not valid UTF-8 text for
    /// any consumer, and the boundary is exactly where a long response body
    /// lands.
    #[test]
    fn a_long_multibyte_cell_is_cut_on_a_character_boundary() {
        let body: String = "é".repeat(MAX_CELL + 10);
        let res = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&["a"], &[("Body", &body)])],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains('…'), "the cut is marked: {out:?}");
        assert_eq!(out.matches('é').count(), MAX_CELL, "{}", out.len());
    }

    /// The time a CI viewer charts per case: every `…Time` cell the row
    /// carries, in seconds, because milliseconds is not what the format means.
    #[test]
    fn a_cases_time_is_the_rows_own_milliseconds_in_seconds() {
        let res = ReportResult {
            column_order: vec!["Ping.Time".into(), "Pong.Time".into()],
            rows: vec![row(&["a"], &[("Ping.Time", "1200"), ("Pong.Time", "300")])],
            ..Default::default()
        };
        let out = xml(&res);
        assert!(out.contains("time=\"1.500\""), "{out}");
    }
}