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
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
//! Allure 2.x reporter: writes per-test JSON results for Allure Report.
//!
//! Output format: one `{uuid}-result.json` per test case in `allure-results/`,
//! plus `environment.properties` and `categories.json`. Attachments are copied
//! as `{uuid}-attachment.{ext}` files alongside the results.
//!
//! Compatible with `allure serve allure-results` and Allure Report CI plugins.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rustc_hash::FxHashMap;
use serde::Serialize;

use crate::model::{AttachmentBody, TestAnnotation, TestOutcome, TestStatus, TestStep};
use crate::reporter::{Reporter, ReporterEvent};

// ── Allure JSON schema types ──

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AllureResult {
  uuid: String,
  history_id: String,
  name: String,
  full_name: String,
  status: &'static str,
  #[serde(skip_serializing_if = "Option::is_none")]
  status_details: Option<AllureStatusDetails>,
  stage: &'static str,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  steps: Vec<AllureStep>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  attachments: Vec<AllureAttachment>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  parameters: Vec<AllureParameter>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  labels: Vec<AllureLabel>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  links: Vec<AllureLink>,
  start: u64,
  stop: u64,
}

#[derive(Serialize)]
struct AllureStatusDetails {
  #[serde(skip_serializing_if = "Option::is_none")]
  message: Option<String>,
  #[serde(skip_serializing_if = "Option::is_none")]
  trace: Option<String>,
}

#[derive(Serialize)]
struct AllureStep {
  name: String,
  status: &'static str,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  steps: Vec<AllureStep>,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  attachments: Vec<AllureAttachment>,
  start: u64,
  stop: u64,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AllureAttachment {
  name: String,
  source: String,
  #[serde(rename = "type")]
  content_type: String,
}

#[derive(Serialize)]
struct AllureParameter {
  name: String,
  value: String,
}

#[derive(Serialize)]
struct AllureLabel {
  name: String,
  value: String,
}

#[derive(Serialize)]
struct AllureLink {
  name: String,
  url: String,
  #[serde(rename = "type")]
  link_type: String,
}

#[derive(Serialize)]
struct AllureCategory {
  name: String,
  #[serde(skip_serializing_if = "Vec::is_empty")]
  #[serde(rename = "matchedStatuses")]
  matched_statuses: Vec<String>,
  #[serde(skip_serializing_if = "Option::is_none")]
  #[serde(rename = "messageRegex")]
  message_regex: Option<String>,
}

// ── Reporter ──

pub struct AllureReporter {
  output_dir: PathBuf,
  /// Optional suite title override from config.
  suite_title: Option<String>,
  /// Collected results to write in finalize.
  results: Vec<PendingResult>,
  /// Run-level environment info.
  env: BTreeMap<String, String>,
  /// Per-test start timestamps (recorded on TestStarted events).
  test_starts: FxHashMap<String, u64>,
  /// Run start timestamp (epoch ms).
  run_start: u64,
}

struct PendingResult {
  result: AllureResult,
  attachments: Vec<PendingAttachment>,
}

struct PendingAttachment {
  filename: String,
  body: AttachmentBody,
}

impl AllureReporter {
  pub fn new(output_dir: PathBuf) -> Self {
    Self {
      output_dir,
      suite_title: None,
      results: Vec::new(),
      env: BTreeMap::new(),
      test_starts: FxHashMap::default(),
      run_start: epoch_ms(),
    }
  }

  pub fn with_suite_title(mut self, title: String) -> Self {
    self.suite_title = Some(title);
    self
  }
}

#[async_trait::async_trait]
impl Reporter for AllureReporter {
  async fn on_event(&mut self, event: &ReporterEvent) {
    match event {
      ReporterEvent::RunStarted {
        total_tests,
        num_workers,
        ..
      } => {
        self.run_start = epoch_ms();
        self.env.insert("Total Tests".into(), total_tests.to_string());
        self.env.insert("Workers".into(), num_workers.to_string());
        self.env.insert("OS".into(), std::env::consts::OS.into());
        self.env.insert("Arch".into(), std::env::consts::ARCH.into());
        self.env.insert("ferridriver".into(), env!("CARGO_PKG_VERSION").into());
      },
      ReporterEvent::TestStarted { test_id, .. } => {
        self.test_starts.insert(test_id.full_name(), epoch_ms());
      },
      ReporterEvent::TestFinished { outcome, .. } => {
        self.collect_result(outcome);
      },
      ReporterEvent::RunFinished { duration, .. } => {
        self
          .env
          .insert("Duration".into(), format!("{:.1}s", duration.as_secs_f64()));
      },
      _ => {},
    }
  }

  async fn finalize(&mut self) -> ferridriver::error::Result<()> {
    std::fs::create_dir_all(&self.output_dir)?;

    // Write each test result.
    for pending in &self.results {
      let filename = format!("{}-result.json", pending.result.uuid);
      let path = self.output_dir.join(&filename);
      let json = serde_json::to_string_pretty(&pending.result)?;
      std::fs::write(&path, json)?;

      // Write attachments.
      for attach in &pending.attachments {
        let attach_path = self.output_dir.join(&attach.filename);
        match &attach.body {
          AttachmentBody::Bytes(bytes) => {
            std::fs::write(&attach_path, bytes)?;
          },
          AttachmentBody::Path(src) => {
            if src.exists() {
              std::fs::copy(src, &attach_path)?;
            }
          },
        }
      }
    }

    // Write environment.properties.
    if !self.env.is_empty() {
      let props: String = self
        .env
        .iter()
        .map(|(k, v)| format!("{k}={v}"))
        .collect::<Vec<_>>()
        .join("\n");
      std::fs::write(self.output_dir.join("environment.properties"), props).ok();
    }

    // Write categories.json (default error classification).
    let categories = vec![
      AllureCategory {
        name: "Test failures".into(),
        matched_statuses: vec!["failed".into()],
        message_regex: None,
      },
      AllureCategory {
        name: "Timeouts".into(),
        matched_statuses: vec!["broken".into()],
        message_regex: Some(".*timed? ?out.*".into()),
      },
      AllureCategory {
        name: "Infrastructure".into(),
        matched_statuses: vec!["broken".into()],
        message_regex: None,
      },
    ];
    let cats_json = serde_json::to_string_pretty(&categories)?;
    std::fs::write(self.output_dir.join("categories.json"), cats_json).ok();

    let count = self.results.len();
    tracing::info!(
      "Allure results written to {} ({count} tests)",
      self.output_dir.display()
    );
    Ok(())
  }
}

impl AllureReporter {
  fn collect_result(&mut self, outcome: &TestOutcome) {
    let uuid = make_uuid();
    let start_ms = self
      .test_starts
      .remove(&outcome.test_id.full_name())
      .unwrap_or(self.run_start);
    let stop_ms = start_ms + outcome.duration.as_millis() as u64;

    let status = map_status(&outcome.status);
    let status_details = outcome.error.as_ref().map(|e| AllureStatusDetails {
      message: Some(e.message.clone()),
      trace: e.stack.clone(),
    });

    // Convert steps.
    let steps = convert_steps(&outcome.steps, start_ms);

    // Convert attachments.
    let mut allure_attachments = Vec::new();
    let mut pending_attachments = Vec::new();
    for attach in &outcome.attachments {
      let ext = mime_to_ext(&attach.content_type);
      let attach_uuid = make_uuid();
      let filename = format!("{attach_uuid}-attachment.{ext}");
      allure_attachments.push(AllureAttachment {
        name: attach.name.clone(),
        source: filename.clone(),
        content_type: attach.content_type.clone(),
      });
      pending_attachments.push(PendingAttachment {
        filename,
        body: attach.body.clone(),
      });
    }

    // Also handle screenshot-on-failure embedded in the error.
    if let Some(ref err) = outcome.error {
      if let Some(ref screenshot) = err.screenshot {
        let attach_uuid = make_uuid();
        let filename = format!("{attach_uuid}-attachment.png");
        allure_attachments.push(AllureAttachment {
          name: "Screenshot on failure".into(),
          source: filename.clone(),
          content_type: "image/png".into(),
        });
        pending_attachments.push(PendingAttachment {
          filename,
          body: AttachmentBody::Bytes(screenshot.clone()),
        });
      }
    }

    // Build labels from annotations.
    let suite_value = self
      .suite_title
      .clone()
      .or_else(|| outcome.test_id.suite.clone())
      .unwrap_or_default();
    let mut labels = vec![
      AllureLabel {
        name: "suite".into(),
        value: suite_value,
      },
      AllureLabel {
        name: "parentSuite".into(),
        value: outcome.test_id.file.clone(),
      },
    ];
    let mut links = Vec::new();

    for annotation in &outcome.annotations {
      match annotation {
        TestAnnotation::Tag(tag) => {
          labels.push(AllureLabel {
            name: "tag".into(),
            value: tag.clone(),
          });
        },
        TestAnnotation::Info { type_name, description } => match type_name.as_str() {
          "severity" => labels.push(AllureLabel {
            name: "severity".into(),
            value: description.clone(),
          }),
          "owner" => labels.push(AllureLabel {
            name: "owner".into(),
            value: description.clone(),
          }),
          "epic" => labels.push(AllureLabel {
            name: "epic".into(),
            value: description.clone(),
          }),
          "feature" => labels.push(AllureLabel {
            name: "feature".into(),
            value: description.clone(),
          }),
          "story" => labels.push(AllureLabel {
            name: "story".into(),
            value: description.clone(),
          }),
          "issue" => links.push(AllureLink {
            name: description.clone(),
            url: description.clone(),
            link_type: "issue".into(),
          }),
          "tms" => links.push(AllureLink {
            name: description.clone(),
            url: description.clone(),
            link_type: "tms".into(),
          }),
          _ => labels.push(AllureLabel {
            name: type_name.clone(),
            value: description.clone(),
          }),
        },
        TestAnnotation::Slow { .. } => {
          labels.push(AllureLabel {
            name: "tag".into(),
            value: "slow".into(),
          });
        },
        TestAnnotation::Fixme { reason, .. } => {
          labels.push(AllureLabel {
            name: "tag".into(),
            value: "fixme".into(),
          });
          if let Some(r) = reason {
            labels.push(AllureLabel {
              name: "description".into(),
              value: r.clone(),
            });
          }
        },
        TestAnnotation::Fail { .. } => {
          labels.push(AllureLabel {
            name: "tag".into(),
            value: "expected-failure".into(),
          });
        },
        _ => {},
      }
    }

    // Flaky label.
    if outcome.status == TestStatus::Flaky {
      labels.push(AllureLabel {
        name: "tag".into(),
        value: "flaky".into(),
      });
    }

    // Parameters: attempt info if retried.
    let mut parameters = Vec::new();
    if outcome.max_attempts > 1 {
      parameters.push(AllureParameter {
        name: "attempt".into(),
        value: format!("{}/{}", outcome.attempt, outcome.max_attempts),
      });
    }

    // Stable history ID for Allure trend tracking.
    let history_id = format!("{:x}", simple_hash(&outcome.test_id.full_name()));

    let result = AllureResult {
      uuid: uuid.clone(),
      history_id,
      name: outcome.test_id.name.clone(),
      full_name: outcome.test_id.full_name(),
      status,
      status_details,
      stage: "finished",
      steps,
      attachments: allure_attachments,
      parameters,
      labels,
      links,
      start: start_ms,
      stop: stop_ms,
    };

    self.results.push(PendingResult {
      result,
      attachments: pending_attachments,
    });
  }
}

// ── Helpers ──

fn convert_steps(steps: &[TestStep], parent_start: u64) -> Vec<AllureStep> {
  let mut offset = parent_start;
  steps
    .iter()
    .map(|s| {
      let start = offset;
      let stop = start + s.duration.as_millis() as u64;
      offset = stop;
      AllureStep {
        name: s.title.clone(),
        status: map_step_status(s),
        steps: convert_steps(&s.steps, start),
        attachments: Vec::new(),
        start,
        stop,
      }
    })
    .collect()
}

fn map_status(status: &TestStatus) -> &'static str {
  match status {
    TestStatus::Passed | TestStatus::Flaky => "passed",
    TestStatus::Failed => "failed",
    TestStatus::TimedOut | TestStatus::Interrupted => "broken",
    TestStatus::Skipped => "skipped",
  }
}

fn map_step_status(step: &TestStep) -> &'static str {
  match step.status {
    crate::model::StepStatus::Passed => "passed",
    crate::model::StepStatus::Failed => "failed",
    crate::model::StepStatus::Skipped => "skipped",
    crate::model::StepStatus::Pending => "skipped",
  }
}

fn mime_to_ext(content_type: &str) -> &str {
  match content_type {
    "image/png" => "png",
    "image/jpeg" | "image/jpg" => "jpg",
    "text/plain" => "txt",
    "text/html" => "html",
    "application/json" => "json",
    "video/webm" => "webm",
    "application/zip" => "zip",
    _ => "bin",
  }
}

/// Simple non-cryptographic hash for stable history IDs.
fn simple_hash(s: &str) -> u64 {
  let mut hash: u64 = 5381;
  for b in s.bytes() {
    hash = hash.wrapping_mul(33).wrapping_add(u64::from(b));
  }
  hash
}

/// Generate a UUID-v4-like string (no external dep, good enough for Allure).
fn make_uuid() -> String {
  use std::sync::atomic::{AtomicU64, Ordering};
  static COUNTER: AtomicU64 = AtomicU64::new(0);

  let ts = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .unwrap_or(Duration::ZERO)
    .as_nanos() as u64;
  let count = COUNTER.fetch_add(1, Ordering::Relaxed);

  // Mix timestamp + counter for uniqueness.
  let a = ts ^ (count.wrapping_mul(0x517c_c1b7_2722_0a95));
  let b = ts.wrapping_mul(0x6c62_272e_07bb_0142) ^ count;

  format!(
    "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
    (a >> 32) as u32,
    (a >> 16) as u16,
    a as u16 & 0x0fff,
    ((b >> 48) as u16 & 0x3fff) | 0x8000,
    b & 0xffff_ffff_ffff,
  )
}

fn epoch_ms() -> u64 {
  SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .unwrap_or(Duration::ZERO)
    .as_millis() as u64
}