1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Scope {
57 Test,
59 Module,
61 Suite,
63}
64
65type Teardown = Box<dyn FnOnce() + Send + 'static>;
66
67pub struct FixtureInit<T> {
72 pub resource: Arc<T>,
74 pub teardown: Option<Teardown>,
76}
77
78pub trait IntoFixture<T> {
83 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
123pub 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
160pub 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
173pub 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
187pub struct TestScopeGuard;
190
191impl Drop for TestScopeGuard {
192 fn drop(&mut self) {
193 end_test_scope();
194 }
195}
196
197#[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#[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 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 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 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}