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    pub fn new() -> Arc<TestTransport> {
53        Arc::new(TestTransport {
54            collected: Mutex::new(vec![]),
55        })
56    }
57
58    /// Fetches and clears the contained events.
59    pub fn fetch_and_clear_events(&self) -> Vec<Event<'static>> {
60        self.fetch_and_clear_envelopes()
61            .into_iter()
62            .filter_map(|envelope| envelope.event().cloned())
63            .collect()
64    }
65
66    /// Fetches and clears the contained envelopes.
67    pub fn fetch_and_clear_envelopes(&self) -> Vec<Envelope> {
68        let mut guard = self.collected.lock().unwrap();
69        std::mem::take(&mut *guard)
70    }
71}
72
73impl Transport for TestTransport {
74    fn send_envelope(&self, envelope: Envelope) {
75        self.collected.lock().unwrap().push(envelope);
76    }
77}
78
79/// Runs some code with the default test hub and returns the captured events.
80///
81/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
82pub fn with_captured_events<F: FnOnce()>(f: F) -> Vec<Event<'static>> {
83    with_captured_events_options(f, ClientOptions::default())
84}
85
86/// Runs some code with the default test hub with the given options and
87/// returns the captured events.
88///
89/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
90pub fn with_captured_events_options<F: FnOnce(), O: Into<ClientOptions>>(
91    f: F,
92    options: O,
93) -> Vec<Event<'static>> {
94    with_captured_envelopes_options(f, options)
95        .into_iter()
96        .filter_map(|envelope| envelope.event().cloned())
97        .collect()
98}
99
100/// Runs some code with the default test hub and returns the captured envelopes.
101///
102/// See [`with_captured_envelopes_options`](fn.with_captured_envelopes_options.html)
103pub fn with_captured_envelopes<F: FnOnce()>(f: F) -> Vec<Envelope> {
104    with_captured_envelopes_options(f, ClientOptions::default())
105}
106
107/// Runs some code with the default test hub with the given options and
108/// returns the captured envelopes.
109///
110/// If no DSN is set on the options a default test DSN is inserted.  The
111/// transport on the options is also overridden with a `TestTransport`.
112///
113/// This is a shortcut for creating a testable client with the supplied options
114/// and `TestTransport`, and bind it to a newly created hub for the duration of
115/// the call.
116pub fn with_captured_envelopes_options<F: FnOnce(), O: Into<ClientOptions>>(
117    f: F,
118    options: O,
119) -> Vec<Envelope> {
120    let transport = TestTransport::new();
121    let mut options = options.into();
122    options.dsn = Some(options.dsn.unwrap_or_else(|| TEST_DSN.clone()));
123    options.transport = Some(Arc::new(transport.clone()));
124    Hub::run(
125        Arc::new(Hub::new(
126            Some(Arc::new(options.into())),
127            Arc::new(Default::default()),
128        )),
129        f,
130    );
131    transport.fetch_and_clear_envelopes()
132}