Skip to content

Commit

Permalink
Adjust test to use new/updated mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
toger5 committed Nov 25, 2024
1 parent 1b8cf17 commit a7d0264
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 63 deletions.
49 changes: 30 additions & 19 deletions crates/matrix-sdk/src/test_utils/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ use matrix_sdk_test::{
};
use ruma::{
directory::PublicRoomsChunk,
events::{MessageLikeEventType, StateEventType},
events::{AnyStateEvent, AnyTimelineEvent, MessageLikeEventType, StateEventType},
serde::Raw,
MxcUri, OwnedEventId, OwnedRoomId, RoomId, ServerName,
};
use serde::Deserialize;
Expand Down Expand Up @@ -344,7 +345,7 @@ impl MatrixMockServer {
///
/// let event_id = event_id!("$some_id");
/// mock_server
/// .mock_send_room_state()
/// .mock_room_send_state()
/// .ok(event_id)
/// .expect(1)
/// .mount()
Expand All @@ -368,7 +369,7 @@ impl MatrixMockServer {
let mock = Mock::given(method("PUT"))
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/.*"))
.and(header("authorization", "Bearer 1234"));
MockEndpoint { mock, server: &self.server, endpoint: RoomSendStateEndpoint::new() }
MockEndpoint { mock, server: &self.server, endpoint: RoomSendStateEndpoint::default() }
}

/// Creates a prebuilt mock for asking whether *a* room is encrypted or not.
Expand Down Expand Up @@ -495,7 +496,7 @@ impl MatrixMockServer {
if let Some(l) = limit {
mock = mock.and(query_param("limit", l.to_string()));
}
MockEndpoint { mock, server: &self.server, endpoint: RoomMessagesEndpoint {} }
MockEndpoint { mock, server: &self.server, endpoint: RoomMessagesEndpoint }
}

/// Create a prebuilt mock for uploading media.
Expand Down Expand Up @@ -902,7 +903,7 @@ impl<'a> MockEndpoint<'a, RoomSendEndpoint> {
/// .mount()
/// .await;
/// mock_server
/// .mock_send_room_state()
/// .mock_room_send_state()
/// .for_type("m.room.message".into())
/// .ok(event_id)
/// .expect(1)
Expand Down Expand Up @@ -973,24 +974,19 @@ impl<'a> MockEndpoint<'a, RoomSendEndpoint> {
}

/// A prebuilt mock for sending a state event in a room.
#[derive(Default)]
pub struct RoomSendStateEndpoint {
state_key: Option<String>,
event_type: Option<StateEventType>,
}
impl RoomSendStateEndpoint {
/// Create new RoomSendStateEndpoint with unset state_key and event_type.
pub fn new() -> Self {
Self { state_key: None, event_type: None }
}
}

impl<'a> MockEndpoint<'a, RoomSendStateEndpoint> {
fn generate_path_regex(endpoint: &RoomSendStateEndpoint) -> String {
return format!(
format!(
r"^/_matrix/client/v3/rooms/.*/state/{}/{}",
endpoint.event_type.as_ref().map(|t| t.to_string()).unwrap_or(".*".to_owned()),
endpoint.state_key.as_ref().map(|k| k.to_string()).unwrap_or(".*".to_owned())
);
)
}
/// Ensures that the body of the request is a superset of the provided
/// `body` parameter.
Expand Down Expand Up @@ -1381,9 +1377,22 @@ pub struct RoomMessagesEndpoint;
impl<'a> MockEndpoint<'a, RoomMessagesEndpoint> {
/// Returns a messages endpoint that emulates success, i.e. the messages
/// provided as `response` could be retrieved.
pub fn ok(self, response: impl Into<Value>) -> MatrixMock<'a> {
let body: Value = response.into();
let mock = self.mock.respond_with(ResponseTemplate::new(200).set_body_json(body));
///
/// Note: pass `chunk` in the correct order: topological for forward
/// pagination, reverse topological for backwards pagination.
pub fn ok(
self,
start: String,
end: Option<String>,
chunk: Vec<impl Into<Raw<AnyTimelineEvent>>>,
state: Vec<impl Into<Raw<AnyStateEvent>>>,
) -> MatrixMock<'a> {
let mock = self.mock.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"start": start,
"end": end,
"chunk": chunk.into_iter().map(|ev| ev.into()).collect::<Vec<_>>(),
"state": state.into_iter().map(|ev| ev.into()).collect::<Vec<_>>(),
})));
MatrixMock { server: self.server, mock }
}
}
Expand Down Expand Up @@ -1552,10 +1561,12 @@ mod tests {
use crate::{
ruma::{
event_id,
events::room::{
create::RoomCreateEventContent, power_levels::RoomPowerLevelsEventContent,
events::{
room::{
create::RoomCreateEventContent, power_levels::RoomPowerLevelsEventContent,
},
StateEventType,
},
events::StateEventType,
room_id,
},
test_utils::mocks::MatrixMockServer,
Expand Down
1 change: 1 addition & 0 deletions crates/matrix-sdk/tests/integration/event_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ async fn test_ignored_unignored() {
/// Puts a mounting point for /messages for a pagination request, matching
/// against a precise `from` token given as `expected_from`, and returning the
/// chunk of events and the next token as `end` (if available).
// TODO: replace this with the `mock_room_messages` form mocks.rs
async fn mock_messages(
server: &MockServer,
expected_from: &str,
Expand Down
68 changes: 24 additions & 44 deletions crates/matrix-sdk/tests/integration/widget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ use matrix_sdk::{
Client,
};
use matrix_sdk_common::{executor::spawn, timeout::timeout};
use matrix_sdk_test::{async_test, EventBuilder, JoinedRoomBuilder, ALICE, BOB};
use matrix_sdk_test::{
async_test, event_factory::EventFactory, EventBuilder, JoinedRoomBuilder, ALICE, BOB,
};
use once_cell::sync::Lazy;
use ruma::{
event_id,
Expand All @@ -36,10 +38,10 @@ use ruma::{
name::RoomNameEventContent,
topic::RoomTopicEventContent,
},
StateEventType,
AnyStateEvent, StateEventType,
},
owned_room_id,
serde::JsonObject,
serde::{JsonObject, Raw},
user_id, OwnedRoomId,
};
use serde::Serialize;
Expand Down Expand Up @@ -300,46 +302,22 @@ async fn test_read_messages_with_msgtype_capabilities() {
// No messages from the driver
assert_matches!(recv_message(&driver_handle).now_or_never(), None);

{
let response_json = json!({
"chunk": [
{
"content": {
"body": "custom content",
"msgtype": "m.custom.element",
},
"event_id": "$msda7m0df9E9op3",
"origin_server_ts": 152037220,
"sender": "@example:localhost",
"type": "m.room.message",
"room_id": &*ROOM_ID,
},
{
"content": {
"body": "hello",
"msgtype": "m.text",
},
"event_id": "$msda7m0df9E9op5",
"origin_server_ts": 152037280,
"sender": "@example:localhost",
"type": "m.room.message",
"room_id": &*ROOM_ID,
},
{
"content": {
},
"event_id": "$msda7m0df9E9op7",
"origin_server_ts": 152037290,
"sender": "@example:localhost",
"type": "m.reaction",
"room_id": &*ROOM_ID,
},
],
"end": "t47409-4357353_219380_26003_2269",
"start": "t392-516_47314_0_7_1_1_1_11444_1"
});
let f = EventFactory::new().room(&*ROOM_ID).sender(user_id!("@example:localhost"));

mock_server.mock_room_messages(Some(3)).ok(response_json).mock_once().mount().await;
{
let start = "t392-516_47314_0_7_1_1_1_11444_1".to_owned();
let end = Some("t47409-4357353_219380_26003_2269".to_owned());
let chun2 = vec![
f.notice("custom content").event_id(event_id!("$msda7m0df9E9op3")).into_raw_timeline(),
f.text_msg("hello").event_id(event_id!("$msda7m0df9E9op5")).into_raw_timeline(),
f.reaction(event_id!("$event_id"), "annotation".to_string()).into_raw_timeline(),
];
mock_server
.mock_room_messages(Some(3))
.ok(start, end, chun2, Vec::<Raw<AnyStateEvent>>::new())
.mock_once()
.mount()
.await;

// Ask the driver to read messages
send_request(
Expand Down Expand Up @@ -506,7 +484,8 @@ async fn test_send_room_message() {
.await;

mock_server
.mock_room_send_for_type("m.room.message".into())
.mock_room_send()
.for_type("m.room.message".into())
.ok(event_id!("$foobar"))
.mock_once()
.mount()
Expand Down Expand Up @@ -547,7 +526,8 @@ async fn test_send_room_name() {
.await;

mock_server
.mock_room_state_for_type(StateEventType::RoomName)
.mock_room_send_state()
.for_type(StateEventType::RoomName)
.ok(event_id!("$foobar"))
.mock_once()
.mount()
Expand Down

0 comments on commit a7d0264

Please sign in to comment.