spectacular 0.2.0

An RSpec-inspired test framework for Rust with stackable before/after hooks
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
// Doc examples show `#[test]` as part of the test_suite API — they are illustrative, not runnable tests.
#![allow(clippy::test_attr_in_doctest)]
//! An RSpec-inspired test framework for Rust with stackable before/after hooks.
//!
//! Spectacular provides three layers of test hooks that stack in a predictable order:
//!
//! | Layer | Runs once per… | Runs per test |
//! |-------|----------------|---------------|
//! | **Suite** | binary (`before`) | test (`before_each` / `after_each`) |
//! | **Group** | group (`before` / `after`) | test (`before_each` / `after_each`) |
//! | **Test** | — | the test body |
//!
//! # Hook Execution Order
//!
//! For each test in a group that opts into suite hooks:
//!
//! ```text
//! suite::before          (Once — first test in binary triggers it)
//!   group::before        (Once — first test in group triggers it)
//!     suite::before_each
//!       group::before_each
//!         TEST
//!       group::after_each
//!     suite::after_each
//!   group::after         (countdown — last test in group triggers it)
//! ```
//!
//! Groups without `suite;` skip the suite layer entirely.
//!
//! # Quick Start
//!
//! ```
//! use spectacular::spec;
//!
//! spec! {
//!     mod arithmetic {
//!         it "adds two numbers" {
//!             assert_eq!(2 + 2, 4);
//!         }
//!
//!         it "multiplies two numbers" {
//!             assert_eq!(3 * 7, 21);
//!         }
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! # Group Hooks
//!
//! ```
//! use spectacular::spec;
//! use std::sync::atomic::{AtomicBool, Ordering};
//!
//! static READY: AtomicBool = AtomicBool::new(false);
//!
//! spec! {
//!     mod with_hooks {
//!         use super::*;
//!
//!         before { READY.store(true, Ordering::SeqCst); }
//!
//!         it "runs after setup" {
//!             assert!(READY.load(Ordering::SeqCst));
//!         }
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! # Suite Hooks (3-Layer)
//!
//! Place [`suite!`] as a sibling of your test groups, then opt in with `suite;`
//! (in [`spec!`]) or `#[test_suite(suite)]` (attribute style):
//!
//! ```
//! use spectacular::{suite, spec};
//! use std::sync::atomic::{AtomicBool, Ordering};
//!
//! static DB_READY: AtomicBool = AtomicBool::new(false);
//!
//! suite! {
//!     before { DB_READY.store(true, Ordering::SeqCst); }
//! }
//!
//! spec! {
//!     mod database_tests {
//!         use super::*;
//!         suite;
//!
//!         it "has database access" {
//!             assert!(DB_READY.load(Ordering::SeqCst));
//!         }
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! # Attribute Style
//!
//! For those who prefer standard Rust attribute syntax — just use `#[test]`:
//!
//! ```
//! use spectacular::{test_suite, before};
//!
//! #[test_suite]
//! mod my_tests {
//!     #[before]
//!     fn setup() { }
//!
//!     #[test]
//!     fn it_works() {
//!         assert_eq!(1 + 1, 2);
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! # Async Tests
//!
//! Both `spec!` and `#[test_suite]` support async test cases and hooks.
//! Specify a runtime (`tokio` or `async_std`) to enable async:
//!
//! ```
//! # // doc-test can't depend on tokio, so just show the syntax
//! # fn main() {}
//! ```
//!
//! **`spec!` style:**
//! ```ignore
//! use spectacular::spec;
//!
//! spec! {
//!     mod my_async_tests {
//!         tokio;  // or async_std;
//!
//!         async before_each { db_connect().await; }
//!
//!         async it "fetches data" {
//!             let result = fetch().await;
//!             assert!(result.is_ok());
//!         }
//!
//!         it "sync test works too" {
//!             assert_eq!(1 + 1, 2);
//!         }
//!     }
//! }
//! ```
//!
//! **Attribute style:**
//! ```ignore
//! use spectacular::{test_suite, before_each};
//!
//! #[test_suite(tokio)]
//! mod my_async_tests {
//!     #[before_each]
//!     async fn setup() { db_connect().await; }
//!
//!     #[test]
//!     async fn it_works() {
//!         let result = fetch().await;
//!         assert!(result.is_ok());
//!     }
//! }
//! ```
//!
//! Async `after_each` hooks are panic-safe — they run even if the test body
//! panics, using an async-compatible `catch_unwind` wrapper.
//!
//! **Feature-based default:** If you enable the `tokio` or `async-std` feature
//! on `spectacular`, async tests auto-detect the runtime so you can omit the
//! explicit `tokio;` / `#[test_suite(tokio)]` argument:
//!
//! ```toml
//! [dev-dependencies]
//! spectacular = { version = "0.1", features = ["tokio"] }
//! ```
//!
//! With the feature enabled, `async it` / `async fn` test cases Just Work.
//! Explicit runtime arguments always take precedence over the feature default.
//! If both features are enabled simultaneously, you must specify explicitly
//! (the macro will emit a compile error).
//!
//! # Context Injection
//!
//! Hooks can produce context values that flow naturally to tests and teardown hooks,
//! eliminating the need for `thread_local! + RefCell` patterns.
//!
//! ## `before` → shared `&T` via `OnceLock`
//!
//! When `before` returns a value, it's stored in a `OnceLock<T>`. Tests, `before_each`,
//! `after_each`, and `after` all receive `&T`.
//!
//! ## `before_each` → owned `T` per test
//!
//! When `before_each` returns a value, each test gets an owned `T`. The test borrows it
//! through `catch_unwind`, and `after_each` consumes it for cleanup.
//!
//! **How params are distinguished:** Reference params (`&T`) come from `before` context.
//! Owned params come from `before_each` context.
//!
//! **`spec!` style:**
//! ```ignore
//! use spectacular::spec;
//!
//! spec! {
//!     mod my_tests {
//!         tokio;
//!
//!         before -> PgPool {
//!             PgPool::connect("postgres://...").unwrap()
//!         }
//!
//!         after |pool: &PgPool| {
//!             pool.close();
//!         }
//!
//!         async before_each |pool: &PgPool| -> TestContext {
//!             TestContext::seed(pool).await
//!         }
//!
//!         async after_each |pool: &PgPool, ctx: TestContext| {
//!             ctx.cleanup(pool).await;
//!         }
//!
//!         async it "creates a team" |pool: &PgPool, ctx: TestContext| {
//!             // pool from before (shared &ref), ctx from before_each (owned)
//!         }
//!     }
//! }
//! ```
//!
//! **Attribute style:**
//! ```ignore
//! use spectacular::{test_suite, before, after, before_each, after_each};
//!
//! #[test_suite(tokio)]
//! mod my_tests {
//!     #[before]
//!     fn init() -> PgPool {
//!         PgPool::connect("postgres://...").unwrap()
//!     }
//!
//!     #[after]
//!     fn cleanup(pool: &PgPool) {
//!         pool.close();
//!     }
//!
//!     #[before_each]
//!     async fn setup(pool: &PgPool) -> TestContext {
//!         TestContext::seed(pool).await
//!     }
//!
//!     #[after_each]
//!     async fn teardown(pool: &PgPool, ctx: TestContext) {
//!         ctx.cleanup(pool).await;
//!     }
//!
//!     #[test]
//!     async fn test_create_team(pool: &PgPool, ctx: TestContext) {
//!         // pool from before (shared &ref), ctx from before_each (owned)
//!     }
//! }
//! ```
//!
//! ## Inferred context (no return type)
//!
//! When `before_each` has no return type, the last expression of the body **is**
//! the context. Tests and `after_each` use `_` as the param type to receive it.
//! The macro detects `_`-typed params and inlines the body automatically.
//!
//! Without `_` params, a void `before_each` is fire-and-forget as usual.

/// Defines suite-level hooks that run across all opted-in test groups.
///
/// Generates a hidden `__spectacular_suite` module containing `before()`,
/// `before_each()`, and `after_each()` functions. The `before` hook uses
/// [`std::sync::Once`] internally so it executes at most once per test binary.
///
/// Groups opt in with `suite;` inside [`spec!`] or `#[test_suite(suite)]` for
/// attribute style. Groups without opt-in are completely unaffected.
///
/// All three hook types are optional. Omitted hooks generate empty functions.
///
/// ```
/// use spectacular::{suite, spec};
///
/// suite! {
///     before { /* runs once per binary */ }
///     before_each { /* runs before each opted-in test */ }
///     after_each { /* runs after each opted-in test */ }
/// }
///
/// spec! {
///     mod my_group {
///         suite;
///
///         it "uses suite hooks" {
///             assert!(true);
///         }
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::suite;

/// Defines a test group using RSpec-style DSL.
///
/// Each `it "description" { body }` block becomes a `#[test]` function whose
/// name is the slugified description. Groups support `before`, `after`,
/// `before_each`, and `after_each` hooks. Add `suite;` to opt into
/// suite-level hooks defined by [`suite!`].
///
/// ## `describe` syntax
///
/// You can use `describe "string"` instead of `mod name` for a BDD-style feel:
///
/// ```ignore
/// spec! {
///     describe "user authentication" {
///         it "rejects invalid passwords" { /* ... */ }
///     }
/// }
/// ```
///
/// The string is slugified into a module name (`user_authentication`).
///
/// For async tests, add `tokio;` or `async_std;` to the module and prefix
/// test cases or hooks with `async`: `async it "..." { ... }`,
/// `async before_each { ... }`.
///
/// Helper functions, constants, and `use` statements can appear alongside
/// hooks and test cases.
///
/// # Context Injection
///
/// Hooks can return context values using `-> Type` syntax, and receive
/// context via `|params|` syntax:
///
/// - `before -> Type { }` — returns shared context stored in `OnceLock<T>`
/// - `before { }` — inferred shared context when consumers use explicit `&T` params
/// - `before_each |shared: &T| -> U { }` — receives shared `&T`, returns owned `U`
/// - `before_each { }` — inferred context when tests use `_` params
/// - `after_each |shared: &T, owned: U| { }` — receives both contexts
/// - `it "desc" |shared: &T, owned: U| { }` — receives both contexts
/// - `after |shared: &T| { }` — receives shared context
///
/// # Basic usage
///
/// ```
/// use spectacular::spec;
///
/// spec! {
///     mod my_group {
///         fn helper() -> i32 { 42 }
///
///         before_each { /* per-test setup */ }
///
///         it "uses a helper" {
///             assert_eq!(helper(), 42);
///         }
///
///         it "does arithmetic" {
///             assert_eq!(2 + 2, 4);
///         }
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Context injection
///
/// ```
/// use spectacular::spec;
///
/// spec! {
///     mod with_context {
///         before -> i32 { 42 }
///
///         before_each |n: &i32| -> String {
///             format!("val-{}", n)
///         }
///
///         after_each |n: &i32, s: String| {
///             assert_eq!(*n, 42);
///             assert_eq!(s, "val-42");
///         }
///
///         it "receives both" |n: &i32, s: String| {
///             assert_eq!(*n, 42);
///             assert_eq!(s, "val-42");
///         }
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Inferred context (`before`)
///
/// When `before` has no `-> Type` but consumers use explicit `&T` params,
/// the macro infers `OnceLock<T>` automatically:
///
/// ```
/// use spectacular::spec;
///
/// spec! {
///     mod inferred_before {
///         before { String::from("shared") }
///
///         it "receives shared ref" |val: &String| {
///             assert_eq!(val, "shared");
///         }
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Inferred context (`before_each`)
///
/// When `before_each` has no return type and tests use `_` params,
/// the last expression becomes the context:
///
/// ```
/// use spectacular::spec;
///
/// spec! {
///     mod inferred {
///         before_each {
///             (String::from("hello"), 42u32)
///         }
///
///         it "receives inferred values" |s: _, n: _| {
///             assert_eq!(s, "hello");
///             assert_eq!(n, 42);
///         }
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::spec;

/// Marks a module as a test suite using standard Rust attribute syntax.
///
/// Test functions are marked with the standard `#[test]` attribute. Hook
/// functions are marked with [`#[before]`](macro@before),
/// [`#[after]`](macro@after), [`#[before_each]`](macro@before_each), or
/// [`#[after_each]`](macro@after_each).
///
/// Pass `suite` to opt into suite-level hooks: `#[test_suite(suite)]`.
///
/// For async support, pass `tokio` or `async_std`: `#[test_suite(tokio)]`.
/// Combine with suite: `#[test_suite(suite, tokio)]`. Async test and hook
/// functions are detected automatically from `async fn` signatures.
///
/// # Context Injection
///
/// Hook functions with return types or parameters enable context injection.
/// The macro reads function signatures to determine context flow:
///
/// - `#[before] fn init() -> T` — shared context via `OnceLock<T>`
/// - `#[before] fn init()` — inferred shared context when consumers use explicit `&T` params
/// - `#[before_each] fn setup(shared: &T) -> U` — per-test context with shared input
/// - `#[before_each] fn setup()` — inferred context when tests use `_` params
/// - `#[after_each] fn teardown(shared: &T, owned: U)` — receives both
/// - `#[after] fn cleanup(shared: &T)` — receives shared context
/// - `#[test] fn test_name(shared: &T, owned: U)` — receives both
///
/// Reference params (`&T`) come from `before` context. Owned params come
/// from `before_each` context.
///
/// # Basic usage
///
/// ```
/// use spectacular::{test_suite, before_each};
///
/// #[test_suite]
/// mod my_tests {
///     #[before_each]
///     fn setup() { }
///
///     #[test]
///     fn it_works() {
///         assert_eq!(2 + 2, 4);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Context injection
///
/// ```
/// use spectacular::{test_suite, before, before_each, after_each};
///
/// #[test_suite]
/// mod with_context {
///     #[before]
///     fn init() -> i32 { 42 }
///
///     #[before_each]
///     fn setup(n: &i32) -> String {
///         format!("val-{}", n)
///     }
///
///     #[after_each]
///     fn teardown(n: &i32, s: String) {
///         assert_eq!(*n, 42);
///         assert_eq!(s, "val-42");
///     }
///
///     #[test]
///     fn receives_both(n: &i32, s: String) {
///         assert_eq!(*n, 42);
///         assert_eq!(s, "val-42");
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::test_suite;

/// Marks a function as a once-per-group setup hook inside a
/// [`#[test_suite]`](macro@test_suite) module.
///
/// The function runs exactly once before the first test in the group. Only one
/// `#[before]` per module is allowed. Must be sync.
///
/// When the function returns a value (`fn init() -> T`), the return value is
/// stored in an `OnceLock<T>` and made available as `&T` to tests,
/// `before_each`, `after_each`, and `after` hooks via their parameters.
/// Without a return type, the hook is fire-and-forget using `Once::call_once`
/// — unless downstream consumers use explicit `&T` params, in which case the
/// macro infers `OnceLock<T>` automatically.
///
/// In [`spec!`] blocks, use `before { ... }` or `before -> Type { ... }`.
///
/// # Fire-and-forget
///
/// ```
/// use spectacular::{test_suite, before};
///
/// #[test_suite]
/// mod example {
///     #[before]
///     fn setup() { }
///
///     #[test]
///     fn my_test() {
///         assert!(true);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Returning shared context
///
/// ```
/// use spectacular::{test_suite, before};
///
/// #[test_suite]
/// mod with_context {
///     #[before]
///     fn init() -> String {
///         "shared-resource".to_string()
///     }
///
///     #[test]
///     fn receives_ref(val: &String) {
///         assert_eq!(val, "shared-resource");
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Inferred return type
///
/// When the function has no return type but consumers use explicit `&T` params,
/// the macro infers the `OnceLock<T>` type automatically:
///
/// ```
/// use spectacular::{test_suite, before};
///
/// #[test_suite]
/// mod inferred {
///     #[before]
///     fn init() {
///         42i32
///     }
///
///     #[test]
///     fn receives_ref(val: &i32) {
///         assert_eq!(*val, 42);
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::before;

/// Marks a function as a once-per-group teardown hook inside a
/// [`#[test_suite]`](macro@test_suite) module.
///
/// The function runs exactly once after the last test in the group completes,
/// using an atomic countdown. Only one `#[after]` per module is allowed.
/// Must be sync.
///
/// When `#[before]` returns context, `after` can receive it as `&T` via a
/// reference parameter: `fn cleanup(pool: &PgPool)`. Without parameters,
/// the hook is fire-and-forget.
///
/// In [`spec!`] blocks, use `after { ... }` or `after |name: &Type| { ... }`.
///
/// # Fire-and-forget
///
/// ```
/// use spectacular::{test_suite, after};
///
/// #[test_suite]
/// mod example {
///     #[after]
///     fn teardown() { }
///
///     #[test]
///     fn my_test() {
///         assert!(true);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Receiving shared context
///
/// ```
/// use spectacular::{test_suite, before, after};
///
/// #[test_suite]
/// mod with_context {
///     #[before]
///     fn init() -> String {
///         "resource".to_string()
///     }
///
///     #[after]
///     fn cleanup(val: &String) {
///         assert_eq!(val, "resource");
///     }
///
///     #[test]
///     fn my_test(val: &String) {
///         assert_eq!(val, "resource");
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::after;

/// Marks a function as a per-test setup hook inside a
/// [`#[test_suite]`](macro@test_suite) module.
///
/// The function runs before every test in the group. Only one `#[before_each]`
/// per module is allowed. Can be `async fn`.
///
/// When the function has a return type (`fn setup() -> T`), the return value
/// is passed as an owned `T` to the test and `after_each`. When the function
/// has reference parameters (`fn setup(pool: &PgPool) -> T`), those are bound
/// from the `#[before]` context. Without a return type, the hook is
/// fire-and-forget — unless tests use `_`-typed params, in which case
/// the body is inlined and the last expression becomes the context.
///
/// In [`spec!`] blocks, use `before_each { ... }` or
/// `before_each |name: &Type| -> Type { ... }`.
///
/// # Fire-and-forget
///
/// ```
/// use spectacular::{test_suite, before_each};
///
/// #[test_suite]
/// mod example {
///     #[before_each]
///     fn setup() { }
///
///     #[test]
///     fn my_test() {
///         assert!(true);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Returning per-test context
///
/// ```
/// use spectacular::{test_suite, before_each, after_each};
///
/// #[test_suite]
/// mod with_context {
///     #[before_each]
///     fn setup() -> usize {
///         42
///     }
///
///     #[after_each]
///     fn teardown(val: usize) {
///         assert_eq!(val, 42);
///     }
///
///     #[test]
///     fn receives_owned(val: usize) {
///         assert_eq!(val, 42);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Inferred context (no return type)
///
/// When tests or `#[after_each]` use `_` params, the body is inlined and
/// the last expression becomes the context with compiler-inferred types:
///
/// ```
/// use spectacular::{test_suite, before_each};
///
/// #[test_suite]
/// mod inferred {
///     #[before_each]
///     fn setup() {
///         (String::from("hello"), 42u32)
///     }
///
///     #[test]
///     fn receives_inferred(s: _, n: _) {
///         assert_eq!(s, "hello");
///         assert_eq!(n, 42);
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::before_each;

/// Marks a function as a per-test teardown hook inside a
/// [`#[test_suite]`](macro@test_suite) module.
///
/// The function runs after every test in the group, even if the test panics
/// (protected by [`std::panic::catch_unwind`]). Only one `#[after_each]`
/// per module is allowed. Can be `async fn`.
///
/// When the function has parameters, reference params (`&T`) are bound from
/// `#[before]` context, and owned params (`T`) consume the value returned by
/// `#[before_each]`. Without parameters, the hook is fire-and-forget.
///
/// In [`spec!`] blocks, use `after_each { ... }` or
/// `after_each |name: &Type, name: Type| { ... }`.
///
/// # Fire-and-forget
///
/// ```
/// use spectacular::{test_suite, after_each};
///
/// #[test_suite]
/// mod example {
///     #[after_each]
///     fn cleanup() { }
///
///     #[test]
///     fn my_test() {
///         assert!(true);
///     }
/// }
/// # fn main() {}
/// ```
///
/// # Receiving context
///
/// ```
/// use spectacular::{test_suite, before_each, after_each};
///
/// #[test_suite]
/// mod with_context {
///     #[before_each]
///     fn setup() -> String {
///         "hello".to_string()
///     }
///
///     #[after_each]
///     fn cleanup(val: String) {
///         assert_eq!(val, "hello");
///     }
///
///     #[test]
///     fn my_test(val: String) {
///         assert_eq!(val, "hello");
///     }
/// }
/// # fn main() {}
/// ```
pub use spectacular_macros::after_each;

/// Internal helpers used by generated code. Not part of the public API.
#[doc(hidden)]
pub mod __internal {
    use std::any::Any;
    use std::future::Future;
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::task::Poll;

    /// Like `std::panic::catch_unwind` but for async blocks.
    ///
    /// Wraps each `poll` call in `catch_unwind` so panics inside `.await`ed
    /// futures are caught without requiring the future itself to be `UnwindSafe`.
    pub async fn catch_unwind_future<F: Future>(f: F) -> Result<F::Output, Box<dyn Any + Send>> {
        let mut f = Box::pin(f);
        std::future::poll_fn(move |cx| {
            match catch_unwind(AssertUnwindSafe(|| f.as_mut().poll(cx))) {
                Ok(Poll::Ready(v)) => Poll::Ready(Ok(v)),
                Ok(Poll::Pending) => Poll::Pending,
                Err(e) => Poll::Ready(Err(e)),
            }
        })
        .await
    }
}

/// Convenience re-export of all spectacular macros.
///
/// ```
/// use spectacular::prelude::*;
/// # fn main() {}
/// ```
pub mod prelude {
    pub use spectacular_macros::{after, after_each, before, before_each, spec, suite, test_suite};
}

#[cfg(test)]
mod tests {
    use super::prelude::*;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    static UNIT_SUITE_BEFORE: AtomicBool = AtomicBool::new(false);
    static UNIT_SUITE_BEFORE_EACH: AtomicUsize = AtomicUsize::new(0);
    static UNIT_SUITE_AFTER_EACH: AtomicUsize = AtomicUsize::new(0);

    suite! {
        before {
            UNIT_SUITE_BEFORE.store(true, Ordering::SeqCst);
        }
        before_each {
            UNIT_SUITE_BEFORE_EACH.fetch_add(1, Ordering::SeqCst);
        }
        after_each {
            UNIT_SUITE_AFTER_EACH.fetch_add(1, Ordering::SeqCst);
        }
    }

    spec! {
        mod suite_in_unit_tests {
            use super::*;
            suite;

            it "suite hooks work in unit test context" {
                assert!(UNIT_SUITE_BEFORE.load(Ordering::SeqCst));
                assert!(UNIT_SUITE_BEFORE_EACH.load(Ordering::SeqCst) >= 1);
            }

            it "suite before_each fires for each test" {
                assert!(UNIT_SUITE_BEFORE_EACH.load(Ordering::SeqCst) >= 1);
            }
        }
    }

    spec! {
        mod group_without_suite_in_unit {
            it "works without suite opt-in" {
                assert_eq!(2 + 2, 4);
            }
        }
    }
}