relux-runtime 0.8.0

Internal: runtime for Relux. No semver guarantees.
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
use std::fmt::Write;
use std::path::Path;

use crate::observe::structured::MatchContext;
use crate::report::result::Failure;
use crate::report::result::Outcome;
use crate::report::result::TestResult;
use crate::report::result::events_json_link;
use crate::report::result::log_link;
use relux_core::diagnostics::IrSpan;
use relux_core::table::SourceTable;

/// Compute the 1-based line number for a byte offset in a source string.
fn line_number(source: &str, offset: usize) -> usize {
    source[..offset.min(source.len())]
        .bytes()
        .filter(|&b| b == b'\n')
        .count()
        + 1
}

/// Escape a string for use as a YAML double-quoted scalar.
fn yaml_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Extract the source span from a Failure. Every failure carries one.
fn failure_span(failure: &Failure) -> &IrSpan {
    match failure {
        Failure::MatchTimeout { span, .. }
        | Failure::FailPatternMatched { span, .. }
        | Failure::ShellExited { span, .. }
        | Failure::PureMatch { span, .. }
        | Failure::MultiMatch { span, .. }
        | Failure::Runtime { span, .. } => span,
    }
}

/// Extract the shell name from a Failure, if present.
fn failure_shell(failure: &Failure) -> Option<&str> {
    match failure {
        Failure::MatchTimeout { shell, .. }
        | Failure::FailPatternMatched { shell, .. }
        | Failure::ShellExited { shell, .. }
        | Failure::MultiMatch { shell, .. } => Some(shell),
        Failure::PureMatch { match_context, .. } => match_context.shell_name_ref(),
        Failure::Runtime { shell, .. } => shell.as_deref(),
    }
}

/// Human-readable match context for a pure-match failure, so a non-shell
/// context (fn / test-preamble / effect-preamble) is not dropped from TAP
/// output the way the `shell:` line drops it. A `Shell` context already has
/// its name on the `shell:` line via `failure_shell`, so this returns
/// `None` for it to avoid printing the same shell twice.
fn failure_match_context(failure: &Failure) -> Option<String> {
    match failure {
        Failure::PureMatch {
            match_context: MatchContext::Shell { .. },
            ..
        } => None,
        Failure::PureMatch { match_context, .. } => Some(match_context.to_string()),
        _ => None,
    }
}

/// Extract the pattern from a Failure, if present.
fn failure_pattern(failure: &Failure) -> Option<&str> {
    match failure {
        Failure::MatchTimeout { pattern, .. }
        | Failure::FailPatternMatched { pattern, .. }
        | Failure::PureMatch { pattern, .. } => Some(pattern),
        _ => None,
    }
}

/// Render TAP version 14 output for the given test results.
fn render_tap(
    run_dir: &Path,
    _suite_name: &str,
    results: &[TestResult],
    source_table: &SourceTable,
) -> String {
    let mut out = String::new();

    writeln!(out, "TAP version 14").unwrap();
    writeln!(out, "1..{}", results.len()).unwrap();

    for (i, result) in results.iter().enumerate() {
        let num = i + 1;

        match &result.outcome {
            Outcome::Pass => {
                writeln!(out, "ok {num} - {}", result.test_name).unwrap();
                writeln!(out, "  ---").unwrap();
                writeln!(out, "  duration_ms: {}", result.duration.as_millis()).unwrap();
                if let Some(link) = log_link(run_dir, result) {
                    writeln!(out, "  log: {link}").unwrap();
                }
                if let Some(link) = events_json_link(run_dir, result) {
                    writeln!(out, "  log_json: {link}").unwrap();
                }
                writeln!(out, "  ...").unwrap();
            }
            Outcome::Fail(failure) => {
                writeln!(out, "not ok {num} - {}", result.test_name).unwrap();
                writeln!(out, "  ---").unwrap();
                writeln!(out, "  message: \"{}\"", yaml_escape(&failure.summary())).unwrap();

                if let Some(shell) = failure_shell(failure) {
                    writeln!(out, "  shell: {shell}").unwrap();
                }
                if let Some(ctx) = failure_match_context(failure) {
                    writeln!(out, "  context: {ctx}").unwrap();
                }
                if let Some(pattern) = failure_pattern(failure) {
                    writeln!(out, "  pattern: {pattern}").unwrap();
                }
                let span = failure_span(failure);
                if let Some(sf) = source_table.get(span.file()) {
                    writeln!(out, "  file: {}", sf.path.display()).unwrap();
                    writeln!(
                        out,
                        "  line: {}",
                        line_number(&sf.source, span.span().start())
                    )
                    .unwrap();
                }
                writeln!(out, "  duration_ms: {}", result.duration.as_millis()).unwrap();
                if let Some(link) = log_link(run_dir, result) {
                    writeln!(out, "  log: {link}").unwrap();
                }
                if let Some(link) = events_json_link(run_dir, result) {
                    writeln!(out, "  log_json: {link}").unwrap();
                }
                writeln!(out, "  ...").unwrap();
            }
            Outcome::Cancelled(c) => {
                writeln!(out, "not ok {num} - {}", result.test_name).unwrap();
                writeln!(out, "  ---").unwrap();
                writeln!(out, "  cancellation: {}", c.reason_tag()).unwrap();
                writeln!(out, "  duration_ms: {}", result.duration.as_millis()).unwrap();
                if let Some(link) = log_link(run_dir, result) {
                    writeln!(out, "  log: {link}").unwrap();
                }
                if let Some(link) = events_json_link(run_dir, result) {
                    writeln!(out, "  log_json: {link}").unwrap();
                }
                writeln!(out, "  ...").unwrap();
            }
            Outcome::Skipped(reason) => {
                writeln!(out, "ok {num} - {} # SKIP {reason}", result.test_name).unwrap();
            }
            Outcome::Invalid(reason) => {
                writeln!(
                    out,
                    "not ok {num} - {} # INVALID {reason}",
                    result.test_name
                )
                .unwrap();
            }
        }
    }

    out
}

/// Generate TAP version 14 output and write it to `run_dir/results.tap`.
pub fn generate_tap(
    run_dir: &Path,
    suite_name: &str,
    results: &[TestResult],
    source_table: &SourceTable,
) {
    let tap = render_tap(run_dir, suite_name, results, source_table);
    let path = run_dir.join("results.tap");
    std::fs::write(path, tap).expect("failed to write results.tap");
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::result::Failure;
    use crate::report::result::FailureContext;
    use crate::report::result::Outcome;
    use crate::report::result::TestResult;
    use relux_core::diagnostics::IrSpan;
    use relux_core::table::FileId;
    use relux_core::table::SharedTable;
    use relux_core::table::SourceFile;
    use std::path::Path;
    use std::path::PathBuf;
    use std::time::Duration;

    fn test_source_table() -> SourceTable {
        let table: SourceTable = SharedTable::new();
        table.insert(
            FileId::new(PathBuf::from("tests/auth/login.relux")),
            SourceFile::new(
                PathBuf::from("tests/auth/login.relux"),
                "line 1\nline 2\nline 3\n".to_string(),
            ),
        );
        table
    }

    fn test_span(offset_start: usize, offset_end: usize) -> IrSpan {
        IrSpan::new(
            FileId::new(PathBuf::from("tests/auth/login.relux")),
            relux_core::Span::new(offset_start, offset_end),
        )
    }

    fn run_dir() -> &'static Path {
        Path::new("/tmp/runs/run-001")
    }

    fn pass_result(name: &str, ms: u64, log_dir: Option<&str>) -> TestResult {
        TestResult {
            test_name: name.into(),
            test_path: format!("tests/{name}.relux"),
            outcome: Outcome::Pass,
            duration: Duration::from_millis(ms),

            progress: String::new(),
            log_dir: log_dir.map(PathBuf::from),
            warnings: Vec::new(),
            flaky_retries: 0,
        }
    }

    fn fail_result(name: &str, ms: u64, failure: Failure, log_dir: Option<&str>) -> TestResult {
        TestResult {
            test_name: name.into(),
            test_path: format!("tests/{name}.relux"),
            outcome: Outcome::Fail(failure),
            duration: Duration::from_millis(ms),

            progress: String::new(),
            log_dir: log_dir.map(PathBuf::from),
            warnings: Vec::new(),
            flaky_retries: 0,
        }
    }

    fn skip_result(name: &str, reason: &str) -> TestResult {
        TestResult {
            test_name: name.into(),
            test_path: format!("tests/{name}.relux"),
            outcome: Outcome::Skipped(reason.into()),
            duration: Duration::ZERO,

            progress: String::new(),
            log_dir: None,
            warnings: Vec::new(),
            flaky_retries: 0,
        }
    }

    #[test]
    fn header_and_plan_line() {
        let st = test_source_table();
        let results = vec![pass_result("a", 100, None), pass_result("b", 200, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        let lines: Vec<&str> = tap.lines().collect();
        assert_eq!(lines[0], "TAP version 14");
        assert_eq!(lines[1], "1..2");
    }

    #[test]
    fn passed_test_with_log() {
        let st = test_source_table();
        let results = vec![pass_result(
            "login-test",
            1230,
            Some("/tmp/runs/run-001/logs/auth/login-test"),
        )];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        let lines: Vec<&str> = tap.lines().collect();
        assert_eq!(lines[2], "ok 1 - login-test");
        assert_eq!(lines[3], "  ---");
        assert_eq!(lines[4], "  duration_ms: 1230");
        assert_eq!(lines[5], "  log: logs/auth/login-test/event.html");
        assert_eq!(lines[6], "  log_json: logs/auth/login-test/events.json");
        assert_eq!(lines[7], "  ...");
    }

    #[test]
    fn passed_test_without_log() {
        let st = test_source_table();
        let results = vec![pass_result("simple", 50, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        assert!(tap.contains("ok 1 - simple"));
        assert!(tap.contains("duration_ms: 50"));
        assert!(!tap.contains("log:"));
        assert!(!tap.contains("log_json:"));
    }

    #[test]
    fn failed_test_with_diagnostics() {
        let st = test_source_table();
        // span at byte 14 = start of line 3
        let failure = Failure::MatchTimeout {
            pattern: "/ready/".into(),
            span: test_span(14, 20),
            shell: "default".into(),
            effective: Box::new(relux_ir::IrTimeout::tolerance(
                std::time::Duration::from_secs(5),
            )),
            context: FailureContext::pre_vm(),
        };
        let results = vec![fail_result(
            "timeout-test",
            5000,
            failure,
            Some("/tmp/runs/run-001/logs/auth/timeout-test"),
        )];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        let lines: Vec<&str> = tap.lines().collect();

        assert_eq!(lines[2], "not ok 1 - timeout-test");
        assert_eq!(lines[3], "  ---");
        assert!(lines[4].starts_with("  message: \""));
        assert!(lines[4].contains("match timeout"));
        assert_eq!(lines[5], "  shell: default");
        assert_eq!(lines[6], "  pattern: /ready/");
        assert_eq!(lines[7], "  file: tests/auth/login.relux");
        assert_eq!(lines[8], "  line: 3");
        assert_eq!(lines[9], "  duration_ms: 5000");
        assert_eq!(lines[10], "  log: logs/auth/timeout-test/event.html");
        assert_eq!(lines[11], "  log_json: logs/auth/timeout-test/events.json");
        assert_eq!(lines[12], "  ...");
    }

    #[test]
    fn failed_runtime_error_with_source_less_span() {
        let st = test_source_table();
        let failure = Failure::Runtime {
            message: "something broke".into(),
            span: IrSpan::synthetic(),
            shell: None,
            context: FailureContext::pre_vm(),
        };
        let results = vec![fail_result("broken", 100, failure, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        assert!(tap.contains("not ok 1 - broken"));
        assert!(tap.contains("message: \"runtime error: something broke\""));
        assert!(!tap.contains("shell:"));
        assert!(!tap.contains("pattern:"));
        assert!(!tap.contains("file:"));
        assert!(!tap.contains("line:"));
    }

    #[test]
    fn skipped_test() {
        let st = test_source_table();
        let results = vec![skip_result("linux-only", "os:linux")];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        let lines: Vec<&str> = tap.lines().collect();
        assert_eq!(lines[2], "ok 1 - linux-only # SKIP os:linux");
        // No diagnostics block for skipped tests
        assert_eq!(lines.len(), 3);
    }

    #[test]
    fn mixed_results() {
        let st = test_source_table();
        let failure = Failure::ShellExited {
            shell: "main".into(),
            exit_code: Some(1),
            span: test_span(0, 5),
            context: FailureContext::pre_vm(),
        };
        let results = vec![
            pass_result("test-a", 100, None),
            fail_result("test-b", 200, failure, None),
            skip_result("test-c", "os:macos"),
        ];
        let tap = render_tap(run_dir(), "suite", &results, &st);

        assert!(tap.starts_with("TAP version 14\n1..3\n"));
        assert!(tap.contains("ok 1 - test-a"));
        assert!(tap.contains("not ok 2 - test-b"));
        assert!(tap.contains("ok 3 - test-c # SKIP os:macos"));
    }

    #[test]
    fn message_with_quotes_is_escaped() {
        let st = test_source_table();
        let failure = Failure::FailPatternMatched {
            pattern: "/error/".into(),
            matched_line: "got \"error\" here".into(),
            span: test_span(0, 5),
            shell: "default".into(),
            context: FailureContext::pre_vm(),
        };
        let results = vec![fail_result("quote-test", 100, failure, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        // Inner quotes should be escaped
        assert!(tap.contains("\\\"error\\\""));
    }

    #[test]
    fn pure_match_shell_context_has_shell_line_no_context_line() {
        let st = test_source_table();
        let failure = Failure::PureMatch {
            value: "actual".into(),
            pattern: "expected".into(),
            is_regex: false,
            span: test_span(0, 5),
            match_context: MatchContext::Shell {
                name: "default".into(),
            },
            context: FailureContext::pre_vm(),
        };
        let results = vec![fail_result("shell-pure-match", 100, failure, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        assert!(tap.contains("shell: default"), "tap: {tap}");
        assert!(!tap.contains("context:"), "tap: {tap}");
    }

    #[test]
    fn pure_match_non_shell_context_has_context_line_no_shell_line() {
        let st = test_source_table();
        let failure = Failure::PureMatch {
            value: "actual".into(),
            pattern: "expected".into(),
            is_regex: false,
            span: test_span(0, 5),
            match_context: MatchContext::TestPreamble {
                name: "login".into(),
            },
            context: FailureContext::pre_vm(),
        };
        let results = vec![fail_result("preamble-pure-match", 100, failure, None)];
        let tap = render_tap(run_dir(), "suite", &results, &st);
        assert!(tap.contains("context:"), "tap: {tap}");
        assert!(!tap.contains("shell:"), "tap: {tap}");
    }

    #[test]
    fn line_number_computation() {
        let source = "line 1\nline 2\nline 3\n";
        assert_eq!(line_number(source, 0), 1); // start of line 1
        assert_eq!(line_number(source, 6), 1); // last char of line 1 (before \n at 6)
        assert_eq!(line_number(source, 7), 2); // start of line 2 (after \n)
        assert_eq!(line_number(source, 14), 3); // start of line 3
    }
}