1#[cfg(feature = "chromiumoxide")]
68pub mod chromiumoxide;
69mod fixture;
70pub mod system;
71
72pub use fixture::{without_fixture, Fixture, SetupFn};
73
74use std::cell::RefCell;
75use std::collections::HashMap;
76use std::future::{poll_fn, Future};
77use std::marker::PhantomData;
78use std::pin::pin;
79use std::sync::{Arc, Mutex, OnceLock, Weak};
80
81use encore_sdk_core::objects;
82use encore_sdk_core::postgres::{Access, Pool};
83use encore_sdk_core::test_scope::{self, FixtureChoiceError, TestScope as CoreScope};
84use tokio::runtime::{Handle, Id, RuntimeFlavor};
85
86use crate::config;
87use crate::error::{ErrCode, Error};
88use crate::runtime::core;
89use crate::secrets;
90
91pub fn current() -> Result<TestScope, Error> {
96 match active()? {
97 Some(scope) => Ok(TestScope { scope }),
98 None => Err(Error::new(
99 ErrCode::FailedPrecondition,
100 "there is no current test: the process is not running under `encore test`",
101 )),
102 }
103}
104
105pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
119 topic: &crate::pubsub::Topic<T, E, O>,
120) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
121 if core().system_test().is_some() {
122 return Err(Error::new(
123 ErrCode::Unimplemented,
124 "what a system test published is sent, and is not kept by the test: read what \
125 the app did with it instead, once it has `settled`",
126 ));
127 }
128 match active()? {
129 Some(test) => topic.published_in(&test),
130 None => Err(Error::new(
131 ErrCode::FailedPrecondition,
132 "there is no current test: the process is not running under `encore test`",
133 )),
134 }
135}
136
137pub async fn deliver<T: Send + 'static>(
158 subscription: &'static crate::pubsub::Subscription<T>,
159) -> Result<usize, Error> {
160 if core().system_test().is_some() {
161 return Err(Error::new(
162 ErrCode::FailedPrecondition,
163 "subscriptions run on their own in a system test, in the services that declare \
164 them: wait for them to have handled what was published with \
165 `encore::testing::system::settled`",
166 ));
167 }
168 match active()? {
169 Some(test) => subscription.deliver_in(&test).await,
170 None => Err(Error::new(
171 ErrCode::FailedPrecondition,
172 "there is no current test: the process is not running under `encore test`",
173 )),
174 }
175}
176
177pub fn set_secret<T: secrets::SecretValue>(
188 secret: &secrets::Secret<T>,
189 value: impl AsRef<[u8]>,
190) -> Result<(), Error> {
191 if core().system_test().is_some() {
192 return Err(Error::new(
193 ErrCode::FailedPrecondition,
194 SECRET_IN_SYSTEM_TEST,
195 ));
196 }
197 match active()? {
198 Some(test) => {
199 test.core_scope()?.set_secret(secret.name(), value.as_ref());
201 Ok(())
202 }
203 None => Err(Error::new(
204 ErrCode::FailedPrecondition,
205 "there is no current test: the process is not running under `encore test`",
206 )),
207 }
208}
209
210pub fn set_config<T: config::ConfigType>(
228 config: &config::Config<T>,
229 value: impl serde::Serialize,
230) -> Result<(), Error> {
231 if core().system_test().is_some() {
232 return Err(Error::new(
233 ErrCode::FailedPrecondition,
234 CONFIG_IN_SYSTEM_TEST,
235 ));
236 }
237 match active()? {
238 Some(test) => {
239 let name = config.key();
240 let mut value = serde_json::to_value(value).map_err(|err| {
241 Error::invalid_argument(format!("the value for config {name:?} is not JSON: {err}"))
242 })?;
243 config_form(&mut value);
244 let value = test
245 .core_scope()?
246 .set_config(name, value)
247 .map_err(|errors| {
248 Error::invalid_argument(format!(
249 "the value for config {name:?} does not satisfy its schema: {}",
250 errors.join("; ")
251 ))
252 })?;
253 let value = config::test_value::<T>(name, value)?;
254 test.configs
255 .lock()
256 .unwrap_or_else(|e| e.into_inner())
257 .insert(name, value);
258 Ok(())
259 }
260 None => Err(Error::new(
261 ErrCode::FailedPrecondition,
262 "there is no current test: the process is not running under `encore test`",
263 )),
264 }
265}
266
267fn config_form(value: &mut serde_json::Value) {
271 match value {
272 serde_json::Value::Object(fields) => {
273 fields.retain(|_, field| !field.is_null() && !is_secret_placeholder(field));
274 fields.values_mut().for_each(config_form);
275 }
276 serde_json::Value::Array(items) => items.iter_mut().for_each(config_form),
277 _ => {}
278 }
279}
280
281fn is_secret_placeholder(value: &serde_json::Value) -> bool {
283 value.as_object().is_some_and(|fields| {
284 fields.len() == 1
285 && fields
286 .get(encore_sdk_core::config::PLACEHOLDER_KEY)
287 .is_some_and(serde_json::Value::is_string)
288 })
289}
290
291const SECRET_IN_SYSTEM_TEST: &str = "a system test can't give a secret a value of its own: the \
293 services it calls read theirs, not the test's. Give the secret its value for tests in \
294 secrets.test.toml";
295
296const CONFIG_IN_SYSTEM_TEST: &str = "a system test can't give a config a value of its own: the \
298 services it calls read theirs, not the test's. Give the config its value for tests in its \
299 `test` config file (<name>.test.config.toml)";
300
301#[derive(Clone)]
307pub struct TestScope {
308 scope: Arc<Scope>,
309}
310
311impl TestScope {
312 pub fn enter(&self) -> ScopeGuard<'_> {
314 THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
315 ScopeGuard {
316 _scope: PhantomData,
317 _not_send: PhantomData,
318 }
319 }
320
321 pub async fn scope<F: Future>(&self, future: F) -> F::Output {
323 let mut future = pin!(future);
324 poll_fn(|cx| {
325 let _guard = self.enter();
326 future.as_mut().poll(cx)
327 })
328 .await
329 }
330
331 pub fn name(&self) -> Option<&str> {
335 self.scope.name.get().map(String::as_str)
336 }
337}
338
339pub struct ScopeGuard<'a> {
341 _scope: PhantomData<&'a TestScope>,
342 _not_send: PhantomData<*const ()>,
344}
345
346impl Drop for ScopeGuard<'_> {
347 fn drop(&mut self) {
348 THREAD.with(|thread| thread.borrow_mut().entered.pop());
349 }
350}
351
352#[doc(hidden)]
355pub mod __private {
356 use super::*;
357
358 pub struct TestInfo {
360 pub module: &'static str,
361 pub name: &'static str,
362 pub file: &'static str,
363 pub line: u32,
364 }
365
366 pub use super::fixture::FIXTURES;
367 pub use linkme;
368
369 pub struct RuntimeConfig {
371 pub multi_thread: bool,
372 pub worker_threads: Option<usize>,
373 }
374
375 pub enum FixtureArg {
377 Module,
379 Named(&'static Fixture),
380 None,
381 }
382
383 async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
386 let choice = match fixture {
388 FixtureArg::Module => fixture::for_module(info.module, true).map(Some),
389 FixtureArg::Named(fixture) => Some(Some(fixture)),
390 FixtureArg::None => Some(None),
391 };
392 let Some(choice) = choice else {
393 return;
394 };
395 if core().test_scopes().is_none() {
396 return;
397 }
398 let loaded = match choice {
399 Some(fixture) => fixture.load().await,
400 None => without_fixture(),
401 };
402 if let Err(err) = loaded {
403 panic!("{}", err.message);
404 }
405 }
406
407 pub(in crate::testing) struct EndTest;
410
411 impl Drop for EndTest {
412 fn drop(&mut self) {
413 THREAD.with(|thread| thread.borrow_mut().own = None);
414 }
415 }
416
417 fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
419 BEGUN.store(true, std::sync::atomic::Ordering::Relaxed);
421 let scope = Scope::new();
422 scope.set_module(info.module.to_string(), true);
423 let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
425 let name = if module.is_empty() {
426 info.name.to_string()
427 } else {
428 format!("{module}::{}", info.name)
429 };
430 let _ = scope.name.set(name);
431 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
432 (scope, EndTest)
433 }
434
435 pub fn run<R, F: Future<Output = R>>(
438 info: TestInfo,
439 config: RuntimeConfig,
440 fixture: FixtureArg,
441 failed: fn(&R) -> bool,
442 test: F,
443 ) -> R {
444 let (scope, _end) = begin(&info);
446 let reported = system::Reported::new(scope.clone());
447 let mut builder = if config.multi_thread {
448 tokio::runtime::Builder::new_multi_thread()
449 } else {
450 tokio::runtime::Builder::new_current_thread()
451 };
452 if let Some(threads) = config.worker_threads {
453 builder.worker_threads(threads);
454 }
455 let runtime = builder
456 .enable_all()
457 .build()
458 .expect("failed to build the test's Tokio runtime");
459 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
460 drop(scope);
461 let result = runtime.block_on(async {
462 load_fixture(&info, fixture).await;
463 test.await
464 });
465 reported.ended(failed(&result));
466 result
467 }
468
469 pub struct Probe<'a, R>(pub &'a R);
477
478 pub trait FailedIfErr {
479 fn failed(&self) -> bool;
480 }
481
482 impl<T, E> FailedIfErr for Probe<'_, Result<T, E>> {
483 fn failed(&self) -> bool {
484 self.0.is_err()
485 }
486 }
487
488 pub trait NeverFailed {
489 fn failed(&self) -> bool;
490 }
491
492 impl<R> NeverFailed for &Probe<'_, R> {
493 fn failed(&self) -> bool {
494 false
495 }
496 }
497
498 pub fn run_sync<R, F: FnOnce() -> R>(
500 info: TestInfo,
501 fixture: FixtureArg,
502 failed: fn(&R) -> bool,
503 test: F,
504 ) -> R {
505 let (scope, _end) = begin(&info);
506 let reported = system::Reported::new(scope);
507 tokio::runtime::Builder::new_current_thread()
509 .enable_all()
510 .build()
511 .expect("failed to build a Tokio runtime to load the test's fixture")
512 .block_on(load_fixture(&info, fixture));
513 let result = test();
514 reported.ended(failed(&result));
515 result
516 }
517}
518
519pub(crate) struct Scope {
523 name: OnceLock<String>,
524 module: OnceLock<(String, bool)>,
527 core: OnceLock<Arc<CoreScope>>,
531 configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
534}
535
536type ConfigKey = &'static str;
539
540impl Scope {
541 fn new() -> Arc<Self> {
542 Arc::new(Self {
543 name: OnceLock::new(),
544 module: OnceLock::new(),
545 core: OnceLock::new(),
546 configs: Mutex::new(HashMap::new()),
547 })
548 }
549
550 fn building(core: Arc<CoreScope>, name: String) -> Arc<Self> {
552 let scope = Self::new();
553 let _ = scope.name.set(name);
554 let _ = scope.core.set(core);
555 scope
556 }
557
558 pub(crate) fn core_scope(&self) -> Result<&Arc<CoreScope>, Error> {
561 if let Some(scope) = self.core.get() {
562 return Ok(scope);
563 }
564 let scopes = core().test_scopes().ok_or_else(|| {
565 Error::new(
566 ErrCode::FailedPrecondition,
567 "there is no current test: the process is not running under `encore test`",
568 )
569 })?;
570 let scope = self
571 .core
572 .get_or_init(|| scopes.begin(self.name.get().map(String::as_str)));
573 self.require_module_fixture();
574 Ok(scope)
575 }
576
577 fn set_module(&self, module: String, full: bool) {
579 let _ = self.module.set((module, full));
580 self.require_module_fixture();
581 }
582
583 fn require_module_fixture(&self) {
587 let (Some(core), Some((module, full))) = (self.core.get(), self.module.get()) else {
588 return;
589 };
590 if let Some(reason) = unloaded_module_fixture(module, *full) {
591 core.require_use_fixture(reason);
592 }
593 }
594
595 pub(crate) fn choose(&self, fixture: Option<&'static Fixture>) -> Result<(), Error> {
598 self.core_scope()?
599 .use_fixture(fixture.map(Fixture::name))
600 .map_err(infra_err)
601 }
602
603 pub(crate) fn secret(&self, name: &str) -> Option<Arc<[u8]>> {
605 self.core.get()?.secret(name)
606 }
607
608 pub(crate) fn config(
610 &self,
611 name: &'static str,
612 ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
613 self.configs
614 .lock()
615 .unwrap_or_else(|e| e.into_inner())
616 .get(name)
617 .cloned()
618 }
619
620 pub(crate) fn published(&self, name: &str) -> Vec<test_scope::Published> {
622 self.core
623 .get()
624 .map(|core| core.published(name))
625 .unwrap_or_default()
626 }
627
628 pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
631 self.core_scope()?.bucket(&name.into()).map_err(infra_err)
632 }
633
634 pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
637 self.core_scope()?.database(&name.into()).map_err(infra_err)
638 }
639
640 pub(crate) fn redis_client(
645 &self,
646 name: &'static str,
647 ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
648 self.core_scope()?.redis(&name.into()).map_err(infra_err)
649 }
650
651 pub(crate) fn database_connection_string(
654 &self,
655 name: &'static str,
656 access: Access,
657 ) -> Result<String, Error> {
658 self.core_scope()?
659 .connection_string(&name.into(), access)
660 .map_err(infra_err)
661 }
662}
663
664fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
667 let fixture = fixture::for_module(module, full)?;
668 Some(format!(
669 "this test is in a module whose tests start from the fixture {:?}, but has not \
670 loaded it. Make it an `#[encore::test]`, which does, or call `.load().await?` on the \
671 fixture — or `encore::testing::without_fixture()?` — before the test first uses a \
672 resource",
673 fixture.name()
674 ))
675}
676
677fn infra_err(err: anyhow::Error) -> Error {
680 if err.downcast_ref::<FixtureChoiceError>().is_some() {
681 Error::new(ErrCode::FailedPrecondition, err.to_string())
682 } else {
683 Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
684 }
685}
686
687fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
690 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
691 let _end = __private::EndTest;
693 let runtime = tokio::runtime::Builder::new_current_thread()
694 .enable_all()
695 .build()
696 .expect("failed to build a Tokio runtime");
697 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
698 drop(scope);
699 runtime.block_on(work)
700}
701
702pub(crate) fn outgoing(
709 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
710) -> encore_sdk_core::telemetry::opentelemetry::Context {
711 if core().system_test().is_none() {
712 return cx.clone();
713 }
714 let Ok(Some(test)) = active() else {
715 return cx.clone();
716 };
717 match test.core_scope() {
718 Ok(scope) => scope.outgoing_context(cx),
719 Err(_) => cx.clone(),
720 }
721}
722
723pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
726 if core().test_scopes().is_none() {
727 return Ok(None);
728 }
729 resolve().map(Some)
730}
731
732#[derive(Default)]
736struct ThreadScopes {
737 own: Option<Arc<Scope>>,
739 joined: Vec<Arc<Scope>>,
741 entered: Vec<Arc<Scope>>,
743}
744
745thread_local! {
746 static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
747}
748
749enum Link {
751 Test(Weak<Scope>),
752 Shared,
754}
755
756static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
757
758fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
759 let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
760 f(runtimes.get_or_insert_with(HashMap::new))
761}
762
763static BEGUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
768
769pub(crate) fn runner_detected() -> bool {
774 BEGUN.load(std::sync::atomic::Ordering::Relaxed)
775 || std::env::var_os("NEXTEST").is_some()
776 || test_name(std::thread::current().name()).is_some()
777}
778
779fn test_name(thread: Option<&str>) -> Option<&str> {
780 thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
781}
782
783fn resolve() -> Result<Arc<Scope>, Error> {
786 let handle = Handle::try_current().ok();
787 let runtime = handle.as_ref().map(Handle::id);
788 let thread = std::thread::current();
789 THREAD.with(|state| {
790 let mut state = state.borrow_mut();
791 if let Some(scope) = state.entered.last() {
792 return Ok(scope.clone());
793 }
794
795 if let Some(scope) = &state.own {
797 let scope = scope.clone();
798 if let Some(id) = runtime {
799 with_runtimes(|runtimes| link(runtimes, id, &scope));
800 }
801 return Ok(scope);
802 }
803
804 if let Some(name) = test_name(thread.name()) {
805 let scope = match &state.own {
806 Some(scope) => scope.clone(),
807 None => {
808 let scope = runtime
810 .and_then(|id| {
811 with_runtimes(|runtimes| match runtimes.get(&id) {
812 Some(Link::Test(scope)) => {
813 scope.upgrade().filter(|scope| scope.name.get().is_none())
814 }
815 _ => None,
816 })
817 })
818 .unwrap_or_else(Scope::new);
819 let _ = scope.name.set(name.to_string());
820 let module = name.rsplit_once("::").map_or("", |(module, _)| module);
821 scope.set_module(module.to_string(), false);
822 state.own = Some(scope.clone());
823 scope
824 }
825 };
826 if let Some(id) = runtime {
827 with_runtimes(|runtimes| link(runtimes, id, &scope));
828 }
829 return Ok(scope);
830 }
831
832 let Some(id) = runtime else {
833 return Err(not_a_test_thread(thread.name()));
834 };
835 let scope = with_runtimes(|runtimes| {
836 match runtimes.get(&id) {
837 Some(Link::Shared) => return Err(shared_runtime(thread.name())),
838 Some(Link::Test(scope)) => {
839 if let Some(scope) = scope.upgrade() {
840 return Ok(scope);
841 }
842 }
843 None => {}
844 }
845 let multi_thread = handle
850 .as_ref()
851 .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
852 if !multi_thread {
853 return Err(not_a_test_thread(thread.name()));
854 }
855 let scope = Scope::new();
856 link(runtimes, id, &scope);
857 Ok(scope)
858 })?;
859 if !state
860 .joined
861 .iter()
862 .any(|joined| Arc::ptr_eq(joined, &scope))
863 {
864 state.joined.push(scope.clone());
865 }
866 Ok(scope)
867 })
868}
869
870fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
873 let shared = match runtimes.get(&id) {
874 Some(Link::Shared) => true,
875 Some(Link::Test(current)) => current
876 .upgrade()
877 .is_some_and(|current| !Arc::ptr_eq(¤t, scope)),
878 None => false,
879 };
880 if !shared {
881 runtimes.retain(|_, link| match link {
883 Link::Test(scope) => scope.strong_count() > 0,
884 Link::Shared => true,
885 });
886 }
887 let link = if shared {
888 Link::Shared
889 } else {
890 Link::Test(Arc::downgrade(scope))
891 };
892 runtimes.insert(id, link);
893}
894
895fn thread_label(name: Option<&str>) -> String {
896 match name {
897 Some(name) => format!("thread {name:?}"),
898 None => "an unnamed thread".to_string(),
899 }
900}
901
902fn not_a_test_thread(thread: Option<&str>) -> Error {
903 Error::new(
904 ErrCode::FailedPrecondition,
905 format!(
906 "an Encore resource was used on {}, which Encore cannot link to a running test. \
907 Each test gets infrastructure of its own, so Encore needs to know which test \
908 this thread belongs to.\n\n\
909 In the test, capture the scope and enter it on the new thread:\n\n \
910 let scope = encore::testing::current()?;\n \
911 std::thread::spawn(move || {{\n \
912 let _guard = scope.enter();\n \
913 …\n \
914 }});",
915 thread_label(thread)
916 ),
917 )
918}
919
920fn shared_runtime(thread: Option<&str>) -> Error {
921 Error::new(
922 ErrCode::FailedPrecondition,
923 format!(
924 "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
925 so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
926 its own.\n\n\
927 Run the work as part of its test:\n\n \
928 let scope = encore::testing::current()?;\n \
929 runtime.spawn(async move {{ scope.scope(work()).await }});",
930 thread_label(thread)
931 ),
932 )
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938
939 #[test]
940 fn a_typed_config_value_is_given_in_its_files_form() {
941 #[derive(serde::Serialize)]
942 struct Limits {
943 max: u32,
944 timeout: config::Duration,
945 key: secrets::Secret,
946 note: Option<String>,
947 tiers: Vec<Tier>,
948 }
949 #[derive(serde::Serialize)]
950 struct Tier {
951 name: &'static str,
952 key: secrets::Secret,
953 }
954 let mut value = serde_json::to_value(Limits {
955 max: 5,
956 timeout: config::Duration(std::time::Duration::from_millis(1500)),
957 key: secrets::Secret::new("StripeKey"),
958 note: None,
959 tiers: vec![Tier {
960 name: "gold",
961 key: secrets::Secret::new("GoldKey"),
962 }],
963 })
964 .unwrap();
965 config_form(&mut value);
966 assert_eq!(
967 value,
968 serde_json::json!({
969 "max": 5,
970 "timeout": "1500000us",
971 "tiers": [{"name": "gold"}],
972 })
973 );
974 assert_eq!(
976 config::parse_duration("1500000us"),
977 Some(std::time::Duration::from_millis(1500))
978 );
979 }
980
981 fn here() -> Result<(Option<String>, usize), String> {
983 resolve()
984 .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
985 .map_err(|err| err.message)
986 }
987
988 #[test]
989 fn a_test_thread_is_its_test() {
990 let (name, id) = here().unwrap();
991 assert_eq!(
992 name.as_deref(),
993 Some("testing::tests::a_test_thread_is_its_test")
994 );
995 assert_eq!(here().unwrap().1, id);
997 }
998
999 #[test]
1000 fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
1001 let (_, id) = here().unwrap();
1002 let scope = TestScope {
1003 scope: resolve().unwrap(),
1004 };
1005
1006 let err = std::thread::spawn(here).join().unwrap().unwrap_err();
1007 assert!(err.contains("an unnamed thread"), "{err}");
1008 assert!(err.contains("scope.enter()"), "{err}");
1009
1010 let entered = std::thread::spawn(move || {
1011 let inside = {
1012 let _guard = scope.enter();
1013 here()
1014 };
1015 (inside, here())
1016 })
1017 .join()
1018 .unwrap();
1019 assert_eq!(entered.0.unwrap().1, id);
1020 assert!(entered.1.is_err());
1022 }
1023
1024 #[tokio::test]
1025 async fn a_current_thread_runtime_is_its_test() {
1026 let (name, id) = here().unwrap();
1027 assert!(name.is_some());
1028 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1029 assert_eq!(
1030 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1031 id
1032 );
1033 }
1034
1035 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1036 async fn a_multi_thread_runtime_is_its_test() {
1037 let (_, id) = here().unwrap();
1038 for _ in 0..8 {
1039 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1040 }
1041 assert_eq!(
1042 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1043 id
1044 );
1045 }
1046
1047 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1048 async fn a_test_adopts_what_its_runtime_started() {
1049 let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1051 assert_eq!(name, None);
1052 let (name, adopted) = here().unwrap();
1054 assert_eq!(adopted, id);
1055 assert!(name
1056 .unwrap()
1057 .ends_with("a_test_adopts_what_its_runtime_started"));
1058 let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1059 assert_eq!(again, id);
1060 assert!(name.is_some());
1061 }
1062
1063 #[test]
1064 fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
1065 let runtime = tokio::runtime::Builder::new_multi_thread()
1066 .worker_threads(1)
1067 .build()
1068 .unwrap();
1069 let handle = runtime.handle().clone();
1070 let (ready_tx, ready_rx) = std::sync::mpsc::channel();
1071 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1072 let first = std::thread::Builder::new()
1074 .name("tests::first".to_string())
1075 .spawn({
1076 let handle = handle.clone();
1077 move || {
1078 let _enter = handle.enter();
1079 let id = here().unwrap().1;
1080 ready_tx.send(id).unwrap();
1081 let _ = done_rx.recv();
1082 }
1083 })
1084 .unwrap();
1085 let first_id = ready_rx.recv().unwrap();
1086 let second_id = std::thread::Builder::new()
1088 .name("tests::second".to_string())
1089 .spawn({
1090 let handle = handle.clone();
1091 move || {
1092 let _enter = handle.enter();
1093 here().unwrap().1
1094 }
1095 })
1096 .unwrap()
1097 .join()
1098 .unwrap();
1099 assert_ne!(first_id, second_id);
1100
1101 let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
1103 let err = err.unwrap_err();
1105 assert!(err.contains("several tests share"), "{err}");
1106 assert!(err.contains("scope.scope("), "{err}");
1107
1108 done_tx.send(()).unwrap();
1109 first.join().unwrap();
1110 }
1111
1112 #[tokio::test]
1113 async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
1114 let (_, id) = here().unwrap();
1115 let scope = TestScope {
1116 scope: resolve().unwrap(),
1117 };
1118 assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
1119 let other = std::thread::spawn(move || {
1121 tokio::runtime::Builder::new_current_thread()
1122 .build()
1123 .unwrap()
1124 .block_on(async {
1125 let outside = here();
1126 let inside = scope.scope(async { here().unwrap().1 }).await;
1127 (outside, inside)
1128 })
1129 })
1130 .join()
1131 .unwrap();
1132 let err = other.0.unwrap_err();
1133 assert!(err.contains("cannot link to a running test"), "{err}");
1134 assert_eq!(other.1, id);
1135 }
1136
1137 #[encore::test]
1138 async fn the_macro_runs_a_test_in_its_own_runtime() {
1139 let (name, id) = here().unwrap();
1140 assert_eq!(
1142 name.as_deref(),
1143 Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
1144 );
1145 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1146 assert_eq!(
1148 Handle::current().runtime_flavor(),
1149 RuntimeFlavor::CurrentThread
1150 );
1151 }
1152
1153 #[encore::test(flavor = "multi_thread", worker_threads = 2)]
1154 async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
1155 let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
1157 assert!(name.unwrap().ends_with("before_the_test_runs"));
1158 assert_eq!(here()?.1, id);
1159 assert_eq!(Handle::current().metrics().num_workers(), 2);
1160 Ok(())
1161 }
1162
1163 #[encore::test]
1164 #[should_panic(expected = "as any test")]
1165 async fn the_macro_keeps_the_tests_other_attributes() {
1166 panic!("as any test");
1167 }
1168
1169 #[encore::test]
1170 fn the_macro_takes_a_test_that_is_not_async() {
1171 let (name, _) = here().unwrap();
1172 assert!(name.unwrap().ends_with("is_not_async"));
1173 }
1174
1175 #[test]
1176 fn the_macro_ends_the_test_when_it_returns() {
1177 let weak = std::thread::spawn(|| {
1178 let weak = __private::run(
1179 __private::TestInfo {
1180 module: "app::tests",
1181 name: "returns",
1182 file: file!(),
1183 line: line!(),
1184 },
1185 __private::RuntimeConfig {
1186 multi_thread: true,
1187 worker_threads: Some(1),
1188 },
1189 __private::FixtureArg::Module,
1190 |_| false,
1191 async {
1192 tokio::spawn(async { here().unwrap() }).await.unwrap();
1193 Arc::downgrade(&resolve().unwrap())
1194 },
1195 );
1196 assert!(weak.upgrade().is_none());
1198 assert!(here().is_err());
1199 })
1200 .join();
1201 weak.unwrap();
1202 }
1203
1204 mod billing {
1205 crate::fixture! {
1206 pub static SEEDED for mod = async { Ok(()) };
1208
1209 pub static EXTRA: SEEDED = async { Ok(()) };
1211 }
1212
1213 pub mod invoices {
1214 crate::fixture! {
1215 pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
1216 }
1217 }
1218 }
1219
1220 #[test]
1221 fn a_fixture_is_named_after_where_it_is_declared() {
1222 assert_eq!(
1223 billing::SEEDED.name(),
1224 "encore::testing::tests::billing::SEEDED"
1225 );
1226 assert_eq!(
1227 billing::invoices::INVOICED.name(),
1228 "encore::testing::tests::billing::invoices::INVOICED"
1229 );
1230 assert_eq!(
1232 billing::EXTRA.name(),
1233 "encore::testing::tests::billing::EXTRA"
1234 );
1235 }
1236
1237 #[test]
1238 fn a_modules_fixture_is_found_from_the_tests_inside_it() {
1239 let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
1240 assert_eq!(
1242 found("encore::testing::tests::billing", true),
1243 Some(billing::SEEDED.name())
1244 );
1245 assert_eq!(
1246 found("encore::testing::tests::billing::reports::monthly", true),
1247 Some(billing::SEEDED.name())
1248 );
1249 assert_eq!(
1251 found("encore::testing::tests::billing::invoices", true),
1252 Some(billing::invoices::INVOICED.name())
1253 );
1254 assert_eq!(
1256 found("testing::tests::billing::invoices::overdue", false),
1257 Some(billing::invoices::INVOICED.name())
1258 );
1259 assert_eq!(found("encore::testing::tests::billing_reports", true), None);
1262 assert_eq!(found("encore::testing::tests", true), None);
1263 assert_eq!(found("testing::tests", false), None);
1264 }
1265
1266 #[test]
1267 fn a_test_in_a_module_with_a_fixture_has_to_say_what_it_starts_from() {
1268 let reason = unloaded_module_fixture("testing::tests::billing::reports", false).unwrap();
1271 assert!(reason.contains("has not loaded it"), "{reason}");
1272 assert!(reason.contains(billing::SEEDED.name()), "{reason}");
1273 assert!(reason.contains("without_fixture()"), "{reason}");
1274
1275 assert_eq!(unloaded_module_fixture("testing::tests", false), None);
1277 }
1278
1279 #[test]
1280 fn a_scope_ends_with_the_threads_that_are_part_of_it() {
1281 let weak = std::thread::Builder::new()
1282 .name("tests::short_lived".to_string())
1283 .spawn(|| Arc::downgrade(&resolve().unwrap()))
1284 .unwrap()
1285 .join()
1286 .unwrap();
1287 assert!(weak.upgrade().is_none());
1288
1289 let scope = std::thread::Builder::new()
1291 .name("tests::held".to_string())
1292 .spawn(|| TestScope {
1293 scope: resolve().unwrap(),
1294 })
1295 .unwrap()
1296 .join()
1297 .unwrap();
1298 let weak = Arc::downgrade(&scope.scope);
1299 assert!(weak.upgrade().is_some());
1300 drop(scope);
1301 assert!(weak.upgrade().is_none());
1302 }
1303}