encore-dev 2.0.0-beta.10

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
//! Tests. Under `encore test` every test gets infrastructure of its own —
//! databases, buckets and topics no other test sees — with nothing to set up:
//!
//! ```ignore
//! #[tokio::test]
//! async fn creates_a_user() -> Result<(), encore::Error> {
//!     create_user("ada").await?; // uses the `static DB`, isolated to this test
//!     let row = DB.query_one("SELECT count(*) FROM users", &[]).await?;
//!     assert_eq!(row.get::<_, i64>(0), 1);
//!     Ok(())
//! }
//! ```
//!
//! Encore works out which test a call belongs to from where it is made: on the
//! test's own thread (the test harness names it after the test), or on a thread
//! of the Tokio runtime the test runs in — a spawned task, `spawn_blocking`. The
//! test's infrastructure is released when the test ends.
//!
//! # Without `encore test`
//!
//! `cargo test` and cargo-nextest work too, and so does an editor's button that
//! runs one test: Encore finds the app the test is in, and starts its daemon
//! with the `encore` on `PATH` if it is not running. Its secrets and configs
//! have the values configured for tests, as under `encore test`. The app's
//! `.env` files are not read: give a test the variables it needs yourself.
//! `ENCORE_TEST=0` turns this off, and `ENCORE_TEST=1` turns it on for a test
//! runner Encore does not recognize.
//!
//! # `#[encore::test]`
//!
//! Any test works: `#[test]`, `#[tokio::test]`. [`#[encore::test]`](macro@crate::test)
//! is `#[tokio::test]` — it takes the same `flavor` and `worker_threads` — that
//! tells Encore about the test before it runs, rather than leaving it to be
//! worked out at the first call. Its runtime's threads are part of the test from
//! the start, and its infrastructure is released as soon as it returns.
//!
//! ```ignore
//! #[encore::test(flavor = "multi_thread")]
//! async fn handles_concurrent_requests() -> Result<(), encore::Error> {
//!     // …
//! }
//! ```
//!
//! # Fixtures
//!
//! A test starts from the app's freshly provisioned resources: an empty,
//! migrated database, an empty bucket. A [`Fixture`] is a state to start from instead, built
//! once by a setup of yours and then copied for each test that loads it. See
//! [`Fixture`] and [`fixture!`](crate::fixture).
//!
//! # Other threads
//!
//! A thread the test starts itself is neither, so Encore cannot tell which test
//! it belongs to, and using a resource on it is an error. (The exception is a
//! multi-thread runtime built on such a thread, which Encore takes for a test's:
//! it gets infrastructure of its own.) Link the thread to the test with a
//! [`TestScope`]:
//!
//! ```ignore
//! let scope = encore::testing::current()?;
//! std::thread::spawn(move || {
//!     let _guard = scope.enter();
//!     // … part of the test from here on
//! });
//! ```

#[cfg(feature = "chromiumoxide")]
pub mod chromiumoxide;
mod fixture;
pub mod system;

pub use fixture::{without_fixture, Fixture, SetupFn};

use std::cell::RefCell;
use std::collections::HashMap;
use std::future::{poll_fn, Future};
use std::marker::PhantomData;
use std::pin::pin;
use std::sync::{Arc, Mutex, OnceLock, Weak};

use encore_sdk_core::objects;
use encore_sdk_core::postgres::{Access, Pool};
use encore_sdk_core::test_scope::{self, FixtureChoiceError, TestScope as CoreScope};
use tokio::runtime::{Handle, Id, RuntimeFlavor};

use crate::config;
use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::secrets;

/// The test the calling thread belongs to.
///
/// Fails outside `encore test`, and on a thread Encore cannot link to a test:
/// see the [module documentation](self).
pub fn current() -> Result<TestScope, Error> {
    match active()? {
        Some(scope) => Ok(TestScope { scope }),
        None => Err(Error::new(
            ErrCode::FailedPrecondition,
            "there is no current test: the process is not running under `encore test`",
        )),
    }
}

/// What the current test has published to `topic`, in the order it was
/// published: by the test itself, and by the code it called.
///
/// Under `encore test` nothing handles what a test publishes. This is how the
/// test sees it, to assert on — and, when it wants a handler run, to hand to it.
///
/// ```ignore
/// signed_up("ada").await?;
/// let published = encore::testing::published(&SIGNUPS)?;
/// assert_eq!(published.len(), 1);
/// assert_eq!(published[0].data.user_id, "ada");
/// send_welcome(published[0].clone()).await?;
/// ```
pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
    topic: &crate::pubsub::Topic<T, E, O>,
) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
    if core().system_test().is_some() {
        return Err(Error::new(
            ErrCode::Unimplemented,
            "what a system test published is sent, and is not kept by the test: read what \
             the app did with it instead, once it has `settled`",
        ));
    }
    match active()? {
        Some(test) => topic.published_in(&test),
        None => Err(Error::new(
            ErrCode::FailedPrecondition,
            "there is no current test: the process is not running under `encore test`",
        )),
    }
}

/// Runs `subscription`'s handler on each message the current test — or the
/// code it called — published to its topic that the subscription has not
/// handled yet, one at a time, in the order they were published, as part of
/// the test. Returns how many it handled.
///
/// Nothing handles what a test publishes otherwise: this is how a test has
/// one run. As in a real delivery, the handler gets a message only if the
/// subscription's filter matches it, with the Request Context fields it was
/// published with, and `delivery_attempt` 1 the first time. What the handler
/// publishes to the topic in turn is handed over in the same call.
///
/// It stops at the first message the handler fails, and returns its error.
/// That message stays unhandled: the next call hands it over again, its
/// `delivery_attempt` one more. Retry policies, ack deadlines and dead letters
/// play no part.
///
/// ```ignore
/// signup("ada").await?; // publishes to SIGNUPS
/// assert_eq!(encore::testing::deliver(&SEND_WELCOME).await?, 1);
/// ```
pub async fn deliver<T: Send + 'static>(
    subscription: &'static crate::pubsub::Subscription<T>,
) -> Result<usize, Error> {
    if core().system_test().is_some() {
        return Err(Error::new(
            ErrCode::FailedPrecondition,
            "subscriptions run on their own in a system test, in the services that declare \
             them: wait for them to have handled what was published with \
             `encore::testing::system::settled`",
        ));
    }
    match active()? {
        Some(test) => subscription.deliver_in(&test).await,
        None => Err(Error::new(
            ErrCode::FailedPrecondition,
            "there is no current test: the process is not running under `encore test`",
        )),
    }
}

/// Gives `secret` a value for the current test, in place of the app's. No
/// other test sees it, and it is gone when the test ends.
///
/// Not in a system test, whose services read their own values: give the
/// secret its value for tests in `secrets.test.toml` instead.
///
/// ```ignore
/// encore::testing::set_secret(&API_KEY, "test-key")?;
/// assert_eq!(*API_KEY.value(), "test-key");
/// ```
pub fn set_secret<T: secrets::SecretValue>(
    secret: &secrets::Secret<T>,
    value: impl AsRef<[u8]>,
) -> Result<(), Error> {
    if core().system_test().is_some() {
        return Err(Error::new(
            ErrCode::FailedPrecondition,
            SECRET_IN_SYSTEM_TEST,
        ));
    }
    match active()? {
        Some(test) => {
            // A secret name has one scope across the app.
            test.core_scope()?.set_secret(secret.name(), value.as_ref());
            Ok(())
        }
        None => Err(Error::new(
            ErrCode::FailedPrecondition,
            "there is no current test: the process is not running under `encore test`",
        )),
    }
}

/// Gives `config` a value for the current test, in place of the app's. No
/// other test sees it, and it is gone when the test ends. The value is checked
/// against the config's schema, and read as its type, here.
///
/// The value is a value of the config's type, which then derives
/// `Serialize` as well as `Deserialize`, or its JSON form, as its files would
/// hold it. A secret field is left out: it reads its secret as ever. So is a
/// field that serializes as `null`, as an `Option` that is `None` does.
///
/// Not in a system test, whose services read their own values: give the
/// config its value for tests in its `test` config file instead.
///
/// ```ignore
/// encore::testing::set_config(&CHECKOUT, &Checkout { max_items: 2, ..CHECKOUT.get().clone() })?;
/// encore::testing::set_config(&CHECKOUT, serde_json::json!({"max_items": 2}))?;
/// assert_eq!(CHECKOUT.get().max_items, 2);
/// ```
pub fn set_config<T: config::ConfigType>(
    config: &config::Config<T>,
    value: impl serde::Serialize,
) -> Result<(), Error> {
    if core().system_test().is_some() {
        return Err(Error::new(
            ErrCode::FailedPrecondition,
            CONFIG_IN_SYSTEM_TEST,
        ));
    }
    match active()? {
        Some(test) => {
            let name = config.key();
            let mut value = serde_json::to_value(value).map_err(|err| {
                Error::invalid_argument(format!("the value for config {name:?} is not JSON: {err}"))
            })?;
            config_form(&mut value);
            let value = test
                .core_scope()?
                .set_config(name, value)
                .map_err(|errors| {
                    Error::invalid_argument(format!(
                        "the value for config {name:?} does not satisfy its schema: {}",
                        errors.join("; ")
                    ))
                })?;
            let value = config::test_value::<T>(name, value)?;
            test.configs
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(name, value);
            Ok(())
        }
        None => Err(Error::new(
            ErrCode::FailedPrecondition,
            "there is no current test: the process is not running under `encore test`",
        )),
    }
}

/// Makes `value` what a config's files would hold: without its secret
/// fields, which serialize as their placeholders and which config can't set,
/// and without the fields that are `null`, which a file leaves out.
fn config_form(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Object(fields) => {
            fields.retain(|_, field| !field.is_null() && !is_secret_placeholder(field));
            fields.values_mut().for_each(config_form);
        }
        serde_json::Value::Array(items) => items.iter_mut().for_each(config_form),
        _ => {}
    }
}

/// Whether `value` is the placeholder a secret field serializes as.
fn is_secret_placeholder(value: &serde_json::Value) -> bool {
    value.as_object().is_some_and(|fields| {
        fields.len() == 1
            && fields
                .get(encore_sdk_core::config::PLACEHOLDER_KEY)
                .is_some_and(serde_json::Value::is_string)
    })
}

/// The error of [`set_secret`] in a system test.
const SECRET_IN_SYSTEM_TEST: &str = "a system test can't give a secret a value of its own: the \
     services it calls read theirs, not the test's. Give the secret its value for tests in \
     secrets.test.toml";

/// The error of [`set_config`] in a system test.
const CONFIG_IN_SYSTEM_TEST: &str = "a system test can't give a config a value of its own: the \
     services it calls read theirs, not the test's. Give the config its value for tests in its \
     `test` config file (<name>.test.config.toml)";

/// A handle to one test, made by [`current`]. Cheap to clone, and can be sent
/// to other threads, to make what they do part of the test.
///
/// The test's infrastructure lives for as long as the test or a handle to it
/// does.
#[derive(Clone)]
pub struct TestScope {
    scope: Arc<Scope>,
}

impl TestScope {
    /// Makes the calling thread part of the test, until the guard is dropped.
    pub fn enter(&self) -> ScopeGuard<'_> {
        THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
        ScopeGuard {
            _scope: PhantomData,
            _not_send: PhantomData,
        }
    }

    /// Runs a future as part of the test, on whatever thread polls it.
    pub async fn scope<F: Future>(&self, future: F) -> F::Output {
        let mut future = pin!(future);
        poll_fn(|cx| {
            let _guard = self.enter();
            future.as_mut().poll(cx)
        })
        .await
    }

    /// The test's name, as the test harness reports it: its path within the
    /// crate, such as `tests::creates_a_user`. `None` if the test has only been
    /// seen on its runtime's other threads so far.
    pub fn name(&self) -> Option<&str> {
        self.scope.name.get().map(String::as_str)
    }
}

/// Keeps the thread part of a test. Returned by [`TestScope::enter`].
pub struct ScopeGuard<'a> {
    _scope: PhantomData<&'a TestScope>,
    /// Entered on one thread, so left on it.
    _not_send: PhantomData<*const ()>,
}

impl Drop for ScopeGuard<'_> {
    fn drop(&mut self) {
        THREAD.with(|thread| thread.borrow_mut().entered.pop());
    }
}

/// What `#[encore::test]` expands to. Not for use by hand: it changes with the
/// macro.
#[doc(hidden)]
pub mod __private {
    use super::*;

    /// The test, as the macro sees it where it is written.
    pub struct TestInfo {
        pub module: &'static str,
        pub name: &'static str,
        pub file: &'static str,
        pub line: u32,
    }

    pub use super::fixture::FIXTURES;
    pub use linkme;

    /// The runtime to run the test in, from the macro's arguments.
    pub struct RuntimeConfig {
        pub multi_thread: bool,
        pub worker_threads: Option<usize>,
    }

    /// The fixture the test starts from, from the macro's arguments.
    pub enum FixtureArg {
        /// Its module's, if a module it is in has one.
        Module,
        Named(&'static Fixture),
        None,
    }

    /// Loads the test's fixture, before the test runs. Only in test mode:
    /// anywhere else there is nothing to load it into.
    async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
        // What the test starts from, when there is something to say.
        let choice = match fixture {
            FixtureArg::Module => fixture::for_module(info.module, true).map(Some),
            FixtureArg::Named(fixture) => Some(Some(fixture)),
            FixtureArg::None => Some(None),
        };
        let Some(choice) = choice else {
            return;
        };
        if core().test_scopes().is_none() {
            return;
        }
        let loaded = match choice {
            Some(fixture) => fixture.load().await,
            None => without_fixture(),
        };
        if let Err(err) = loaded {
            panic!("{}", err.message);
        }
    }

    /// Ends the test on this thread when dropped: its scope is let go of, and
    /// with it — once the runtime's threads have, too — its infrastructure.
    pub(in crate::testing) struct EndTest;

    impl Drop for EndTest {
        fn drop(&mut self) {
            THREAD.with(|thread| thread.borrow_mut().own = None);
        }
    }

    /// Begins the test on this thread: a scope of its own, before any call.
    fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
        // The process is a test runner's: see `runner_detected`.
        BEGUN.store(true, std::sync::atomic::Ordering::Relaxed);
        let scope = Scope::new();
        scope.set_module(info.module.to_string(), true);
        // As the test harness names it: the path within the crate.
        let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
        let name = if module.is_empty() {
            info.name.to_string()
        } else {
            format!("{module}::{}", info.name)
        };
        let _ = scope.name.set(name);
        THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
        (scope, EndTest)
    }

    /// Runs an `async fn` test: in a runtime of its own, as `#[tokio::test]`
    /// does, that is the test's from the start.
    pub fn run<R, F: Future<Output = R>>(
        info: TestInfo,
        config: RuntimeConfig,
        fixture: FixtureArg,
        failed: fn(&R) -> bool,
        test: F,
    ) -> R {
        // Dropped last, after the runtime has stopped its threads.
        let (scope, _end) = begin(&info);
        let reported = system::Reported::new(scope.clone());
        let mut builder = if config.multi_thread {
            tokio::runtime::Builder::new_multi_thread()
        } else {
            tokio::runtime::Builder::new_current_thread()
        };
        if let Some(threads) = config.worker_threads {
            builder.worker_threads(threads);
        }
        let runtime = builder
            .enable_all()
            .build()
            .expect("failed to build the test's Tokio runtime");
        with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
        drop(scope);
        let result = runtime.block_on(async {
            load_fixture(&info, fixture).await;
            test.await
        });
        reported.ended(failed(&result));
        result
    }

    /// What a test returned, for the macro to say whether it failed where
    /// it knows the type: an `Err` is a failure, as a panic is, and nothing
    /// else a test may return says. In a system test, a failed test says
    /// what it caused in the app.
    ///
    /// `(&Probe(&result)).failed()` is [`FailedIfErr`]'s for a `Result`,
    /// which it finds first, and [`NeverFailed`]'s for anything else.
    pub struct Probe<'a, R>(pub &'a R);

    pub trait FailedIfErr {
        fn failed(&self) -> bool;
    }

    impl<T, E> FailedIfErr for Probe<'_, Result<T, E>> {
        fn failed(&self) -> bool {
            self.0.is_err()
        }
    }

    pub trait NeverFailed {
        fn failed(&self) -> bool;
    }

    impl<R> NeverFailed for &Probe<'_, R> {
        fn failed(&self) -> bool {
            false
        }
    }

    /// Runs a test that is not `async`.
    pub fn run_sync<R, F: FnOnce() -> R>(
        info: TestInfo,
        fixture: FixtureArg,
        failed: fn(&R) -> bool,
        test: F,
    ) -> R {
        let (scope, _end) = begin(&info);
        let reported = system::Reported::new(scope);
        // Loading a fixture is `async`, though the test is not.
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to build a Tokio runtime to load the test's fixture")
            .block_on(load_fixture(&info, fixture));
        let result = test();
        reported.ended(failed(&result));
        result
    }
}

/// One test, as this SDK tracks it: the threads and runtimes that are part of
/// it, and its infrastructure, which the core's test scope holds and releases
/// when the last thread that is part of the test lets go of it.
pub(crate) struct Scope {
    name: OnceLock<String>,
    /// The module the test is in, and whether that is its full path (with the
    /// crate, from `#[encore::test]`) or the test harness's (without).
    module: OnceLock<(String, bool)>,
    /// The core's scope, which holds the test's infrastructure and the values
    /// it gave secrets and configs: begun when the test first needs it, as
    /// only under `encore test` is there one.
    core: OnceLock<Arc<CoreScope>>,
    /// The values the test has given configs, in place of the app's, each
    /// already read as the config's type.
    configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
}

/// The scope and name a config is held under.
/// A config's name: a config name has one scope across the app.
type ConfigKey = &'static str;

impl Scope {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            name: OnceLock::new(),
            module: OnceLock::new(),
            core: OnceLock::new(),
            configs: Mutex::new(HashMap::new()),
        })
    }

    /// The scope a fixture is built in: the core's.
    fn building(core: Arc<CoreScope>, name: String) -> Arc<Self> {
        let scope = Self::new();
        let _ = scope.name.set(name);
        let _ = scope.core.set(core);
        scope
    }

    /// The core's scope for the test, begun if this is the first the test
    /// needs it.
    pub(crate) fn core_scope(&self) -> Result<&Arc<CoreScope>, Error> {
        if let Some(scope) = self.core.get() {
            return Ok(scope);
        }
        let scopes = core().test_scopes().ok_or_else(|| {
            Error::new(
                ErrCode::FailedPrecondition,
                "there is no current test: the process is not running under `encore test`",
            )
        })?;
        let scope = self
            .core
            .get_or_init(|| scopes.begin(self.name.get().map(String::as_str)));
        self.require_module_fixture();
        Ok(scope)
    }

    /// Notes the module the test is in.
    fn set_module(&self, module: String, full: bool) {
        let _ = self.module.set((module, full));
        self.require_module_fixture();
    }

    /// Makes a test in a module with a fixture of its own say what it starts
    /// from before it first uses a resource, rather than start from nothing:
    /// once both the module and the core's scope are known.
    fn require_module_fixture(&self) {
        let (Some(core), Some((module, full))) = (self.core.get(), self.module.get()) else {
            return;
        };
        if let Some(reason) = unloaded_module_fixture(module, *full) {
            core.require_use_fixture(reason);
        }
    }

    /// Sets what the test's resources start from. An error once it has some,
    /// unless it is what they started from.
    pub(crate) fn choose(&self, fixture: Option<&'static Fixture>) -> Result<(), Error> {
        self.core_scope()?
            .use_fixture(fixture.map(Fixture::name))
            .map_err(infra_err)
    }

    /// The value the test has given the secret, if it has.
    pub(crate) fn secret(&self, name: &str) -> Option<Arc<[u8]>> {
        self.core.get()?.secret(name)
    }

    /// The value the test has given the config, if it has.
    pub(crate) fn config(
        &self,
        name: &'static str,
    ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
        self.configs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(name)
            .cloned()
    }

    /// What the test has published to the topic `name`, in order.
    pub(crate) fn published(&self, name: &str) -> Vec<test_scope::Published> {
        self.core
            .get()
            .map(|core| core.published(name))
            .unwrap_or_default()
    }

    /// The test's instance of the bucket `name`, provisioned for this test
    /// when first asked for.
    pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
        self.core_scope()?.bucket(&name.into()).map_err(infra_err)
    }

    /// The test's pool for the database `name`, on an instance of the database
    /// provisioned for this test when first asked for.
    pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
        self.core_scope()?.database(&name.into()).map_err(infra_err)
    }

    /// The test's instance of the ClickHouse database `name`, provisioned and
    /// migrated for this test when first asked for.
    pub(crate) fn clickhouse_database(
        &self,
        name: &'static str,
    ) -> Result<Arc<encore_sdk_core::clickhouse::Database>, Error> {
        self.core_scope()?
            .clickhouse(&name.into())
            .map_err(infra_err)
    }

    /// The test's client for the Redis database `name`, on an instance of the
    /// database provisioned for this test when first asked for: with keys and
    /// channels no other test sees, and holding what the test's fixture left
    /// in it, or nothing.
    pub(crate) fn redis_client(
        &self,
        name: &'static str,
    ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
        self.core_scope()?.redis(&name.into()).map_err(infra_err)
    }

    /// The connection string of the test's instance of the database `name`,
    /// for `access`.
    pub(crate) fn database_connection_string(
        &self,
        name: &'static str,
        access: Access,
    ) -> Result<String, Error> {
        self.core_scope()?
            .connection_string(&name.into(), access)
            .map_err(infra_err)
    }
}

/// Why a test in the module `module` must say what it starts from, if a
/// module it is in has a fixture. `module` is a full path when `full`.
fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
    let fixture = fixture::for_module(module, full)?;
    Some(format!(
        "this test is in a module whose tests start from the fixture {:?}, but has not \
         loaded it. Make it an `#[encore::test]`, which does, or call `.load().await?` on the \
         fixture — or `encore::testing::without_fixture()?` — before the test first uses a \
         resource",
        fixture.name()
    ))
}

/// An error of the core's test scope: a test that cannot start from what it
/// asks for, or infrastructure that could not be provisioned.
fn infra_err(err: anyhow::Error) -> Error {
    if err.downcast_ref::<FixtureChoiceError>().is_some() {
        Error::new(ErrCode::FailedPrecondition, err.to_string())
    } else {
        Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
    }
}

/// Runs `work` on the calling thread as the scope `scope`'s: in a runtime of
/// its own, whose threads are the scope's too.
fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
    THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
    // Dropped last, after the runtime has stopped its threads.
    let _end = __private::EndTest;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("failed to build a Tokio runtime");
    with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
    drop(scope);
    runtime.block_on(work)
}

/// The context a call to a service, or a publish, made now in `cx` is made
/// in. In a system test that is `cx` with the test added where `cx` has
/// none: the Request Context field that carries the test's id, and the
/// test's span for a context with no span, so that what the app does for
/// the test can be found. Anywhere else, and on a thread no test can be
/// told from, it is `cx`.
pub(crate) fn outgoing(
    cx: &encore_sdk_core::telemetry::opentelemetry::Context,
) -> encore_sdk_core::telemetry::opentelemetry::Context {
    if core().system_test().is_none() {
        return cx.clone();
    }
    let Ok(Some(test)) = active() else {
        return cx.clone();
    };
    match test.core_scope() {
        Ok(scope) => scope.outgoing_context(cx),
        Err(_) => cx.clone(),
    }
}

/// The test the calling thread belongs to, if the process runs under `encore
/// test`: `None` otherwise, where resources are the app's own.
pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
    if core().test_scopes().is_none() {
        return Ok(None);
    }
    resolve().map(Some)
}

/// What a thread holds of the tests it is part of. Dropped when the thread
/// exits, which is what ends a test: its own thread exits when it is done, and
/// its runtime's threads with it.
#[derive(Default)]
struct ThreadScopes {
    /// The test this thread is the test harness's thread of.
    own: Option<Arc<Scope>>,
    /// The tests this thread joined through their runtime, kept alive by it.
    joined: Vec<Arc<Scope>>,
    /// The tests entered with [`TestScope::enter`], innermost last.
    entered: Vec<Arc<Scope>>,
}

thread_local! {
    static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
}

/// Which test a Tokio runtime belongs to.
enum Link {
    Test(Weak<Scope>),
    /// Several tests run on it, so its threads belong to none in particular.
    Shared,
}

static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);

fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
    let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
    f(runtimes.get_or_insert_with(HashMap::new))
}

/// The name of the test a thread of this name is the test harness's thread of.
/// The harness names each test's thread after the test; the process's main
/// thread, unnamed threads and Tokio's own are not one.
/// Whether an `#[encore::test]` has begun in this process.
static BEGUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Whether the process is a test runner's, for the core to be in test mode
/// without `encore test`: an `#[encore::test]` has begun, cargo-nextest runs
/// it, or the thread asking is one the test harness named after its test.
/// Called on the thread that first needs the core.
pub(crate) fn runner_detected() -> bool {
    BEGUN.load(std::sync::atomic::Ordering::Relaxed)
        || std::env::var_os("NEXTEST").is_some()
        || test_name(std::thread::current().name()).is_some()
}

fn test_name(thread: Option<&str>) -> Option<&str> {
    thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
}

/// The test the calling thread belongs to: the one it entered, the one it is
/// the test harness's thread of, or the one whose runtime it is a thread of.
fn resolve() -> Result<Arc<Scope>, Error> {
    let handle = Handle::try_current().ok();
    let runtime = handle.as_ref().map(Handle::id);
    let thread = std::thread::current();
    THREAD.with(|state| {
        let mut state = state.borrow_mut();
        if let Some(scope) = state.entered.last() {
            return Ok(scope.clone());
        }

        // `#[encore::test]` began the test on this thread, whatever it is named.
        if let Some(scope) = &state.own {
            let scope = scope.clone();
            if let Some(id) = runtime {
                with_runtimes(|runtimes| link(runtimes, id, &scope));
            }
            return Ok(scope);
        }

        if let Some(name) = test_name(thread.name()) {
            let scope = match &state.own {
                Some(scope) => scope.clone(),
                None => {
                    // The runtime's other threads may have got here first.
                    let scope = runtime
                        .and_then(|id| {
                            with_runtimes(|runtimes| match runtimes.get(&id) {
                                Some(Link::Test(scope)) => {
                                    scope.upgrade().filter(|scope| scope.name.get().is_none())
                                }
                                _ => None,
                            })
                        })
                        .unwrap_or_else(Scope::new);
                    let _ = scope.name.set(name.to_string());
                    let module = name.rsplit_once("::").map_or("", |(module, _)| module);
                    scope.set_module(module.to_string(), false);
                    state.own = Some(scope.clone());
                    scope
                }
            };
            if let Some(id) = runtime {
                with_runtimes(|runtimes| link(runtimes, id, &scope));
            }
            return Ok(scope);
        }

        let Some(id) = runtime else {
            return Err(not_a_test_thread(thread.name()));
        };
        let scope = with_runtimes(|runtimes| {
            match runtimes.get(&id) {
                Some(Link::Shared) => return Err(shared_runtime(thread.name())),
                Some(Link::Test(scope)) => {
                    if let Some(scope) = scope.upgrade() {
                        return Ok(scope);
                    }
                }
                None => {}
            }
            // The first use of the runtime. If it has worker threads, this is
            // one, and got here before the test thread driving it: a test of
            // its own, which that thread adopts when it gets here. One without
            // is driven by this thread, which is not a test's.
            let multi_thread = handle
                .as_ref()
                .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
            if !multi_thread {
                return Err(not_a_test_thread(thread.name()));
            }
            let scope = Scope::new();
            link(runtimes, id, &scope);
            Ok(scope)
        })?;
        if !state
            .joined
            .iter()
            .any(|joined| Arc::ptr_eq(joined, &scope))
        {
            state.joined.push(scope.clone());
        }
        Ok(scope)
    })
}

/// Records that the runtime `id` is `scope`'s — or, if it already is another
/// running test's, that it is shared.
fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
    let shared = match runtimes.get(&id) {
        Some(Link::Shared) => true,
        Some(Link::Test(current)) => current
            .upgrade()
            .is_some_and(|current| !Arc::ptr_eq(&current, scope)),
        None => false,
    };
    if !shared {
        // Runtimes that have ended leave their entries behind.
        runtimes.retain(|_, link| match link {
            Link::Test(scope) => scope.strong_count() > 0,
            Link::Shared => true,
        });
    }
    let link = if shared {
        Link::Shared
    } else {
        Link::Test(Arc::downgrade(scope))
    };
    runtimes.insert(id, link);
}

fn thread_label(name: Option<&str>) -> String {
    match name {
        Some(name) => format!("thread {name:?}"),
        None => "an unnamed thread".to_string(),
    }
}

fn not_a_test_thread(thread: Option<&str>) -> Error {
    Error::new(
        ErrCode::FailedPrecondition,
        format!(
            "an Encore resource was used on {}, which Encore cannot link to a running test. \
             Each test gets infrastructure of its own, so Encore needs to know which test \
             this thread belongs to.\n\n\
             In the test, capture the scope and enter it on the new thread:\n\n    \
             let scope = encore::testing::current()?;\n    \
             std::thread::spawn(move || {{\n        \
             let _guard = scope.enter();\n        \
             …\n    \
             }});",
            thread_label(thread)
        ),
    )
}

fn shared_runtime(thread: Option<&str>) -> Error {
    Error::new(
        ErrCode::FailedPrecondition,
        format!(
            "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
             so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
             its own.\n\n\
             Run the work as part of its test:\n\n    \
             let scope = encore::testing::current()?;\n    \
             runtime.spawn(async move {{ scope.scope(work()).await }});",
            thread_label(thread)
        ),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_typed_config_value_is_given_in_its_files_form() {
        #[derive(serde::Serialize)]
        struct Limits {
            max: u32,
            timeout: config::Duration,
            key: secrets::Secret,
            note: Option<String>,
            tiers: Vec<Tier>,
        }
        #[derive(serde::Serialize)]
        struct Tier {
            name: &'static str,
            key: secrets::Secret,
        }
        let mut value = serde_json::to_value(Limits {
            max: 5,
            timeout: config::Duration(std::time::Duration::from_millis(1500)),
            key: secrets::Secret::new("StripeKey"),
            note: None,
            tiers: vec![Tier {
                name: "gold",
                key: secrets::Secret::new("GoldKey"),
            }],
        })
        .unwrap();
        config_form(&mut value);
        assert_eq!(
            value,
            serde_json::json!({
                "max": 5,
                "timeout": "1500000us",
                "tiers": [{"name": "gold"}],
            })
        );
        // The duration reads back as itself.
        assert_eq!(
            config::parse_duration("1500000us"),
            Some(std::time::Duration::from_millis(1500))
        );
    }

    /// The test the calling thread resolves to, by name and identity.
    fn here() -> Result<(Option<String>, usize), String> {
        resolve()
            .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
            .map_err(|err| err.message)
    }

    #[test]
    fn a_test_thread_is_its_test() {
        let (name, id) = here().unwrap();
        assert_eq!(
            name.as_deref(),
            Some("testing::tests::a_test_thread_is_its_test")
        );
        // The same test every time.
        assert_eq!(here().unwrap().1, id);
    }

    #[test]
    fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
        let (_, id) = here().unwrap();
        let scope = TestScope {
            scope: resolve().unwrap(),
        };

        let err = std::thread::spawn(here).join().unwrap().unwrap_err();
        assert!(err.contains("an unnamed thread"), "{err}");
        assert!(err.contains("scope.enter()"), "{err}");

        let entered = std::thread::spawn(move || {
            let inside = {
                let _guard = scope.enter();
                here()
            };
            (inside, here())
        })
        .join()
        .unwrap();
        assert_eq!(entered.0.unwrap().1, id);
        // Only while the guard is held.
        assert!(entered.1.is_err());
    }

    #[tokio::test]
    async fn a_current_thread_runtime_is_its_test() {
        let (name, id) = here().unwrap();
        assert!(name.is_some());
        assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
        assert_eq!(
            tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
            id
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_multi_thread_runtime_is_its_test() {
        let (_, id) = here().unwrap();
        for _ in 0..8 {
            assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
        }
        assert_eq!(
            tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
            id
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_test_adopts_what_its_runtime_started() {
        // A worker gets there first: a test with no name yet.
        let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
        assert_eq!(name, None);
        // The test thread is that same test, and names it.
        let (name, adopted) = here().unwrap();
        assert_eq!(adopted, id);
        assert!(name
            .unwrap()
            .ends_with("a_test_adopts_what_its_runtime_started"));
        let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
        assert_eq!(again, id);
        assert!(name.is_some());
    }

    #[test]
    fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .build()
            .unwrap();
        let handle = runtime.handle().clone();
        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
        let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
        // One test, holding its scope on the runtime…
        let first = std::thread::Builder::new()
            .name("tests::first".to_string())
            .spawn({
                let handle = handle.clone();
                move || {
                    let _enter = handle.enter();
                    let id = here().unwrap().1;
                    ready_tx.send(id).unwrap();
                    let _ = done_rx.recv();
                }
            })
            .unwrap();
        let first_id = ready_rx.recv().unwrap();
        // …while another starts on the same one.
        let second_id = std::thread::Builder::new()
            .name("tests::second".to_string())
            .spawn({
                let handle = handle.clone();
                move || {
                    let _enter = handle.enter();
                    here().unwrap().1
                }
            })
            .unwrap()
            .join()
            .unwrap();
        assert_ne!(first_id, second_id);

        // Each test thread is still its own test; the workers are neither's.
        let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
        // `block_on` here runs on this test's own thread; the spawned task on a worker.
        let err = err.unwrap_err();
        assert!(err.contains("several tests share"), "{err}");
        assert!(err.contains("scope.scope("), "{err}");

        done_tx.send(()).unwrap();
        first.join().unwrap();
    }

    #[tokio::test]
    async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
        let (_, id) = here().unwrap();
        let scope = TestScope {
            scope: resolve().unwrap(),
        };
        assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
        // On a thread of another runtime, which is no test's.
        let other = std::thread::spawn(move || {
            tokio::runtime::Builder::new_current_thread()
                .build()
                .unwrap()
                .block_on(async {
                    let outside = here();
                    let inside = scope.scope(async { here().unwrap().1 }).await;
                    (outside, inside)
                })
        })
        .join()
        .unwrap();
        let err = other.0.unwrap_err();
        assert!(err.contains("cannot link to a running test"), "{err}");
        assert_eq!(other.1, id);
    }

    #[encore::test]
    async fn the_macro_runs_a_test_in_its_own_runtime() {
        let (name, id) = here().unwrap();
        // Named as the harness names it, without the crate.
        assert_eq!(
            name.as_deref(),
            Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
        );
        assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
        // A current-thread runtime, as `#[tokio::test]` gives by default.
        assert_eq!(
            Handle::current().runtime_flavor(),
            RuntimeFlavor::CurrentThread
        );
    }

    #[encore::test(flavor = "multi_thread", worker_threads = 2)]
    async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
        // A worker gets there first, and already knows the test by name.
        let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
        assert!(name.unwrap().ends_with("before_the_test_runs"));
        assert_eq!(here()?.1, id);
        assert_eq!(Handle::current().metrics().num_workers(), 2);
        Ok(())
    }

    #[encore::test]
    #[should_panic(expected = "as any test")]
    async fn the_macro_keeps_the_tests_other_attributes() {
        panic!("as any test");
    }

    #[encore::test]
    fn the_macro_takes_a_test_that_is_not_async() {
        let (name, _) = here().unwrap();
        assert!(name.unwrap().ends_with("is_not_async"));
    }

    #[test]
    fn the_macro_ends_the_test_when_it_returns() {
        let weak = std::thread::spawn(|| {
            let weak = __private::run(
                __private::TestInfo {
                    module: "app::tests",
                    name: "returns",
                    file: file!(),
                    line: line!(),
                },
                __private::RuntimeConfig {
                    multi_thread: true,
                    worker_threads: Some(1),
                },
                __private::FixtureArg::Module,
                |_| false,
                async {
                    tokio::spawn(async { here().unwrap() }).await.unwrap();
                    Arc::downgrade(&resolve().unwrap())
                },
            );
            // Gone already, though this thread lives on.
            assert!(weak.upgrade().is_none());
            assert!(here().is_err());
        })
        .join();
        weak.unwrap();
    }

    mod billing {
        crate::fixture! {
            /// The module's fixture.
            pub static SEEDED for mod = async { Ok(()) };

            /// One to load by hand.
            pub static EXTRA: SEEDED = async { Ok(()) };
        }

        pub mod invoices {
            crate::fixture! {
                pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
            }
        }
    }

    #[test]
    fn a_fixture_is_named_after_where_it_is_declared() {
        assert_eq!(
            billing::SEEDED.name(),
            "encore::testing::tests::billing::SEEDED"
        );
        assert_eq!(
            billing::invoices::INVOICED.name(),
            "encore::testing::tests::billing::invoices::INVOICED"
        );
        // Whether or not it is a module's.
        assert_eq!(
            billing::EXTRA.name(),
            "encore::testing::tests::billing::EXTRA"
        );
    }

    #[test]
    fn a_modules_fixture_is_found_from_the_tests_inside_it() {
        let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
        // By the full path `#[encore::test]` knows a test by…
        assert_eq!(
            found("encore::testing::tests::billing", true),
            Some(billing::SEEDED.name())
        );
        assert_eq!(
            found("encore::testing::tests::billing::reports::monthly", true),
            Some(billing::SEEDED.name())
        );
        // …the innermost module's winning…
        assert_eq!(
            found("encore::testing::tests::billing::invoices", true),
            Some(billing::invoices::INVOICED.name())
        );
        // …and by the path without the crate the test harness names it by.
        assert_eq!(
            found("testing::tests::billing::invoices::overdue", false),
            Some(billing::invoices::INVOICED.name())
        );
        // A module that merely starts the same is not inside it, and a
        // fixture that is not a module's is nobody's.
        assert_eq!(found("encore::testing::tests::billing_reports", true), None);
        assert_eq!(found("encore::testing::tests", true), None);
        assert_eq!(found("testing::tests", false), None);
    }

    #[test]
    fn a_test_in_a_module_with_a_fixture_has_to_say_what_it_starts_from() {
        // One way or the other: the core's scope fails its first use of a
        // resource with this until it does.
        let reason = unloaded_module_fixture("testing::tests::billing::reports", false).unwrap();
        assert!(reason.contains("has not loaded it"), "{reason}");
        assert!(reason.contains(billing::SEEDED.name()), "{reason}");
        assert!(reason.contains("without_fixture()"), "{reason}");

        // Anywhere else, nothing said is no fixture.
        assert_eq!(unloaded_module_fixture("testing::tests", false), None);
    }

    #[test]
    fn a_scope_ends_with_the_threads_that_are_part_of_it() {
        let weak = std::thread::Builder::new()
            .name("tests::short_lived".to_string())
            .spawn(|| Arc::downgrade(&resolve().unwrap()))
            .unwrap()
            .join()
            .unwrap();
        assert!(weak.upgrade().is_none());

        // A handle keeps it alive past its thread.
        let scope = std::thread::Builder::new()
            .name("tests::held".to_string())
            .spawn(|| TestScope {
                scope: resolve().unwrap(),
            })
            .unwrap()
            .join()
            .unwrap();
        let weak = Arc::downgrade(&scope.scope);
        assert!(weak.upgrade().is_some());
        drop(scope);
        assert!(weak.upgrade().is_none());
    }
}