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
//! Reverse direction of `report/json.rs`: parse a previously-emitted
//! Tarn JSON report back into a [`RunResult`] so other formatters can
//! re-render it.
//!
//! Used by `tarn summary <run.json>` to produce compact/llm output
//! from a stored report without re-running the tests. Only the fields
//! the downstream formatters care about are rehydrated; fields that
//! would require re-executing HTTP requests (raw response bytes,
//! timings beyond `duration_ms`) are approximated from what the JSON
//! already contains.

use crate::assert::types::{
    AssertionResult, FailureCategory, FileResult, RequestInfo, ResponseInfo, RunResult, StepResult,
    TestResult,
};
use crate::model::{Location, RedactionConfig};
use serde_json::Value;
use std::collections::HashMap;

#[derive(Debug)]
pub struct ParseError(pub String);

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for ParseError {}

/// Parse a JSON report into a `RunResult`. Returns `Err` when the
/// report isn't shaped like a tarn v1 report (wrong top-level type,
/// missing `files` array, etc.).
pub fn parse(input: &str) -> Result<RunResult, ParseError> {
    let value: Value =
        serde_json::from_str(input).map_err(|e| ParseError(format!("invalid JSON: {}", e)))?;

    let obj = value
        .as_object()
        .ok_or_else(|| ParseError("expected top-level JSON object".into()))?;

    let files_value = obj
        .get("files")
        .ok_or_else(|| ParseError("missing `files` array".into()))?;
    let files_array = files_value
        .as_array()
        .ok_or_else(|| ParseError("`files` must be an array".into()))?;

    let mut file_results = Vec::with_capacity(files_array.len());
    for (idx, file_value) in files_array.iter().enumerate() {
        let parsed =
            parse_file(file_value).map_err(|e| ParseError(format!("files[{}]: {}", idx, e.0)))?;
        file_results.push(parsed);
    }

    let duration_ms = obj.get("duration_ms").and_then(Value::as_u64).unwrap_or(0);

    Ok(RunResult {
        file_results,
        duration_ms,
    })
}

fn parse_file(value: &Value) -> Result<FileResult, ParseError> {
    let obj = value
        .as_object()
        .ok_or_else(|| ParseError("expected file object".into()))?;

    let file = string_field(obj, "file").unwrap_or_default();
    let name = string_field(obj, "name").unwrap_or_else(|| file.clone());
    let passed = status_to_passed(obj.get("status"));
    let duration_ms = obj.get("duration_ms").and_then(Value::as_u64).unwrap_or(0);

    let setup_results = parse_step_array(obj.get("setup"))?;
    let teardown_results = parse_step_array(obj.get("teardown"))?;
    let test_results = match obj.get("tests").and_then(Value::as_array) {
        Some(tests) => tests
            .iter()
            .map(parse_test)
            .collect::<Result<Vec<_>, _>>()?,
        None => Vec::new(),
    };

    Ok(FileResult {
        file,
        name,
        passed,
        duration_ms,
        redaction: RedactionConfig::default(),
        redacted_values: Vec::new(),
        setup_results,
        test_results,
        teardown_results,
    })
}

fn parse_test(value: &Value) -> Result<TestResult, ParseError> {
    let obj = value
        .as_object()
        .ok_or_else(|| ParseError("expected test object".into()))?;

    let name = string_field(obj, "name").unwrap_or_default();
    let description = string_field(obj, "description");
    let passed = status_to_passed(obj.get("status"));
    let duration_ms = obj.get("duration_ms").and_then(Value::as_u64).unwrap_or(0);

    let captures: HashMap<String, Value> = obj
        .get("captures")
        .and_then(Value::as_object)
        .map(|map| map.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
        .unwrap_or_default();

    let step_results = parse_step_array(obj.get("steps"))?;

    Ok(TestResult {
        name,
        description,
        passed,
        duration_ms,
        step_results,
        captures,
    })
}

fn parse_step_array(value: Option<&Value>) -> Result<Vec<StepResult>, ParseError> {
    match value.and_then(Value::as_array) {
        Some(array) => array.iter().map(parse_step).collect(),
        None => Ok(Vec::new()),
    }
}

fn parse_step(value: &Value) -> Result<StepResult, ParseError> {
    let obj = value
        .as_object()
        .ok_or_else(|| ParseError("expected step object".into()))?;

    let name = string_field(obj, "name").unwrap_or_default();
    let description = string_field(obj, "description");
    let passed = status_to_passed(obj.get("status"));
    let duration_ms = obj.get("duration_ms").and_then(Value::as_u64).unwrap_or(0);
    let response_status = obj
        .get("response_status")
        .and_then(Value::as_u64)
        .map(|n| n as u16);
    let response_summary = string_field(obj, "response_summary");
    let captures_set = obj
        .get("captures_set")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(Value::as_str)
                .map(String::from)
                .collect()
        })
        .unwrap_or_default();

    let assertion_results = obj
        .get("assertions")
        .and_then(Value::as_object)
        .and_then(|a| a.get("details"))
        .and_then(Value::as_array)
        .map(|details| {
            details
                .iter()
                .map(parse_assertion)
                .collect::<Result<Vec<_>, _>>()
        })
        .transpose()?
        .unwrap_or_default();

    let request_info = obj.get("request").and_then(parse_request);
    let response_info = obj.get("response").and_then(parse_response);

    let error_category = obj
        .get("failure_category")
        .and_then(Value::as_str)
        .and_then(parse_failure_category);

    let location = obj.get("location").and_then(parse_location);

    Ok(StepResult {
        name,
        description,
        debug: false,
        passed,
        duration_ms,
        assertion_results,
        request_info,
        response_info,
        error_category,
        response_status,
        response_summary,
        captures_set,
        location,
        response_shape_mismatch: None,
    })
}

fn parse_assertion(value: &Value) -> Result<AssertionResult, ParseError> {
    let obj = value
        .as_object()
        .ok_or_else(|| ParseError("expected assertion object".into()))?;
    let assertion = string_field(obj, "assertion").unwrap_or_default();
    let passed = obj.get("passed").and_then(Value::as_bool).unwrap_or(false);
    let expected = string_field(obj, "expected").unwrap_or_default();
    let actual = string_field(obj, "actual").unwrap_or_default();
    let message = string_field(obj, "message").unwrap_or_default();
    let diff = string_field(obj, "diff");
    let location = obj.get("location").and_then(parse_location);

    Ok(AssertionResult {
        assertion,
        passed,
        expected,
        actual,
        message,
        diff,
        location,
        // Rehydration from JSON doesn't need to carry the shape hint —
        // the lifted copy on StepResult is authoritative, and parsers
        // of the serialized artifact already read it from there.
        response_shape_mismatch: None,
    })
}

fn parse_request(value: &Value) -> Option<RequestInfo> {
    let obj = value.as_object()?;
    let method = string_field(obj, "method")?;
    let url = string_field(obj, "url")?;
    let headers = parse_headers(obj.get("headers"));
    let body = obj.get("body").cloned().filter(|v| !v.is_null());
    Some(RequestInfo {
        method,
        url,
        headers,
        body,
        multipart: None,
    })
}

fn parse_response(value: &Value) -> Option<ResponseInfo> {
    let obj = value.as_object()?;
    let status = obj.get("status").and_then(Value::as_u64)? as u16;
    let headers = parse_headers(obj.get("headers"));
    let body = obj.get("body").cloned().filter(|v| !v.is_null());
    Some(ResponseInfo {
        status,
        headers,
        body,
    })
}

fn parse_headers(value: Option<&Value>) -> HashMap<String, String> {
    let Some(Value::Object(map)) = value else {
        return HashMap::new();
    };
    map.iter()
        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
        .collect()
}

fn parse_location(value: &Value) -> Option<Location> {
    let obj = value.as_object()?;
    Some(Location {
        file: string_field(obj, "file")?,
        line: obj.get("line").and_then(Value::as_u64)? as usize,
        column: obj.get("column").and_then(Value::as_u64)? as usize,
    })
}

fn parse_failure_category(s: &str) -> Option<FailureCategory> {
    Some(match s {
        "assertion_failed" => FailureCategory::AssertionFailed,
        "connection_error" => FailureCategory::ConnectionError,
        "timeout" => FailureCategory::Timeout,
        "parse_error" => FailureCategory::ParseError,
        "capture_error" => FailureCategory::CaptureError,
        "unresolved_template" => FailureCategory::UnresolvedTemplate,
        "response_shape_mismatch" => FailureCategory::ResponseShapeMismatch,
        "skipped_due_to_failed_capture" => FailureCategory::SkippedDueToFailedCapture,
        "skipped_due_to_fail_fast" => FailureCategory::SkippedDueToFailFast,
        "skipped_by_condition" => FailureCategory::SkippedByCondition,
        _ => return None,
    })
}

fn status_to_passed(value: Option<&Value>) -> bool {
    matches!(value.and_then(Value::as_str), Some("PASSED"))
}

fn string_field(obj: &serde_json::Map<String, Value>, name: &str) -> Option<String> {
    obj.get(name).and_then(Value::as_str).map(|s| s.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::json::render;

    fn build_run() -> RunResult {
        let mut tr = TestResult {
            name: "t1".into(),
            description: Some("desc".into()),
            passed: false,
            duration_ms: 100,
            step_results: vec![StepResult {
                name: "bad".into(),
                description: None,
                debug: false,
                passed: false,
                duration_ms: 50,
                assertion_results: vec![AssertionResult::fail(
                    "status",
                    "200",
                    "500",
                    "Expected 200, got 500",
                )],
                request_info: Some(RequestInfo {
                    method: "GET".into(),
                    url: "/foo".into(),
                    headers: HashMap::new(),
                    body: None,
                    multipart: None,
                }),
                response_info: Some(ResponseInfo {
                    status: 500,
                    headers: HashMap::new(),
                    body: Some(serde_json::json!({"err": "x"})),
                }),
                error_category: Some(FailureCategory::AssertionFailed),
                response_status: Some(500),
                response_summary: None,
                captures_set: vec!["id".into()],
                location: None,
                response_shape_mismatch: None,
            }],
            captures: HashMap::new(),
        };
        tr.captures.insert("token".into(), serde_json::json!("abc"));

        RunResult {
            duration_ms: 200,
            file_results: vec![FileResult {
                file: "x.tarn.yaml".into(),
                name: "x".into(),
                passed: false,
                duration_ms: 200,
                redaction: RedactionConfig::default(),
                redacted_values: vec![],
                setup_results: vec![],
                test_results: vec![tr],
                teardown_results: vec![],
            }],
        }
    }

    #[test]
    fn round_trip_preserves_fail_status_and_duration() {
        let run = build_run();
        let json = render(&run);
        let parsed = parse(&json).unwrap();
        assert_eq!(parsed.duration_ms, run.duration_ms);
        assert_eq!(parsed.total_files(), 1);
        assert_eq!(parsed.failed_steps(), 1);
        assert_eq!(parsed.passed_steps(), 0);
    }

    #[test]
    fn round_trip_preserves_assertion_and_request() {
        let run = build_run();
        let json = render(&run);
        let parsed = parse(&json).unwrap();
        let step = &parsed.file_results[0].test_results[0].step_results[0];
        assert_eq!(step.assertion_results.len(), 1);
        assert_eq!(step.assertion_results[0].assertion, "status");
        assert_eq!(step.request_info.as_ref().unwrap().url, "/foo");
        assert_eq!(step.response_info.as_ref().unwrap().status, 500);
        assert_eq!(step.response_status, Some(500));
        assert_eq!(step.error_category, Some(FailureCategory::AssertionFailed));
    }

    #[test]
    fn round_trip_preserves_captures_and_captures_set() {
        let run = build_run();
        let json = render(&run);
        let parsed = parse(&json).unwrap();
        let test = &parsed.file_results[0].test_results[0];
        assert_eq!(test.captures.get("token"), Some(&serde_json::json!("abc")));
        assert_eq!(test.step_results[0].captures_set, vec!["id".to_string()]);
    }

    #[test]
    fn parse_recognizes_new_failure_categories() {
        for (raw, expected) in [
            (
                "response_shape_mismatch",
                FailureCategory::ResponseShapeMismatch,
            ),
            (
                "skipped_due_to_failed_capture",
                FailureCategory::SkippedDueToFailedCapture,
            ),
            (
                "skipped_due_to_fail_fast",
                FailureCategory::SkippedDueToFailFast,
            ),
            ("skipped_by_condition", FailureCategory::SkippedByCondition),
        ] {
            assert_eq!(parse_failure_category(raw), Some(expected));
        }
    }

    #[test]
    fn parse_rejects_invalid_json() {
        assert!(parse("not json").is_err());
    }

    #[test]
    fn parse_rejects_missing_files_array() {
        let err = parse("{\"duration_ms\":0}").unwrap_err();
        assert!(err.to_string().contains("files"));
    }
}