1//! Miscellaneous test code for Zebra.
2#![doc(html_favicon_url = "https://zfnd.org/wp-content/uploads/2022/03/zebra-favicon-128.png")]
3#![doc(html_logo_url = "https://zfnd.org/wp-content/uploads/2022/03/zebra-icon.png")]
4#![doc(html_root_url = "https://docs.rs/zebra_test")]
5// Each lazy_static variable uses additional recursion
6#![recursion_limit = "512"]
78use std::sync::Once;
910use color_eyre::section::PanicMessage;
11use once_cell::sync::Lazy;
12use owo_colors::OwoColorize;
13use tracing_error::ErrorLayer;
14use tracing_subscriber::{fmt, prelude::*, EnvFilter};
1516#[allow(missing_docs)]
17pub mod command;
1819pub mod mock_service;
20pub mod net;
21pub mod network_addr;
22pub mod prelude;
23pub mod service_extensions;
24pub mod transcript;
25pub mod vectors;
26pub mod zip0143;
27pub mod zip0243;
28pub mod zip0244;
2930/// A single-threaded Tokio runtime that can be shared between tests.
31/// This runtime should be used for tests that need a single thread for consistent timings.
32///
33/// This shared runtime should be used in tests that use shared background tasks. An example is
34/// with shared global `Lazy<BatchVerifier>` types, because they spawn a background task when they
35/// are first initialized. This background task is stopped when the runtime is shut down, so having
36/// a runtime per test means that only the first test actually manages to successfully use the
37/// background task. Using the shared runtime allows the background task to keep running for the
38/// other tests that also use it.
39///
40/// A shared runtime should not be used in tests that need to pause and resume the Tokio timer.
41/// This is because multiple tests might be sharing the runtime at the same time, so there could be
42/// conflicts with pausing and resuming the timer at incorrect points. Even if only one test runs
43/// at a time, there's a risk of a test finishing while the timer is paused (due to a test failure,
44/// for example) and that means that the next test will already start with an incorrect timer
45/// state.
46pub static SINGLE_THREADED_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
47 tokio::runtime::Builder::new_current_thread()
48 .enable_all()
49 .build()
50 .expect("Failed to create Tokio runtime")
51});
5253/// A multi-threaded Tokio runtime that can be shared between tests.
54/// This runtime should be used for tests that spawn blocking threads.
55///
56/// See [`SINGLE_THREADED_RUNTIME`] for details.
57pub static MULTI_THREADED_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
58 tokio::runtime::Builder::new_multi_thread()
59 .enable_all()
60 .build()
61 .expect("Failed to create Tokio runtime")
62});
6364static INIT: Once = Once::new();
6566/// Initialize global and thread-specific settings for tests,
67/// such as tracing configs, panic hooks, and `cargo insta` settings.
68///
69/// This function should be called at the start of every test.
70///
71/// It returns a drop guard that must be stored in a variable, so that it
72/// gets dropped when the test finishes.
73#[must_use]
74pub fn init() -> impl Drop {
75// Per-test
7677 // Settings for threads that snapshots data using `insta`
7879let mut settings = insta::Settings::clone_current();
80 settings.set_prepend_module_to_snapshot(false);
81let drop_guard = settings.bind_to_scope();
8283// Globals
8485INIT.call_once(|| {
86let fmt_layer = fmt::layer().with_target(false);
87// Use the RUST_LOG env var, or by default:
88 // - warn for most tests, and
89 // - for some modules, hide expected warn logs
90let filter_layer = EnvFilter::try_from_default_env()
91 .unwrap_or_else(|_| {
92// These filters apply when RUST_LOG isn't set
93EnvFilter::try_new("warn")
94 .unwrap()
95 .add_directive("zebra_consensus=error".parse().unwrap())
96 .add_directive("zebra_network=error".parse().unwrap())
97 .add_directive("zebra_state=error".parse().unwrap())
98 .add_directive("zebrad=error".parse().unwrap())
99 .add_directive("tor_circmgr=error".parse().unwrap())
100 })
101// These filters apply on top of RUST_LOG.
102 // Avoid adding filters to this list, because users can't override them.
103 //
104 // (There are currently no always-on directives.)
105;
106107 tracing_subscriber::registry()
108 .with(filter_layer)
109 .with(fmt_layer)
110 .with(ErrorLayer::default())
111 .init();
112113 color_eyre::config::HookBuilder::default()
114 .add_frame_filter(Box::new(|frames| {
115let mut displayed = std::collections::HashSet::new();
116let filters = &[
117"tokio::",
118"<futures_util::",
119"std::panic",
120"test::run_test_in_process",
121"core::ops::function::FnOnce::call_once",
122"std::thread::local",
123"<core::future::",
124"<alloc::boxed::Box",
125"<std::panic::AssertUnwindSafe",
126"core::result::Result",
127"<T as futures_util",
128"<tracing_futures::Instrumented",
129"test::assert_test_result",
130"spandoc::",
131 ];
132133 frames.retain(|frame| {
134let loc = (frame.lineno, &frame.filename);
135let inserted = displayed.insert(loc);
136137if !inserted {
138return false;
139 }
140141 !filters.iter().any(|f| {
142let name = if let Some(name) = frame.name.as_ref() {
143 name.as_str()
144 } else {
145return true;
146 };
147148 name.starts_with(f)
149 })
150 });
151 }))
152 .panic_message(SkipTestReturnedErrPanicMessages)
153 .install()
154 .unwrap();
155 });
156157 drop_guard
158}
159160/// Initialize globals for tests that need a separate Tokio runtime instance.
161///
162/// This is generally used in proptests, which don't support the `#[tokio::test]` attribute.
163///
164/// If a runtime needs to be shared between tests, use the [`SINGLE_THREADED_RUNTIME`] or
165/// [`MULTI_THREADED_RUNTIME`] instances instead.
166///
167/// See also the [`init`] function, which is called by this function.
168pub fn init_async() -> (tokio::runtime::Runtime, impl Drop) {
169let drop_guard = init();
170171 (
172 tokio::runtime::Builder::new_current_thread()
173 .enable_all()
174 .build()
175 .expect("Failed to create Tokio runtime"),
176 drop_guard,
177 )
178}
179180struct SkipTestReturnedErrPanicMessages;
181182impl PanicMessage for SkipTestReturnedErrPanicMessages {
183fn display(
184&self,
185 pi: &std::panic::PanicHookInfo<'_>,
186 f: &mut std::fmt::Formatter<'_>,
187 ) -> std::fmt::Result {
188let payload = pi
189 .payload()
190 .downcast_ref::<String>()
191 .map(String::as_str)
192 .or_else(|| pi.payload().downcast_ref::<&str>().cloned())
193 .unwrap_or("<non string panic payload>");
194195// skip panic output that is clearly from tests that returned an `Err`
196 // and assume that the test handler has already printed the value inside
197 // of the `Err`.
198if payload.contains("the test returned a termination value with a non-zero status code") {
199return write!(f, "---- end of test output ----");
200 }
201202writeln!(f, "{}", "\nThe application panicked (crashed).".red())?;
203204write!(f, "Message: ")?;
205writeln!(f, "{}", payload.cyan())?;
206207// If known, print panic location.
208write!(f, "Location: ")?;
209if let Some(loc) = pi.location() {
210write!(f, "{}", loc.file().purple())?;
211write!(f, ":")?;
212write!(f, "{}", loc.line().purple())?;
213 } else {
214write!(f, "<unknown>")?;
215 }
216217Ok(())
218 }
219}