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 clickhouse_database(
643 &self,
644 name: &'static str,
645 ) -> Result<Arc<encore_sdk_core::clickhouse::Database>, Error> {
646 self.core_scope()?
647 .clickhouse(&name.into())
648 .map_err(infra_err)
649 }
650
651 pub(crate) fn redis_client(
656 &self,
657 name: &'static str,
658 ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
659 self.core_scope()?.redis(&name.into()).map_err(infra_err)
660 }
661
662 pub(crate) fn database_connection_string(
665 &self,
666 name: &'static str,
667 access: Access,
668 ) -> Result<String, Error> {
669 self.core_scope()?
670 .connection_string(&name.into(), access)
671 .map_err(infra_err)
672 }
673}
674
675fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
678 let fixture = fixture::for_module(module, full)?;
679 Some(format!(
680 "this test is in a module whose tests start from the fixture {:?}, but has not \
681 loaded it. Make it an `#[encore::test]`, which does, or call `.load().await?` on the \
682 fixture — or `encore::testing::without_fixture()?` — before the test first uses a \
683 resource",
684 fixture.name()
685 ))
686}
687
688fn infra_err(err: anyhow::Error) -> Error {
691 if err.downcast_ref::<FixtureChoiceError>().is_some() {
692 Error::new(ErrCode::FailedPrecondition, err.to_string())
693 } else {
694 Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
695 }
696}
697
698fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
701 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
702 let _end = __private::EndTest;
704 let runtime = tokio::runtime::Builder::new_current_thread()
705 .enable_all()
706 .build()
707 .expect("failed to build a Tokio runtime");
708 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
709 drop(scope);
710 runtime.block_on(work)
711}
712
713pub(crate) fn outgoing(
720 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
721) -> encore_sdk_core::telemetry::opentelemetry::Context {
722 if core().system_test().is_none() {
723 return cx.clone();
724 }
725 let Ok(Some(test)) = active() else {
726 return cx.clone();
727 };
728 match test.core_scope() {
729 Ok(scope) => scope.outgoing_context(cx),
730 Err(_) => cx.clone(),
731 }
732}
733
734pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
737 if core().test_scopes().is_none() {
738 return Ok(None);
739 }
740 resolve().map(Some)
741}
742
743#[derive(Default)]
747struct ThreadScopes {
748 own: Option<Arc<Scope>>,
750 joined: Vec<Arc<Scope>>,
752 entered: Vec<Arc<Scope>>,
754}
755
756thread_local! {
757 static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
758}
759
760enum Link {
762 Test(Weak<Scope>),
763 Shared,
765}
766
767static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
768
769fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
770 let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
771 f(runtimes.get_or_insert_with(HashMap::new))
772}
773
774static BEGUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
779
780pub(crate) fn runner_detected() -> bool {
785 BEGUN.load(std::sync::atomic::Ordering::Relaxed)
786 || std::env::var_os("NEXTEST").is_some()
787 || test_name(std::thread::current().name()).is_some()
788}
789
790fn test_name(thread: Option<&str>) -> Option<&str> {
791 thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
792}
793
794fn resolve() -> Result<Arc<Scope>, Error> {
797 let handle = Handle::try_current().ok();
798 let runtime = handle.as_ref().map(Handle::id);
799 let thread = std::thread::current();
800 THREAD.with(|state| {
801 let mut state = state.borrow_mut();
802 if let Some(scope) = state.entered.last() {
803 return Ok(scope.clone());
804 }
805
806 if let Some(scope) = &state.own {
808 let scope = scope.clone();
809 if let Some(id) = runtime {
810 with_runtimes(|runtimes| link(runtimes, id, &scope));
811 }
812 return Ok(scope);
813 }
814
815 if let Some(name) = test_name(thread.name()) {
816 let scope = match &state.own {
817 Some(scope) => scope.clone(),
818 None => {
819 let scope = runtime
821 .and_then(|id| {
822 with_runtimes(|runtimes| match runtimes.get(&id) {
823 Some(Link::Test(scope)) => {
824 scope.upgrade().filter(|scope| scope.name.get().is_none())
825 }
826 _ => None,
827 })
828 })
829 .unwrap_or_else(Scope::new);
830 let _ = scope.name.set(name.to_string());
831 let module = name.rsplit_once("::").map_or("", |(module, _)| module);
832 scope.set_module(module.to_string(), false);
833 state.own = Some(scope.clone());
834 scope
835 }
836 };
837 if let Some(id) = runtime {
838 with_runtimes(|runtimes| link(runtimes, id, &scope));
839 }
840 return Ok(scope);
841 }
842
843 let Some(id) = runtime else {
844 return Err(not_a_test_thread(thread.name()));
845 };
846 let scope = with_runtimes(|runtimes| {
847 match runtimes.get(&id) {
848 Some(Link::Shared) => return Err(shared_runtime(thread.name())),
849 Some(Link::Test(scope)) => {
850 if let Some(scope) = scope.upgrade() {
851 return Ok(scope);
852 }
853 }
854 None => {}
855 }
856 let multi_thread = handle
861 .as_ref()
862 .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
863 if !multi_thread {
864 return Err(not_a_test_thread(thread.name()));
865 }
866 let scope = Scope::new();
867 link(runtimes, id, &scope);
868 Ok(scope)
869 })?;
870 if !state
871 .joined
872 .iter()
873 .any(|joined| Arc::ptr_eq(joined, &scope))
874 {
875 state.joined.push(scope.clone());
876 }
877 Ok(scope)
878 })
879}
880
881fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
884 let shared = match runtimes.get(&id) {
885 Some(Link::Shared) => true,
886 Some(Link::Test(current)) => current
887 .upgrade()
888 .is_some_and(|current| !Arc::ptr_eq(¤t, scope)),
889 None => false,
890 };
891 if !shared {
892 runtimes.retain(|_, link| match link {
894 Link::Test(scope) => scope.strong_count() > 0,
895 Link::Shared => true,
896 });
897 }
898 let link = if shared {
899 Link::Shared
900 } else {
901 Link::Test(Arc::downgrade(scope))
902 };
903 runtimes.insert(id, link);
904}
905
906fn thread_label(name: Option<&str>) -> String {
907 match name {
908 Some(name) => format!("thread {name:?}"),
909 None => "an unnamed thread".to_string(),
910 }
911}
912
913fn not_a_test_thread(thread: Option<&str>) -> Error {
914 Error::new(
915 ErrCode::FailedPrecondition,
916 format!(
917 "an Encore resource was used on {}, which Encore cannot link to a running test. \
918 Each test gets infrastructure of its own, so Encore needs to know which test \
919 this thread belongs to.\n\n\
920 In the test, capture the scope and enter it on the new thread:\n\n \
921 let scope = encore::testing::current()?;\n \
922 std::thread::spawn(move || {{\n \
923 let _guard = scope.enter();\n \
924 …\n \
925 }});",
926 thread_label(thread)
927 ),
928 )
929}
930
931fn shared_runtime(thread: Option<&str>) -> Error {
932 Error::new(
933 ErrCode::FailedPrecondition,
934 format!(
935 "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
936 so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
937 its own.\n\n\
938 Run the work as part of its test:\n\n \
939 let scope = encore::testing::current()?;\n \
940 runtime.spawn(async move {{ scope.scope(work()).await }});",
941 thread_label(thread)
942 ),
943 )
944}
945
946#[cfg(test)]
947mod tests {
948 use super::*;
949
950 #[test]
951 fn a_typed_config_value_is_given_in_its_files_form() {
952 #[derive(serde::Serialize)]
953 struct Limits {
954 max: u32,
955 timeout: config::Duration,
956 key: secrets::Secret,
957 note: Option<String>,
958 tiers: Vec<Tier>,
959 }
960 #[derive(serde::Serialize)]
961 struct Tier {
962 name: &'static str,
963 key: secrets::Secret,
964 }
965 let mut value = serde_json::to_value(Limits {
966 max: 5,
967 timeout: config::Duration(std::time::Duration::from_millis(1500)),
968 key: secrets::Secret::new("StripeKey"),
969 note: None,
970 tiers: vec![Tier {
971 name: "gold",
972 key: secrets::Secret::new("GoldKey"),
973 }],
974 })
975 .unwrap();
976 config_form(&mut value);
977 assert_eq!(
978 value,
979 serde_json::json!({
980 "max": 5,
981 "timeout": "1500000us",
982 "tiers": [{"name": "gold"}],
983 })
984 );
985 assert_eq!(
987 config::parse_duration("1500000us"),
988 Some(std::time::Duration::from_millis(1500))
989 );
990 }
991
992 fn here() -> Result<(Option<String>, usize), String> {
994 resolve()
995 .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
996 .map_err(|err| err.message)
997 }
998
999 #[test]
1000 fn a_test_thread_is_its_test() {
1001 let (name, id) = here().unwrap();
1002 assert_eq!(
1003 name.as_deref(),
1004 Some("testing::tests::a_test_thread_is_its_test")
1005 );
1006 assert_eq!(here().unwrap().1, id);
1008 }
1009
1010 #[test]
1011 fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
1012 let (_, id) = here().unwrap();
1013 let scope = TestScope {
1014 scope: resolve().unwrap(),
1015 };
1016
1017 let err = std::thread::spawn(here).join().unwrap().unwrap_err();
1018 assert!(err.contains("an unnamed thread"), "{err}");
1019 assert!(err.contains("scope.enter()"), "{err}");
1020
1021 let entered = std::thread::spawn(move || {
1022 let inside = {
1023 let _guard = scope.enter();
1024 here()
1025 };
1026 (inside, here())
1027 })
1028 .join()
1029 .unwrap();
1030 assert_eq!(entered.0.unwrap().1, id);
1031 assert!(entered.1.is_err());
1033 }
1034
1035 #[tokio::test]
1036 async fn a_current_thread_runtime_is_its_test() {
1037 let (name, id) = here().unwrap();
1038 assert!(name.is_some());
1039 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1040 assert_eq!(
1041 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1042 id
1043 );
1044 }
1045
1046 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1047 async fn a_multi_thread_runtime_is_its_test() {
1048 let (_, id) = here().unwrap();
1049 for _ in 0..8 {
1050 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1051 }
1052 assert_eq!(
1053 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1054 id
1055 );
1056 }
1057
1058 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1059 async fn a_test_adopts_what_its_runtime_started() {
1060 let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1062 assert_eq!(name, None);
1063 let (name, adopted) = here().unwrap();
1065 assert_eq!(adopted, id);
1066 assert!(name
1067 .unwrap()
1068 .ends_with("a_test_adopts_what_its_runtime_started"));
1069 let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1070 assert_eq!(again, id);
1071 assert!(name.is_some());
1072 }
1073
1074 #[test]
1075 fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
1076 let runtime = tokio::runtime::Builder::new_multi_thread()
1077 .worker_threads(1)
1078 .build()
1079 .unwrap();
1080 let handle = runtime.handle().clone();
1081 let (ready_tx, ready_rx) = std::sync::mpsc::channel();
1082 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1083 let first = std::thread::Builder::new()
1085 .name("tests::first".to_string())
1086 .spawn({
1087 let handle = handle.clone();
1088 move || {
1089 let _enter = handle.enter();
1090 let id = here().unwrap().1;
1091 ready_tx.send(id).unwrap();
1092 let _ = done_rx.recv();
1093 }
1094 })
1095 .unwrap();
1096 let first_id = ready_rx.recv().unwrap();
1097 let second_id = std::thread::Builder::new()
1099 .name("tests::second".to_string())
1100 .spawn({
1101 let handle = handle.clone();
1102 move || {
1103 let _enter = handle.enter();
1104 here().unwrap().1
1105 }
1106 })
1107 .unwrap()
1108 .join()
1109 .unwrap();
1110 assert_ne!(first_id, second_id);
1111
1112 let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
1114 let err = err.unwrap_err();
1116 assert!(err.contains("several tests share"), "{err}");
1117 assert!(err.contains("scope.scope("), "{err}");
1118
1119 done_tx.send(()).unwrap();
1120 first.join().unwrap();
1121 }
1122
1123 #[tokio::test]
1124 async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
1125 let (_, id) = here().unwrap();
1126 let scope = TestScope {
1127 scope: resolve().unwrap(),
1128 };
1129 assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
1130 let other = std::thread::spawn(move || {
1132 tokio::runtime::Builder::new_current_thread()
1133 .build()
1134 .unwrap()
1135 .block_on(async {
1136 let outside = here();
1137 let inside = scope.scope(async { here().unwrap().1 }).await;
1138 (outside, inside)
1139 })
1140 })
1141 .join()
1142 .unwrap();
1143 let err = other.0.unwrap_err();
1144 assert!(err.contains("cannot link to a running test"), "{err}");
1145 assert_eq!(other.1, id);
1146 }
1147
1148 #[encore::test]
1149 async fn the_macro_runs_a_test_in_its_own_runtime() {
1150 let (name, id) = here().unwrap();
1151 assert_eq!(
1153 name.as_deref(),
1154 Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
1155 );
1156 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1157 assert_eq!(
1159 Handle::current().runtime_flavor(),
1160 RuntimeFlavor::CurrentThread
1161 );
1162 }
1163
1164 #[encore::test(flavor = "multi_thread", worker_threads = 2)]
1165 async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
1166 let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
1168 assert!(name.unwrap().ends_with("before_the_test_runs"));
1169 assert_eq!(here()?.1, id);
1170 assert_eq!(Handle::current().metrics().num_workers(), 2);
1171 Ok(())
1172 }
1173
1174 #[encore::test]
1175 #[should_panic(expected = "as any test")]
1176 async fn the_macro_keeps_the_tests_other_attributes() {
1177 panic!("as any test");
1178 }
1179
1180 #[encore::test]
1181 fn the_macro_takes_a_test_that_is_not_async() {
1182 let (name, _) = here().unwrap();
1183 assert!(name.unwrap().ends_with("is_not_async"));
1184 }
1185
1186 #[test]
1187 fn the_macro_ends_the_test_when_it_returns() {
1188 let weak = std::thread::spawn(|| {
1189 let weak = __private::run(
1190 __private::TestInfo {
1191 module: "app::tests",
1192 name: "returns",
1193 file: file!(),
1194 line: line!(),
1195 },
1196 __private::RuntimeConfig {
1197 multi_thread: true,
1198 worker_threads: Some(1),
1199 },
1200 __private::FixtureArg::Module,
1201 |_| false,
1202 async {
1203 tokio::spawn(async { here().unwrap() }).await.unwrap();
1204 Arc::downgrade(&resolve().unwrap())
1205 },
1206 );
1207 assert!(weak.upgrade().is_none());
1209 assert!(here().is_err());
1210 })
1211 .join();
1212 weak.unwrap();
1213 }
1214
1215 mod billing {
1216 crate::fixture! {
1217 pub static SEEDED for mod = async { Ok(()) };
1219
1220 pub static EXTRA: SEEDED = async { Ok(()) };
1222 }
1223
1224 pub mod invoices {
1225 crate::fixture! {
1226 pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
1227 }
1228 }
1229 }
1230
1231 #[test]
1232 fn a_fixture_is_named_after_where_it_is_declared() {
1233 assert_eq!(
1234 billing::SEEDED.name(),
1235 "encore::testing::tests::billing::SEEDED"
1236 );
1237 assert_eq!(
1238 billing::invoices::INVOICED.name(),
1239 "encore::testing::tests::billing::invoices::INVOICED"
1240 );
1241 assert_eq!(
1243 billing::EXTRA.name(),
1244 "encore::testing::tests::billing::EXTRA"
1245 );
1246 }
1247
1248 #[test]
1249 fn a_modules_fixture_is_found_from_the_tests_inside_it() {
1250 let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
1251 assert_eq!(
1253 found("encore::testing::tests::billing", true),
1254 Some(billing::SEEDED.name())
1255 );
1256 assert_eq!(
1257 found("encore::testing::tests::billing::reports::monthly", true),
1258 Some(billing::SEEDED.name())
1259 );
1260 assert_eq!(
1262 found("encore::testing::tests::billing::invoices", true),
1263 Some(billing::invoices::INVOICED.name())
1264 );
1265 assert_eq!(
1267 found("testing::tests::billing::invoices::overdue", false),
1268 Some(billing::invoices::INVOICED.name())
1269 );
1270 assert_eq!(found("encore::testing::tests::billing_reports", true), None);
1273 assert_eq!(found("encore::testing::tests", true), None);
1274 assert_eq!(found("testing::tests", false), None);
1275 }
1276
1277 #[test]
1278 fn a_test_in_a_module_with_a_fixture_has_to_say_what_it_starts_from() {
1279 let reason = unloaded_module_fixture("testing::tests::billing::reports", false).unwrap();
1282 assert!(reason.contains("has not loaded it"), "{reason}");
1283 assert!(reason.contains(billing::SEEDED.name()), "{reason}");
1284 assert!(reason.contains("without_fixture()"), "{reason}");
1285
1286 assert_eq!(unloaded_module_fixture("testing::tests", false), None);
1288 }
1289
1290 #[test]
1291 fn a_scope_ends_with_the_threads_that_are_part_of_it() {
1292 let weak = std::thread::Builder::new()
1293 .name("tests::short_lived".to_string())
1294 .spawn(|| Arc::downgrade(&resolve().unwrap()))
1295 .unwrap()
1296 .join()
1297 .unwrap();
1298 assert!(weak.upgrade().is_none());
1299
1300 let scope = std::thread::Builder::new()
1302 .name("tests::held".to_string())
1303 .spawn(|| TestScope {
1304 scope: resolve().unwrap(),
1305 })
1306 .unwrap()
1307 .join()
1308 .unwrap();
1309 let weak = Arc::downgrade(&scope.scope);
1310 assert!(weak.upgrade().is_some());
1311 drop(scope);
1312 assert!(weak.upgrade().is_none());
1313 }
1314}