relay_test/
lib.rs

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