Skip to main content

larust_mail/
fake.rs

1use crate::Mailable;
2use std::sync::{Mutex, OnceLock};
3
4static FAKE_SENT: OnceLock<Mutex<Vec<SentMail>>> = OnceLock::new();
5
6/// Activates recording - every `send()` call for the rest of this
7/// process records instead of dispatching (log/smtp), regardless of
8/// `mail_driver`. Idempotent: a second call in the same process is a
9/// no-op (first-writer-wins, matching every other process-wide registry
10/// in this codebase - `larust_orm::connect()`, the route-name registry,
11/// the event-listener registry). The recorded list from the first
12/// activation keeps accumulating; nothing resets it.
13pub fn fake() {
14    FAKE_SENT.get_or_init(|| Mutex::new(Vec::new()));
15}
16
17/// Whether `fake()` has been called - `MailBuilder::send` checks this
18/// before building a `SentMail` at all, so the common, real-dispatch case
19/// (`fake()` never called) never pays for cloning the rendered body/
20/// recipients just to immediately drop them.
21pub(crate) fn is_active() -> bool {
22    FAKE_SENT.get().is_some()
23}
24
25/// A rendered, already-sent (recorded, not dispatched) email - the
26/// *output* of a `Mailable`, not the typed instance itself. Recording the
27/// instance would require `Mailable: 'static`, which would force every
28/// Mailable (including the real `WelcomeMail<'a>`, which borrows its
29/// `User`) to own its data instead of borrowing - a breaking constraint
30/// this design avoids entirely.
31#[derive(Debug, Clone)]
32pub struct SentMail {
33    pub(crate) mailable_type: &'static str,
34    pub to: Vec<String>,
35    pub subject: String,
36    pub html_body: String,
37}
38
39/// Records `mail` if `fake()` has been called; returns whether it did.
40/// `MailBuilder::send` uses the return value to decide whether to fall
41/// through to the real log/smtp dispatch - `false` (the common case,
42/// `fake()` never called) means recording didn't happen and nothing else
43/// about `send()`'s behavior changes.
44pub(crate) fn record(mail: SentMail) -> bool {
45    let Some(recorder) = FAKE_SENT.get() else {
46        return false;
47    };
48    recorder.lock().unwrap().push(mail);
49    true
50}
51
52/// Panics unless at least one recorded `M` satisfies `predicate`.
53///
54/// Computes its result and releases the `Mutex` guard *before* asserting -
55/// panicking with a lock still held would poison it (`std::sync::Mutex`
56/// poisons on an unwind through a held lock), breaking every later
57/// `assert_sent`/`assert_not_sent`/`send()` call in the same process with
58/// a confusing `PoisonError` instead of the real assertion failure.
59pub fn assert_sent<M: Mailable>(predicate: impl Fn(&SentMail) -> bool) {
60    let type_name = std::any::type_name::<M>();
61    let matching: Vec<SentMail> = {
62        let sent = FAKE_SENT
63            .get()
64            .expect("Mail::fake() was not called before assert_sent()")
65            .lock()
66            .unwrap();
67        sent.iter()
68            .filter(|mail| mail.mailable_type == type_name)
69            .cloned()
70            .collect()
71    };
72    assert!(
73        matching.iter().any(predicate),
74        "expected a `{type_name}` to have been sent matching the predicate, \
75         but none did (sent of this type: {matching:#?})"
76    );
77}
78
79/// Panics if any recorded `M` satisfies `predicate`. Same lock-then-drop-
80/// before-asserting shape as `assert_sent`, for the same reason.
81pub fn assert_not_sent<M: Mailable>(predicate: impl Fn(&SentMail) -> bool) {
82    let type_name = std::any::type_name::<M>();
83    let matched: bool = {
84        let sent = FAKE_SENT
85            .get()
86            .expect("Mail::fake() was not called before assert_not_sent()")
87            .lock()
88            .unwrap();
89        sent.iter()
90            .any(|mail| mail.mailable_type == type_name && predicate(mail))
91    };
92    assert!(
93        !matched,
94        "expected no `{type_name}` to have been sent matching the predicate, but one did"
95    );
96}
97
98#[cfg(test)]
99mod tests {
100    use crate::mail;
101
102    // All scenarios live in one `#[tokio::test]` fn, not several - every
103    // scenario shares the one process-wide `FAKE_SENT` list (it's never
104    // reset, by design; see `fake()`'s own doc comment), and separate
105    // `#[test]`/`#[tokio::test]` fns in one binary aren't guaranteed to
106    // run in any particular order or without overlapping (same
107    // constraint `larust-testing/tests/db_test.rs` documents). Distinct
108    // dummy `Mailable` types per scenario keep them isolated from each
109    // other via `assert_sent`/`assert_not_sent`'s own type-based
110    // filtering, the same way `larust-events`' `dispatch_test.rs` used
111    // distinct event types to prove type isolation.
112
113    struct Greeting;
114    impl crate::Mailable for Greeting {
115        fn subject(&self) -> String {
116            "Hello".to_string()
117        }
118        fn html_body(&self) -> String {
119            "<p>Hi</p>".to_string()
120        }
121    }
122
123    struct Farewell;
124    impl crate::Mailable for Farewell {
125        fn subject(&self) -> String {
126            "Goodbye".to_string()
127        }
128        fn html_body(&self) -> String {
129            "<p>Bye</p>".to_string()
130        }
131    }
132
133    struct Reminder;
134    impl crate::Mailable for Reminder {
135        fn subject(&self) -> String {
136            "Don't forget".to_string()
137        }
138        fn html_body(&self) -> String {
139            "<p>Reminder</p>".to_string()
140        }
141    }
142
143    #[tokio::test]
144    async fn fake_mode_records_instead_of_dispatching_and_assertions_work() {
145        // Calling `fake()` and `send()` here, with `larust_core::config()`
146        // never having been populated by an `Application::new()` call
147        // anywhere in this test binary, and this *not* panicking, is
148        // itself the proof that `send()`'s real log/smtp dispatch (which
149        // reads `config()` and would panic without it) was never reached
150        // - the fake short-circuit happens first.
151        super::fake();
152
153        mail().to("alice@example.com").send(Greeting).await.unwrap();
154
155        // A matching recorded `Greeting` is found.
156        super::assert_sent::<Greeting>(|sent| sent.to == vec!["alice@example.com".to_string()]);
157
158        // A `Greeting` was sent, but not to this address.
159        let result = std::panic::catch_unwind(|| {
160            super::assert_sent::<Greeting>(|sent| sent.to == vec!["bob@example.com".to_string()]);
161        });
162        assert!(
163            result.is_err(),
164            "assert_sent should panic when no recorded mail matches the predicate"
165        );
166
167        // No `Farewell` was ever sent - type isolation from `Greeting`.
168        let result = std::panic::catch_unwind(|| {
169            super::assert_sent::<Farewell>(|_| true);
170        });
171        assert!(
172            result.is_err(),
173            "assert_sent should panic for a type nothing was ever sent as"
174        );
175        super::assert_not_sent::<Farewell>(|_| true);
176
177        // `assert_not_sent` for `Greeting` itself panics, since one *was*
178        // sent matching this always-true predicate.
179        let result = std::panic::catch_unwind(|| {
180            super::assert_not_sent::<Greeting>(|_| true);
181        });
182        assert!(
183            result.is_err(),
184            "assert_not_sent should panic when a matching mail was in fact sent"
185        );
186
187        // `.queue()` folds into the exact same recorded list as `.send()`
188        // under fake mode - there's no separate `assertQueued` concept
189        // yet (see `docs/ARCHITECTURE.md`'s Mail section). Reaching this
190        // without a `larust_queue::dispatch()` call ever touching a real
191        // (nonexistent, in this test) database is itself the proof that
192        // `.queue()`'s fake short-circuit, like `.send()`'s, happens
193        // before the real dispatch path.
194        mail()
195            .to("carol@example.com")
196            .queue(Reminder)
197            .await
198            .unwrap();
199        super::assert_sent::<Reminder>(|sent| sent.to == vec!["carol@example.com".to_string()]);
200    }
201}