tarn 0.11.4

CLI-first API testing tool
Documentation
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
//! Compact one-file-per-line output format (NAZ-240).
//!
//! The compact format is a middle ground between human and llm: it shows
//! a one-line header for the run, a single line per file with a
//! pass/fail badge and aggregate counts, then expands failures inline
//! with the first failing assertion plus a `METHOD URL -> status`
//! breadcrumb. With `-v` the expanded block also shows captured values
//! for each test. With `--only-failed` every passing file is elided.
//!
//! Colors are honored when the caller did not request `no_color`. The
//! `group_failures` helper powers the trailing `HTTP 500: 3 | JSONPath
//! mismatch: 18`-style tally so operators can see failure shape at a
//! glance without scrolling the whole block.

use crate::assert::types::{FileResult, RunResult, TestResult};
use crate::report::failure::{
    group_failures, primary_failure_message, request_arrow_response, skip_cascade_summary,
    truncate_string, CAPTURE_VALUE_CAP, COMPACT_MESSAGE_CAP,
};
use crate::report::RenderOptions;
use colored::Colorize;

/// Render with default options (no filtering, no verbose captures).
pub fn render(result: &RunResult) -> String {
    render_with_options(result, RenderOptions::default())
}

/// Render respecting the caller's options. `only_failed` hides fully
/// passing files; `verbose` surfaces captured values per test; `no_color`
/// strips every ANSI escape.
pub fn render_with_options(result: &RunResult, opts: RenderOptions) -> String {
    // Centralize the "paint or not?" decision. `colored` normally makes
    // this per-call, but we want every code path in this module to
    // respect the caller's `no_color` preference uniformly.
    if opts.no_color {
        colored::control::set_override(false);
    } else {
        colored::control::unset_override();
    }

    let mut out = String::new();
    out.push_str(&render_header(result));
    out.push('\n');

    for file in &result.file_results {
        if opts.only_failed && file.passed {
            continue;
        }
        render_file(&mut out, file, opts);
    }

    let groups = group_failures(result);
    if !groups.is_empty() {
        out.push('\n');
        out.push_str(&render_group_summary(&groups));
        out.push('\n');
    }

    // Always unset the override on exit so unrelated rendering (e.g.
    // the streaming human progress reporter in the same process) keeps
    // its own color policy.
    colored::control::unset_override();
    out
}

fn render_header(result: &RunResult) -> String {
    let files = result.total_files();
    let tests: usize = result
        .file_results
        .iter()
        .map(|f| f.test_results.len())
        .sum();
    let steps_total = result.total_steps();
    let steps_passed = result.passed_steps();
    let seconds = duration_seconds(result.duration_ms);
    format!(
        "tarn: {} file{}, {} test{}, {}/{} steps passed, {}s",
        files,
        plural(files),
        tests,
        plural(tests),
        steps_passed,
        steps_total,
        seconds
    )
}

fn render_file(out: &mut String, file: &FileResult, opts: RenderOptions) {
    let total = file.total_steps();
    let passed = file.passed_steps();
    if file.passed {
        out.push_str(&format!(
            "{} {}  ({}/{})\n",
            "✓".green(),
            file.file,
            passed,
            total
        ));
    } else {
        out.push_str(&format!(
            "{} {}  ({}/{})\n",
            "✗".red(),
            file.file.bold(),
            passed,
            total
        ));
        render_file_failures(out, file, opts);
    }
}

fn render_file_failures(out: &mut String, file: &FileResult, opts: RenderOptions) {
    // Setup failures use `<setup>` as the test label so readers can
    // tell the phase apart from a real test.
    for step in &file.setup_results {
        if step.passed {
            continue;
        }
        let message = primary_failure_message(
            step,
            &file.redaction,
            &file.redacted_values,
            COMPACT_MESSAGE_CAP,
        );
        out.push_str(&format!(
            "  {} <setup> — {} — {}\n",
            "FAIL:".red().bold(),
            step.name,
            message
        ));
        out.push_str(&format!(
            "    {}\n",
            request_arrow_response(step, &file.redaction, &file.redacted_values).dimmed()
        ));
    }

    for test in &file.test_results {
        if test.passed && !opts.verbose {
            continue;
        }
        render_test_failures(out, file, test, opts);
    }

    for step in &file.teardown_results {
        if step.passed {
            continue;
        }
        let message = primary_failure_message(
            step,
            &file.redaction,
            &file.redacted_values,
            COMPACT_MESSAGE_CAP,
        );
        out.push_str(&format!(
            "  {} <teardown> — {} — {}\n",
            "FAIL:".red().bold(),
            step.name,
            message
        ));
        out.push_str(&format!(
            "    {}\n",
            request_arrow_response(step, &file.redaction, &file.redacted_values).dimmed()
        ));
    }
}

fn render_test_failures(
    out: &mut String,
    file: &FileResult,
    test: &TestResult,
    opts: RenderOptions,
) {
    let mut printed_anything = false;

    for step in &test.step_results {
        if step.passed {
            continue;
        }
        let message = primary_failure_message(
            step,
            &file.redaction,
            &file.redacted_values,
            COMPACT_MESSAGE_CAP,
        );
        out.push_str(&format!(
            "  {} {} — {} — {}\n",
            "FAIL:".red().bold(),
            test.name,
            step.name,
            message
        ));
        out.push_str(&format!(
            "    {}\n",
            request_arrow_response(step, &file.redaction, &file.redacted_values).dimmed()
        ));
        printed_anything = true;
    }

    // Cascade summary: one line per failed-capture dependency group so
    // readers see how much fallout was suppressed.
    for (capture, count) in skip_cascade_summary(test) {
        out.push_str(&format!(
            "    {} {} step{} (depended on failed capture '{}')\n",
            "skipped:".yellow(),
            count,
            plural(count),
            capture
        ));
        printed_anything = true;
    }

    // Verbose: render every captured value (keys are sorted for
    // deterministic output) with a short preview.
    if opts.verbose && !test.captures.is_empty() {
        // Ensure the verbose block is scoped to a test that produced
        // visible content above — we don't want captures on a silent
        // pass to create orphan output unless the caller opts in.
        if printed_anything || test.passed {
            out.push_str(&format!("    {} ({})\n", "captures".dimmed(), test.name));
            let mut keys: Vec<&String> = test.captures.keys().collect();
            keys.sort();
            for key in keys {
                let rendered =
                    serde_json::to_string(&test.captures[key]).unwrap_or_else(|_| "null".into());
                out.push_str(&format!(
                    "      {} = {}\n",
                    key,
                    truncate_string(&rendered, CAPTURE_VALUE_CAP)
                ));
            }
        }
    }
}

fn render_group_summary(groups: &[(String, usize)]) -> String {
    groups
        .iter()
        .map(|(label, count)| format!("{}: {}", label, count))
        .collect::<Vec<_>>()
        .join(" | ")
}

fn duration_seconds(ms: u64) -> String {
    let seconds = ms as f64 / 1000.0;
    if seconds >= 10.0 {
        format!("{:.0}", seconds)
    } else {
        format!("{:.1}", seconds)
    }
}

fn plural(n: usize) -> &'static str {
    if n == 1 {
        ""
    } else {
        "s"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assert::types::*;
    use crate::model::RedactionConfig;
    use serde_json::json;
    use std::collections::HashMap;

    fn strip_ansi(s: &str) -> String {
        // `colored` writes ANSI escape sequences; strip them with a
        // minimal regex so assertions stay legible.
        let re = regex::Regex::new(r"\x1b\[[0-9;]*[A-Za-z]").unwrap();
        re.replace_all(s, "").into_owned()
    }

    fn base_passed_step(name: &str) -> StepResult {
        StepResult {
            name: name.into(),
            description: None,
            debug: false,
            passed: true,
            duration_ms: 20,
            assertion_results: vec![AssertionResult::pass("status", "200", "200")],
            request_info: None,
            response_info: None,
            error_category: None,
            response_status: Some(200),
            response_summary: None,
            captures_set: vec![],
            location: None,
            response_shape_mismatch: None,
        }
    }

    fn failing_step(name: &str, status: u16) -> StepResult {
        StepResult {
            name: name.into(),
            description: None,
            debug: false,
            passed: false,
            duration_ms: 30,
            assertion_results: vec![AssertionResult::fail(
                "status",
                "200",
                status.to_string(),
                format!("Expected 200, got {}", status),
            )],
            request_info: Some(RequestInfo {
                method: "GET".into(),
                url: "/foo".into(),
                headers: HashMap::new(),
                body: None,
                multipart: None,
            }),
            response_info: Some(ResponseInfo {
                status,
                headers: HashMap::new(),
                body: Some(json!({"err": "boom"})),
            }),
            error_category: Some(FailureCategory::AssertionFailed),
            response_status: Some(status),
            response_summary: None,
            captures_set: vec![],
            location: None,
            response_shape_mismatch: None,
        }
    }

    fn build_run(files: Vec<FileResult>) -> RunResult {
        let duration_ms = files.iter().map(|f| f.duration_ms).sum();
        RunResult {
            file_results: files,
            duration_ms,
        }
    }

    fn file_with(name: &str, passed: bool, steps: Vec<StepResult>) -> FileResult {
        let total_steps = steps.len();
        let passed_steps = steps.iter().filter(|s| s.passed).count();
        let _ = total_steps;
        let _ = passed_steps;
        FileResult {
            file: name.into(),
            name: name.into(),
            passed,
            duration_ms: 10,
            redaction: RedactionConfig::default(),
            redacted_values: vec![],
            setup_results: vec![],
            test_results: vec![TestResult {
                name: "t".into(),
                description: None,
                passed,
                duration_ms: 10,
                step_results: steps,
                captures: HashMap::new(),
            }],
            teardown_results: vec![],
        }
    }

    #[test]
    fn header_has_counts_and_duration() {
        let run = build_run(vec![file_with(
            "a.tarn.yaml",
            true,
            vec![base_passed_step("s1"), base_passed_step("s2")],
        )]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.starts_with("tarn: 1 file, 1 test, 2/2 steps passed,"));
    }

    #[test]
    fn passing_file_renders_checkmark_line() {
        let run = build_run(vec![file_with(
            "a.tarn.yaml",
            true,
            vec![base_passed_step("s1")],
        )]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.contains("\u{2713} a.tarn.yaml  (1/1)"));
    }

    #[test]
    fn only_failed_hides_passing_files() {
        let run = build_run(vec![
            file_with("a.tarn.yaml", true, vec![base_passed_step("s1")]),
            file_with("b.tarn.yaml", false, vec![failing_step("bad", 500)]),
        ]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                only_failed: true,
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(!out.contains("a.tarn.yaml"));
        assert!(out.contains("b.tarn.yaml"));
    }

    #[test]
    fn failed_file_shows_fail_line_and_arrow() {
        let run = build_run(vec![file_with(
            "b.tarn.yaml",
            false,
            vec![failing_step("bad", 500)],
        )]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.contains("\u{2717} b.tarn.yaml  (0/1)"));
        assert!(out.contains("FAIL: t \u{2014} bad \u{2014} Expected 200, got 500"));
        assert!(out.contains("GET /foo -> 500"));
    }

    #[test]
    fn group_summary_lists_categories_by_count() {
        let run = build_run(vec![file_with(
            "b.tarn.yaml",
            false,
            vec![
                failing_step("a", 500),
                failing_step("b", 500),
                failing_step("c", 404),
            ],
        )]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.contains("HTTP 500: 2 | HTTP 404: 1"));
    }

    #[test]
    fn verbose_shows_captures_for_test() {
        let mut tr = TestResult {
            name: "cap_test".into(),
            description: None,
            passed: false,
            duration_ms: 10,
            step_results: vec![failing_step("login", 500)],
            captures: HashMap::new(),
        };
        tr.captures.insert("token".into(), json!("abc"));
        tr.captures.insert("user_id".into(), json!(42));
        let file = FileResult {
            file: "b.tarn.yaml".into(),
            name: "b".into(),
            passed: false,
            duration_ms: 10,
            redaction: RedactionConfig::default(),
            redacted_values: vec![],
            setup_results: vec![],
            test_results: vec![tr],
            teardown_results: vec![],
        };
        let run = build_run(vec![file]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                verbose: true,
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.contains("captures (cap_test)"));
        assert!(out.contains("token = \"abc\""));
        assert!(out.contains("user_id = 42"));
    }

    #[test]
    fn long_capture_value_is_truncated() {
        let mut tr = TestResult {
            name: "cap".into(),
            description: None,
            passed: false,
            duration_ms: 10,
            step_results: vec![failing_step("login", 500)],
            captures: HashMap::new(),
        };
        tr.captures.insert("payload".into(), json!("a".repeat(200)));
        let file = FileResult {
            file: "b.tarn.yaml".into(),
            name: "b".into(),
            passed: false,
            duration_ms: 10,
            redaction: RedactionConfig::default(),
            redacted_values: vec![],
            setup_results: vec![],
            test_results: vec![tr],
            teardown_results: vec![],
        };
        let run = build_run(vec![file]);
        let out = strip_ansi(&render_with_options(
            &run,
            RenderOptions {
                verbose: true,
                no_color: true,
                ..RenderOptions::default()
            },
        ));
        assert!(out.contains("payload = "));
        assert!(out.contains("..."));
        // The line should not contain the full 200 'a' string uncut.
        assert!(!out.contains(&"a".repeat(150)));
    }
}