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