Skip to main content

encore/testing/
mod.rs

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