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