Skip to main content

elfo_test/
utils.rs

1use elfo_core::{msg, Envelope, Message, Request, ResponseToken};
2
3/// Extracts message with the provided type from [`Envelope`], panics otherwise.
4#[track_caller]
5pub fn extract_message<M: Message>(envelope: Envelope) -> M {
6    msg!(match envelope {
7        msg @ M => msg,
8        msg => panic!(
9            r#"expected {}, got {:#?}"#,
10            elfo_core::dumping::extract_name_by_type::<M>(),
11            msg.message()
12        ),
13    })
14}
15
16/// Extracts request message with the provided type from [`Envelope`], panics
17/// otherwise.
18#[track_caller]
19pub fn extract_request<R: Request>(envelope: Envelope) -> (R, ResponseToken<R>) {
20    msg!(match envelope {
21        (req @ R, token) => (req, token),
22        msg => panic!(
23            r#"expected {}, got {:#?}"#,
24            elfo_core::dumping::extract_name_by_type::<R>(),
25            msg.message()
26        ),
27    })
28}
29
30#[cfg(test)]
31mod tests {
32    use elfo_core::{_priv::MessageKind, message, scope::Scope, ActorMeta, Addr};
33
34    use super::*;
35
36    #[message]
37    #[derive(PartialEq)]
38    struct TestMessage;
39
40    #[message(ret = ())]
41    #[derive(PartialEq)]
42    struct TestRequest;
43
44    #[test]
45    fn extract_message_test() {
46        create_scope().sync_within(|| {
47            let envelop = Envelope::new(TestMessage, MessageKind::regular(Addr::NULL));
48            let resp = extract_message::<TestMessage>(envelop);
49            assert_eq!(resp, TestMessage);
50        });
51    }
52
53    #[test]
54    #[should_panic(expected = "expected TestMessage, got TestRequest")]
55    fn extract_message_panic_test() {
56        create_scope().sync_within(|| {
57            let envelop = Envelope::new(TestRequest, MessageKind::regular(Addr::NULL));
58            extract_message::<TestMessage>(envelop);
59        });
60    }
61
62    #[test]
63    fn extract_request_test() {
64        create_scope().sync_within(|| {
65            let envelop = Envelope::new(TestRequest, MessageKind::regular(Addr::NULL));
66            let (resp, _token) = extract_request::<TestRequest>(envelop);
67            assert_eq!(resp, TestRequest);
68        });
69    }
70
71    fn create_scope() -> Scope {
72        Scope::test(
73            Addr::NULL,
74            ActorMeta {
75                group: "group".into(),
76                key: "key".into(),
77            }
78            .into(),
79        )
80    }
81}