Skip to main content

sentry_core/
test.rs

1//! This provides testing functionality for building tests.
2//!
3//! **Feature:** `test` (*disabled by default*)
4//!
5//! If the sentry crate has been compiled with the test support feature this
6//! module becomes available and provides functionality to capture events
7//! in a block.
8//!
9//! # Example usage
10//!
11//! ```
12//! use sentry::test::with_captured_events;
13//! use sentry::{capture_message, Level};
14//!
15//! let events = with_captured_events(|| {
16//!     capture_message("Hello World!", Level::Warning);
17//! });
18//! assert_eq!(events.len(), 1);
19//! assert_eq!(events[0].message.as_ref().unwrap(), "Hello World!");
20//! ```
21
22use std::sync::{Arc, LazyLock, Mutex};
23
24use crate::protocol::Event;
25use crate::types::Dsn;
26use crate::{ClientOptions, Envelope, Hub, Transport};
27
28static TEST_DSN: LazyLock<Dsn> =
29    LazyLock::new(|| "https://public@sentry.invalid/1".parse().unwrap());
30
31/// Collects events instead of sending them.
32///
33/// # Examples
34///
35/// ```
36/// use sentry::test::TestTransport;
37/// use sentry::{ClientOptions, Hub};
38/// use std::sync::Arc;
39///
40/// let transport = TestTransport::new();
41/// let options = ClientOptions::new()
42///     .dsn("https://public@example.com/1")
43///     .transport(transport.clone());
44/// Hub::current().bind_client(Some(Arc::new(options.into())));
45/// ```
46pub struct TestTransport {
47    collected: Mutex<Vec<Envelope>>,
48}
49
50impl TestTransport {
51    /// Creates a new test transport.
52    #[allow(clippy::new_ret_no_self)]
53    pub fn new() -> Arc<TestTransport> {
54        Arc::new(TestTransport {
55            collected: Mutex::new(vec![]),
56        })
57    }
58
59    /// Fetches and clears the contained events.
60    pub fn fetch_and_clear_events(&self) -> Vec<Event<'static>> {
61        self.fetch_and_clear_envelopes()
62            .into_iter()
63            .filter_map(|envelope| envelope.event().cloned())
64            .collect()
65    }
66
67    /// Fetches and clears the contained envelopes.
68    pub fn fetch_and_clear_envelopes(&self) -> Vec<Envelope> {
69        let mut guard = self.collected.lock().unwrap();
70        std::mem::take(&mut *guard)
71    }
72}
73
74impl Transport for TestTransport {
75    fn send_envelope(&self, envelope: Envelope) {
76        self.collected.lock().unwrap().push(envelope);
77    }
78}
79
80/// Runs some code with the default test hub and returns the captured events.
81///
82/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
83pub fn with_captured_events<F: FnOnce()>(f: F) -> Vec<Event<'static>> {
84    with_captured_events_options(f, ClientOptions::default())
85}
86
87/// Runs some code with the default test hub with the given options and
88/// returns the captured events.
89///
90/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
91pub fn with_captured_events_options<F: FnOnce(), O: Into<ClientOptions>>(
92    f: F,
93    options: O,
94) -> Vec<Event<'static>> {
95    with_captured_envelopes_options(f, options)
96        .into_iter()
97        .filter_map(|envelope| envelope.event().cloned())
98        .collect()
99}
100
101/// Runs some code with the default test hub and returns the captured envelopes.
102///
103/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
104pub fn with_captured_envelopes<F: FnOnce()>(f: F) -> Vec<Envelope> {
105    with_captured_envelopes_options(f, ClientOptions::default())
106}
107
108/// Runs some code with the default test hub with the given options and
109/// returns the captured envelopes.
110///
111/// If no DSN is set on the options a default test DSN is inserted.  The
112/// transport on the options is also overridden with a `TestTransport`.
113///
114/// This is a shortcut for creating a testable client with the supplied options
115/// and `TestTransport`, and bind it to a newly created hub for the duration of
116/// the call.
117pub fn with_captured_envelopes_options<F: FnOnce(), O: Into<ClientOptions>>(
118    f: F,
119    options: O,
120) -> Vec<Envelope> {
121    let transport = TestTransport::new();
122    let mut options = options.into();
123    options.dsn = Some(options.dsn.unwrap_or_else(|| TEST_DSN.clone()));
124    options.transport = Some(Arc::new(transport.clone()));
125    Hub::run(
126        Arc::new(Hub::new(
127            Some(Arc::new(options.into())),
128            Arc::new(Default::default()),
129        )),
130        f,
131    );
132    transport.fetch_and_clear_envelopes()
133}