rvtest 0.2.0

A Next Level Testing Library for Rust — BDD specs, property-based testing, parametrized tests, rich reporting, and code coverage
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
836
837
838
//! BDD-style test specification builder.
//!
//! The [`Spec`] type lets you organise tests in a nested, descriptive
//! hierarchy using [`describe`] / [`it`](Spec::it) blocks, attach
//! metadata ([`tag()`](Spec::tag), [`timeout()`](Spec::timeout),
//! [`retries()`](Spec::retries)), and register lifecycle hooks
//! ([`before_all()`](Spec::before_all), [`after_all()`](Spec::after_all),
//! [`before_each()`](Spec::before_each), [`after_each()`](Spec::after_each)).
//!
//! # Example
//!
//! ```ignore
//! use rvtest::spec::describe;
//!
//! #[test]
//! fn my_tests() {
//!     describe("Calculator")
//!         .it("adds", || assert_eq!(2 + 2, 4))
//!         .tag("arithmetic")
//!         .run()
//!         .assert_all_pass();
//! }
//! ```

use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::core::{RunnerConfig, SourceLocation, TestCase, TestStatus, TestSuite};

/// A BDD-style test specification builder.
///
/// `Spec` lets you organise tests in a nested, descriptive hierarchy using
/// [`describe`] / [`it`](Spec::it) blocks, attach metadata such as
/// [`tags`](Spec::tag), [`timeout`](Spec::timeout) and [`retries`](Spec::retries),
/// and register lifecycle hooks via [`before_all`](Spec::before_all) /
/// [`after_all`](Spec::after_all).
///
/// # Example inside `#[test]` (recommended)
///
/// ```ignore
/// use rvtest::spec::describe;
///
/// #[test]
/// fn my_tests() {
///     describe("Calculator")
///         .describe("addition")
///             .it("adds positive numbers", || {
///                 assert_eq!(2 + 2, 4);
///             })
///             .tag("arithmetic")
///             .timeout(std::time::Duration::from_secs(2))
///         .run()
///         .assert_all_pass();
/// }
/// ```
///
/// Call [`run`](Spec::run) to execute all leaf tests and produce a [`TestSuite`],
/// then call [`assert_all_pass`](crate::core::TestSuite::assert_all_pass) to
/// verify results inside a `#[test]`.
pub struct Spec {
    name: String,
    description: Option<String>,
    tags: Vec<String>,
    setup: Option<Arc<dyn Fn() + Send + Sync>>,
    teardown: Option<Arc<dyn Fn() + Send + Sync>>,
    before_each: Option<Arc<dyn Fn() + Send + Sync>>,
    after_each: Option<Arc<dyn Fn() + Send + Sync>>,
    children: Vec<Spec>,
    tests: Vec<TestEntry>,
    timeout: Option<Duration>,
    retries: u32,
}

struct TestEntry {
    name: String,
    location: Option<SourceLocation>,
    test_fn: Arc<dyn Fn() + Send + Sync>,
}

/// Create a new top-level `Spec` with the given name.
///
/// This is the entry point for BDD-style test organisation. Use chained
/// method calls to describe the expected behaviour, then call [`run`](Spec::run).
pub fn describe(name: &str) -> Spec {
    Spec::new(name)
}

impl Spec {
    /// Create a new `Spec` with the given name.
    pub fn new(name: &str) -> Self {
        Spec {
            name: name.to_owned(),
            description: None,
            tags: Vec::new(),
            setup: None,
            teardown: None,
            before_each: None,
            after_each: None,
            children: Vec::new(),
            tests: Vec::new(),
            timeout: None,
            retries: 0,
        }
    }

    /// Attach a description to this spec block.
    pub fn description(mut self, text: &str) -> Self {
        self.description = Some(text.to_owned());
        self
    }

    /// Add a tag to this spec and all contained tests.
    pub fn tag(mut self, tag: &str) -> Self {
        self.tags.push(tag.to_owned());
        self
    }

    /// Set the default timeout for tests in this block.
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = Some(duration);
        self
    }

    /// Set the number of retries for flaky tests in this block.
    pub fn retries(mut self, count: u32) -> Self {
        self.retries = count;
        self
    }

    /// Register a setup hook run once before any test in this block.
    pub fn before_all(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.setup = Some(Arc::new(hook));
        self
    }

    /// Register a teardown hook run once after all tests in this block.
    pub fn after_all(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.teardown = Some(Arc::new(hook));
        self
    }

    /// Register a hook run before each test in this block (and child blocks).
    ///
    /// When nested, parent `before_each` hooks run before child `before_each`
    /// hooks. If the hook panics, the test is marked as failed but execution
    /// continues with the next test.
    pub fn before_each(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.before_each = Some(Arc::new(hook));
        self
    }

    /// Register a hook run after each test in this block (and child blocks).
    ///
    /// When nested, child `after_each` hooks run before parent `after_each`
    /// hooks. The hook runs even if the test itself panics.
    pub fn after_each(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.after_each = Some(Arc::new(hook));
        self
    }

    /// Register a leaf test case with the given name and body.
    ///
    /// The test body should use `assert!` / `assert_eq!` and will have its
    /// panics caught and reported as failures.
    #[track_caller]
    pub fn it(mut self, name: &str, test: impl Fn() + Send + Sync + 'static) -> Self {
        let loc = std::panic::Location::caller();
        self.tests.push(TestEntry {
            name: name.to_owned(),
            location: Some(SourceLocation {
                file: loc.file().to_owned(),
                line: loc.line(),
                column: None,
            }),
            test_fn: Arc::new(test),
        });
        self
    }

    /// Nest a child spec block inside this one.
    ///
    /// Child specs inherit the parent's tags, timeout, retry, and
    /// before_each/after_each settings unless they override them.
    pub fn describe(mut self, name: &str) -> SpecBuilder {
        let child_index = self.children.len();
        let child = Spec::new(name);
        self.children.push(child);
        SpecBuilder { parent: self, path: vec![child_index] }
    }

    /// Execute all leaf tests in this spec tree and return a `TestSuite`.
    ///
    /// Hooks (`before_all` / `after_all` / `before_each` / `after_each`) are
    /// honoured per block. Timing information is collected for each test and
    /// for the suite as a whole.
    pub fn run(self) -> TestSuite {
        let config = RunnerConfig::default();
        self.run_with_config(&config)
    }

    /// Execute tests with an explicit [`RunnerConfig`].
    pub fn run_with_config(self, config: &RunnerConfig) -> TestSuite {
        let mut suite = TestSuite::new(&self.name);
        suite.description = self.description.clone();

        // Enable output capture if configured
        if config.output_capture {
            crate::capture::set_capture_enabled(true);
        }

        let start = Instant::now();

        let test_cases = self.execute_recursive("", &[], None, 0, &[], &[], config);

        suite.duration = start.elapsed();
        suite.tests = test_cases;
        suite
    }

    /// Check whether this spec (or any descendant) produces at least one
    /// test that passes the current tag/name filters.
    fn has_matching(
        &self,
        prefix: &str,
        inherited_tags: &[String],
        config: &RunnerConfig,
    ) -> bool {
        let full_name = if prefix.is_empty() {
            self.name.clone()
        } else {
            format!("{} :: {}", prefix, self.name)
        };

        let merged_tags: Vec<String> = inherited_tags
            .iter()
            .cloned()
            .chain(self.tags.iter().cloned())
            .collect();

        for entry in &self.tests {
            let test_name = format!("{} :: {}", full_name, entry.name);
            if crate::tag::tags_match(&merged_tags, config)
                && crate::tag::name_matches(&test_name, config.filter.as_deref())
            {
                return true;
            }
        }

        for child in &self.children {
            if child.has_matching(&full_name, &merged_tags, config) {
                return true;
            }
        }

        false
    }

    /// Recursively execute this spec and all descendants, respecting nesting
    /// of hooks, tags, timeouts, and retries.
    fn execute_recursive(
        &self,
        prefix: &str,
        inherited_tags: &[String],
        inherited_timeout: Option<Duration>,
        inherited_retries: u32,
        inherited_before_each: &[Arc<dyn Fn() + Send + Sync>],
        inherited_after_each: &[Arc<dyn Fn() + Send + Sync>],
        config: &RunnerConfig,
    ) -> Vec<TestCase> {
        let full_name = if prefix.is_empty() {
            self.name.clone()
        } else {
            format!("{} :: {}", prefix, self.name)
        };

        let merged_tags: Vec<String> = inherited_tags
            .iter()
            .cloned()
            .chain(self.tags.iter().cloned())
            .collect();

        let merged_timeout = self.timeout.or(inherited_timeout).or(config.default_timeout);
        let merged_retries = if self.retries > 0 {
            self.retries
        } else {
            inherited_retries.max(config.default_retries)
        };

        // Build effective before_each / after_each lists.
        // Parent hooks are inherited; self hooks are appended so they
        // run after parent hooks on the way in and before them on the way out.
        let before_each: Vec<Arc<dyn Fn() + Send + Sync>> = inherited_before_each
            .iter()
            .cloned()
            .chain(self.before_each.iter().cloned())
            .collect();
        let after_each: Vec<Arc<dyn Fn() + Send + Sync>> = inherited_after_each
            .iter()
            .cloned()
            .chain(self.after_each.iter().cloned())
            .collect();

        // Skip this entire subtree if nothing matches the filters.
        // Hooks are NOT run when there are no matching tests.
        if !self.has_matching(prefix, inherited_tags, config) {
            return Vec::new();
        }

        let mut results = Vec::new();

        // --- before_all hook ---
        if let Some(ref setup) = self.setup {
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| setup()));
        }

        // --- leaf tests ---
        for entry in &self.tests {
            let test_name = format!("{} :: {}", full_name, entry.name);

            if !crate::tag::tags_match(&merged_tags, config)
                || !crate::tag::name_matches(&test_name, config.filter.as_deref())
            {
                continue;
            }

            let test_start = Instant::now();

            // before_each hooks (outermost → innermost)
            let mut hook_failed = false;
            for hook in &before_each {
                if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook())).is_err() {
                    hook_failed = true;
                }
            }

            let (status, captured_output) = if hook_failed {
                (TestStatus::Failed {
                    reason: "before_each hook failed".to_owned(),
                    location: None,
                }, None)
            } else {
                execute_with_capture(&entry.test_fn, merged_timeout, merged_retries)
            };

            let duration = test_start.elapsed();
            let is_failed = status.is_failed();

            // after_each hooks (innermost → outermost)
            for hook in after_each.iter().rev() {
                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook()));
            }

            results.push(TestCase {
                name: test_name,
                suite: Some(full_name.clone()),
                tags: merged_tags.clone(),
                status,
                duration,
                assertions: 0,
                location: entry.location.clone(),
                parameters: Vec::new(), captured_output,
            });

            if config.fail_fast && is_failed {
                break;
            }
        }

        // --- children ---
        let had_failures = results.iter().any(|t| t.status.is_failed());
        if !config.fail_fast || !had_failures {
            for child in &self.children {
                let child_results = child.execute_recursive(
                    &full_name,
                    &merged_tags,
                    merged_timeout,
                    merged_retries,
                    &before_each,
                    &after_each,
                    config,
                );
                let child_failed = child_results.iter().any(|t| t.status.is_failed());
                results.extend(child_results);
                if config.fail_fast && child_failed {
                    break;
                }
            }
        }

        // --- after_all hook ---
        if let Some(ref teardown) = self.teardown {
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| teardown()));
        }

        results
    }
}

/// A builder that lets you chain `.describe()` calls on a parent spec.
///
/// Created by [`Spec::describe`], this wrapper holds a reference to the
/// parent and allows you to chain configuration on the child before
/// returning to the parent.
pub struct SpecBuilder {
    parent: Spec,
    /// Path of indices from `parent` to the current child.
    path: Vec<usize>,
}

impl SpecBuilder {
    fn child_mut(&mut self) -> &mut Spec {
        let mut current = &mut self.parent;
        for &idx in &self.path {
            current = &mut current.children[idx];
        }
        current
    }

    /// Attach a description to the child spec.
    pub fn description(mut self, text: &str) -> Self {
        self.child_mut().description = Some(text.to_owned());
        self
    }

    /// Add a tag to the child spec.
    pub fn tag(mut self, tag: &str) -> Self {
        self.child_mut().tags.push(tag.to_owned());
        self
    }

    /// Set a timeout on the child spec.
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.child_mut().timeout = Some(duration);
        self
    }

    /// Set retries on the child spec.
    pub fn retries(mut self, count: u32) -> Self {
        self.child_mut().retries = count;
        self
    }

    /// Register a setup hook on the child spec.
    pub fn before_all(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.child_mut().setup = Some(Arc::new(hook));
        self
    }

    /// Register a teardown hook on the child spec.
    pub fn after_all(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.child_mut().teardown = Some(Arc::new(hook));
        self
    }

    /// Register a hook run before each test in the child spec (and its children).
    pub fn before_each(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.child_mut().before_each = Some(Arc::new(hook));
        self
    }

    /// Register a hook run after each test in the child spec (and its children).
    pub fn after_each(mut self, hook: impl Fn() + Send + Sync + 'static) -> Self {
        self.child_mut().after_each = Some(Arc::new(hook));
        self
    }

    /// Add a leaf test to the child spec.
    #[track_caller]
    pub fn it(mut self, name: &str, test: impl Fn() + Send + Sync + 'static) -> Self {
        let loc = std::panic::Location::caller();
        self.child_mut().tests.push(TestEntry {
            name: name.to_owned(),
            location: Some(SourceLocation {
                file: loc.file().to_owned(),
                line: loc.line(),
                column: None,
            }),
            test_fn: Arc::new(test),
        });
        self
    }

    /// Nest a deeper spec inside the child.
    pub fn describe(mut self, name: &str) -> SpecBuilder {
        let child = Spec::new(name);
        self.child_mut().children.push(child);
        let child_index = self.child_mut().children.len() - 1;
        let mut path = self.path;
        path.push(child_index);
        SpecBuilder { parent: self.parent, path }
    }

    /// Run all tests starting from the parent spec.
    pub fn run(self) -> TestSuite {
        self.parent.run()
    }

    /// Run all tests with an explicit config.
    pub fn run_with_config(self, config: &RunnerConfig) -> TestSuite {
        self.parent.run_with_config(config)
    }
}

// ---------------------------------------------------------------------------
// Execution helpers
// ---------------------------------------------------------------------------

fn run_with_retry(test: &Arc<dyn Fn() + Send + Sync>, retries: u32) -> TestStatus {
    let max_attempts = retries.saturating_add(1);

    for attempt in 1..=max_attempts {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            (test)();
        }));

        match result {
            Ok(_) => return TestStatus::Passed,
            Err(panic_info) => {
                if attempt == max_attempts {
                    let reason = extract_panic_message(&panic_info);
                    return TestStatus::Failed { reason, location: None };
                }
            }
        }
    }

    TestStatus::Failed {
        reason: "exhausted retries".to_owned(),
        location: None,
    }
}

fn run_with_timeout(
    test: &Arc<dyn Fn() + Send + Sync>,
    timeout: Duration,
    retries: u32,
) -> TestStatus {
    let test = Arc::clone(test);

    let (tx, rx) = std::sync::mpsc::channel();

    let _handle = std::thread::spawn(move || {
        let status = run_with_retry(&test, retries);
        let _ = tx.send(status);
    });

    match rx.recv_timeout(timeout) {
        Ok(status) => status,
        Err(_) => TestStatus::TimedOut { duration: timeout, location: None },
    }
}

/// Execute a test with optional stdout/stderr capture.
///
/// Returns `(status, captured_output)` where `captured_output` is `Some`
/// only when capture is enabled AND the test produced any output.
fn execute_with_capture(
    test_fn: &Arc<dyn Fn() + Send + Sync>,
    timeout: Option<Duration>,
    retries: u32,
) -> (TestStatus, Option<String>) {
    if !crate::capture::is_capture_enabled() {
        let status = match timeout {
            Some(to) => run_with_timeout(test_fn, to, retries),
            None => run_with_retry(test_fn, retries),
        };
        return (status, None);
    }

    let test_fn = Arc::clone(test_fn);
    let (status, stdout, stderr) = crate::capture::capture(move || {
        match timeout {
            Some(to) => run_with_timeout(&test_fn, to, retries),
            None => run_with_retry(&test_fn, retries),
        }
    });

    let output = {
        let mut parts: Vec<String> = Vec::new();
        if !stdout.is_empty() {
            parts.push(format!("stdout:\n{}", stdout));
        }
        if !stderr.is_empty() {
            parts.push(format!("stderr:\n{}", stderr));
        }
        if parts.is_empty() { None } else { Some(parts.join("\n")) }
    };

    (status, output)
}

fn extract_panic_message(panic_info: &Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = panic_info.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = panic_info.downcast_ref::<String>() {
        s.clone()
    } else {
        "test panicked".to_owned()
    }
}

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

    #[test]
    fn describe_creates_spec() {
        let s = describe("test");
        assert_eq!(s.name, "test");
        assert!(s.tests.is_empty());
        assert!(s.children.is_empty());
    }

    #[test]
    fn spec_description() {
        let s = Spec::new("math").description("arithmetic operations");
        assert_eq!(s.description, Some("arithmetic operations".to_owned()));
    }

    #[test]
    fn spec_tag_adds_tag() {
        let s = Spec::new("x").tag("smoke").tag("fast");
        assert_eq!(s.tags, vec!["smoke", "fast"]);
    }

    #[test]
    fn spec_timeout() {
        let s = Spec::new("x").timeout(Duration::from_secs(5));
        assert_eq!(s.timeout, Some(Duration::from_secs(5)));
    }

    #[test]
    fn spec_retries() {
        let s = Spec::new("x").retries(3);
        assert_eq!(s.retries, 3);
    }

    #[test]
    fn spec_before_all() {
        let s = Spec::new("x").before_all(|| {});
        assert!(s.setup.is_some());
    }

    #[test]
    fn spec_after_all() {
        let s = Spec::new("x").after_all(|| {});
        assert!(s.teardown.is_some());
    }

    #[test]
    fn spec_before_each() {
        let s = Spec::new("x").before_each(|| {});
        assert!(s.before_each.is_some());
    }

    #[test]
    fn spec_after_each() {
        let s = Spec::new("x").after_each(|| {});
        assert!(s.after_each.is_some());
    }

    #[test]
    fn spec_new_defaults() {
        let s = Spec::new("empty");
        assert_eq!(s.name, "empty");
        assert!(s.description.is_none());
        assert!(s.tags.is_empty());
        assert!(s.setup.is_none());
        assert!(s.teardown.is_none());
        assert!(s.before_each.is_none());
        assert!(s.after_each.is_none());
        assert!(s.children.is_empty());
        assert!(s.tests.is_empty());
        assert!(s.timeout.is_none());
        assert_eq!(s.retries, 0);
    }

    #[test]
    fn spec_run_passes() {
        let suite = Spec::new("pass")
            .it("works", || {})
            .run();
        assert_eq!(suite.tests.len(), 1);
        assert!(suite.tests[0].status.is_passed());
    }

    #[test]
    fn spec_run_with_config() {
        let config = RunnerConfig { default_timeout: Some(Duration::from_secs(10)), ..RunnerConfig::default() };
        let suite = Spec::new("cfg")
            .it("ok", || {})
            .run_with_config(&config);
        assert!(suite.success());
    }

    #[test]
    fn spec_run_empty() {
        let suite = Spec::new("empty").run();
        assert!(suite.tests.is_empty());
        assert!(suite.success());
    }

    #[test]
    fn spec_builder_methods() {
        let suite = describe("root")
            .describe("child")
                .description("a child spec")
                .tag("nested")
                .timeout(Duration::from_secs(3))
                .retries(1)
                .before_all(|| {})
                .after_all(|| {})
                .before_each(|| {})
                .after_each(|| {})
                .it("leaf", || {})
            .run();
        assert_eq!(suite.tests.len(), 1);
    }

    #[test]
    fn run_with_timeout_integration() {
        let suite = Spec::new("timeout")
            .it("fast", || {})
            .timeout(Duration::from_secs(5))
            .run();
        assert!(suite.success());
    }

    #[test]
    fn has_matching_with_filter() {
        let spec = describe("Parent")
            .tag("smoke")
            .it("child_test", || {});

        let yes = spec.has_matching("", &[], &RunnerConfig { filter: Some("child".into()), ..RunnerConfig::default() });
        assert!(yes);

        let no = spec.has_matching("", &[], &RunnerConfig { filter: Some("nonexistent".into()), ..RunnerConfig::default() });
        assert!(!no);
    }

    #[test]
    fn spec_collects_hooks_inherited() {
        let ran = Arc::new(std::sync::Mutex::new(Vec::new()));
        let r = Arc::clone(&ran);
        let spec = describe("root")
            .before_each(move || r.lock().unwrap().push("root"))
            .describe("child")
                .it("test", move || {
                    ran.lock().unwrap().push("test");
                });
        let suite = spec.run();
        assert_eq!(suite.tests.len(), 1);
    }

    #[test]
    fn spec_run_with_empty_children() {
        let suite = describe("root")
            .describe("empty_child")
            .run();
        assert!(suite.success());
        assert!(suite.tests.is_empty());
    }

    #[test]
    fn spec_describe_chaining() {
        let suite = describe("root")
            .describe("a")
                .tag("t1")
                .it("a1", || {})
            .describe("b")
                .tag("t2")
                .it("b1", || {})
            .run();
        assert_eq!(suite.tests.len(), 2);
    }

    #[test]
    fn spec_tag_on_child() {
        let suite = describe("root")
            .describe("child")
                .tag("exclude_me")
                .it("test", || {})
            .run_with_config(&RunnerConfig {
                exclude_tags: vec!["exclude_me".into()],
                ..RunnerConfig::default()
            });
        assert_eq!(suite.tests.len(), 0);
    }

    #[test]
    fn extract_panic_message_called() {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            panic!("test panic");
        }));
        let e = result.unwrap_err();
        let msg = extract_panic_message(&e);
        assert_eq!(msg, "test panic");
    }

    #[test]
    fn spec_builder_description() {
        let suite = describe("root")
            .describe("child")
                .description("a child spec")
            .run();
        let _ = suite; // just verify it compiles and runs
    }

    #[test]
    fn spec_builder_all_methods() {
        let suite = describe("root")
            .describe("child")
                .tag("smoke")
                .timeout(Duration::from_secs(3))
                .retries(2)
                .before_all(|| {})
                .after_all(|| {})
                .before_each(|| {})
                .after_each(|| {})
                .it("test", || {})
            .run();
        assert_eq!(suite.tests.len(), 1);
        assert!(suite.success());
    }

    #[test]
    fn spec_builder_nested_describe() {
        let suite = describe("root")
            .describe("level1")
                .describe("level2")
                    .it("deep", || {})
            .run();
        assert_eq!(suite.tests.len(), 1);
        assert_eq!(suite.tests[0].name, "root :: level1 :: level2 :: deep");
    }
}