1mod fixture;
58
59pub use fixture::{without_fixture, Fixture, SetupFn};
60
61use std::cell::RefCell;
62use std::collections::{HashMap, HashSet};
63use std::future::{poll_fn, Future};
64use std::marker::PhantomData;
65use std::pin::pin;
66use std::sync::atomic::{AtomicU64, Ordering};
67use std::sync::{Arc, Mutex, OnceLock, Weak};
68
69use encore_sdk_core::objects;
70use encore_sdk_core::postgres::{Access, Pool};
71use encore_sdk_core::pubsub;
72use tokio::runtime::{Handle, Id, RuntimeFlavor};
73
74use crate::config;
75use crate::error::{ErrCode, Error};
76use crate::runtime::core;
77use crate::secrets;
78
79pub fn current() -> Result<TestScope, Error> {
84 match active()? {
85 Some(scope) => Ok(TestScope { scope }),
86 None => Err(Error::new(
87 ErrCode::FailedPrecondition,
88 "there is no current test: the process is not running under `encore test`",
89 )),
90 }
91}
92
93pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
107 topic: &crate::pubsub::Topic<T, E, O>,
108) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
109 match active()? {
110 Some(test) => topic.published_in(&test),
111 None => Err(Error::new(
112 ErrCode::FailedPrecondition,
113 "there is no current test: the process is not running under `encore test`",
114 )),
115 }
116}
117
118pub fn set_secret(secret: &impl secrets::AnySecret, value: impl AsRef<[u8]>) -> Result<(), Error> {
126 match active()? {
127 Some(test) => {
128 test.secrets
129 .lock()
130 .unwrap_or_else(|e| e.into_inner())
131 .insert(secrets::key_of(secret), value.as_ref().into());
132 Ok(())
133 }
134 None => Err(Error::new(
135 ErrCode::FailedPrecondition,
136 "there is no current test: the process is not running under `encore test`",
137 )),
138 }
139}
140
141pub fn set_config<T: config::ConfigType>(
150 config: &impl config::AnyConfig<T>,
151 value: serde_json::Value,
152) -> Result<(), Error> {
153 match active()? {
154 Some(test) => {
155 let value = config::test_value(config, value)?;
156 test.configs
157 .lock()
158 .unwrap_or_else(|e| e.into_inner())
159 .insert(config::key_of(config), value);
160 Ok(())
161 }
162 None => Err(Error::new(
163 ErrCode::FailedPrecondition,
164 "there is no current test: the process is not running under `encore test`",
165 )),
166 }
167}
168
169#[derive(Clone)]
175pub struct TestScope {
176 scope: Arc<Scope>,
177}
178
179impl TestScope {
180 pub fn enter(&self) -> ScopeGuard<'_> {
182 THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
183 ScopeGuard {
184 _scope: PhantomData,
185 _not_send: PhantomData,
186 }
187 }
188
189 pub async fn scope<F: Future>(&self, future: F) -> F::Output {
191 let mut future = pin!(future);
192 poll_fn(|cx| {
193 let _guard = self.enter();
194 future.as_mut().poll(cx)
195 })
196 .await
197 }
198
199 pub fn name(&self) -> Option<&str> {
203 self.scope.name.get().map(String::as_str)
204 }
205}
206
207pub struct ScopeGuard<'a> {
209 _scope: PhantomData<&'a TestScope>,
210 _not_send: PhantomData<*const ()>,
212}
213
214impl Drop for ScopeGuard<'_> {
215 fn drop(&mut self) {
216 THREAD.with(|thread| thread.borrow_mut().entered.pop());
217 }
218}
219
220#[doc(hidden)]
223pub mod __private {
224 use super::*;
225
226 pub struct TestInfo {
228 pub module: &'static str,
229 pub name: &'static str,
230 pub file: &'static str,
231 pub line: u32,
232 }
233
234 pub use super::fixture::FIXTURES;
235 pub use linkme;
236
237 pub struct RuntimeConfig {
239 pub multi_thread: bool,
240 pub worker_threads: Option<usize>,
241 }
242
243 pub enum FixtureArg {
245 Module,
247 Named(&'static Fixture),
248 None,
249 }
250
251 async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
254 if encore_sdk_core::test_mode::test_mode_app_ref().is_none() {
255 return;
256 }
257 let loaded = match fixture {
258 FixtureArg::Module => match fixture::for_module(info.module, true) {
259 Some(fixture) => fixture.load().await,
260 None => Ok(()),
261 },
262 FixtureArg::Named(fixture) => fixture.load().await,
263 FixtureArg::None => without_fixture(),
264 };
265 if let Err(err) = loaded {
266 panic!("{}", err.message);
267 }
268 }
269
270 pub(in crate::testing) struct EndTest;
273
274 impl Drop for EndTest {
275 fn drop(&mut self) {
276 THREAD.with(|thread| thread.borrow_mut().own = None);
277 }
278 }
279
280 fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
282 let scope = Scope::new();
283 let _ = scope.module.set((info.module.to_string(), true));
284 let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
286 let name = if module.is_empty() {
287 info.name.to_string()
288 } else {
289 format!("{module}::{}", info.name)
290 };
291 let _ = scope.name.set(name);
292 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
293 (scope, EndTest)
294 }
295
296 pub fn run<R, F: Future<Output = R>>(
299 info: TestInfo,
300 config: RuntimeConfig,
301 fixture: FixtureArg,
302 test: F,
303 ) -> R {
304 let (scope, _end) = begin(&info);
306 let mut builder = if config.multi_thread {
307 tokio::runtime::Builder::new_multi_thread()
308 } else {
309 tokio::runtime::Builder::new_current_thread()
310 };
311 if let Some(threads) = config.worker_threads {
312 builder.worker_threads(threads);
313 }
314 let runtime = builder
315 .enable_all()
316 .build()
317 .expect("failed to build the test's Tokio runtime");
318 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
319 drop(scope);
320 runtime.block_on(async {
321 load_fixture(&info, fixture).await;
322 test.await
323 })
324 }
325
326 pub fn run_sync<R, F: FnOnce() -> R>(info: TestInfo, fixture: FixtureArg, test: F) -> R {
328 let (_scope, _end) = begin(&info);
329 tokio::runtime::Builder::new_current_thread()
331 .enable_all()
332 .build()
333 .expect("failed to build a Tokio runtime to load the test's fixture")
334 .block_on(load_fixture(&info, fixture));
335 test()
336 }
337}
338
339pub(crate) struct Scope {
342 instance_id: String,
344 name: OnceLock<String>,
345 module: OnceLock<(String, bool)>,
348 fixture: Mutex<Choice>,
350 databases: Mutex<HashMap<&'static str, Arc<Pool>>>,
351 buckets: Mutex<HashSet<&'static str>>,
353 redis: Mutex<HashMap<&'static str, Arc<encore_sdk_core::cache::Client>>>,
355 published: Mutex<HashMap<&'static str, Vec<Published>>>,
358 secrets: Mutex<HashMap<SecretKey, Arc<[u8]>>>,
360 configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
363}
364
365type SecretKey = (secrets::Scope, &'static str);
367
368type ConfigKey = (config::Scope, &'static str);
370
371#[derive(Clone)]
373pub(crate) struct Published {
374 pub(crate) id: String,
375 pub(crate) payload: Vec<u8>,
376 pub(crate) attributes: HashMap<String, String>,
377 pub(crate) ordering_key: Option<String>,
378 pub(crate) publish_time: std::time::SystemTime,
379}
380
381#[derive(Clone, Copy)]
383pub(crate) enum Choice {
384 Unset,
386 None,
388 Fixture(&'static Fixture),
389}
390
391impl Choice {
392 fn is(self, other: Choice) -> bool {
393 match (self, other) {
394 (Choice::Unset, Choice::Unset) | (Choice::None, Choice::None) => true,
395 (Choice::Fixture(a), Choice::Fixture(b)) => std::ptr::eq(a, b),
396 _ => false,
397 }
398 }
399}
400
401impl Scope {
402 fn new() -> Arc<Self> {
403 static NEXT: AtomicU64 = AtomicU64::new(0);
404 Arc::new(Self {
405 instance_id: format!(
406 "t{:x}x{:x}",
407 std::process::id(),
408 NEXT.fetch_add(1, Ordering::Relaxed)
409 ),
410 name: OnceLock::new(),
411 module: OnceLock::new(),
412 fixture: Mutex::new(Choice::Unset),
413 databases: Mutex::new(HashMap::new()),
414 buckets: Mutex::new(HashSet::new()),
415 redis: Mutex::new(HashMap::new()),
416 published: Mutex::new(HashMap::new()),
417 secrets: Mutex::new(HashMap::new()),
418 configs: Mutex::new(HashMap::new()),
419 })
420 }
421
422 pub(crate) fn choose(&self, choice: Choice) -> Result<(), Error> {
425 let mut current = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
426 if current.is(choice) {
427 return Ok(());
428 }
429 let used = !self
430 .databases
431 .lock()
432 .unwrap_or_else(|e| e.into_inner())
433 .is_empty()
434 || !self
435 .buckets
436 .lock()
437 .unwrap_or_else(|e| e.into_inner())
438 .is_empty()
439 || !self
440 .redis
441 .lock()
442 .unwrap_or_else(|e| e.into_inner())
443 .is_empty();
444 if used {
445 return Err(Error::new(
446 ErrCode::FailedPrecondition,
447 "the test has already used a resource, so what it starts from can no longer \
448 change: load the fixture before the test first uses one",
449 ));
450 }
451 *current = choice;
452 Ok(())
453 }
454
455 fn fixture_name(&self) -> Result<&'static str, Error> {
459 let mut choice = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
460 if let Choice::Unset = *choice {
461 if let Some((module, full)) = self.module.get() {
462 if let Some(fixture) = fixture::for_module(module, *full) {
463 return Err(Error::new(
464 ErrCode::FailedPrecondition,
465 format!(
466 "this test is in a module whose tests start from the fixture {:?}, \
467 but has not loaded it. Make it an `#[encore::test]`, which does, \
468 or call `.load().await?` on the fixture — or \
469 `encore::testing::without_fixture()?` — before the test first \
470 uses a resource",
471 fixture.name()
472 ),
473 ));
474 }
475 }
476 *choice = Choice::None;
477 }
478 Ok(match *choice {
479 Choice::Fixture(fixture) => fixture.name(),
480 Choice::None | Choice::Unset => "",
481 })
482 }
483
484 fn forget(&self) {
487 self.databases
488 .lock()
489 .unwrap_or_else(|e| e.into_inner())
490 .clear();
491 self.buckets
492 .lock()
493 .unwrap_or_else(|e| e.into_inner())
494 .clear();
495 self.redis.lock().unwrap_or_else(|e| e.into_inner()).clear();
496 }
497
498 pub(crate) fn secret(&self, scope: secrets::Scope, name: &'static str) -> Option<Arc<[u8]>> {
500 self.secrets
501 .lock()
502 .unwrap_or_else(|e| e.into_inner())
503 .get(&(scope, name))
504 .cloned()
505 }
506
507 pub(crate) fn config(
509 &self,
510 scope: config::Scope,
511 name: &'static str,
512 ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
513 self.configs
514 .lock()
515 .unwrap_or_else(|e| e.into_inner())
516 .get(&(scope, name))
517 .cloned()
518 }
519
520 pub(crate) fn topic(&self, name: &'static str) -> Result<pubsub::TopicObj, Error> {
523 let topic = core()
524 .pubsub()
525 .topic_instance(name.into(), &self.instance_id)
526 .ok_or_else(|| {
527 Error::unavailable(format!("could not provision the test's topic {name:?}"))
528 })?;
529 self.published
530 .lock()
531 .unwrap_or_else(|e| e.into_inner())
532 .entry(name)
533 .or_default();
534 Ok(topic)
535 }
536
537 pub(crate) fn note_published(&self, name: &'static str, message: Published) {
539 self.published
540 .lock()
541 .unwrap_or_else(|e| e.into_inner())
542 .entry(name)
543 .or_default()
544 .push(message);
545 }
546
547 pub(crate) fn published(&self, name: &str) -> Vec<Published> {
549 self.published
550 .lock()
551 .unwrap_or_else(|e| e.into_inner())
552 .get(name)
553 .cloned()
554 .unwrap_or_default()
555 }
556
557 pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
560 let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
561 let fixture = if buckets.contains(name) {
562 ""
564 } else {
565 self.fixture_name()?
566 };
567 let bucket = core()
568 .objects()
569 .try_bucket_instance_from(name.into(), &self.instance_id, fixture)
570 .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
571 buckets.insert(name);
572 Ok(bucket)
573 }
574
575 pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
578 let mut databases = self.databases.lock().unwrap_or_else(|e| e.into_inner());
579 if let Some(pool) = databases.get(name) {
580 return Ok(pool.clone());
581 }
582 let fixture = self.fixture_name()?;
583 let pool = core()
584 .postgres()
585 .try_database_instance_from(&name.into(), &self.instance_id, fixture)
586 .and_then(|db| db.new_pool())
587 .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
588 let pool = Arc::new(pool);
589 databases.insert(name, pool.clone());
590 Ok(pool)
591 }
592
593 pub(crate) fn redis_client(
598 &self,
599 name: &'static str,
600 ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
601 let mut clients = self.redis.lock().unwrap_or_else(|e| e.into_inner());
602 if let Some(client) = clients.get(name) {
603 return Ok(client.clone());
604 }
605 let fixture = self.fixture_name()?;
606 let client = core()
607 .cache()
608 .cluster_instance_from(&name.into(), &self.instance_id, fixture)
609 .client()
610 .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
611 let client = Arc::new(client);
612 clients.insert(name, client.clone());
613 Ok(client)
614 }
615
616 pub(crate) fn database_connection_string(
619 &self,
620 name: &'static str,
621 access: Access,
622 ) -> Result<String, Error> {
623 self.database_pool(name)?;
625 core()
626 .postgres()
627 .try_database_instance(&name.into(), &self.instance_id)
628 .map(|db| db.proxy_conn_string(access))
629 .map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))
630 }
631}
632
633impl Drop for Scope {
634 fn drop(&mut self) {
635 let databases = std::mem::take(self.databases.get_mut().unwrap_or_else(|e| e.into_inner()));
636 let names: Vec<&'static str> = databases.keys().copied().collect();
639 drop(databases);
640 for name in names {
641 core()
642 .postgres()
643 .release_instance(&name.into(), &self.instance_id);
644 }
645 let topics = std::mem::take(self.published.get_mut().unwrap_or_else(|e| e.into_inner()));
646 for name in topics.into_keys() {
647 core()
648 .pubsub()
649 .release_topic_instance(&name.into(), &self.instance_id);
650 }
651 let redis = std::mem::take(self.redis.get_mut().unwrap_or_else(|e| e.into_inner()));
652 let names: Vec<&'static str> = redis.keys().copied().collect();
654 drop(redis);
655 for name in names {
656 core()
657 .cache()
658 .release_instance(&name.into(), &self.instance_id);
659 }
660 let buckets = std::mem::take(self.buckets.get_mut().unwrap_or_else(|e| e.into_inner()));
661 for name in buckets {
662 core()
663 .objects()
664 .release_instance(&name.into(), &self.instance_id);
665 }
666 }
667}
668
669fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
672 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
673 let _end = __private::EndTest;
675 let runtime = tokio::runtime::Builder::new_current_thread()
676 .enable_all()
677 .build()
678 .expect("failed to build a Tokio runtime");
679 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
680 drop(scope);
681 runtime.block_on(work)
682}
683
684pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
687 if !core().postgres().isolates_instances() {
688 return Ok(None);
689 }
690 resolve().map(Some)
691}
692
693#[derive(Default)]
697struct ThreadScopes {
698 own: Option<Arc<Scope>>,
700 joined: Vec<Arc<Scope>>,
702 entered: Vec<Arc<Scope>>,
704}
705
706thread_local! {
707 static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
708}
709
710enum Link {
712 Test(Weak<Scope>),
713 Shared,
715}
716
717static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
718
719fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
720 let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
721 f(runtimes.get_or_insert_with(HashMap::new))
722}
723
724fn test_name(thread: Option<&str>) -> Option<&str> {
728 thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
729}
730
731fn resolve() -> Result<Arc<Scope>, Error> {
734 let handle = Handle::try_current().ok();
735 let runtime = handle.as_ref().map(Handle::id);
736 let thread = std::thread::current();
737 THREAD.with(|state| {
738 let mut state = state.borrow_mut();
739 if let Some(scope) = state.entered.last() {
740 return Ok(scope.clone());
741 }
742
743 if let Some(scope) = &state.own {
745 let scope = scope.clone();
746 if let Some(id) = runtime {
747 with_runtimes(|runtimes| link(runtimes, id, &scope));
748 }
749 return Ok(scope);
750 }
751
752 if let Some(name) = test_name(thread.name()) {
753 let scope = match &state.own {
754 Some(scope) => scope.clone(),
755 None => {
756 let scope = runtime
758 .and_then(|id| {
759 with_runtimes(|runtimes| match runtimes.get(&id) {
760 Some(Link::Test(scope)) => {
761 scope.upgrade().filter(|scope| scope.name.get().is_none())
762 }
763 _ => None,
764 })
765 })
766 .unwrap_or_else(Scope::new);
767 let _ = scope.name.set(name.to_string());
768 let module = name.rsplit_once("::").map_or("", |(module, _)| module);
769 let _ = scope.module.set((module.to_string(), false));
770 state.own = Some(scope.clone());
771 scope
772 }
773 };
774 if let Some(id) = runtime {
775 with_runtimes(|runtimes| link(runtimes, id, &scope));
776 }
777 return Ok(scope);
778 }
779
780 let Some(id) = runtime else {
781 return Err(not_a_test_thread(thread.name()));
782 };
783 let scope = with_runtimes(|runtimes| {
784 match runtimes.get(&id) {
785 Some(Link::Shared) => return Err(shared_runtime(thread.name())),
786 Some(Link::Test(scope)) => {
787 if let Some(scope) = scope.upgrade() {
788 return Ok(scope);
789 }
790 }
791 None => {}
792 }
793 let multi_thread = handle
798 .as_ref()
799 .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
800 if !multi_thread {
801 return Err(not_a_test_thread(thread.name()));
802 }
803 let scope = Scope::new();
804 link(runtimes, id, &scope);
805 Ok(scope)
806 })?;
807 if !state
808 .joined
809 .iter()
810 .any(|joined| Arc::ptr_eq(joined, &scope))
811 {
812 state.joined.push(scope.clone());
813 }
814 Ok(scope)
815 })
816}
817
818fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
821 let shared = match runtimes.get(&id) {
822 Some(Link::Shared) => true,
823 Some(Link::Test(current)) => current
824 .upgrade()
825 .is_some_and(|current| !Arc::ptr_eq(¤t, scope)),
826 None => false,
827 };
828 if !shared {
829 runtimes.retain(|_, link| match link {
831 Link::Test(scope) => scope.strong_count() > 0,
832 Link::Shared => true,
833 });
834 }
835 let link = if shared {
836 Link::Shared
837 } else {
838 Link::Test(Arc::downgrade(scope))
839 };
840 runtimes.insert(id, link);
841}
842
843fn thread_label(name: Option<&str>) -> String {
844 match name {
845 Some(name) => format!("thread {name:?}"),
846 None => "an unnamed thread".to_string(),
847 }
848}
849
850fn not_a_test_thread(thread: Option<&str>) -> Error {
851 Error::new(
852 ErrCode::FailedPrecondition,
853 format!(
854 "an Encore resource was used on {}, which Encore cannot link to a running test. \
855 Each test gets infrastructure of its own, so Encore needs to know which test \
856 this thread belongs to.\n\n\
857 In the test, capture the scope and enter it on the new thread:\n\n \
858 let scope = encore::testing::current()?;\n \
859 std::thread::spawn(move || {{\n \
860 let _guard = scope.enter();\n \
861 …\n \
862 }});",
863 thread_label(thread)
864 ),
865 )
866}
867
868fn shared_runtime(thread: Option<&str>) -> Error {
869 Error::new(
870 ErrCode::FailedPrecondition,
871 format!(
872 "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
873 so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
874 its own.\n\n\
875 Run the work as part of its test:\n\n \
876 let scope = encore::testing::current()?;\n \
877 runtime.spawn(async move {{ scope.scope(work()).await }});",
878 thread_label(thread)
879 ),
880 )
881}
882
883#[cfg(test)]
884mod tests {
885 use super::*;
886
887 fn here() -> Result<(Option<String>, usize), String> {
889 resolve()
890 .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
891 .map_err(|err| err.message)
892 }
893
894 #[test]
895 fn a_test_thread_is_its_test() {
896 let (name, id) = here().unwrap();
897 assert_eq!(
898 name.as_deref(),
899 Some("testing::tests::a_test_thread_is_its_test")
900 );
901 assert_eq!(here().unwrap().1, id);
903 }
904
905 #[test]
906 fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
907 let (_, id) = here().unwrap();
908 let scope = TestScope {
909 scope: resolve().unwrap(),
910 };
911
912 let err = std::thread::spawn(here).join().unwrap().unwrap_err();
913 assert!(err.contains("an unnamed thread"), "{err}");
914 assert!(err.contains("scope.enter()"), "{err}");
915
916 let entered = std::thread::spawn(move || {
917 let inside = {
918 let _guard = scope.enter();
919 here()
920 };
921 (inside, here())
922 })
923 .join()
924 .unwrap();
925 assert_eq!(entered.0.unwrap().1, id);
926 assert!(entered.1.is_err());
928 }
929
930 #[tokio::test]
931 async fn a_current_thread_runtime_is_its_test() {
932 let (name, id) = here().unwrap();
933 assert!(name.is_some());
934 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
935 assert_eq!(
936 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
937 id
938 );
939 }
940
941 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
942 async fn a_multi_thread_runtime_is_its_test() {
943 let (_, id) = here().unwrap();
944 for _ in 0..8 {
945 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
946 }
947 assert_eq!(
948 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
949 id
950 );
951 }
952
953 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
954 async fn a_test_adopts_what_its_runtime_started() {
955 let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
957 assert_eq!(name, None);
958 let (name, adopted) = here().unwrap();
960 assert_eq!(adopted, id);
961 assert!(name
962 .unwrap()
963 .ends_with("a_test_adopts_what_its_runtime_started"));
964 let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
965 assert_eq!(again, id);
966 assert!(name.is_some());
967 }
968
969 #[test]
970 fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
971 let runtime = tokio::runtime::Builder::new_multi_thread()
972 .worker_threads(1)
973 .build()
974 .unwrap();
975 let handle = runtime.handle().clone();
976 let (ready_tx, ready_rx) = std::sync::mpsc::channel();
977 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
978 let first = std::thread::Builder::new()
980 .name("tests::first".to_string())
981 .spawn({
982 let handle = handle.clone();
983 move || {
984 let _enter = handle.enter();
985 let id = here().unwrap().1;
986 ready_tx.send(id).unwrap();
987 let _ = done_rx.recv();
988 }
989 })
990 .unwrap();
991 let first_id = ready_rx.recv().unwrap();
992 let second_id = std::thread::Builder::new()
994 .name("tests::second".to_string())
995 .spawn({
996 let handle = handle.clone();
997 move || {
998 let _enter = handle.enter();
999 here().unwrap().1
1000 }
1001 })
1002 .unwrap()
1003 .join()
1004 .unwrap();
1005 assert_ne!(first_id, second_id);
1006
1007 let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
1009 let err = err.unwrap_err();
1011 assert!(err.contains("several tests share"), "{err}");
1012 assert!(err.contains("scope.scope("), "{err}");
1013
1014 done_tx.send(()).unwrap();
1015 first.join().unwrap();
1016 }
1017
1018 #[tokio::test]
1019 async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
1020 let (_, id) = here().unwrap();
1021 let scope = TestScope {
1022 scope: resolve().unwrap(),
1023 };
1024 assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
1025 let other = std::thread::spawn(move || {
1027 tokio::runtime::Builder::new_current_thread()
1028 .build()
1029 .unwrap()
1030 .block_on(async {
1031 let outside = here();
1032 let inside = scope.scope(async { here().unwrap().1 }).await;
1033 (outside, inside)
1034 })
1035 })
1036 .join()
1037 .unwrap();
1038 let err = other.0.unwrap_err();
1039 assert!(err.contains("cannot link to a running test"), "{err}");
1040 assert_eq!(other.1, id);
1041 }
1042
1043 #[encore::test]
1044 async fn the_macro_runs_a_test_in_its_own_runtime() {
1045 let (name, id) = here().unwrap();
1046 assert_eq!(
1048 name.as_deref(),
1049 Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
1050 );
1051 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1052 assert_eq!(
1054 Handle::current().runtime_flavor(),
1055 RuntimeFlavor::CurrentThread
1056 );
1057 }
1058
1059 #[encore::test(flavor = "multi_thread", worker_threads = 2)]
1060 async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
1061 let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
1063 assert!(name.unwrap().ends_with("before_the_test_runs"));
1064 assert_eq!(here()?.1, id);
1065 assert_eq!(Handle::current().metrics().num_workers(), 2);
1066 Ok(())
1067 }
1068
1069 #[encore::test]
1070 #[should_panic(expected = "as any test")]
1071 async fn the_macro_keeps_the_tests_other_attributes() {
1072 panic!("as any test");
1073 }
1074
1075 #[encore::test]
1076 fn the_macro_takes_a_test_that_is_not_async() {
1077 let (name, _) = here().unwrap();
1078 assert!(name.unwrap().ends_with("is_not_async"));
1079 }
1080
1081 #[test]
1082 fn the_macro_ends_the_test_when_it_returns() {
1083 let weak = std::thread::spawn(|| {
1084 let weak = __private::run(
1085 __private::TestInfo {
1086 module: "app::tests",
1087 name: "returns",
1088 file: file!(),
1089 line: line!(),
1090 },
1091 __private::RuntimeConfig {
1092 multi_thread: true,
1093 worker_threads: Some(1),
1094 },
1095 __private::FixtureArg::Module,
1096 async {
1097 tokio::spawn(async { here().unwrap() }).await.unwrap();
1098 Arc::downgrade(&resolve().unwrap())
1099 },
1100 );
1101 assert!(weak.upgrade().is_none());
1103 assert!(here().is_err());
1104 })
1105 .join();
1106 weak.unwrap();
1107 }
1108
1109 mod billing {
1110 crate::fixture! {
1111 pub static SEEDED for mod = async { Ok(()) };
1113
1114 pub static EXTRA: SEEDED = async { Ok(()) };
1116 }
1117
1118 pub mod invoices {
1119 crate::fixture! {
1120 pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
1121 }
1122 }
1123 }
1124
1125 #[test]
1126 fn a_fixture_is_named_after_where_it_is_declared() {
1127 assert_eq!(
1128 billing::SEEDED.name(),
1129 "encore::testing::tests::billing::SEEDED"
1130 );
1131 assert_eq!(
1132 billing::invoices::INVOICED.name(),
1133 "encore::testing::tests::billing::invoices::INVOICED"
1134 );
1135 }
1136
1137 #[test]
1138 fn a_modules_fixture_is_found_from_the_tests_inside_it() {
1139 let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
1140 assert_eq!(
1142 found("encore::testing::tests::billing", true),
1143 Some(billing::SEEDED.name())
1144 );
1145 assert_eq!(
1146 found("encore::testing::tests::billing::reports::monthly", true),
1147 Some(billing::SEEDED.name())
1148 );
1149 assert_eq!(
1151 found("encore::testing::tests::billing::invoices", true),
1152 Some(billing::invoices::INVOICED.name())
1153 );
1154 assert_eq!(
1156 found("testing::tests::billing::invoices::overdue", false),
1157 Some(billing::invoices::INVOICED.name())
1158 );
1159 assert_eq!(found("encore::testing::tests::billing_reports", true), None);
1162 assert_eq!(found("encore::testing::tests", true), None);
1163 assert_eq!(found("testing::tests", false), None);
1164 }
1165
1166 #[test]
1167 fn what_a_test_starts_from_is_settled_at_first_use() {
1168 let scope = Scope::new();
1169 scope.choose(Choice::Fixture(&billing::EXTRA)).unwrap();
1170 scope.choose(Choice::Fixture(&billing::SEEDED)).unwrap();
1171 assert_eq!(scope.fixture_name().unwrap(), billing::SEEDED.name());
1172
1173 let unsaid = Scope::new();
1175 let _ = unsaid
1176 .module
1177 .set(("testing::tests::billing".to_string(), false));
1178 let err = unsaid.fixture_name().unwrap_err();
1179 assert!(err.message.contains("has not loaded it"), "{err}");
1180 unsaid.choose(Choice::None).unwrap();
1181 assert_eq!(unsaid.fixture_name().unwrap(), "");
1182
1183 let plain = Scope::new();
1185 let _ = plain.module.set(("testing::tests".to_string(), false));
1186 assert_eq!(plain.fixture_name().unwrap(), "");
1187 }
1188
1189 #[test]
1190 fn a_scope_ends_with_the_threads_that_are_part_of_it() {
1191 let weak = std::thread::Builder::new()
1192 .name("tests::short_lived".to_string())
1193 .spawn(|| Arc::downgrade(&resolve().unwrap()))
1194 .unwrap()
1195 .join()
1196 .unwrap();
1197 assert!(weak.upgrade().is_none());
1198
1199 let scope = std::thread::Builder::new()
1201 .name("tests::held".to_string())
1202 .spawn(|| TestScope {
1203 scope: resolve().unwrap(),
1204 })
1205 .unwrap()
1206 .join()
1207 .unwrap();
1208 let weak = Arc::downgrade(&scope.scope);
1209 assert!(weak.upgrade().is_some());
1210 drop(scope);
1211 assert!(weak.upgrade().is_none());
1212 }
1213}