Skip to main content

tpt_fixture/
lib.rs

1//! Session- and module-scoped test fixtures with async init and teardown.
2//!
3//! `tpt-fixture` fills the `beforeAll` / `afterAll` gap that `rstest` issue
4//! #119 leaves open: it lets an init function run **once** per test scope and
5//! share its resource (as a thread-safe [`Arc<T>`](std::sync::Arc)) across every
6//! test in that scope, tearing it down when the scope ends.
7//!
8//! Use the companion [`tpt_fixture`](macro@crate::tpt_fixture) attribute macro to
9//! declare fixtures and to inject them into tests:
10//!
11//! ```ignore
12//! use std::sync::Arc;
13//! use tpt_fixture::tpt_fixture;
14//!
15//! #[tpt_fixture(scope = "suite")]
16//! async fn db() -> Database {
17//!     Database::connect().await
18//! }
19//!
20//! #[tpt_fixture]
21//! #[tokio::test]
22//! async fn reads_rows(db: Arc<Database>) {
23//!     assert!(db.row_count() > 0);
24//! }
25//! ```
26//!
27//! # Scopes
28//!
29//! | Scope    | Initialised | Shared across        | Teardown |
30//! |----------|-------------|----------------------|----------|
31//! | `test`   | every test  | — (fresh each call)  | end of that test |
32//! | `module` | once        | the test binary      | `shutdown()` |
33//! | `suite`  | once        | the whole test binary| `shutdown()` |
34//!
35//! `module` and `suite` are both process-lifetime singletons (Rust has no runtime
36//! module identity), initialised exactly once via a global `OnceLock`. They differ
37//! only in *intent*; both are cleaned up by [`shutdown`] (call it from a teardown
38//! test, or rely on the per-process model of `cargo-nextest`).
39//!
40//! # Async init
41//!
42//! Async init functions are awaited with [`block_on`]. By default this uses a tiny
43//! single-threaded executor; enable the `tokio` feature to drive them on a real
44//! tokio current-thread runtime (needed for async I/O, timers, etc.).
45
46use std::any::Any;
47use std::cell::RefCell;
48use std::collections::HashMap;
49use std::future::Future;
50use std::sync::{Arc, Mutex, OnceLock};
51
52pub use tpt_fixture_macros::tpt_fixture;
53
54/// The lifetime of a fixture.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Scope {
57    /// A fresh resource for every test; torn down when the test ends.
58    Test,
59    /// One resource for the test binary; torn down at process exit ([`shutdown`]).
60    Module,
61    /// One resource for the whole suite; torn down at process exit ([`shutdown`]).
62    Suite,
63}
64
65type Teardown = Box<dyn FnOnce() + Send + 'static>;
66
67/// The result of normalising a fixture's init return value.
68///
69/// Returning `T` gives no teardown; returning `(T, teardown)` registers a
70/// synchronous teardown closure run when the scope ends.
71pub struct FixtureInit<T> {
72    /// The shared resource.
73    pub resource: Arc<T>,
74    /// Optional teardown run when the scope ends.
75    pub teardown: Option<Teardown>,
76}
77
78/// Normalises a fixture init return value into a [`FixtureInit`].
79///
80/// Blanket-implemented for any `T` (no teardown) and for `(T, F)` where `F` is a
81/// teardown closure (sync).
82pub trait IntoFixture<T> {
83    /// Convert this init result into a [`FixtureInit`].
84    fn into_fixture(self) -> FixtureInit<T>;
85}
86
87impl<T> IntoFixture<T> for T {
88    fn into_fixture(self) -> FixtureInit<T> {
89        FixtureInit {
90            resource: Arc::new(self),
91            teardown: None,
92        }
93    }
94}
95
96impl<T, F> IntoFixture<T> for (T, F)
97where
98    F: FnOnce() + Send + 'static,
99{
100    fn into_fixture(self) -> FixtureInit<T> {
101        FixtureInit {
102            resource: Arc::new(self.0),
103            teardown: Some(Box::new(self.1)),
104        }
105    }
106}
107
108struct Cached {
109    resource: Arc<dyn Any + Send + Sync>,
110    teardown: Option<Teardown>,
111}
112
113static CACHE: OnceLock<Mutex<HashMap<String, Cached>>> = OnceLock::new();
114
115fn cache() -> &'static Mutex<HashMap<String, Cached>> {
116    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
117}
118
119thread_local! {
120    static TEST_TEARDOWNS: RefCell<Vec<Teardown>> = const { RefCell::new(Vec::new()) };
121}
122
123/// Resolve (or create) a fixture resource of type `T` for `scope`.
124///
125/// For `test` scope a fresh resource is built and its teardown is queued on the
126/// current thread. For `module`/`suite` scope the resource is cached process-wide
127/// and initialised exactly once.
128pub fn fixture_access<T>(name: &str, scope: Scope, init: impl FnOnce() -> FixtureInit<T>) -> Arc<T>
129where
130    T: 'static + Send + Sync,
131{
132    match scope {
133        Scope::Test => {
134            let built = init();
135            if let Some(teardown) = built.teardown {
136                TEST_TEARDOWNS.with(|c| c.borrow_mut().push(teardown));
137            }
138            built.resource
139        }
140        Scope::Module | Scope::Suite => {
141            let mut cache = cache().lock().expect("fixture cache poisoned");
142            if let Some(entry) = cache.get(name) {
143                return entry
144                    .resource
145                    .clone()
146                    .downcast::<T>()
147                    .expect("fixture type mismatch for name");
148            }
149            let built = init();
150            let entry = Cached {
151                resource: built.resource.clone() as Arc<dyn Any + Send + Sync>,
152                teardown: built.teardown,
153            };
154            cache.insert(name.to_string(), entry);
155            built.resource
156        }
157    }
158}
159
160/// Run all `test`-scope teardowns queued on the current thread.
161///
162/// Called automatically by [`TestScopeGuard`]'s `Drop` at the end of every test
163/// that uses a `test`-scope fixture, so you rarely call this directly.
164pub fn end_test_scope() {
165    TEST_TEARDOWNS.with(|c| {
166        let mut v = c.borrow_mut();
167        for teardown in v.drain(..) {
168            teardown();
169        }
170    });
171}
172
173/// Tear down every `module`/`suite`-scope fixture.
174///
175/// Call this from a dedicated teardown test or rely on `cargo-nextest`'s
176/// per-process model. Safe to call multiple times; once torn down, fixtures are
177/// not rebuilt.
178pub fn shutdown() {
179    let mut cache = cache().lock().expect("fixture cache poisoned");
180    for (_, entry) in cache.drain() {
181        if let Some(teardown) = entry.teardown {
182            teardown();
183        }
184    }
185}
186
187/// RAII guard that runs all `test`-scope teardowns when the test ends — even on
188/// panic. Inserted by the `#[tpt_fixture]` macro at the top of each test.
189pub struct TestScopeGuard;
190
191impl Drop for TestScopeGuard {
192    fn drop(&mut self) {
193        end_test_scope();
194    }
195}
196
197/// Drive a future to completion.
198///
199/// With the default features this is a minimal single-threaded executor suitable
200/// for futures that are ready without external wake-ups. Enable the `tokio` feature
201/// to run real async I/O / timers on a current-thread tokio runtime.
202///
203/// When called from inside an already-running tokio runtime (e.g. fixture init
204/// triggered from a `#[tokio::test]` async test), building and blocking on a
205/// nested runtime on the same thread would panic. To support that case, the
206/// `tokio`-feature implementation detects this and drives the future to
207/// completion on a dedicated OS thread with its own runtime instead.
208#[cfg(feature = "tokio")]
209pub fn block_on<F>(future: F) -> F::Output
210where
211    F: Future + Send + 'static,
212    F::Output: Send + 'static,
213{
214    if tokio::runtime::Handle::try_current().is_ok() {
215        std::thread::spawn(move || {
216            let rt = tokio::runtime::Builder::new_current_thread()
217                .enable_all()
218                .build()
219                .expect("failed to build tokio runtime for fixture init");
220            rt.block_on(future)
221        })
222        .join()
223        .expect("fixture init thread panicked")
224    } else {
225        let rt = tokio::runtime::Builder::new_current_thread()
226            .enable_all()
227            .build()
228            .expect("failed to build tokio runtime for fixture init");
229        rt.block_on(future)
230    }
231}
232
233/// Drive a future to completion.
234///
235/// This is a minimal single-threaded executor suitable for futures that are
236/// ready without external wake-ups. Enable the `tokio` feature to run real
237/// async I/O / timers on a current-thread tokio runtime.
238#[cfg(not(feature = "tokio"))]
239pub fn block_on<F: Future>(future: F) -> F::Output {
240    use std::pin::Pin;
241    use std::task::{Context, Poll};
242
243    let mut future = future;
244    // Pin to the stack; `future` is not moved after this point.
245    let mut future = unsafe { Pin::new_unchecked(&mut future) };
246    let waker = noop_waker();
247    let mut cx = Context::from_waker(&waker);
248    loop {
249        if let Poll::Ready(v) = future.as_mut().poll(&mut cx) {
250            return v;
251        }
252        std::thread::yield_now();
253    }
254}
255
256#[cfg(not(feature = "tokio"))]
257fn noop_waker() -> std::task::Waker {
258    use std::task::{RawWaker, RawWakerVTable, Waker};
259
260    fn noop(_: *const ()) {}
261    fn clone(_: *const ()) -> RawWaker {
262        noop_raw_waker()
263    }
264    fn noop_raw_waker() -> RawWaker {
265        RawWaker::new(std::ptr::null(), &NOOP_VTABLE)
266    }
267    static NOOP_VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
268    unsafe { Waker::from_raw(noop_raw_waker()) }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use std::sync::atomic::{AtomicUsize, Ordering};
275    use std::sync::Mutex as StdMutex;
276
277    #[test]
278    fn test_scope_builds_fresh_each_time_and_tears_down() {
279        static COUNT: AtomicUsize = AtomicUsize::new(0);
280        static DROPS: AtomicUsize = AtomicUsize::new(0);
281
282        fn make() -> Arc<u32> {
283            fixture_access("fresh", Scope::Test, || {
284                COUNT.fetch_add(1, Ordering::SeqCst);
285                let drop_flag = &DROPS;
286                IntoFixture::into_fixture((42u32, move || {
287                    drop_flag.fetch_add(1, Ordering::SeqCst);
288                }))
289            })
290        }
291
292        let _g = TestScopeGuard;
293        let a = make();
294        let b = make();
295        assert_ne!(Arc::as_ptr(&a), Arc::as_ptr(&b), "test scope must be fresh");
296        assert_eq!(COUNT.load(Ordering::SeqCst), 2);
297        drop(_g);
298        assert_eq!(DROPS.load(Ordering::SeqCst), 2, "teardown runs at test end");
299    }
300
301    #[test]
302    fn suite_scope_initialises_once_and_is_shared() {
303        static INIT: AtomicUsize = AtomicUsize::new(0);
304
305        fn db() -> Arc<String> {
306            fixture_access("shared_db", Scope::Suite, || {
307                INIT.fetch_add(1, Ordering::SeqCst);
308                IntoFixture::into_fixture("resource".to_string())
309            })
310        }
311
312        let a = db();
313        let b = db();
314        assert_eq!(
315            Arc::as_ptr(&a),
316            Arc::as_ptr(&b),
317            "suite scope shares the same Arc"
318        );
319        assert_eq!(INIT.load(Ordering::SeqCst), 1, "initialised exactly once");
320
321        shutdown();
322        // After shutdown the cache is empty; a fresh init would increment again.
323        let _c = db();
324        assert_eq!(INIT.load(Ordering::SeqCst), 2, "rebuild after shutdown");
325        shutdown();
326    }
327
328    #[test]
329    fn async_init_runs_via_block_on() {
330        fn counter() -> Arc<u64> {
331            fixture_access("async_counter", Scope::Test, || {
332                // A future that resolves without external wake-ups.
333                IntoFixture::into_fixture(block_on(async { 7u64 }))
334            })
335        }
336        let _g = TestScopeGuard;
337        assert_eq!(*counter(), 7);
338    }
339
340    #[test]
341    fn parallel_test_scopes_isolated() {
342        use std::sync::Arc as StdArc;
343        let log: StdArc<StdMutex<Vec<String>>> = StdArc::new(StdMutex::new(Vec::new()));
344
345        let mut handles = Vec::new();
346        for i in 0..4 {
347            let log = StdArc::clone(&log);
348            handles.push(std::thread::spawn(move || {
349                let _g = TestScopeGuard;
350                let res: Arc<i32> = fixture_access(&format!("iso_{i}"), Scope::Test, || {
351                    IntoFixture::into_fixture((i, move || {
352                        log.lock().unwrap().push(format!("dropped {i}"));
353                    }))
354                });
355                assert_eq!(*res, i);
356            }));
357        }
358        for h in handles {
359            h.join().unwrap();
360        }
361        let log = log.lock().unwrap();
362        assert_eq!(log.len(), 4, "each thread tore its own fixture down");
363    }
364}