relay_test/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
//! Helpers for testing the web server and services.
//!
//! When writing tests, keep the following points in mind:
//!
//! - In every test, call [`setup`]. This will set up the logger so that all console output is
//! captured by the test runner. All logs emitted with [`relay_log`] will show up for test
//! failures or when run with `--nocapture`.
//!
//! # Example
//!
//! ```no_run
//! #[test]
//! fn my_test() {
//! relay_test::setup();
//!
//! relay_log::debug!("hello, world!");
//! }
//! ```
#![doc(
html_logo_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png",
html_favicon_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png"
)]
#![allow(clippy::derive_partial_eq_without_eq)]
use relay_system::{channel, Addr, Interface};
use tokio::task::JoinHandle;
/// Setup the test environment.
///
/// - Initializes logs: The logger only captures logs from this crate and mutes all other logs.
pub fn setup() {
relay_log::init_test!();
}
/// Spawns a mock service that handles messages through a closure.
///
/// Note: Addr must be dropped before handle can be awaited.
pub fn mock_service<S, I, F>(name: &'static str, mut state: S, mut f: F) -> (Addr<I>, JoinHandle<S>)
where
S: Send + 'static,
I: Interface,
F: FnMut(&mut S, I) + Send + 'static,
{
let (addr, mut rx) = channel(name);
let handle = relay_system::spawn!(async move {
while let Some(msg) = rx.recv().await {
f(&mut state, msg);
}
state
});
(addr, handle)
}