Skip to main content

matrix_sdk_test/
lib.rs

1use std::{fmt, sync::LazyLock};
2
3use http::Response;
4pub use matrix_sdk_test_macros::async_test;
5use ruma::{
6    RoomId,
7    api::{IncomingResponse, IncomingResponseExt as _, OutgoingResponse, OutgoingResponseExt as _},
8    room_id,
9    serde::{Base64, base64::UrlSafe},
10};
11use sha2::{Digest, Sha256};
12
13/// Create a `Raw<AnyMessageLikeEventContent>` from arbitrary JSON.
14///
15/// Forwards all arguments to [`serde_json::json`].
16#[macro_export]
17macro_rules! message_like_event_content {
18    ($( $tt:tt )*) => {
19        ::ruma::serde::Raw::new(&::serde_json::json!( $($tt)* ))
20            .unwrap()
21            .cast_unchecked::<::ruma::events::AnyMessageLikeEventContent>()
22    }
23}
24
25/// Create a `Raw<AnyTimelineEvent>` from arbitrary JSON.
26///
27/// Forwards all arguments to [`serde_json::json`].
28#[macro_export]
29macro_rules! timeline_event {
30    ($( $tt:tt )*) => {
31        ::ruma::serde::Raw::new(&::serde_json::json!( $($tt)* ))
32            .unwrap()
33            .cast_unchecked::<::ruma::events::AnyTimelineEvent>()
34    }
35}
36
37/// Create a `Raw<AnySyncTimelineEvent>` from arbitrary JSON.
38///
39/// Forwards all arguments to [`serde_json::json`].
40#[macro_export]
41macro_rules! sync_timeline_event {
42    ($( $tt:tt )*) => {
43        ::ruma::serde::Raw::new(&::serde_json::json!( $($tt)* ))
44            .unwrap()
45            .cast_unchecked::<::ruma::events::AnySyncTimelineEvent>()
46    }
47}
48
49/// Create a `Raw<AnySyncStateEvent>` from arbitrary JSON.
50///
51/// Forwards all arguments to [`serde_json::json`].
52#[macro_export]
53macro_rules! sync_state_event {
54    ($( $tt:tt )*) => {
55        ::ruma::serde::Raw::new(&::serde_json::json!( $($tt)* ))
56            .unwrap()
57            .cast_unchecked::<::ruma::events::AnySyncStateEvent>()
58    }
59}
60
61/// Create a `Raw<AnyStrippedStateEvent>` from arbitrary JSON.
62///
63/// Forwards all arguments to [`serde_json::json`].
64#[macro_export]
65macro_rules! stripped_state_event {
66    ($( $tt:tt )*) => {
67        ::ruma::serde::Raw::new(&::serde_json::json!( $($tt)* ))
68            .unwrap()
69            .cast_unchecked::<::ruma::events::AnyStrippedStateEvent>()
70    }
71}
72
73pub mod event_factory;
74mod identifiers;
75pub mod notification_settings;
76mod sync_builder;
77pub mod test_json;
78
79pub use self::{
80    identifiers::*,
81    sync_builder::{
82        InvitedRoomBuilder, JoinedRoomBuilder, KnockedRoomBuilder, LeftRoomBuilder,
83        SyncResponseBuilder, bulk_room_members,
84    },
85};
86
87/// The default room ID for tests.
88pub static DEFAULT_TEST_ROOM_ID: LazyLock<&RoomId> =
89    LazyLock::new(|| room_id!("!SVkFJHzfwvuaIEawgC:localhost"));
90
91/// Build a typed Ruma [`IncomingResponse`] object from a json body.
92pub fn ruma_response_from_json<ResponseType: IncomingResponse>(
93    json: &serde_json::Value,
94) -> ResponseType {
95    let json_bytes = serde_json::to_vec(json).expect("JSON-serialization of response value failed");
96    let http_response = Response::builder()
97        .status(200)
98        .body(json_bytes.as_slice())
99        .expect("Failed to build HTTP response");
100    ResponseType::try_from_http_response(http_response).expect("Can't parse the response json")
101}
102
103/// Serialise a typed Ruma [`OutgoingResponse`] object to JSON.
104pub fn ruma_response_to_json<ResponseType: OutgoingResponse>(
105    response: ResponseType,
106) -> serde_json::Value {
107    let http_response: Response<Vec<u8>> =
108        response.try_into_http_response().expect("Failed to build HTTP response");
109    let json_bytes = http_response.into_body();
110    serde_json::from_slice(&json_bytes).expect("Can't parse the response JSON")
111}
112
113#[derive(Debug)] // required to be able to return TestResult from #[test] fns
114pub enum TestError {}
115
116// If this was just `T: Debug`, it would conflict with
117// the `impl From<T> for T` in `std`.
118//
119// Adding a dummy `Display` bound works around this.
120impl<T: fmt::Display + fmt::Debug> From<T> for TestError {
121    #[track_caller]
122    fn from(value: T) -> Self {
123        panic!("error: {value:?}")
124    }
125}
126
127pub type TestResult = Result<(), TestError>;
128
129/// Compute the sha256 hash of the given bytes and convert it to unpadded
130/// URL-safe base64.
131///
132/// This matches the format of event IDs since room version 4, and of room IDs
133/// since room version 12.
134pub fn base64_sha256_hash(bytes: &[u8]) -> String {
135    Base64::<UrlSafe, _>::new(Sha256::digest(bytes)).encode()
136}