paperboy 0.8.1

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
//! What a row's drill-down holds: the things too big for a grid cell.
//!
//! The grid answers "what happened across the run"; the drill-down answers
//! "what happened in *this* row": which compared fields differed from the
//! baseline, its pictures at full size, its `DETAIL` columns in full, and,
//! when the run kept the baseline row, a field-by-field diff of whichever of
//! those columns are JSON on both sides.
//!
//! Deciding *what* goes in the panel lives here rather than in a renderer,
//! because more than one renderer shows it: the interactive HTML export and the
//! in-app results views. The selection rules are fiddly (a `DETAIL` column with
//! an empty value is not worth a heading; a diff of identical JSON is not worth
//! a table; a row with none of them should not offer an expander at all)
//! and two copies of them would drift.

use super::jsondiff::FieldDiff;
use super::model::{ImageData, OutputColumn, ReportResult, Verdict};

/// Split a run's columns into the ones the grid shows and the ones the
/// drill-down does.
///
/// A `DETAIL` column leaves the grid, *unless* every column is one: an empty
/// grid helps nobody, so the flag is ignored rather than obeyed into an
/// unreadable report. Shared so the in-app grid and the export agree about
/// which columns are where — a column that vanished from one and not the other
/// would look like a bug in whichever you noticed second.
pub fn split_columns(all: &[OutputColumn]) -> (Vec<OutputColumn>, Vec<&OutputColumn>) {
    let grid: Vec<OutputColumn> = if all.iter().all(|c| c.detail) {
        all.to_vec()
    } else {
        all.iter().filter(|c| !c.detail).cloned().collect()
    };
    (grid, all.iter().filter(|c| c.detail).collect())
}

/// One section of a row's drill-down panel, in the order the panel shows them.
#[derive(Debug, Clone, PartialEq)]
pub enum DetailSection<'a> {
    /// A picture, shown larger than its grid cell can manage.
    Image {
        header: &'a str,
        image: &'a ImageData,
        /// The cell's text — the path or URL the picture was resolved from,
        /// which is what a reader hovers to find out where it came from.
        value: String,
    },
    /// A `DETAIL` column's full value, pretty-printed when it is JSON.
    Text {
        header: &'a str,
        value: String,
        /// How this cell scored, when its column declares a `TRUTH`, and what
        /// it was scored against. The grid tints such a cell by whether it is
        /// *right*; the drill-down is where the same cell is actually read, so
        /// it has to say the same thing — a full value read out of a panel
        /// that stayed silent about it would be taken for a value nobody
        /// checked. [`Verdict::Untested`] is `None`: an unlabelled row must
        /// never borrow the appearance of one that passed.
        verdict: Option<(Verdict, String)>,
    },
    /// A `DETAIL` column's fields against the baseline's. Unchanged fields are
    /// kept: the reader can then find the field they care about whether or not
    /// it moved, and the *highlight* rather than the omission points at the
    /// difference.
    Diff {
        header: &'a str,
        fields: Vec<FieldDiff>,
    },
    /// Every compared field that differed between the baseline and the
    /// comparison, read from the row's `Result` cell.
    ///
    /// The `Result` cell is one line of JSON that answers "what changed?" but
    /// is too long to read in a grid cell. This section shows the same answer
    /// as a table. A field whose value is JSON on both sides is broken down to
    /// the leaves that moved (`body.checks.face`), so a changed 4 KB response
    /// shows the one number that differs rather than two copies of the body.
    /// Only differing entries are listed, because that is all the `Result`
    /// cell records.
    Comparison {
        /// The environment names the two sides ran against.
        baseline: String,
        comparison: String,
        fields: Vec<FieldDiff>,
    },
}

/// Everything row `r` has to show in its drill-down, or an empty vector when it
/// has nothing — an expander that opens onto an empty panel teaches the reader
/// to stop clicking.
///
/// `all_columns` is every column the run produced, `detail_columns` those
/// flagged `DETAIL`. Pictures are collected from `all_columns`, deliberately: a
/// picture is worth showing larger whether or not its column is `DETAIL`, and
/// the grid cell it also appears in is a thumbnail.
pub fn sections<'a>(
    result: &'a ReportResult,
    r: usize,
    all_columns: &'a [OutputColumn],
    detail_columns: &[&'a OutputColumn],
) -> Vec<DetailSection<'a>> {
    let Some(row) = result.rows.get(r) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    // First, because it says why the row is a difference, which is usually the
    // reason a comparison row gets opened.
    if let Some(cmp) = comparison_section(row) {
        out.push(cmp);
    }
    for c in all_columns {
        if let Some(image) = result.images.get(&(r, c.header.clone())) {
            out.push(DetailSection::Image {
                header: &c.header,
                image,
                value: c.value(row, &result.no_match_marker),
            });
        }
    }
    for c in detail_columns {
        let value = c.value(row, &result.no_match_marker);
        if !value.trim().is_empty() {
            out.push(DetailSection::Text {
                header: &c.header,
                value: pretty_json(&value),
                verdict: verdict_for(result, r, &c.header),
            });
        }
    }
    if let Some(b) = result.baseline_rows.get(&r) {
        for c in detail_columns {
            let was = c.value(b, &result.no_match_marker);
            let now = c.value(row, &result.no_match_marker);
            let Some(fields) = super::jsondiff::diff_texts(&was, &now) else {
                continue;
            };
            if fields.iter().any(|f| f.differs()) {
                out.push(DetailSection::Diff {
                    header: &c.header,
                    fields,
                });
            }
        }
    }
    out
}

/// The [`DetailSection::Comparison`] for `row`, or `None` when its `Result`
/// is not a difference (a match, `no baseline`, a dry run, or no comparison
/// at all).
///
/// [`super::compare::compute_result`] writes a difference as
/// `{"<env> (baseline)": {field: value…}, "<env>": {field: value…}}`. This
/// parses it back into that shape instead of keeping the baseline row around.
/// That works for every comparison, including one against a saved snapshot,
/// and costs a finished result nothing extra to hold.
pub fn comparison_section(row: &super::model::ReportRow) -> Option<DetailSection<'static>> {
    use serde_json::Value;
    let cell = row.cells.get(super::compare::RESULT_COLUMN)?;
    let Value::Object(sides) = serde_json::from_str::<Value>(cell.trim()).ok()? else {
        return None;
    };
    let (base_key, base) = sides
        .iter()
        .find(|(k, _)| k.ends_with(" (baseline)"))
        .and_then(|(k, v)| Some((k, v.as_object()?)))?;
    let (cand_key, cand) = sides
        .iter()
        .find(|(k, _)| *k != base_key)
        .and_then(|(k, v)| Some((k, v.as_object()?)))?;
    let text = |v: &Value| match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    let mut seen = std::collections::HashSet::new();
    let mut fields = Vec::new();
    for name in base.keys().chain(cand.keys()) {
        if !seen.insert(name) {
            continue;
        }
        let (b, c) = (base.get(name), cand.get(name));
        // A structured value on both sides is broken down to the leaves that
        // moved; a scalar, or a value that changed shape, is one line.
        let structured = |v: Option<&Value>| v.is_some_and(|v| v.is_object() || v.is_array());
        if structured(b) && structured(c) {
            let leaves: Vec<FieldDiff> = super::jsondiff::diff(b.unwrap(), c.unwrap())
                .into_iter()
                .filter(FieldDiff::differs)
                .map(|f| FieldDiff {
                    path: if f.path.is_empty() {
                        name.clone()
                    } else if f.path.starts_with('[') {
                        format!("{name}{}", f.path)
                    } else {
                        format!("{name}.{}", f.path)
                    },
                    ..f
                })
                .collect();
            if !leaves.is_empty() {
                fields.extend(leaves);
                continue;
            }
        }
        fields.push(FieldDiff {
            path: name.clone(),
            baseline: b.map(text),
            candidate: c.map(text),
        });
    }
    if fields.is_empty() {
        return None;
    }
    Some(DetailSection::Comparison {
        baseline: base_key.trim_end_matches(" (baseline)").to_string(),
        comparison: cand_key.clone(),
        fields,
    })
}

/// How a ground-truthed cell scored and what it was scored against, or `None`
/// when its column declares no `TRUTH` or the row wasn't labelled.
fn verdict_for(result: &ReportResult, r: usize, header: &str) -> Option<(Verdict, String)> {
    let key = (r, header.to_string());
    match result.verdicts.get(&key)? {
        Verdict::Untested => None,
        v => Some((*v, result.truths.get(&key).cloned().unwrap_or_default())),
    }
}

/// What a ground-truthed detail section says beside its heading: the verdict,
/// and — when it is wrong — what was expected instead, which is otherwise only
/// findable by going back to the grid or reading the script.
pub fn verdict_label(v: Verdict, truth: &str) -> String {
    match (v, truth.trim()) {
        (Verdict::Incorrect, t) if !t.is_empty() => {
            format!("{} \u{2014} expected {t}", v.as_str())
        }
        _ => v.as_str().to_string(),
    }
}

/// `text` pretty-printed if it is JSON, and unchanged if it isn't. A detail
/// column is very often a whole response body, which arrives on one line.
pub fn pretty_json(text: &str) -> String {
    serde_json::from_str::<serde_json::Value>(text.trim())
        .ok()
        .and_then(|v| serde_json::to_string_pretty(&v).ok())
        .unwrap_or_else(|| text.to_string())
}

#[cfg(test)]
mod tests {
    /// Every column being `DETAIL` would leave an empty grid, so the flag is
    /// ignored rather than obeyed off a cliff.
    #[test]
    fn an_all_detail_run_keeps_its_grid() {
        let mut a = super::tests::col("A");
        let mut b = super::tests::col("B");
        a.detail = true;
        b.detail = true;
        let cols = [a, b];
        let (grid, detail) = super::split_columns(&cols);
        assert_eq!(grid.len(), 2, "the grid keeps every column");
        assert_eq!(detail.len(), 2, "and the panel still offers them in full");
    }

    /// The ordinary case: a `DETAIL` column leaves the grid for the panel.
    #[test]
    fn a_detail_column_leaves_the_grid() {
        let a = super::tests::col("A");
        let mut b = super::tests::col("Body");
        b.detail = true;
        let cols = [a, b];
        let (grid, detail) = super::split_columns(&cols);
        assert_eq!(grid.len(), 1, "only the plain column is in the grid");
        assert_eq!(detail.len(), 1);
        assert_eq!(detail[0].header, "Body");
    }

    use super::*;
    use crate::report::model::{ReportRow, StatKind};

    fn col(header: &str) -> OutputColumn {
        OutputColumn {
            header: header.to_string(),
            sources: vec![header.to_string()],
            stats: Vec::<StatKind>::new(),
            image: None,
            truth: None,
            detail: false,
        }
    }

    fn row(pairs: &[(&str, &str)]) -> ReportRow {
        let mut r = ReportRow::default();
        for (k, v) in pairs {
            r.cells.insert(k.to_string(), v.to_string());
        }
        r
    }

    /// A row whose comparison differed opens on what differed: each changed
    /// field once, with a nested value broken down to the leaves that moved.
    #[test]
    fn a_differing_comparison_lists_the_fields_that_moved() {
        let cell = r#"{"prod (baseline)":{"status":"ok","body":{"a":1,"b":[1,2]}},"staging":{"status":"err","body":{"a":1,"b":[1,3]}}}"#;
        let result = ReportResult {
            column_order: vec!["Name".into()],
            rows: vec![row(&[
                ("Name", "x"),
                (crate::report::compare::RESULT_COLUMN, cell),
            ])],
            ..Default::default()
        };
        let cols = [col("Name")];
        let got = sections(&result, 0, &cols, &[]);
        let Some(DetailSection::Comparison {
            baseline,
            comparison,
            fields,
        }) = got.first()
        else {
            panic!("the comparison leads the panel: {got:?}");
        };
        assert_eq!(
            (baseline.as_str(), comparison.as_str()),
            ("prod", "staging")
        );
        let paths: Vec<&str> = fields.iter().map(|f| f.path.as_str()).collect();
        assert!(paths.contains(&"status"), "{paths:?}");
        assert!(
            paths.contains(&"body.b[1]"),
            "only the moved leaf: {paths:?}"
        );
        assert!(!paths.iter().any(|p| p.starts_with("body.a")), "{paths:?}");
    }

    /// A row that matched its baseline has nothing to compare.
    #[test]
    fn a_matching_comparison_adds_no_section() {
        let result = ReportResult {
            column_order: vec!["Name".into()],
            rows: vec![row(&[
                ("Name", "x"),
                (
                    crate::report::compare::RESULT_COLUMN,
                    crate::report::compare::MATCH,
                ),
            ])],
            ..Default::default()
        };
        assert!(sections(&result, 0, &[col("Name")], &[]).is_empty());
    }

    /// A row with nothing worth drilling into gets no sections, so no renderer
    /// offers an expander onto an empty panel.
    #[test]
    fn an_ordinary_row_has_nothing_to_drill_into() {
        let cols = vec![col("Name")];
        let result = ReportResult {
            column_order: vec!["Name".into()],
            rows: vec![row(&[("Name", "a")])],
            ..Default::default()
        };
        assert!(sections(&result, 0, &cols, &[]).is_empty());
    }

    /// A `DETAIL` column whose value is blank is not worth a heading -- the
    /// panel would be a title over nothing.
    #[test]
    fn a_blank_detail_column_is_left_out() {
        let cols = vec![col("Body")];
        let detail: Vec<&OutputColumn> = cols.iter().collect();
        let result = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&[("Body", "   ")])],
            ..Default::default()
        };
        assert!(sections(&result, 0, &cols, &detail).is_empty());
    }

    /// The panel leads with pictures, then the detail text: the picture is what
    /// the reader opened the row to see.
    #[test]
    fn pictures_come_before_the_detail_text() {
        let cols = vec![col("Frame"), col("Body")];
        let detail = vec![&cols[1]];
        let mut result = ReportResult {
            column_order: vec!["Frame".into(), "Body".into()],
            rows: vec![row(&[("Frame", "shots/a.png"), ("Body", "{\"a\":1}")])],
            ..Default::default()
        };
        result.images.insert(
            (0, "Frame".to_string()),
            ImageData {
                bytes: crate::report::image::tests::png_1x1(),
                mime: "image/png".to_string(),
                natural: (1, 1),
            },
        );
        let got = sections(&result, 0, &cols, &detail);
        assert!(
            matches!(got[0], DetailSection::Image { header, .. } if header == "Frame"),
            "picture first: {got:?}"
        );
        match &got[1] {
            DetailSection::Text { header, value, .. } => {
                assert_eq!(*header, "Body");
                assert!(value.contains('\n'), "JSON is pretty-printed: {value}");
            }
            other => panic!("expected the detail text second, got {other:?}"),
        }
    }

    /// A `DETAIL` column that declares a `TRUTH` carries its verdict into the
    /// panel: the grid tints such a cell by whether it is right, and the panel
    /// is where the value is actually read.
    #[test]
    fn a_ground_truthed_detail_column_carries_its_verdict() {
        let mut c = col("Body");
        c.detail = true;
        c.truth = Some("Low Risk".to_string());
        let cols = vec![c];
        let mut result = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&[("Body", "High Risk")])],
            ..Default::default()
        };
        result
            .verdicts
            .insert((0, "Body".into()), Verdict::Incorrect);
        result
            .truths
            .insert((0, "Body".into()), "Low Risk".to_string());
        let (_, detail) = split_columns(&cols);
        let got = sections(&result, 0, &cols, &detail);
        let DetailSection::Text { verdict, .. } = &got[0] else {
            panic!("expected the detail text, got {got:?}");
        };
        assert_eq!(
            verdict.as_ref().map(|(v, t)| (*v, t.as_str())),
            Some((Verdict::Incorrect, "Low Risk")),
            "the verdict and what it was scored against travel together"
        );
        // What the reader is shown: the verdict, and the answer that was
        // wanted — otherwise the only way to find it is to read the script.
        assert_eq!(
            verdict_label(Verdict::Incorrect, "Low Risk"),
            "incorrect \u{2014} expected Low Risk"
        );
        assert_eq!(
            verdict_label(Verdict::Correct, "Low Risk"),
            "correct",
            "a right answer doesn't repeat the answer back"
        );
    }

    /// An unlabelled row is not a pass: it carries no verdict at all, so no
    /// renderer can paint it like one.
    #[test]
    fn an_unlabelled_row_carries_no_verdict() {
        let mut c = col("Body");
        c.detail = true;
        let cols = vec![c];
        let mut result = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&[("Body", "High Risk")])],
            ..Default::default()
        };
        result
            .verdicts
            .insert((0, "Body".into()), Verdict::Untested);
        let (_, detail) = split_columns(&cols);
        let got = sections(&result, 0, &cols, &detail);
        assert!(
            matches!(&got[0], DetailSection::Text { verdict: None, .. }),
            "an untested cell says nothing: {got:?}"
        );
    }

    /// A picture is worth showing larger whether or not its column is `DETAIL`,
    /// so the panel collects pictures from every column.
    #[test]
    fn a_grid_picture_still_appears_in_the_panel() {
        let cols = vec![col("Frame")];
        let mut result = ReportResult {
            column_order: vec!["Frame".into()],
            rows: vec![row(&[("Frame", "shots/a.png")])],
            ..Default::default()
        };
        result.images.insert(
            (0, "Frame".to_string()),
            ImageData {
                bytes: crate::report::image::tests::png_1x1(),
                mime: "image/png".to_string(),
                natural: (1, 1),
            },
        );
        // No DETAIL columns at all, and the picture is still offered.
        assert_eq!(sections(&result, 0, &cols, &[]).len(), 1);
    }

    /// A diff of two identical bodies says nothing, so it is not a section --
    /// otherwise every unchanged row would sprout a table of unchanged fields.
    #[test]
    fn an_unchanged_body_produces_no_diff_section() {
        let cols = vec![col("Body")];
        let detail: Vec<&OutputColumn> = cols.iter().collect();
        let mut result = ReportResult {
            column_order: vec!["Body".into()],
            rows: vec![row(&[("Body", "{\"a\":1}")])],
            ..Default::default()
        };
        result
            .baseline_rows
            .insert(0, row(&[("Body", "{\"a\":1}")]));
        let got = sections(&result, 0, &cols, &detail);
        assert!(
            got.iter().all(|s| !matches!(s, DetailSection::Diff { .. })),
            "identical bodies differ in nothing: {got:?}"
        );

        result
            .baseline_rows
            .insert(0, row(&[("Body", "{\"a\":2}")]));
        let got = sections(&result, 0, &cols, &detail);
        assert!(
            got.iter().any(|s| matches!(s, DetailSection::Diff { .. })),
            "but a changed one does: {got:?}"
        );
    }
}