Skip to main content

encore/testing/
mod.rs

1//! Tests. Under `encore test` every test gets infrastructure of its own —
2//! databases, buckets and topics no other test sees — with nothing to set up:
3//!
4//! ```ignore
5//! #[tokio::test]
6//! async fn creates_a_user() -> Result<(), encore::Error> {
7//!     create_user("ada").await?; // uses the `static DB`, isolated to this test
8//!     let row = DB.query_one("SELECT count(*) FROM users", &[]).await?;
9//!     assert_eq!(row.get::<_, i64>(0), 1);
10//!     Ok(())
11//! }
12//! ```
13//!
14//! Encore works out which test a call belongs to from where it is made: on the
15//! test's own thread (the test harness names it after the test), or on a thread
16//! of the Tokio runtime the test runs in — a spawned task, `spawn_blocking`. The
17//! test's infrastructure is released when the test ends.
18//!
19//! # `#[encore::test]`
20//!
21//! Any test works: `#[test]`, `#[tokio::test]`. [`#[encore::test]`](macro@crate::test)
22//! is `#[tokio::test]` — it takes the same `flavor` and `worker_threads` — that
23//! tells Encore about the test before it runs, rather than leaving it to be
24//! worked out at the first call. Its runtime's threads are part of the test from
25//! the start, and its infrastructure is released as soon as it returns.
26//!
27//! ```ignore
28//! #[encore::test(flavor = "multi_thread")]
29//! async fn handles_concurrent_requests() -> Result<(), encore::Error> {
30//!     // …
31//! }
32//! ```
33//!
34//! # Fixtures
35//!
36//! A test starts from the app's freshly provisioned resources: an empty,
37//! migrated database, an empty bucket. A [`Fixture`] is a state to start from instead, built
38//! once by a setup of yours and then copied for each test that loads it. See
39//! [`Fixture`] and [`fixture!`](crate::fixture).
40//!
41//! # Other threads
42//!
43//! A thread the test starts itself is neither, so Encore cannot tell which test
44//! it belongs to, and using a resource on it is an error. (The exception is a
45//! multi-thread runtime built on such a thread, which Encore takes for a test's:
46//! it gets infrastructure of its own.) Link the thread to the test with a
47//! [`TestScope`]:
48//!
49//! ```ignore
50//! let scope = encore::testing::current()?;
51//! std::thread::spawn(move || {
52//!     let _guard = scope.enter();
53//!     // … part of the test from here on
54//! });
55//! ```
56
57mod fixture;
58
59pub use fixture::{without_fixture, Fixture, SetupFn};
60
61use std::cell::RefCell;
62use std::collections::{HashMap, HashSet};
63use std::future::{poll_fn, Future};
64use std::marker::PhantomData;
65use std::pin::pin;
66use std::sync::atomic::{AtomicU64, Ordering};
67use std::sync::{Arc, Mutex, OnceLock, Weak};
68
69use encore_sdk_core::objects;
70use encore_sdk_core::postgres::{Access, Pool};
71use encore_sdk_core::pubsub;
72use tokio::runtime::{Handle, Id, RuntimeFlavor};
73
74use crate::config;
75use crate::error::{ErrCode, Error};
76use crate::runtime::core;
77use crate::secrets;
78
79/// The test the calling thread belongs to.
80///
81/// Fails outside `encore test`, and on a thread Encore cannot link to a test:
82/// see the [module documentation](self).
83pub fn current() -> Result<TestScope, Error> {
84    match active()? {
85        Some(scope) => Ok(TestScope { scope }),
86        None => Err(Error::new(
87            ErrCode::FailedPrecondition,
88            "there is no current test: the process is not running under `encore test`",
89        )),
90    }
91}
92
93/// What the current test has published to `topic`, in the order it was
94/// published: by the test itself, and by the code it called.
95///
96/// Under `encore test` nothing handles what a test publishes. This is how the
97/// test sees it, to assert on — and, when it wants a handler run, to hand to it.
98///
99/// ```ignore
100/// signed_up("ada").await?;
101/// let published = encore::testing::published(&SIGNUPS)?;
102/// assert_eq!(published.len(), 1);
103/// assert_eq!(published[0].data.user_id, "ada");
104/// send_welcome(published[0].clone()).await?;
105/// ```
106pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
107    topic: &crate::pubsub::Topic<T, E, O>,
108) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
109    match active()? {
110        Some(test) => topic.published_in(&test),
111        None => Err(Error::new(
112            ErrCode::FailedPrecondition,
113            "there is no current test: the process is not running under `encore test`",
114        )),
115    }
116}
117
118/// Gives `secret` a value for the current test, in place of the app's. No
119/// other test sees it, and it is gone when the test ends.
120///
121/// ```ignore
122/// encore::testing::set_secret(&API_KEY, "test-key")?;
123/// assert_eq!(*API_KEY.value()?, "test-key");
124/// ```
125pub fn set_secret(secret: &impl secrets::AnySecret, value: impl AsRef<[u8]>) -> Result<(), Error> {
126    match active()? {
127        Some(test) => {
128            test.secrets
129                .lock()
130                .unwrap_or_else(|e| e.into_inner())
131                .insert(secrets::key_of(secret), value.as_ref().into());
132            Ok(())
133        }
134        None => Err(Error::new(
135            ErrCode::FailedPrecondition,
136            "there is no current test: the process is not running under `encore test`",
137        )),
138    }
139}
140
141/// Gives `config` a value for the current test, in place of the app's. No
142/// other test sees it, and it is gone when the test ends. The value is checked
143/// against the config's schema, and read as its type, here.
144///
145/// ```ignore
146/// encore::testing::set_config(&CHECKOUT, serde_json::json!({"max_items": 2}))?;
147/// assert_eq!(CHECKOUT.get().max_items, 2);
148/// ```
149pub fn set_config<T: config::ConfigType>(
150    config: &impl config::AnyConfig<T>,
151    value: serde_json::Value,
152) -> Result<(), Error> {
153    match active()? {
154        Some(test) => {
155            let value = config::test_value(config, value)?;
156            test.configs
157                .lock()
158                .unwrap_or_else(|e| e.into_inner())
159                .insert(config::key_of(config), value);
160            Ok(())
161        }
162        None => Err(Error::new(
163            ErrCode::FailedPrecondition,
164            "there is no current test: the process is not running under `encore test`",
165        )),
166    }
167}
168
169/// A handle to one test, made by [`current`]. Cheap to clone, and can be sent
170/// to other threads, to make what they do part of the test.
171///
172/// The test's infrastructure lives for as long as the test or a handle to it
173/// does.
174#[derive(Clone)]
175pub struct TestScope {
176    scope: Arc<Scope>,
177}
178
179impl TestScope {
180    /// Makes the calling thread part of the test, until the guard is dropped.
181    pub fn enter(&self) -> ScopeGuard<'_> {
182        THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
183        ScopeGuard {
184            _scope: PhantomData,
185            _not_send: PhantomData,
186        }
187    }
188
189    /// Runs a future as part of the test, on whatever thread polls it.
190    pub async fn scope<F: Future>(&self, future: F) -> F::Output {
191        let mut future = pin!(future);
192        poll_fn(|cx| {
193            let _guard = self.enter();
194            future.as_mut().poll(cx)
195        })
196        .await
197    }
198
199    /// The test's name, as the test harness reports it: its path within the
200    /// crate, such as `tests::creates_a_user`. `None` if the test has only been
201    /// seen on its runtime's other threads so far.
202    pub fn name(&self) -> Option<&str> {
203        self.scope.name.get().map(String::as_str)
204    }
205}
206
207/// Keeps the thread part of a test. Returned by [`TestScope::enter`].
208pub struct ScopeGuard<'a> {
209    _scope: PhantomData<&'a TestScope>,
210    /// Entered on one thread, so left on it.
211    _not_send: PhantomData<*const ()>,
212}
213
214impl Drop for ScopeGuard<'_> {
215    fn drop(&mut self) {
216        THREAD.with(|thread| thread.borrow_mut().entered.pop());
217    }
218}
219
220/// What `#[encore::test]` expands to. Not for use by hand: it changes with the
221/// macro.
222#[doc(hidden)]
223pub mod __private {
224    use super::*;
225
226    /// The test, as the macro sees it where it is written.
227    pub struct TestInfo {
228        pub module: &'static str,
229        pub name: &'static str,
230        pub file: &'static str,
231        pub line: u32,
232    }
233
234    pub use super::fixture::FIXTURES;
235    pub use linkme;
236
237    /// The runtime to run the test in, from the macro's arguments.
238    pub struct RuntimeConfig {
239        pub multi_thread: bool,
240        pub worker_threads: Option<usize>,
241    }
242
243    /// The fixture the test starts from, from the macro's arguments.
244    pub enum FixtureArg {
245        /// Its module's, if a module it is in has one.
246        Module,
247        Named(&'static Fixture),
248        None,
249    }
250
251    /// Loads the test's fixture, before the test runs. Only under `encore
252    /// test`: anywhere else there is nothing to load it into.
253    async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
254        if encore_sdk_core::test_mode::test_mode_app_ref().is_none() {
255            return;
256        }
257        let loaded = match fixture {
258            FixtureArg::Module => match fixture::for_module(info.module, true) {
259                Some(fixture) => fixture.load().await,
260                None => Ok(()),
261            },
262            FixtureArg::Named(fixture) => fixture.load().await,
263            FixtureArg::None => without_fixture(),
264        };
265        if let Err(err) = loaded {
266            panic!("{}", err.message);
267        }
268    }
269
270    /// Ends the test on this thread when dropped: its scope is let go of, and
271    /// with it — once the runtime's threads have, too — its infrastructure.
272    pub(in crate::testing) struct EndTest;
273
274    impl Drop for EndTest {
275        fn drop(&mut self) {
276            THREAD.with(|thread| thread.borrow_mut().own = None);
277        }
278    }
279
280    /// Begins the test on this thread: a scope of its own, before any call.
281    fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
282        let scope = Scope::new();
283        let _ = scope.module.set((info.module.to_string(), true));
284        // As the test harness names it: the path within the crate.
285        let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
286        let name = if module.is_empty() {
287            info.name.to_string()
288        } else {
289            format!("{module}::{}", info.name)
290        };
291        let _ = scope.name.set(name);
292        THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
293        (scope, EndTest)
294    }
295
296    /// Runs an `async fn` test: in a runtime of its own, as `#[tokio::test]`
297    /// does, that is the test's from the start.
298    pub fn run<R, F: Future<Output = R>>(
299        info: TestInfo,
300        config: RuntimeConfig,
301        fixture: FixtureArg,
302        test: F,
303    ) -> R {
304        // Dropped last, after the runtime has stopped its threads.
305        let (scope, _end) = begin(&info);
306        let mut builder = if config.multi_thread {
307            tokio::runtime::Builder::new_multi_thread()
308        } else {
309            tokio::runtime::Builder::new_current_thread()
310        };
311        if let Some(threads) = config.worker_threads {
312            builder.worker_threads(threads);
313        }
314        let runtime = builder
315            .enable_all()
316            .build()
317            .expect("failed to build the test's Tokio runtime");
318        with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
319        drop(scope);
320        runtime.block_on(async {
321            load_fixture(&info, fixture).await;
322            test.await
323        })
324    }
325
326    /// Runs a test that is not `async`.
327    pub fn run_sync<R, F: FnOnce() -> R>(info: TestInfo, fixture: FixtureArg, test: F) -> R {
328        let (_scope, _end) = begin(&info);
329        // Loading a fixture is `async`, though the test is not.
330        tokio::runtime::Builder::new_current_thread()
331            .enable_all()
332            .build()
333            .expect("failed to build a Tokio runtime to load the test's fixture")
334            .block_on(load_fixture(&info, fixture));
335        test()
336    }
337}
338
339/// One test's infrastructure: what its resources resolve to, released when the
340/// last thread that is part of the test lets go of it.
341pub(crate) struct Scope {
342    /// The id the runtime knows this test's resource instances by.
343    instance_id: String,
344    name: OnceLock<String>,
345    /// The module the test is in, and whether that is its full path (with the
346    /// crate, from `#[encore::test]`) or the test harness's (without).
347    module: OnceLock<(String, bool)>,
348    /// What the test's resources start from.
349    fixture: Mutex<Choice>,
350    databases: Mutex<HashMap<&'static str, Arc<Pool>>>,
351    /// The buckets the test has an instance of.
352    buckets: Mutex<HashSet<&'static str>>,
353    /// The test's client for each Redis database it has an instance of.
354    redis: Mutex<HashMap<&'static str, Arc<encore_sdk_core::cache::Client>>>,
355    /// What the test has published, by topic. A topic it has published to is
356    /// one it has an instance of.
357    published: Mutex<HashMap<&'static str, Vec<Published>>>,
358    /// The values the test has given secrets, in place of the app's.
359    secrets: Mutex<HashMap<SecretKey, Arc<[u8]>>>,
360    /// The values the test has given configs, in place of the app's, each
361    /// already read as the config's type.
362    configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
363}
364
365/// The scope and name a secret is held under.
366type SecretKey = (secrets::Scope, &'static str);
367
368/// The scope and name a config is held under.
369type ConfigKey = (config::Scope, &'static str);
370
371/// A message a test published, as it was sent.
372#[derive(Clone)]
373pub(crate) struct Published {
374    pub(crate) id: String,
375    pub(crate) payload: Vec<u8>,
376    pub(crate) attributes: HashMap<String, String>,
377    pub(crate) ordering_key: Option<String>,
378    pub(crate) publish_time: std::time::SystemTime,
379}
380
381/// What a test's resources start from.
382#[derive(Clone, Copy)]
383pub(crate) enum Choice {
384    /// Not said yet. Settled when the test first uses a resource.
385    Unset,
386    /// Their initial state.
387    None,
388    Fixture(&'static Fixture),
389}
390
391impl Choice {
392    fn is(self, other: Choice) -> bool {
393        match (self, other) {
394            (Choice::Unset, Choice::Unset) | (Choice::None, Choice::None) => true,
395            (Choice::Fixture(a), Choice::Fixture(b)) => std::ptr::eq(a, b),
396            _ => false,
397        }
398    }
399}
400
401impl Scope {
402    fn new() -> Arc<Self> {
403        static NEXT: AtomicU64 = AtomicU64::new(0);
404        Arc::new(Self {
405            instance_id: format!(
406                "t{:x}x{:x}",
407                std::process::id(),
408                NEXT.fetch_add(1, Ordering::Relaxed)
409            ),
410            name: OnceLock::new(),
411            module: OnceLock::new(),
412            fixture: Mutex::new(Choice::Unset),
413            databases: Mutex::new(HashMap::new()),
414            buckets: Mutex::new(HashSet::new()),
415            redis: Mutex::new(HashMap::new()),
416            published: Mutex::new(HashMap::new()),
417            secrets: Mutex::new(HashMap::new()),
418            configs: Mutex::new(HashMap::new()),
419        })
420    }
421
422    /// Sets what the test's resources start from. An error once it has some,
423    /// unless it is what they started from.
424    pub(crate) fn choose(&self, choice: Choice) -> Result<(), Error> {
425        let mut current = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
426        if current.is(choice) {
427            return Ok(());
428        }
429        let used = !self
430            .databases
431            .lock()
432            .unwrap_or_else(|e| e.into_inner())
433            .is_empty()
434            || !self
435                .buckets
436                .lock()
437                .unwrap_or_else(|e| e.into_inner())
438                .is_empty()
439            || !self
440                .redis
441                .lock()
442                .unwrap_or_else(|e| e.into_inner())
443                .is_empty();
444        if used {
445            return Err(Error::new(
446                ErrCode::FailedPrecondition,
447                "the test has already used a resource, so what it starts from can no longer \
448                 change: load the fixture before the test first uses one",
449            ));
450        }
451        *current = choice;
452        Ok(())
453    }
454
455    /// The fixture the test's resources start from, settling it at first use:
456    /// none, unless one was loaded. A test in a module with a fixture of its
457    /// own must have said — `#[encore::test]` does.
458    fn fixture_name(&self) -> Result<&'static str, Error> {
459        let mut choice = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
460        if let Choice::Unset = *choice {
461            if let Some((module, full)) = self.module.get() {
462                if let Some(fixture) = fixture::for_module(module, *full) {
463                    return Err(Error::new(
464                        ErrCode::FailedPrecondition,
465                        format!(
466                            "this test is in a module whose tests start from the fixture {:?}, \
467                             but has not loaded it. Make it an `#[encore::test]`, which does, \
468                             or call `.load().await?` on the fixture — or \
469                             `encore::testing::without_fixture()?` — before the test first \
470                             uses a resource",
471                            fixture.name()
472                        ),
473                    ));
474                }
475            }
476            *choice = Choice::None;
477        }
478        Ok(match *choice {
479            Choice::Fixture(fixture) => fixture.name(),
480            Choice::None | Choice::Unset => "",
481        })
482    }
483
484    /// Lets go of the test's resources without releasing them: they are a
485    /// fixture's now.
486    fn forget(&self) {
487        self.databases
488            .lock()
489            .unwrap_or_else(|e| e.into_inner())
490            .clear();
491        self.buckets
492            .lock()
493            .unwrap_or_else(|e| e.into_inner())
494            .clear();
495        self.redis.lock().unwrap_or_else(|e| e.into_inner()).clear();
496    }
497
498    /// The value the test has given the secret, if it has.
499    pub(crate) fn secret(&self, scope: secrets::Scope, name: &'static str) -> Option<Arc<[u8]>> {
500        self.secrets
501            .lock()
502            .unwrap_or_else(|e| e.into_inner())
503            .get(&(scope, name))
504            .cloned()
505    }
506
507    /// The value the test has given the config, if it has.
508    pub(crate) fn config(
509        &self,
510        scope: config::Scope,
511        name: &'static str,
512    ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
513        self.configs
514            .lock()
515            .unwrap_or_else(|e| e.into_inner())
516            .get(&(scope, name))
517            .cloned()
518    }
519
520    /// The test's instance of the topic `name`, provisioned for this test when
521    /// first asked for: nothing published to it reaches another test.
522    pub(crate) fn topic(&self, name: &'static str) -> Result<pubsub::TopicObj, Error> {
523        let topic = core()
524            .pubsub()
525            .topic_instance(name.into(), &self.instance_id)
526            .ok_or_else(|| {
527                Error::unavailable(format!("could not provision the test's topic {name:?}"))
528            })?;
529        self.published
530            .lock()
531            .unwrap_or_else(|e| e.into_inner())
532            .entry(name)
533            .or_default();
534        Ok(topic)
535    }
536
537    /// Notes a message the test published to the topic `name`.
538    pub(crate) fn note_published(&self, name: &'static str, message: Published) {
539        self.published
540            .lock()
541            .unwrap_or_else(|e| e.into_inner())
542            .entry(name)
543            .or_default()
544            .push(message);
545    }
546
547    /// What the test has published to the topic `name`, in order.
548    pub(crate) fn published(&self, name: &str) -> Vec<Published> {
549        self.published
550            .lock()
551            .unwrap_or_else(|e| e.into_inner())
552            .get(name)
553            .cloned()
554            .unwrap_or_default()
555    }
556
557    /// The test's instance of the bucket `name`, provisioned for this test
558    /// when first asked for.
559    pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
560        let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
561        let fixture = if buckets.contains(name) {
562            // Provisioned already: the runtime has it by its id.
563            ""
564        } else {
565            self.fixture_name()?
566        };
567        let bucket = core()
568            .objects()
569            .try_bucket_instance_from(name.into(), &self.instance_id, fixture)
570            .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
571        buckets.insert(name);
572        Ok(bucket)
573    }
574
575    /// The test's pool for the database `name`, on an instance of the database
576    /// provisioned for this test when first asked for.
577    pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
578        let mut databases = self.databases.lock().unwrap_or_else(|e| e.into_inner());
579        if let Some(pool) = databases.get(name) {
580            return Ok(pool.clone());
581        }
582        let fixture = self.fixture_name()?;
583        let pool = core()
584            .postgres()
585            .try_database_instance_from(&name.into(), &self.instance_id, fixture)
586            .and_then(|db| db.new_pool())
587            .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
588        let pool = Arc::new(pool);
589        databases.insert(name, pool.clone());
590        Ok(pool)
591    }
592
593    /// The test's client for the Redis database `name`, on an instance of the
594    /// database provisioned for this test when first asked for: with keys and
595    /// channels no other test sees, and holding what the test's fixture left
596    /// in it, or nothing.
597    pub(crate) fn redis_client(
598        &self,
599        name: &'static str,
600    ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
601        let mut clients = self.redis.lock().unwrap_or_else(|e| e.into_inner());
602        if let Some(client) = clients.get(name) {
603            return Ok(client.clone());
604        }
605        let fixture = self.fixture_name()?;
606        let client = core()
607            .cache()
608            .cluster_instance_from(&name.into(), &self.instance_id, fixture)
609            .client()
610            .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
611        let client = Arc::new(client);
612        clients.insert(name, client.clone());
613        Ok(client)
614    }
615
616    /// The connection string of the test's instance of the database `name`,
617    /// for `access`.
618    pub(crate) fn database_connection_string(
619        &self,
620        name: &'static str,
621        access: Access,
622    ) -> Result<String, Error> {
623        // Provisions the instance, which the connection string routes to.
624        self.database_pool(name)?;
625        core()
626            .postgres()
627            .try_database_instance(&name.into(), &self.instance_id)
628            .map(|db| db.proxy_conn_string(access))
629            .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))
630    }
631}
632
633impl Drop for Scope {
634    fn drop(&mut self) {
635        let databases = std::mem::take(self.databases.get_mut().unwrap_or_else(|e| e.into_inner()));
636        // Close the pools first: the instances are dropped with them still open
637        // otherwise.
638        let names: Vec<&'static str> = databases.keys().copied().collect();
639        drop(databases);
640        for name in names {
641            core()
642                .postgres()
643                .release_instance(&name.into(), &self.instance_id);
644        }
645        let topics = std::mem::take(self.published.get_mut().unwrap_or_else(|e| e.into_inner()));
646        for name in topics.into_keys() {
647            core()
648                .pubsub()
649                .release_topic_instance(&name.into(), &self.instance_id);
650        }
651        let redis = std::mem::take(self.redis.get_mut().unwrap_or_else(|e| e.into_inner()));
652        // The clients first, as with the database pools.
653        let names: Vec<&'static str> = redis.keys().copied().collect();
654        drop(redis);
655        for name in names {
656            core()
657                .cache()
658                .release_instance(&name.into(), &self.instance_id);
659        }
660        let buckets = std::mem::take(self.buckets.get_mut().unwrap_or_else(|e| e.into_inner()));
661        for name in buckets {
662            core()
663                .objects()
664                .release_instance(&name.into(), &self.instance_id);
665        }
666    }
667}
668
669/// Runs `work` on the calling thread as the scope `scope`'s: in a runtime of
670/// its own, whose threads are the scope's too.
671fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
672    THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
673    // Dropped last, after the runtime has stopped its threads.
674    let _end = __private::EndTest;
675    let runtime = tokio::runtime::Builder::new_current_thread()
676        .enable_all()
677        .build()
678        .expect("failed to build a Tokio runtime");
679    with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
680    drop(scope);
681    runtime.block_on(work)
682}
683
684/// The test the calling thread belongs to, if the process runs under `encore
685/// test`: `None` otherwise, where resources are the app's own.
686pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
687    if !core().postgres().isolates_instances() {
688        return Ok(None);
689    }
690    resolve().map(Some)
691}
692
693/// What a thread holds of the tests it is part of. Dropped when the thread
694/// exits, which is what ends a test: its own thread exits when it is done, and
695/// its runtime's threads with it.
696#[derive(Default)]
697struct ThreadScopes {
698    /// The test this thread is the test harness's thread of.
699    own: Option<Arc<Scope>>,
700    /// The tests this thread joined through their runtime, kept alive by it.
701    joined: Vec<Arc<Scope>>,
702    /// The tests entered with [`TestScope::enter`], innermost last.
703    entered: Vec<Arc<Scope>>,
704}
705
706thread_local! {
707    static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
708}
709
710/// Which test a Tokio runtime belongs to.
711enum Link {
712    Test(Weak<Scope>),
713    /// Several tests run on it, so its threads belong to none in particular.
714    Shared,
715}
716
717static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
718
719fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
720    let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
721    f(runtimes.get_or_insert_with(HashMap::new))
722}
723
724/// The name of the test a thread of this name is the test harness's thread of.
725/// The harness names each test's thread after the test; the process's main
726/// thread, unnamed threads and Tokio's own are not one.
727fn test_name(thread: Option<&str>) -> Option<&str> {
728    thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
729}
730
731/// The test the calling thread belongs to: the one it entered, the one it is
732/// the test harness's thread of, or the one whose runtime it is a thread of.
733fn resolve() -> Result<Arc<Scope>, Error> {
734    let handle = Handle::try_current().ok();
735    let runtime = handle.as_ref().map(Handle::id);
736    let thread = std::thread::current();
737    THREAD.with(|state| {
738        let mut state = state.borrow_mut();
739        if let Some(scope) = state.entered.last() {
740            return Ok(scope.clone());
741        }
742
743        // `#[encore::test]` began the test on this thread, whatever it is named.
744        if let Some(scope) = &state.own {
745            let scope = scope.clone();
746            if let Some(id) = runtime {
747                with_runtimes(|runtimes| link(runtimes, id, &scope));
748            }
749            return Ok(scope);
750        }
751
752        if let Some(name) = test_name(thread.name()) {
753            let scope = match &state.own {
754                Some(scope) => scope.clone(),
755                None => {
756                    // The runtime's other threads may have got here first.
757                    let scope = runtime
758                        .and_then(|id| {
759                            with_runtimes(|runtimes| match runtimes.get(&id) {
760                                Some(Link::Test(scope)) => {
761                                    scope.upgrade().filter(|scope| scope.name.get().is_none())
762                                }
763                                _ => None,
764                            })
765                        })
766                        .unwrap_or_else(Scope::new);
767                    let _ = scope.name.set(name.to_string());
768                    let module = name.rsplit_once("::").map_or("", |(module, _)| module);
769                    let _ = scope.module.set((module.to_string(), false));
770                    state.own = Some(scope.clone());
771                    scope
772                }
773            };
774            if let Some(id) = runtime {
775                with_runtimes(|runtimes| link(runtimes, id, &scope));
776            }
777            return Ok(scope);
778        }
779
780        let Some(id) = runtime else {
781            return Err(not_a_test_thread(thread.name()));
782        };
783        let scope = with_runtimes(|runtimes| {
784            match runtimes.get(&id) {
785                Some(Link::Shared) => return Err(shared_runtime(thread.name())),
786                Some(Link::Test(scope)) => {
787                    if let Some(scope) = scope.upgrade() {
788                        return Ok(scope);
789                    }
790                }
791                None => {}
792            }
793            // The first use of the runtime. If it has worker threads, this is
794            // one, and got here before the test thread driving it: a test of
795            // its own, which that thread adopts when it gets here. One without
796            // is driven by this thread, which is not a test's.
797            let multi_thread = handle
798                .as_ref()
799                .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
800            if !multi_thread {
801                return Err(not_a_test_thread(thread.name()));
802            }
803            let scope = Scope::new();
804            link(runtimes, id, &scope);
805            Ok(scope)
806        })?;
807        if !state
808            .joined
809            .iter()
810            .any(|joined| Arc::ptr_eq(joined, &scope))
811        {
812            state.joined.push(scope.clone());
813        }
814        Ok(scope)
815    })
816}
817
818/// Records that the runtime `id` is `scope`'s — or, if it already is another
819/// running test's, that it is shared.
820fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
821    let shared = match runtimes.get(&id) {
822        Some(Link::Shared) => true,
823        Some(Link::Test(current)) => current
824            .upgrade()
825            .is_some_and(|current| !Arc::ptr_eq(&current, scope)),
826        None => false,
827    };
828    if !shared {
829        // Runtimes that have ended leave their entries behind.
830        runtimes.retain(|_, link| match link {
831            Link::Test(scope) => scope.strong_count() > 0,
832            Link::Shared => true,
833        });
834    }
835    let link = if shared {
836        Link::Shared
837    } else {
838        Link::Test(Arc::downgrade(scope))
839    };
840    runtimes.insert(id, link);
841}
842
843fn thread_label(name: Option<&str>) -> String {
844    match name {
845        Some(name) => format!("thread {name:?}"),
846        None => "an unnamed thread".to_string(),
847    }
848}
849
850fn not_a_test_thread(thread: Option<&str>) -> Error {
851    Error::new(
852        ErrCode::FailedPrecondition,
853        format!(
854            "an Encore resource was used on {}, which Encore cannot link to a running test. \
855             Each test gets infrastructure of its own, so Encore needs to know which test \
856             this thread belongs to.\n\n\
857             In the test, capture the scope and enter it on the new thread:\n\n    \
858             let scope = encore::testing::current()?;\n    \
859             std::thread::spawn(move || {{\n        \
860             let _guard = scope.enter();\n        \
861             …\n    \
862             }});",
863            thread_label(thread)
864        ),
865    )
866}
867
868fn shared_runtime(thread: Option<&str>) -> Error {
869    Error::new(
870        ErrCode::FailedPrecondition,
871        format!(
872            "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
873             so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
874             its own.\n\n\
875             Run the work as part of its test:\n\n    \
876             let scope = encore::testing::current()?;\n    \
877             runtime.spawn(async move {{ scope.scope(work()).await }});",
878            thread_label(thread)
879        ),
880    )
881}
882
883#[cfg(test)]
884mod tests {
885    use super::*;
886
887    /// The test the calling thread resolves to, by name and identity.
888    fn here() -> Result<(Option<String>, usize), String> {
889        resolve()
890            .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
891            .map_err(|err| err.message)
892    }
893
894    #[test]
895    fn a_test_thread_is_its_test() {
896        let (name, id) = here().unwrap();
897        assert_eq!(
898            name.as_deref(),
899            Some("testing::tests::a_test_thread_is_its_test")
900        );
901        // The same test every time.
902        assert_eq!(here().unwrap().1, id);
903    }
904
905    #[test]
906    fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
907        let (_, id) = here().unwrap();
908        let scope = TestScope {
909            scope: resolve().unwrap(),
910        };
911
912        let err = std::thread::spawn(here).join().unwrap().unwrap_err();
913        assert!(err.contains("an unnamed thread"), "{err}");
914        assert!(err.contains("scope.enter()"), "{err}");
915
916        let entered = std::thread::spawn(move || {
917            let inside = {
918                let _guard = scope.enter();
919                here()
920            };
921            (inside, here())
922        })
923        .join()
924        .unwrap();
925        assert_eq!(entered.0.unwrap().1, id);
926        // Only while the guard is held.
927        assert!(entered.1.is_err());
928    }
929
930    #[tokio::test]
931    async fn a_current_thread_runtime_is_its_test() {
932        let (name, id) = here().unwrap();
933        assert!(name.is_some());
934        assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
935        assert_eq!(
936            tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
937            id
938        );
939    }
940
941    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
942    async fn a_multi_thread_runtime_is_its_test() {
943        let (_, id) = here().unwrap();
944        for _ in 0..8 {
945            assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
946        }
947        assert_eq!(
948            tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
949            id
950        );
951    }
952
953    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
954    async fn a_test_adopts_what_its_runtime_started() {
955        // A worker gets there first: a test with no name yet.
956        let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
957        assert_eq!(name, None);
958        // The test thread is that same test, and names it.
959        let (name, adopted) = here().unwrap();
960        assert_eq!(adopted, id);
961        assert!(name
962            .unwrap()
963            .ends_with("a_test_adopts_what_its_runtime_started"));
964        let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
965        assert_eq!(again, id);
966        assert!(name.is_some());
967    }
968
969    #[test]
970    fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
971        let runtime = tokio::runtime::Builder::new_multi_thread()
972            .worker_threads(1)
973            .build()
974            .unwrap();
975        let handle = runtime.handle().clone();
976        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
977        let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
978        // One test, holding its scope on the runtime…
979        let first = std::thread::Builder::new()
980            .name("tests::first".to_string())
981            .spawn({
982                let handle = handle.clone();
983                move || {
984                    let _enter = handle.enter();
985                    let id = here().unwrap().1;
986                    ready_tx.send(id).unwrap();
987                    let _ = done_rx.recv();
988                }
989            })
990            .unwrap();
991        let first_id = ready_rx.recv().unwrap();
992        // …while another starts on the same one.
993        let second_id = std::thread::Builder::new()
994            .name("tests::second".to_string())
995            .spawn({
996                let handle = handle.clone();
997                move || {
998                    let _enter = handle.enter();
999                    here().unwrap().1
1000                }
1001            })
1002            .unwrap()
1003            .join()
1004            .unwrap();
1005        assert_ne!(first_id, second_id);
1006
1007        // Each test thread is still its own test; the workers are neither's.
1008        let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
1009        // `block_on` here runs on this test's own thread; the spawned task on a worker.
1010        let err = err.unwrap_err();
1011        assert!(err.contains("several tests share"), "{err}");
1012        assert!(err.contains("scope.scope("), "{err}");
1013
1014        done_tx.send(()).unwrap();
1015        first.join().unwrap();
1016    }
1017
1018    #[tokio::test]
1019    async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
1020        let (_, id) = here().unwrap();
1021        let scope = TestScope {
1022            scope: resolve().unwrap(),
1023        };
1024        assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
1025        // On a thread of another runtime, which is no test's.
1026        let other = std::thread::spawn(move || {
1027            tokio::runtime::Builder::new_current_thread()
1028                .build()
1029                .unwrap()
1030                .block_on(async {
1031                    let outside = here();
1032                    let inside = scope.scope(async { here().unwrap().1 }).await;
1033                    (outside, inside)
1034                })
1035        })
1036        .join()
1037        .unwrap();
1038        let err = other.0.unwrap_err();
1039        assert!(err.contains("cannot link to a running test"), "{err}");
1040        assert_eq!(other.1, id);
1041    }
1042
1043    #[encore::test]
1044    async fn the_macro_runs_a_test_in_its_own_runtime() {
1045        let (name, id) = here().unwrap();
1046        // Named as the harness names it, without the crate.
1047        assert_eq!(
1048            name.as_deref(),
1049            Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
1050        );
1051        assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1052        // A current-thread runtime, as `#[tokio::test]` gives by default.
1053        assert_eq!(
1054            Handle::current().runtime_flavor(),
1055            RuntimeFlavor::CurrentThread
1056        );
1057    }
1058
1059    #[encore::test(flavor = "multi_thread", worker_threads = 2)]
1060    async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
1061        // A worker gets there first, and already knows the test by name.
1062        let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
1063        assert!(name.unwrap().ends_with("before_the_test_runs"));
1064        assert_eq!(here()?.1, id);
1065        assert_eq!(Handle::current().metrics().num_workers(), 2);
1066        Ok(())
1067    }
1068
1069    #[encore::test]
1070    #[should_panic(expected = "as any test")]
1071    async fn the_macro_keeps_the_tests_other_attributes() {
1072        panic!("as any test");
1073    }
1074
1075    #[encore::test]
1076    fn the_macro_takes_a_test_that_is_not_async() {
1077        let (name, _) = here().unwrap();
1078        assert!(name.unwrap().ends_with("is_not_async"));
1079    }
1080
1081    #[test]
1082    fn the_macro_ends_the_test_when_it_returns() {
1083        let weak = std::thread::spawn(|| {
1084            let weak = __private::run(
1085                __private::TestInfo {
1086                    module: "app::tests",
1087                    name: "returns",
1088                    file: file!(),
1089                    line: line!(),
1090                },
1091                __private::RuntimeConfig {
1092                    multi_thread: true,
1093                    worker_threads: Some(1),
1094                },
1095                __private::FixtureArg::Module,
1096                async {
1097                    tokio::spawn(async { here().unwrap() }).await.unwrap();
1098                    Arc::downgrade(&resolve().unwrap())
1099                },
1100            );
1101            // Gone already, though this thread lives on.
1102            assert!(weak.upgrade().is_none());
1103            assert!(here().is_err());
1104        })
1105        .join();
1106        weak.unwrap();
1107    }
1108
1109    mod billing {
1110        crate::fixture! {
1111            /// The module's fixture.
1112            pub static SEEDED for mod = async { Ok(()) };
1113
1114            /// One to load by hand.
1115            pub static EXTRA: SEEDED = async { Ok(()) };
1116        }
1117
1118        pub mod invoices {
1119            crate::fixture! {
1120                pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
1121            }
1122        }
1123    }
1124
1125    #[test]
1126    fn a_fixture_is_named_after_where_it_is_declared() {
1127        assert_eq!(
1128            billing::SEEDED.name(),
1129            "encore::testing::tests::billing::SEEDED"
1130        );
1131        assert_eq!(
1132            billing::invoices::INVOICED.name(),
1133            "encore::testing::tests::billing::invoices::INVOICED"
1134        );
1135    }
1136
1137    #[test]
1138    fn a_modules_fixture_is_found_from_the_tests_inside_it() {
1139        let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
1140        // By the full path `#[encore::test]` knows a test by…
1141        assert_eq!(
1142            found("encore::testing::tests::billing", true),
1143            Some(billing::SEEDED.name())
1144        );
1145        assert_eq!(
1146            found("encore::testing::tests::billing::reports::monthly", true),
1147            Some(billing::SEEDED.name())
1148        );
1149        // …the innermost module's winning…
1150        assert_eq!(
1151            found("encore::testing::tests::billing::invoices", true),
1152            Some(billing::invoices::INVOICED.name())
1153        );
1154        // …and by the path without the crate the test harness names it by.
1155        assert_eq!(
1156            found("testing::tests::billing::invoices::overdue", false),
1157            Some(billing::invoices::INVOICED.name())
1158        );
1159        // A module that merely starts the same is not inside it, and a
1160        // fixture that is not a module's is nobody's.
1161        assert_eq!(found("encore::testing::tests::billing_reports", true), None);
1162        assert_eq!(found("encore::testing::tests", true), None);
1163        assert_eq!(found("testing::tests", false), None);
1164    }
1165
1166    #[test]
1167    fn what_a_test_starts_from_is_settled_at_first_use() {
1168        let scope = Scope::new();
1169        scope.choose(Choice::Fixture(&billing::EXTRA)).unwrap();
1170        scope.choose(Choice::Fixture(&billing::SEEDED)).unwrap();
1171        assert_eq!(scope.fixture_name().unwrap(), billing::SEEDED.name());
1172
1173        // A test in a module with a fixture has to say, one way or the other.
1174        let unsaid = Scope::new();
1175        let _ = unsaid
1176            .module
1177            .set(("testing::tests::billing".to_string(), false));
1178        let err = unsaid.fixture_name().unwrap_err();
1179        assert!(err.message.contains("has not loaded it"), "{err}");
1180        unsaid.choose(Choice::None).unwrap();
1181        assert_eq!(unsaid.fixture_name().unwrap(), "");
1182
1183        // Anywhere else, nothing said is no fixture.
1184        let plain = Scope::new();
1185        let _ = plain.module.set(("testing::tests".to_string(), false));
1186        assert_eq!(plain.fixture_name().unwrap(), "");
1187    }
1188
1189    #[test]
1190    fn a_scope_ends_with_the_threads_that_are_part_of_it() {
1191        let weak = std::thread::Builder::new()
1192            .name("tests::short_lived".to_string())
1193            .spawn(|| Arc::downgrade(&resolve().unwrap()))
1194            .unwrap()
1195            .join()
1196            .unwrap();
1197        assert!(weak.upgrade().is_none());
1198
1199        // A handle keeps it alive past its thread.
1200        let scope = std::thread::Builder::new()
1201            .name("tests::held".to_string())
1202            .spawn(|| TestScope {
1203                scope: resolve().unwrap(),
1204            })
1205            .unwrap()
1206            .join()
1207            .unwrap();
1208        let weak = Arc::downgrade(&scope.scope);
1209        assert!(weak.upgrade().is_some());
1210        drop(scope);
1211        assert!(weak.upgrade().is_none());
1212    }
1213}