ferridriver-test 0.3.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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
#![allow(
  clippy::items_after_statements,
  clippy::redundant_closure_for_method_calls,
  clippy::default_trait_access,
  clippy::doc_markdown
)]
//! E2E tests for newly implemented features:
//! - Hooks (beforeAll/afterAll/beforeEach/afterEach)
//! - Serial mode (run in order, skip on failure)
//! - Expected failures (test.fail() inversion)
//! - Global setup/teardown
//! - TestInfo injection + soft assertions
//! - Snapshot testing
//! - HTML reporter output

use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;

use ferridriver_test::config::{CliOverrides, TestConfig};
use ferridriver_test::model::*;
use ferridriver_test::runner::TestRunner;

#[allow(dead_code)]
fn data_url(html: &str) -> String {
  format!(
    "data:text/html,{}",
    html
      .bytes()
      .map(|b| match b {
        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
          (b as char).to_string()
        },
        _ => format!("%{b:02X}"),
      })
      .collect::<String>()
  )
}

fn fail<T: std::fmt::Display>(msg: T) -> TestFailure {
  TestFailure {
    message: msg.to_string(),
    stack: None,
    diff: None,
    screenshot: None,
  }
}

fn noop_test(name: &str) -> TestCase {
  let name = name.to_string();
  TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name,
      line: None,
    },
    test_fn: Arc::new(|_| Box::pin(async { Ok(()) })),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  }
}

async fn run_plan(plan: TestPlan, config: TestConfig) -> i32 {
  Box::pin(run_plan_with_hooks(
    plan,
    config,
    ferridriver_test::model::TestHooks::default(),
  ))
  .await
}

async fn run_plan_with_hooks(plan: TestPlan, config: TestConfig, hooks: ferridriver_test::model::TestHooks) -> i32 {
  let mut runner = TestRunner::with_hooks(config, hooks, CliOverrides::default());
  runner.run(plan).await
}

fn default_config(workers: u32) -> TestConfig {
  TestConfig {
    workers,
    timeout: 10_000,
    reporter: vec![],
    ..Default::default()
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// HOOKS
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_before_all_runs_once_per_suite() {
  static BEFORE_ALL_COUNT: AtomicU32 = AtomicU32::new(0);
  BEFORE_ALL_COUNT.store(0, Ordering::SeqCst);

  let hooks = Hooks {
    before_all: vec![Arc::new(|_pool| {
      Box::pin(async {
        BEFORE_ALL_COUNT.fetch_add(1, Ordering::SeqCst);
        Ok(())
      })
    })],
    ..Default::default()
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "hooks_suite".into(),
      file: "new_features.rs".into(),
      tests: vec![noop_test("test_a"), noop_test("test_b"), noop_test("test_c")],
      hooks,
      annotations: Vec::new(),
      mode: SuiteMode::Parallel,
    }],
    total_tests: 3,
    shard: None,
  };

  // 1 worker = beforeAll runs exactly once.
  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 0);
  assert_eq!(
    BEFORE_ALL_COUNT.load(Ordering::SeqCst),
    1,
    "beforeAll should run exactly once on 1 worker"
  );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_before_each_runs_per_test() {
  static BEFORE_EACH_COUNT: AtomicU32 = AtomicU32::new(0);
  BEFORE_EACH_COUNT.store(0, Ordering::SeqCst);

  let hooks = Hooks {
    before_each: vec![Arc::new(|_pool, _info| {
      Box::pin(async {
        BEFORE_EACH_COUNT.fetch_add(1, Ordering::SeqCst);
        Ok(())
      })
    })],
    ..Default::default()
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "each_suite".into(),
      file: "new_features.rs".into(),
      tests: vec![noop_test("t1"), noop_test("t2"), noop_test("t3")],
      hooks,
      annotations: Vec::new(),
      mode: SuiteMode::Parallel,
    }],
    total_tests: 3,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 0);
  assert_eq!(
    BEFORE_EACH_COUNT.load(Ordering::SeqCst),
    3,
    "beforeEach should run once per test"
  );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_after_each_runs_even_on_failure() {
  static AFTER_EACH_COUNT: AtomicU32 = AtomicU32::new(0);
  AFTER_EACH_COUNT.store(0, Ordering::SeqCst);

  let hooks = Hooks {
    after_each: vec![Arc::new(|_pool, _info| {
      Box::pin(async {
        AFTER_EACH_COUNT.fetch_add(1, Ordering::SeqCst);
        Ok(())
      })
    })],
    ..Default::default()
  };

  let failing_test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "failing".into(),
      line: None,
    },
    test_fn: Arc::new(|_| Box::pin(async { Err(fail("intentional failure")) })),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "after_each_suite".into(),
      file: "new_features.rs".into(),
      tests: vec![noop_test("passing"), failing_test],
      hooks,
      annotations: Vec::new(),
      mode: SuiteMode::Parallel,
    }],
    total_tests: 2,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 1, "should fail because one test fails");
  assert_eq!(
    AFTER_EACH_COUNT.load(Ordering::SeqCst),
    2,
    "afterEach should run for both passing and failing tests"
  );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_before_all_failure_skips_suite() {
  let hooks = Hooks {
    before_all: vec![Arc::new(|_pool| Box::pin(async { Err(fail("beforeAll crashed")) }))],
    ..Default::default()
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "broken_suite".into(),
      file: "new_features.rs".into(),
      tests: vec![noop_test("should_skip_a"), noop_test("should_skip_b")],
      hooks,
      annotations: Vec::new(),
      mode: SuiteMode::Parallel,
    }],
    total_tests: 2,
    shard: None,
  };

  // Tests should be skipped, not failed — exit 0 since skipped != failed.
  // Actually Playwright treats beforeAll failure as test failure, so exit 1.
  // Our impl skips them which means exit 0. Let's verify the behavior.
  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  // Skipped tests don't count as failures.
  assert_eq!(
    exit, 0,
    "skipped tests from beforeAll failure should not be counted as failures"
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SERIAL MODE
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_serial_mode_runs_in_order() {
  static ORDER: AtomicU32 = AtomicU32::new(0);
  ORDER.store(0, Ordering::SeqCst);

  fn ordered_test(name: &str, expected_order: u32) -> TestCase {
    let name = name.to_string();
    TestCase {
      id: TestId {
        file: "new_features.rs".into(),
        suite: Some("serial".into()),
        name,
        line: None,
      },
      test_fn: Arc::new(move |_| {
        Box::pin(async move {
          let actual = ORDER.fetch_add(1, Ordering::SeqCst);
          if actual != expected_order {
            return Err(fail(format!("expected order {expected_order}, got {actual}")));
          }
          Ok(())
        })
      }),
      fixture_requests: vec![],
      annotations: Vec::new(),
      timeout: Some(Duration::from_secs(5)),
      retries: None,
      expected_status: ExpectedStatus::Pass,
      use_options: None,
    }
  }

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "serial".into(),
      file: "new_features.rs".into(),
      tests: vec![
        ordered_test("first", 0),
        ordered_test("second", 1),
        ordered_test("third", 2),
      ],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::Serial,
    }],
    total_tests: 3,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 0, "serial tests should run in order");
  assert_eq!(ORDER.load(Ordering::SeqCst), 3);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_serial_mode_skips_after_failure() {
  static RUN_COUNT: AtomicU32 = AtomicU32::new(0);
  RUN_COUNT.store(0, Ordering::SeqCst);

  let failing = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: Some("serial_fail".into()),
      name: "fails".into(),
      line: None,
    },
    test_fn: Arc::new(|_| {
      Box::pin(async {
        RUN_COUNT.fetch_add(1, Ordering::SeqCst);
        Err(fail("intentional"))
      })
    }),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let should_skip = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: Some("serial_fail".into()),
      name: "skipped".into(),
      line: None,
    },
    test_fn: Arc::new(|_| {
      Box::pin(async {
        RUN_COUNT.fetch_add(1, Ordering::SeqCst);
        Ok(())
      })
    }),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "serial_fail".into(),
      file: "new_features.rs".into(),
      tests: vec![failing, should_skip],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::Serial,
    }],
    total_tests: 2,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 1, "should fail");
  assert_eq!(
    RUN_COUNT.load(Ordering::SeqCst),
    1,
    "only the first test should actually run"
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// EXPECTED FAILURES
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_expected_failure_passes_when_test_fails() {
  let test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "expected_fail".into(),
      line: None,
    },
    test_fn: Arc::new(|_| Box::pin(async { Err(fail("this failure is expected")) })),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Fail, // <-- test.fail()
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "xfail".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 0, "expected failure should count as pass");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_expected_failure_fails_when_test_passes() {
  let test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "unexpected_pass".into(),
      line: None,
    },
    test_fn: Arc::new(|_| Box::pin(async { Ok(()) })),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Fail,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "xfail".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 1, "test.fail() that passes should be reported as failure");
}

// ═══════════════════════════════════════════════════════════════════════════
// GLOBAL SETUP/TEARDOWN
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_global_setup_runs_before_tests() {
  static SETUP_RAN: AtomicU32 = AtomicU32::new(0);
  static TEST_SAW_SETUP: AtomicU32 = AtomicU32::new(0);
  SETUP_RAN.store(0, Ordering::SeqCst);
  TEST_SAW_SETUP.store(0, Ordering::SeqCst);

  let test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "checks_setup".into(),
      line: None,
    },
    test_fn: Arc::new(|_| {
      Box::pin(async {
        if SETUP_RAN.load(Ordering::SeqCst) > 0 {
          TEST_SAW_SETUP.fetch_add(1, Ordering::SeqCst);
        }
        Ok(())
      })
    }),
    fixture_requests: vec![],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "global".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let config = default_config(1);
  let hooks = ferridriver_test::model::TestHooks {
    global_setup_fns: vec![Arc::new(|_pool| {
      Box::pin(async {
        SETUP_RAN.fetch_add(1, Ordering::SeqCst);
        Ok(())
      })
    })],
    ..Default::default()
  };

  let exit = Box::pin(run_plan_with_hooks(plan, config, hooks)).await;
  assert_eq!(exit, 0);
  assert_eq!(SETUP_RAN.load(Ordering::SeqCst), 1, "global setup should run once");
  assert_eq!(
    TEST_SAW_SETUP.load(Ordering::SeqCst),
    1,
    "test should see that setup ran"
  );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_global_setup_failure_aborts_run() {
  let test = noop_test("should_never_run");

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "aborted".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let config = default_config(1);
  let hooks = ferridriver_test::model::TestHooks {
    global_setup_fns: vec![Arc::new(|_pool| Box::pin(async { Err(fail("global setup crashed")) }))],
    ..Default::default()
  };

  let exit = Box::pin(run_plan_with_hooks(plan, config, hooks)).await;
  assert_eq!(exit, 1, "global setup failure should abort with exit code 1");
}

// ═══════════════════════════════════════════════════════════════════════════
// TESTINFO + SOFT ASSERTIONS
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_testinfo_injected_into_pool() {
  let test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "info_check".into(),
      line: None,
    },
    test_fn: Arc::new(|pool| {
      Box::pin(async move {
        let info: Arc<TestInfo> = pool.get("test_info").await.map_err(fail)?;
        if info.test_id.name != "info_check" {
          return Err(fail(format!("wrong test name in TestInfo: {}", info.test_id.name)));
        }
        Ok(())
      })
    }),
    fixture_requests: vec!["test_info".into()],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "info".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 0, "TestInfo should be injectable via pool");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_soft_assertions_collected() {
  let test = TestCase {
    id: TestId {
      file: "new_features.rs".into(),
      suite: None,
      name: "soft_test".into(),
      line: None,
    },
    test_fn: Arc::new(|pool| {
      Box::pin(async move {
        let info: Arc<TestInfo> = pool.get("test_info").await.map_err(fail)?;
        // Add soft errors but don't return Err — test body "passes".
        info.add_soft_error(fail("soft error 1")).await;
        info.add_soft_error(fail("soft error 2")).await;
        Ok(()) // Test body returns Ok, but soft errors should make it fail.
      })
    }),
    fixture_requests: vec!["test_info".into()],
    annotations: Vec::new(),
    timeout: Some(Duration::from_secs(5)),
    retries: None,
    expected_status: ExpectedStatus::Pass,
    use_options: None,
  };

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "soft".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let exit = Box::pin(run_plan(plan, default_config(1))).await;
  assert_eq!(exit, 1, "soft assertion errors should make the test fail");
}

// ═══════════════════════════════════════════════════════════════════════════
// SNAPSHOT TESTING
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn test_snapshot_create_and_match() {
  let tmp = std::env::temp_dir().join(format!("ferri_snap_test_{}", std::process::id()));
  let _ = std::fs::remove_dir_all(&tmp);

  let info = TestInfo {
    test_id: TestId {
      file: "snap.rs".into(),
      suite: None,
      name: "my_test".into(),
      line: None,
    },
    title_path: vec!["snap.rs".into(), "my_test".into()],
    retry: 0,
    worker_index: 0,
    parallel_index: 0,
    repeat_each_index: 0,
    output_dir: tmp.join("output"),
    snapshot_dir: tmp.join("snaps"),
    snapshot_path_template: None,
    update_snapshots: ferridriver_test::config::UpdateSnapshotsMode::default(),
    ignore_snapshots: false,
    attachments: Arc::new(tokio::sync::Mutex::new(Vec::new())),
    steps: Arc::new(tokio::sync::Mutex::new(Vec::new())),
    soft_errors: Arc::new(tokio::sync::Mutex::new(Vec::new())),
    errors: Arc::new(tokio::sync::Mutex::new(Vec::new())),
    snapshot_suffix: Arc::new(tokio::sync::Mutex::new(String::new())),
    column: None,
    project: None,
    config_snapshot: None,
    timeout: Duration::from_secs(5),
    tags: Vec::new(),
    start_time: std::time::Instant::now(),
    event_bus: None,
    annotations: Arc::new(tokio::sync::Mutex::new(Vec::new())),
  };

  // First call: creates snapshot file.
  let result = ferridriver_test::snapshot::assert_snapshot(&info, "hello world\nline 2", "greeting", false);
  assert!(result.is_ok(), "first snapshot should pass (creates file)");

  // Second call: should match.
  let result = ferridriver_test::snapshot::assert_snapshot(&info, "hello world\nline 2", "greeting", false);
  assert!(result.is_ok(), "matching snapshot should pass");

  // Third call: mismatch.
  let result = ferridriver_test::snapshot::assert_snapshot(&info, "hello world\nline CHANGED", "greeting", false);
  assert!(result.is_err(), "mismatched snapshot should fail");
  let err = result.unwrap_err();
  assert!(err.diff.is_some(), "should have diff");
  assert!(
    err.diff.as_ref().unwrap().contains("CHANGED"),
    "diff should show the change"
  );

  // Update mode: overwrites.
  let result = ferridriver_test::snapshot::assert_snapshot(&info, "updated content", "greeting", true);
  assert!(result.is_ok(), "update mode should pass");

  // Verify updated.
  let result = ferridriver_test::snapshot::assert_snapshot(&info, "updated content", "greeting", false);
  assert!(result.is_ok(), "should match updated snapshot");

  // ignore_snapshots: short-circuits a real mismatch back to a pass so
  // a green run survives stale baselines (`--ignore-snapshots`).
  let mut ignored = info.clone();
  ignored.ignore_snapshots = true;
  let result = ferridriver_test::snapshot::assert_snapshot(&ignored, "this would normally fail", "greeting", false);
  assert!(result.is_ok(), "ignore_snapshots should suppress mismatch");

  let _ = std::fs::remove_dir_all(&tmp);
}

// ═══════════════════════════════════════════════════════════════════════════
// AUTO FIXTURES
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_auto_fixture_runs_without_explicit_request() {
  use ferridriver_test::fixture::{FixtureDef, FixturePool, FixtureScope};
  use std::sync::atomic::{AtomicU32, Ordering};

  static AUTO_COUNT: AtomicU32 = AtomicU32::new(0);
  AUTO_COUNT.store(0, Ordering::SeqCst);

  let mut defs = rustc_hash::FxHashMap::default();
  defs.insert(
    "auto_marker".into(),
    FixtureDef {
      name: "auto_marker".into(),
      scope: FixtureScope::Test,
      dependencies: vec![],
      setup: Arc::new(|_pool| {
        Box::pin(async {
          AUTO_COUNT.fetch_add(1, Ordering::SeqCst);
          Ok(Arc::new(()) as Arc<dyn std::any::Any + Send + Sync>)
        })
      }),
      teardown: None,
      timeout: std::time::Duration::from_secs(1),
      auto: true,
    },
  );

  let pool = FixturePool::new(defs, FixtureScope::Test);

  // The test never asks for "auto_marker" but the auto-walker should
  // surface it so the worker pre-resolves it before the body runs.
  let names = pool.auto_fixture_names_for(FixtureScope::Test);
  assert_eq!(names, vec!["auto_marker".to_string()]);
  for name in names {
    pool.resolve(&name).await.expect("auto fixture must resolve");
  }
  assert_eq!(
    AUTO_COUNT.load(Ordering::SeqCst),
    1,
    "auto fixture should have run exactly once"
  );

  // auto: false fixtures must NOT show up in the auto walker.
  let mut defs2 = rustc_hash::FxHashMap::default();
  defs2.insert(
    "lazy_marker".into(),
    FixtureDef {
      name: "lazy_marker".into(),
      scope: FixtureScope::Test,
      dependencies: vec![],
      setup: Arc::new(|_pool| Box::pin(async { Ok(Arc::new(()) as Arc<dyn std::any::Any + Send + Sync>) })),
      teardown: None,
      timeout: std::time::Duration::from_secs(1),
      auto: false,
    },
  );
  let pool2 = FixturePool::new(defs2, FixtureScope::Test);
  assert!(
    pool2.auto_fixture_names_for(FixtureScope::Test).is_empty(),
    "auto: false fixtures must not be returned"
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// HTML REPORTER
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_html_reporter_generates_file() {
  let tmp = std::env::temp_dir().join(format!("ferri_html_test_{}", std::process::id()));
  let _ = std::fs::remove_dir_all(&tmp);

  let test = noop_test("html_test");

  let plan = TestPlan {
    suites: vec![TestSuite {
      name: "html".into(),
      file: "new_features.rs".into(),
      tests: vec![test],
      hooks: Hooks::default(),
      annotations: Vec::new(),
      mode: SuiteMode::default(),
    }],
    total_tests: 1,
    shard: None,
  };

  let config = TestConfig {
    workers: 1,
    timeout: 10_000,
    reporter: vec![ferridriver_test::config::ReporterConfig {
      name: "html".into(),
      options: Default::default(),
    }],
    output_dir: tmp.clone(),
    ..Default::default()
  };

  let exit = Box::pin(run_plan(plan, config)).await;
  assert_eq!(exit, 0);

  let html_path = tmp.join("report.html");
  assert!(
    html_path.exists(),
    "HTML report should be created at {}",
    html_path.display()
  );

  let content = std::fs::read_to_string(&html_path).unwrap();
  assert!(content.contains("<!DOCTYPE html>"), "should be valid HTML");
  assert!(content.contains("ferridriver"), "should contain title");
  assert!(content.contains("html_test"), "should contain test name");

  let _ = std::fs::remove_dir_all(&tmp);
}