relux-runtime 0.7.1

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
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
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;

use colored::Colorize;

use relux_core::diagnostics::IrSpan;
use relux_ir::IrTimeout;

use crate::cancel::CancelReason;
use crate::observe::structured::EventSeq;
use crate::observe::structured::SpanId;
use crate::observe::structured::StackFrame;

/// Diagnostic context captured at failure-construction time. Travels with
/// every `Failure` so that downstream consumers (structured-log artifact,
/// console error renderer) can render the call site, what arrived in the
/// shell, and which user vars were live - without needing to reach back
/// into a VM that is about to be dropped.
///
/// The variant makes the failure's provenance explicit. `Vm` carries the
/// full diagnostic picture; `PreVm` represents failures raised outside any
/// VM (effect resolution, shell-block lookup, cleanup-shell spawn,
/// pre-init PTY spawn) and carries only the surrounding span, when one is
/// known. The structured-log builder flattens both variants into a single
/// on-disk shape via the accessor methods.
#[derive(Debug, Clone)]
pub enum FailureContext {
    /// Captured by a running VM at failure-construction time.
    Vm {
        span: SpanId,
        event_seq: EventSeq,
        call_stack: Vec<StackFrame>,
        buffer_tail: String,
        vars_in_scope: Vec<(String, String)>,
    },
    /// Failure raised before/around any VM. `span` points at the
    /// surrounding span when one is known (effect-setup span,
    /// shell-block span, cleanup-block span), `None` otherwise.
    PreVm { span: Option<SpanId> },
}

impl FailureContext {
    /// Construct a `PreVm` context with no surrounding span.
    pub fn pre_vm() -> Self {
        Self::PreVm { span: None }
    }

    /// Construct a `PreVm` context tied to a known surrounding span.
    pub fn pre_vm_with_span(span: SpanId) -> Self {
        Self::PreVm { span: Some(span) }
    }

    pub fn span(&self) -> Option<SpanId> {
        match self {
            Self::Vm { span, .. } => Some(*span),
            Self::PreVm { span } => *span,
        }
    }

    pub fn event_seq(&self) -> Option<EventSeq> {
        match self {
            Self::Vm { event_seq, .. } => Some(*event_seq),
            Self::PreVm { .. } => None,
        }
    }

    pub fn call_stack(&self) -> &[StackFrame] {
        match self {
            Self::Vm { call_stack, .. } => call_stack,
            Self::PreVm { .. } => &[],
        }
    }

    pub fn buffer_tail(&self) -> &str {
        match self {
            Self::Vm { buffer_tail, .. } => buffer_tail,
            Self::PreVm { .. } => "",
        }
    }

    pub fn vars_in_scope(&self) -> &[(String, String)] {
        match self {
            Self::Vm { vars_in_scope, .. } => vars_in_scope,
            Self::PreVm { .. } => &[],
        }
    }
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum Failure {
    #[error("match timeout in shell '{shell}': timed out waiting for {pattern}")]
    MatchTimeout {
        pattern: String,
        span: IrSpan,
        shell: String,
        /// The timeout that fired. Boxed to keep `Failure`'s variant size
        /// comparable to the others (avoids `clippy::large_enum_variant`).
        effective: Box<IrTimeout>,
        context: FailureContext,
    },
    #[error(
        "fail pattern matched in shell '{shell}': pattern {pattern} triggered, matched: \"{matched_line}\""
    )]
    FailPatternMatched {
        pattern: String,
        matched_line: String,
        span: IrSpan,
        shell: String,
        context: FailureContext,
    },
    #[error(
        "shell '{shell}' exited unexpectedly{}",
        match exit_code {
            Some(code) => format!(" with exit code {code}"),
            None => " without an exit code".to_string(),
        }
    )]
    ShellExited {
        shell: String,
        exit_code: Option<i32>,
        span: IrSpan,
        context: FailureContext,
    },
    #[error(
        "{}",
        match shell {
            Some(s) => format!("runtime error in shell '{s}': {message}"),
            None => format!("runtime error: {message}"),
        }
    )]
    Runtime {
        message: String,
        span: Option<IrSpan>,
        shell: Option<String>,
        context: FailureContext,
    },
    #[error(
        "multimatch did not satisfy all patterns in shell '{shell}' ({matched_count}/{total} matched)",
        matched_count = matched.len(),
        total = patterns.len(),
    )]
    MultiMatch {
        shell: String,
        /// All patterns in source order.
        patterns: Vec<crate::observe::structured::event::MultiMatchPattern>,
        /// Indices into `patterns` that matched before the block timed out.
        matched: Vec<usize>,
        span: IrSpan,
        /// The block-level timeout that fired. Boxed to keep variant size in
        /// line with the other failures (see clippy::large_enum_variant).
        effective: Box<IrTimeout>,
        context: FailureContext,
    },
}

impl Failure {
    pub fn summary(&self) -> String {
        self.to_string()
    }

    pub fn failure_type(&self) -> &'static str {
        match self {
            Failure::MatchTimeout { .. } => "MatchTimeout",
            Failure::FailPatternMatched { .. } => "FailPatternMatched",
            Failure::ShellExited { .. } => "ShellExited",
            Failure::Runtime { .. } => "Runtime",
            Failure::MultiMatch { .. } => "MultiMatch",
        }
    }

    pub fn context(&self) -> &FailureContext {
        match self {
            Failure::MatchTimeout { context, .. }
            | Failure::FailPatternMatched { context, .. }
            | Failure::ShellExited { context, .. }
            | Failure::Runtime { context, .. }
            | Failure::MultiMatch { context, .. } => context,
        }
    }
}

impl From<&Failure> for relux_core::error::DiagnosticReport {
    fn from(failure: &Failure) -> Self {
        use relux_core::error::DiagnosticReport;
        use relux_core::error::Severity;
        match failure {
            Failure::MatchTimeout {
                pattern,
                span,
                shell,
                ..
            } => DiagnosticReport {
                severity: Severity::Error,
                message: format!("match timeout in shell `{shell}`"),
                labels: vec![(span.clone(), format!("timed out waiting for `{pattern}`")).into()],
                help: None,
                note: None,
            },
            Failure::FailPatternMatched {
                pattern,
                matched_line,
                span,
                shell,
                ..
            } => DiagnosticReport {
                severity: Severity::Error,
                message: format!("fail pattern matched in shell `{shell}`"),
                labels: vec![(span.clone(), format!("pattern `{pattern}` triggered here")).into()],
                help: None,
                note: Some(format!("matched output: {matched_line}")),
            },
            Failure::ShellExited {
                shell,
                exit_code,
                span,
                ..
            } => {
                let code_msg = match exit_code {
                    Some(c) => format!("with exit code {c}"),
                    None => "without an exit code".to_string(),
                };
                DiagnosticReport {
                    severity: Severity::Error,
                    message: format!("shell `{shell}` exited unexpectedly"),
                    labels: vec![(span.clone(), code_msg).into()],
                    help: None,
                    note: None,
                }
            }
            Failure::Runtime {
                message,
                span,
                shell,
                ..
            } => {
                let msg = match shell {
                    Some(s) => format!("runtime error in shell `{s}`"),
                    None => "runtime error".to_string(),
                };
                let first_line = message.lines().next().unwrap_or(message);
                let has_detail = message.contains('\n');
                match span {
                    Some(span) => DiagnosticReport {
                        severity: Severity::Error,
                        message: msg,
                        labels: vec![(span.clone(), first_line.to_string()).into()],
                        help: None,
                        note: if has_detail {
                            Some(message.clone())
                        } else {
                            None
                        },
                    },
                    None => DiagnosticReport {
                        severity: Severity::Error,
                        message: format!("{msg}: {first_line}"),
                        labels: vec![],
                        help: None,
                        note: if has_detail {
                            Some(message.clone())
                        } else {
                            None
                        },
                    },
                }
            }
            Failure::MultiMatch {
                shell,
                patterns,
                matched,
                span,
                ..
            } => {
                let matched_set: std::collections::HashSet<usize> =
                    matched.iter().copied().collect();
                let total = patterns.len();
                let hit_count = matched_set.len();
                let header = format!(
                    "multimatch did not satisfy all patterns ({hit_count} matched, {} timed out)",
                    total.saturating_sub(hit_count),
                );
                let mut lines = String::with_capacity(header.len() + patterns.len() * 48);
                lines.push_str(&header);
                lines.push('\n');
                for (i, p) in patterns.iter().enumerate() {
                    let label = if matched_set.contains(&i) {
                        "matched:"
                    } else {
                        "timed out:"
                    };
                    let kind = if p.is_regex { "?" } else { "=" };
                    let line = format!("{label:<13}{kind} {pat}", pat = p.pattern);
                    lines.push_str(&line);
                    lines.push('\n');
                }
                DiagnosticReport {
                    severity: Severity::Error,
                    message: format!("multimatch in shell `{shell}` did not satisfy all patterns"),
                    labels: vec![
                        (span.clone(), "multimatch block timed out here".to_string()).into(),
                    ],
                    help: None,
                    note: Some(lines.trim_end().to_string()),
                }
            }
        }
    }
}

pub fn log_link(run_dir: &Path, result: &TestResult) -> Option<String> {
    let log_dir = result.log_dir.as_ref()?;
    let relative = log_dir.strip_prefix(run_dir).ok()?;
    Some(format!("{}/event.html", relative.display()))
}

/// Companion to `log_link` for the canonical structured artifact.
/// Returns `<log_dir>/events.json` relative to `run_dir`. Machine
/// consumers (custom reporters, dashboards) prefer this over the
/// human-targeted `event.html`.
pub fn events_json_link(run_dir: &Path, result: &TestResult) -> Option<String> {
    let log_dir = result.log_dir.as_ref()?;
    let relative = log_dir.strip_prefix(run_dir).ok()?;
    Some(format!("{}/events.json", relative.display()))
}

/// Top-level marker that the test was interrupted before completing.
/// Distinct from `Failure` because the test did not misbehave - it was
/// stopped by an external event (the per-test watchdog, the suite-wide
/// watchdog, fail-fast, or SIGINT).
#[derive(Debug, Clone, thiserror::Error)]
#[error(
    "{}",
    match reason {
        CancelReason::TestTimeout { duration } => format!("cancelled: test timed out after {duration:?}"),
        CancelReason::SuiteTimeout { duration } => format!("cancelled: suite timed out after {duration:?}"),
        CancelReason::FailFast { trigger_test } => format!("cancelled: suite stopped after `{trigger_test}` failed (fail-fast)"),
        CancelReason::Sigint => "cancelled: interrupted (SIGINT)".to_string(),
    }
)]
pub struct Cancellation {
    pub reason: CancelReason,
    pub context: FailureContext,
}

impl Cancellation {
    pub fn summary(&self) -> String {
        self.to_string()
    }

    pub fn reason_tag(&self) -> &'static str {
        match &self.reason {
            CancelReason::TestTimeout { .. } => "test-timeout",
            CancelReason::SuiteTimeout { .. } => "suite-timeout",
            CancelReason::FailFast { .. } => "fail-fast",
            CancelReason::Sigint => "sigint",
        }
    }
}

impl From<&Cancellation> for relux_core::error::DiagnosticReport {
    fn from(c: &Cancellation) -> Self {
        relux_core::error::DiagnosticReport {
            severity: relux_core::error::Severity::Error,
            message: c.summary(),
            labels: vec![],
            help: None,
            note: None,
        }
    }
}

/// Internal error type used by the VM / BIF / effect machinery while a test
/// is running. `Failure` is "the test misbehaved"; `Cancelled` is "we were
/// stopped from the outside". `run_test` maps each variant onto the
/// corresponding `Outcome`.
#[derive(Debug, Clone, thiserror::Error)]
pub enum ExecError {
    #[error(transparent)]
    Failure(#[from] Failure),
    #[error(transparent)]
    Cancelled(#[from] Cancellation),
}

impl ExecError {
    pub fn summary(&self) -> String {
        self.to_string()
    }
}

#[derive(Debug, Clone)]
pub struct TestResult {
    pub test_name: String,
    pub test_path: String,
    pub outcome: Outcome,
    pub duration: Duration,
    pub progress: String,
    pub log_dir: Option<PathBuf>,
    pub warnings: Vec<crate::effect::Warning>,
    pub flaky_retries: u32,
}

impl TestResult {
    pub fn is_failure(&self) -> bool {
        matches!(self.outcome, Outcome::Fail(_))
    }

    pub fn is_cancelled(&self) -> bool {
        matches!(self.outcome, Outcome::Cancelled(_))
    }
}

#[derive(Debug, Clone)]
pub enum Outcome {
    Pass,
    Fail(Failure),
    Cancelled(Cancellation),
    Skipped(String),
    Invalid(String),
}

impl Outcome {
    pub fn is_failure(&self) -> bool {
        matches!(self, Outcome::Fail(_))
    }

    pub fn is_cancelled(&self) -> bool {
        matches!(self, Outcome::Cancelled(_))
    }

    pub fn is_nonzero_outcome(&self) -> bool {
        matches!(
            self,
            Outcome::Fail(_) | Outcome::Cancelled(_) | Outcome::Invalid(_)
        )
    }

    /// Whether the flaky-retry loop should retry on this outcome. Real
    /// failures and per-test-timeout cancellations are retryable (those are
    /// the test's own clock running out - exactly what flaky retries with
    /// scaled timeouts target). External cancellations (suite-timeout,
    /// fail-fast, SIGINT) are not retryable: rerunning the same test isn't
    /// going to make the external trigger disappear.
    pub fn is_retryable(&self) -> bool {
        match self {
            Outcome::Fail(_) => true,
            Outcome::Cancelled(c) => {
                matches!(c.reason, crate::cancel::CancelReason::TestTimeout { .. })
            }
            _ => false,
        }
    }
}

// --- Run Report ------------------------------------------

pub struct RunReport<'a> {
    pub results: &'a [TestResult],
    pub run_dir: &'a Path,
    pub wall_duration: Duration,
    pub jobs: usize,
}

impl RunReport<'_> {
    pub fn eprint(&self) {
        let mut passed = 0usize;
        let mut failed = 0usize;
        let mut cancelled = 0usize;
        let mut skipped = 0usize;
        let mut invalid = 0usize;
        let mut flaky_retries = 0u32;
        let mut total_duration = Duration::ZERO;

        for result in self.results {
            total_duration += result.duration;
            flaky_retries += result.flaky_retries;
            match &result.outcome {
                Outcome::Pass => passed += 1,
                Outcome::Fail(_) => failed += 1,
                Outcome::Cancelled(_) => cancelled += 1,
                Outcome::Skipped(_) => skipped += 1,
                Outcome::Invalid(_) => invalid += 1,
            }
        }

        let has_problems = failed > 0 || cancelled > 0 || invalid > 0;
        let status = if has_problems {
            "FAILED".red().to_string()
        } else {
            "ok".green().to_string()
        };

        let mut summary = format!("\ntest result: {status}. {passed} passed; {failed} failed");
        if cancelled > 0 {
            summary.push_str(&format!("; {cancelled} cancelled"));
        }
        if invalid > 0 {
            summary.push_str(&format!("; {invalid} invalid"));
        }
        if skipped > 0 {
            summary.push_str(&format!("; {skipped} skipped"));
        }
        if flaky_retries > 0 {
            summary.push_str(&format!("; {flaky_retries} flaky retries"));
        }
        if self.jobs > 1 {
            summary.push_str(&format!(
                "; finished in {} ({} cumulative)\n",
                format_duration(self.wall_duration),
                format_duration(total_duration)
            ));
        } else {
            summary.push_str(&format!(
                "; finished in {}\n",
                format_duration(self.wall_duration)
            ));
        }
        eprint!("{summary}");
        eprintln!(
            "  Test logs: file://{}",
            self.run_dir.join("index.html").display()
        );
        let _ = std::io::stderr().flush();
    }
}

pub fn format_duration(d: Duration) -> String {
    let total_ms = d.as_secs_f64() * 1000.0;
    if total_ms < 1000.0 {
        format!("{:.1} ms", total_ms)
    } else {
        format!("{:.1} s", total_ms / 1000.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    fn dummy_span() -> IrSpan {
        IrSpan::synthetic()
    }

    #[test]
    fn summary_match_timeout() {
        let f = Failure::MatchTimeout {
            pattern: "/ready/".into(),
            shell: "default".into(),
            span: dummy_span(),
            effective: Box::new(IrTimeout::tolerance(std::time::Duration::from_secs(5))),
            context: FailureContext::pre_vm(),
        };
        assert_eq!(
            f.summary(),
            "match timeout in shell 'default': timed out waiting for /ready/"
        );
    }

    #[test]
    fn summary_fail_pattern_matched() {
        let f = Failure::FailPatternMatched {
            pattern: "/error/".into(),
            matched_line: "error: connection refused".into(),
            shell: "default".into(),
            span: dummy_span(),
            context: FailureContext::pre_vm(),
        };
        assert_eq!(
            f.summary(),
            "fail pattern matched in shell 'default': pattern /error/ triggered, matched: \"error: connection refused\""
        );
    }

    #[test]
    fn summary_shell_exited_with_code() {
        let f = Failure::ShellExited {
            shell: "default".into(),
            exit_code: Some(1),
            span: dummy_span(),
            context: FailureContext::pre_vm(),
        };
        assert_eq!(
            f.summary(),
            "shell 'default' exited unexpectedly with exit code 1"
        );
    }

    #[test]
    fn summary_shell_exited_without_code() {
        let f = Failure::ShellExited {
            shell: "default".into(),
            exit_code: None,
            span: dummy_span(),
            context: FailureContext::pre_vm(),
        };
        assert_eq!(
            f.summary(),
            "shell 'default' exited unexpectedly without an exit code"
        );
    }

    #[test]
    fn summary_runtime_with_shell() {
        let f = Failure::Runtime {
            message: "something broke".into(),
            shell: Some("default".into()),
            span: None,
            context: FailureContext::pre_vm(),
        };
        assert_eq!(
            f.summary(),
            "runtime error in shell 'default': something broke"
        );
    }

    #[test]
    fn summary_runtime_without_shell() {
        let f = Failure::Runtime {
            message: "something broke".into(),
            shell: None,
            span: None,
            context: FailureContext::pre_vm(),
        };
        assert_eq!(f.summary(), "runtime error: something broke");
    }

    #[test]
    fn summary_multimatch() {
        use crate::observe::structured::event::MultiMatchPattern;
        let f = Failure::MultiMatch {
            shell: "default".into(),
            patterns: vec![
                MultiMatchPattern {
                    pattern: "^a$".into(),
                    is_regex: true,
                },
                MultiMatchPattern {
                    pattern: "b".into(),
                    is_regex: false,
                },
            ],
            matched: vec![0],
            span: dummy_span(),
            effective: Box::new(IrTimeout::tolerance(std::time::Duration::from_secs(5))),
            context: FailureContext::pre_vm(),
        };
        let summary = f.summary();
        assert!(
            summary.starts_with("multimatch did not satisfy all patterns"),
            "got: {summary}"
        );
    }

    #[test]
    fn failure_type_multimatch() {
        use crate::observe::structured::event::MultiMatchPattern;
        let f = Failure::MultiMatch {
            shell: "default".into(),
            patterns: vec![MultiMatchPattern {
                pattern: "^a$".into(),
                is_regex: true,
            }],
            matched: vec![],
            span: dummy_span(),
            effective: Box::new(IrTimeout::tolerance(std::time::Duration::from_secs(5))),
            context: FailureContext::pre_vm(),
        };
        assert_eq!(f.failure_type(), "MultiMatch");
    }

    #[test]
    fn diagnostic_report_multimatch_lists_per_pattern_status() {
        use crate::observe::structured::event::MultiMatchPattern;
        use relux_core::error::DiagnosticReport;
        let f = Failure::MultiMatch {
            shell: "default".into(),
            patterns: vec![
                MultiMatchPattern {
                    pattern: "^a$".into(),
                    is_regex: true,
                },
                MultiMatchPattern {
                    pattern: "^b$".into(),
                    is_regex: true,
                },
                MultiMatchPattern {
                    pattern: "^c$".into(),
                    is_regex: true,
                },
            ],
            matched: vec![0, 2],
            span: dummy_span(),
            effective: Box::new(IrTimeout::tolerance(std::time::Duration::from_secs(5))),
            context: FailureContext::pre_vm(),
        };
        let rep: DiagnosticReport = (&f).into();
        let note = rep
            .note
            .expect("multimatch DiagnosticReport must carry a per-pattern note");
        assert!(note.contains("matched:"), "matched label present: {note}");
        assert!(
            note.contains("timed out:"),
            "timed-out label present: {note}"
        );
        assert!(note.contains("^a$"), "pattern 0 listed");
        assert!(note.contains("^b$"), "pattern 1 listed");
        assert!(note.contains("^c$"), "pattern 2 listed");
        assert!(note.is_ascii(), "diagnostic note must be ASCII-only");
    }

    #[test]
    fn log_link_with_log_dir() {
        let run_dir = Path::new("/tmp/runs/run-001");
        let result = TestResult {
            test_name: "my_test".into(),
            test_path: "tests/my_test.relux".into(),
            outcome: Outcome::Pass,
            duration: Duration::from_millis(100),

            progress: String::new(),
            log_dir: Some(PathBuf::from("/tmp/runs/run-001/my_test")),
            warnings: Vec::new(),
            flaky_retries: 0,
        };
        assert_eq!(
            log_link(run_dir, &result),
            Some("my_test/event.html".to_string())
        );
    }

    #[test]
    fn cancellation_summary_test_timeout() {
        let c = Cancellation {
            reason: CancelReason::TestTimeout {
                duration: Duration::from_millis(300),
            },
            context: FailureContext::pre_vm(),
        };
        assert_eq!(c.reason_tag(), "test-timeout");
        assert!(c.summary().starts_with("cancelled: test timed out after"));
    }

    #[test]
    fn cancellation_summary_fail_fast() {
        let c = Cancellation {
            reason: CancelReason::FailFast {
                trigger_test: "foo".into(),
            },
            context: FailureContext::pre_vm(),
        };
        assert_eq!(c.reason_tag(), "fail-fast");
        assert!(c.summary().contains("`foo`"));
    }

    #[test]
    fn exec_error_from_conversions() {
        let f = Failure::Runtime {
            message: "x".into(),
            span: None,
            shell: None,
            context: FailureContext::pre_vm(),
        };
        let e: ExecError = f.into();
        assert!(matches!(e, ExecError::Failure(_)));

        let c = Cancellation {
            reason: CancelReason::Sigint,
            context: FailureContext::pre_vm(),
        };
        let e: ExecError = c.into();
        assert!(matches!(e, ExecError::Cancelled(_)));
    }

    #[test]
    fn log_link_without_log_dir() {
        let run_dir = Path::new("/tmp/runs/run-001");
        let result = TestResult {
            test_name: "my_test".into(),
            test_path: "tests/my_test.relux".into(),
            outcome: Outcome::Pass,
            duration: Duration::from_millis(100),

            progress: String::new(),
            log_dir: None,
            warnings: Vec::new(),
            flaky_retries: 0,
        };
        assert_eq!(log_link(run_dir, &result), None);
    }
}