ferridriver-test 0.4.0

E2E test runner for ferridriver. Playwright-compatible API, parallel workers, auto-retrying expect, fixtures, snapshots.
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
//! Rich terminal reporter: unified output for E2E and BDD tests.
//!
//! Automatically detects BDD tests by checking step metadata for `bdd_keyword`.
//! E2E tests show as flat results. BDD tests show Feature > Scenario > Step hierarchy
//! with keyword coloring.

use std::time::Duration;

use console::Style;

use crate::config::ReportSlowTestsConfig;
use crate::model::{StepCategory, StepStatus, TestStatus, TestStep};
use crate::reporter::{Reporter, ReporterEvent};

pub struct TerminalReporter {
  completed: usize,
  total: usize,
  slow_tests_config: Option<ReportSlowTestsConfig>,
  test_durations: Vec<(String, String, Duration)>,
  /// Current BDD feature/suite — used to print Feature headers when suite changes.
  current_suite: Option<String>,
}

impl TerminalReporter {
  pub fn new() -> Self {
    Self {
      completed: 0,
      total: 0,
      slow_tests_config: Some(ReportSlowTestsConfig::default()),
      test_durations: Vec::new(),
      current_suite: None,
    }
  }

  pub fn with_slow_tests_config(mut self, config: Option<ReportSlowTestsConfig>) -> Self {
    self.slow_tests_config = config;
    self
  }
}

impl Default for TerminalReporter {
  fn default() -> Self {
    Self::new()
  }
}

// ── Styles ──

fn s_pass() -> Style {
  Style::new().green()
}
fn s_fail() -> Style {
  Style::new().red().bold()
}
fn s_skip() -> Style {
  Style::new().dim()
}
fn s_flaky() -> Style {
  Style::new().yellow().bold()
}
fn s_warn() -> Style {
  Style::new().yellow()
}
fn s_dim() -> Style {
  Style::new().dim()
}
fn s_bold() -> Style {
  Style::new().bold()
}
fn s_cyan() -> Style {
  Style::new().cyan().bold()
}
fn s_diff_minus() -> Style {
  Style::new().red()
}
fn s_diff_plus() -> Style {
  Style::new().green()
}
fn s_label() -> Style {
  Style::new().bold().cyan()
}

/// Apply colors based on the line's role inside a rendered
/// assertion-failure body:
/// - `Expected:` / `Received:` / `Diff:` labels → bold cyan
/// - lines starting with `-` (with space margin) → red
/// - lines starting with `+` (with space margin) → green
/// - everything else → default
fn style_diff_line(line: &str) -> String {
  let trimmed = line.trim_start();
  if trimmed.starts_with("Expected:") || trimmed.starts_with("Received:") || trimmed.starts_with("Diff:") {
    return s_label().apply_to(line).to_string();
  }
  if trimmed.starts_with('-') && !trimmed.starts_with("--") {
    return s_diff_minus().apply_to(line).to_string();
  }
  if trimmed.starts_with('+') && !trimmed.starts_with("++") {
    return s_diff_plus().apply_to(line).to_string();
  }
  line.to_string()
}
fn s_feature() -> Style {
  Style::new().magenta().bold()
}

fn status_icon(status: &TestStatus) -> (&'static str, Style) {
  match status {
    TestStatus::Passed => ("\u{2713}", s_pass()),
    TestStatus::Failed => ("\u{2717}", s_fail()),
    TestStatus::TimedOut => ("\u{2717}", s_fail()),
    TestStatus::Skipped => ("\u{2212}", s_skip()),
    TestStatus::Flaky => ("\u{25ce}", s_flaky()),
    TestStatus::Interrupted => ("!", s_fail()),
  }
}

fn step_icon(status: StepStatus) -> (&'static str, Style) {
  match status {
    StepStatus::Passed => ("\u{2713}", s_pass()),
    StepStatus::Failed => ("\u{2717}", s_fail()),
    StepStatus::Skipped => ("\u{2212}", s_skip()),
    StepStatus::Pending => ("\u{25cb}", s_skip()),
  }
}

fn format_duration(d: Duration) -> String {
  let ms = d.as_millis();
  if ms < 1000 {
    format!("{ms}ms")
  } else {
    format!("{:.1}s", d.as_secs_f64())
  }
}

/// Check if a test outcome has BDD steps (any step with bdd_keyword metadata).
fn is_bdd_test(steps: &[TestStep]) -> bool {
  steps
    .iter()
    .any(|s| s.metadata.as_ref().is_some_and(|m| m.get("bdd_keyword").is_some()) || is_bdd_test(&s.steps))
}

fn print_steps(steps: &[&TestStep], indent: usize) {
  let pad = " ".repeat(indent);
  for step in steps {
    if step.category == StepCategory::Hook {
      let icon = if step.error.is_some() { "\u{2717}" } else { "\u{2713}" };
      let style = if step.error.is_some() { s_fail() } else { s_dim() };
      let dur = format_duration(step.duration);
      println!(
        "{pad}{} {} {}",
        style.apply_to(icon),
        s_dim().apply_to(format!("[{}]", step.title)),
        s_dim().apply_to(format!("({dur})")),
      );
      if let Some(ref err) = step.error {
        for line in err.lines() {
          println!("{pad}  {}", s_fail().apply_to(line));
        }
      }
      continue;
    }

    let (icon, icon_style) = step_icon(step.status);
    let dur = format_duration(step.duration);

    // BDD steps: color the keyword part in cyan.
    let keyword = step
      .metadata
      .as_ref()
      .and_then(|m| m.get("bdd_keyword"))
      .and_then(|v| v.as_str())
      .map(|k| k.trim().to_string());

    match step.status {
      StepStatus::Passed => {
        if let Some(ref kw) = keyword {
          let rest = step.title.strip_prefix(kw.as_str()).unwrap_or(&step.title);
          println!(
            "{pad}{} {}{} {}",
            icon_style.apply_to(icon),
            s_cyan().apply_to(kw),
            rest,
            s_dim().apply_to(format!("({dur})")),
          );
        } else {
          println!(
            "{pad}{} {} {}",
            icon_style.apply_to(icon),
            step.title,
            s_dim().apply_to(format!("({dur})")),
          );
        }
      },
      StepStatus::Failed => {
        println!(
          "{pad}{} {} {}",
          icon_style.apply_to(icon),
          s_fail().apply_to(&step.title),
          s_dim().apply_to(format!("({dur})")),
        );
        if let Some(ref err) = step.error {
          for line in err.lines() {
            println!("{pad}  {}", s_fail().apply_to(line));
          }
        }
      },
      StepStatus::Skipped | StepStatus::Pending => {
        println!("{pad}{} {}", icon_style.apply_to(icon), s_skip().apply_to(&step.title));
      },
    }

    let nested: Vec<&TestStep> = step.steps.iter().filter(|s| s.category.is_visible()).collect();
    if !nested.is_empty() {
      print_steps(&nested, indent + 2);
    }
  }
}

#[async_trait::async_trait]
impl Reporter for TerminalReporter {
  async fn on_event(&mut self, event: &ReporterEvent) {
    match event {
      ReporterEvent::RunStarted {
        total_tests,
        num_workers,
        ..
      } => {
        self.total = *total_tests;
        println!();
        println!(
          "  {} Running {} test(s) with {} worker(s)",
          s_cyan().apply_to("\u{25b6}"),
          s_bold().apply_to(total_tests),
          num_workers,
        );
        println!();
      },

      ReporterEvent::TestFinished { test_id, outcome } => {
        self.completed += 1;
        self
          .test_durations
          .push((test_id.full_name(), test_id.file.clone(), outcome.duration));

        let bdd = is_bdd_test(&outcome.steps);

        // BDD: print Feature header when suite changes.
        if bdd && self.current_suite.as_ref() != test_id.suite.as_ref() {
          if self.current_suite.is_some() {
            println!();
          }
          if let Some(suite) = &test_id.suite {
            println!("  {} {}", s_feature().apply_to("Feature:"), s_bold().apply_to(suite));
          }
          self.current_suite = test_id.suite.clone();
        }

        let (icon, icon_style) = status_icon(&outcome.status);
        let duration = format_duration(outcome.duration);

        match outcome.status {
          TestStatus::Passed => {
            println!(
              "  {} {} {}",
              icon_style.apply_to(icon),
              test_id.full_name(),
              s_dim().apply_to(format!("({duration})")),
            );
          },
          TestStatus::Failed | TestStatus::TimedOut => {
            println!(
              "  {} {} {}",
              icon_style.apply_to(icon),
              s_fail().apply_to(test_id.full_name()),
              s_dim().apply_to(format!("({duration})")),
            );
          },
          TestStatus::Skipped => {
            println!(
              "  {} {}",
              icon_style.apply_to(icon),
              s_skip().apply_to(test_id.full_name()),
            );
          },
          TestStatus::Flaky => {
            println!(
              "  {} {} {}",
              icon_style.apply_to(icon),
              s_flaky().apply_to(test_id.full_name()),
              s_dim().apply_to(format!("({duration}) [flaky]")),
            );
          },
          TestStatus::Interrupted => {
            println!("  {} {}", icon_style.apply_to(icon), test_id.full_name());
          },
        }

        // Only show step details for failed/timed-out tests. Passing tests
        // (including expected-failure @fail tests whose outcome was inverted)
        // don't need step-level output. Matches Playwright's list reporter
        // which hides steps by default.
        let show_steps = matches!(outcome.status, TestStatus::Failed | TestStatus::TimedOut);
        if show_steps {
          let user_steps: Vec<&TestStep> = outcome.steps.iter().filter(|s| s.category.is_visible()).collect();
          if !user_steps.is_empty() {
            print_steps(&user_steps, 4);
          }
        }

        // Error: title in bold red, then the rich body with per-line
        // colorization for unified-diff `-`/`+` markers + bold cyan
        // labels for the `Expected:` / `Received:` / `Diff:` lines.
        // The captured caller location (if any) prints between title
        // and body.
        if let Some(error) = &outcome.error {
          println!();
          for line in error.message.lines() {
            println!("    {}", s_fail().apply_to(line));
          }
          if let Some(stack) = &error.stack
            && !stack.is_empty()
          {
            for line in stack.lines() {
              println!("    {}", s_dim().apply_to(line));
            }
          }
          if let Some(diff) = &error.diff {
            for line in diff.lines() {
              let styled = style_diff_line(line);
              println!("    {styled}");
            }
          }
          println!();
        }
      },

      ReporterEvent::RunFinished {
        total,
        passed,
        failed,
        skipped,
        flaky,
        duration,
      } => {
        // Slow test report.
        if let Some(ref config) = self.slow_tests_config {
          let threshold = Duration::from_millis(config.threshold);
          let mut slow: Vec<_> = self.test_durations.iter().filter(|(_, _, d)| *d >= threshold).collect();
          slow.sort_by(|a, b| b.2.cmp(&a.2));
          let show = if config.max > 0 {
            config.max.min(slow.len())
          } else {
            slow.len()
          };
          if show > 0 {
            println!();
            println!(
              "  {} Slow test{}",
              s_warn().apply_to("\u{26a0}"),
              if show == 1 { "" } else { "s" }
            );
            for (name, file, dur) in &slow[..show] {
              println!(
                "    {} {} ({})",
                s_warn().apply_to(format_duration(*dur)),
                name,
                s_dim().apply_to(file),
              );
            }
            let remaining = slow.len() - show;
            if remaining > 0 {
              println!("    {} {remaining} more slow test(s)", s_dim().apply_to("\u{2026}"));
            }
          }
        }

        let dur = format_duration(*duration);
        println!();

        let mut parts = Vec::new();
        if *passed > 0 {
          parts.push(format!("{}", s_pass().apply_to(format!("{passed} passed"))));
        }
        if *failed > 0 {
          parts.push(format!("{}", s_fail().apply_to(format!("{failed} failed"))));
        }
        if *flaky > 0 {
          parts.push(format!("{}", s_flaky().apply_to(format!("{flaky} flaky"))));
        }
        if *skipped > 0 {
          parts.push(format!("{}", s_skip().apply_to(format!("{skipped} skipped"))));
        }

        println!(
          "  {} {}: {} {}",
          s_bold().apply_to("Tests"),
          s_dim().apply_to(format!("{total} total")),
          parts.join(&format!("{}", s_dim().apply_to(" | "))),
          s_dim().apply_to(format!("({dur})")),
        );
        println!();
      },

      _ => {},
    }
  }
}