Skip to content

Commit

Permalink
task(tests): create the client with MatrixMockServer::make_client()
Browse files Browse the repository at this point in the history
… instead of embedding one into the struct
  • Loading branch information
bnjbvr committed Nov 7, 2024
1 parent 9fe10da commit 8e73592
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 73 deletions.
43 changes: 21 additions & 22 deletions crates/matrix-sdk/src/test_utils/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,8 @@ use wiremock::{
use super::logged_in_client;
use crate::{Client, Room};

/// A `wiremock` server along with a client connected to it, with useful methods
/// to help mocking Matrix client-server API endpoints easily.
///
/// This is a pair of a [`MockServer`] and a [`Client]` (one can retrieve them
/// respectively with [`Self::server()`] and [`Self::client()`]).
/// A `wiremock` [`MockServer`] along with useful methods to help mocking Matrix
/// client-server API endpoints easily.
///
/// It implements mock endpoints, limiting the shared code as much as possible,
/// so the mocks are still flexible to use as scoped/unscoped mounts, named, and
Expand All @@ -63,7 +60,6 @@ use crate::{Client, Room};
/// mostly defers its implementations to [`wiremock::Mock`] under the hood.
pub struct MatrixMockServer {
server: MockServer,
client: Client,

/// Make the sync response builder stateful, to keep in memory the batch
/// token and avoid the client ignoring subsequent responses after the first
Expand All @@ -75,19 +71,19 @@ impl MatrixMockServer {
/// Create a new `wiremock` server specialized for Matrix usage.
pub async fn new() -> Self {
let server = MockServer::start().await;
let client = logged_in_client(Some(server.uri().to_string())).await;
Self { client, server, sync_response_builder: Default::default() }
Self { server, sync_response_builder: Default::default() }
}

/// Creates a new [`MatrixMockServer`] when both parts have been already
/// created.
pub fn from_parts(server: MockServer, client: Client) -> Self {
Self { client, server, sync_response_builder: Default::default() }
pub fn from_server(server: MockServer) -> Self {
Self { server, sync_response_builder: Default::default() }
}

/// Return the underlying client.
pub fn client(&self) -> Client {
self.client.clone()
/// Creates a new [`Client`] configured to use this server, preconfigured
/// with a session expected by the server endpoints.
pub async fn make_client(&self) -> Client {
logged_in_client(Some(self.server.uri().to_string())).await
}

/// Return the underlying server.
Expand All @@ -98,11 +94,16 @@ impl MatrixMockServer {
/// Overrides the sync/ endpoint with knowledge that the given
/// invited/joined/knocked/left room exists, runs a sync and returns the
/// given room.
pub async fn sync_room(&self, room_id: &RoomId, room_data: impl Into<AnyRoomBuilder>) -> Room {
pub async fn sync_room(
&self,
client: &Client,
room_id: &RoomId,
room_data: impl Into<AnyRoomBuilder>,
) -> Room {
let any_room = room_data.into();

self.mock_sync()
.ok_and_run(move |builder| match any_room {
.ok_and_run(client, move |builder| match any_room {
AnyRoomBuilder::Invited(invited) => {
builder.add_invited_room(invited);
}
Expand All @@ -118,13 +119,13 @@ impl MatrixMockServer {
})
.await;

self.client.get_room(room_id).expect("look at me, the room is known now")
client.get_room(room_id).expect("look at me, the room is known now")
}

/// Overrides the sync/ endpoint with knowledge that the given room exists
/// in the joined state, runs a sync and returns the given room.
pub async fn sync_joined_room(&self, room_id: &RoomId) -> Room {
self.sync_room(room_id, JoinedRoomBuilder::new(room_id)).await
pub async fn sync_joined_room(&self, client: &Client, room_id: &RoomId) -> Room {
self.sync_room(client, room_id, JoinedRoomBuilder::new(room_id)).await
}

/// Verify that the previous mocks expected number of requests match
Expand All @@ -144,7 +145,6 @@ impl MatrixMockServer {
.and(header("authorization", "Bearer 1234"));
MockSync {
mock,
client: self.client.clone(),
server: &self.server,
sync_response_builder: self.sync_response_builder.clone(),
}
Expand Down Expand Up @@ -360,15 +360,14 @@ pub struct MockSync<'a> {
mock: MockBuilder,
server: &'a MockServer,
sync_response_builder: Arc<Mutex<SyncResponseBuilder>>,
client: Client,
}

impl<'a> MockSync<'a> {
/// Temporarily mocks the sync with the given endpoint and runs a client
/// sync with it.
///
/// After calling this function, the sync endpoint isn't mocked anymore.
pub async fn ok_and_run<F: FnOnce(&mut SyncResponseBuilder)>(self, func: F) {
pub async fn ok_and_run<F: FnOnce(&mut SyncResponseBuilder)>(self, client: &Client, func: F) {
let json_response = {
let mut builder = self.sync_response_builder.lock().unwrap();
func(&mut builder);
Expand All @@ -381,7 +380,7 @@ impl<'a> MockSync<'a> {
.mount_as_scoped(self.server)
.await;

let _response = self.client.sync_once(Default::default()).await.unwrap();
let _response = client.sync_once(Default::default()).await.unwrap();
}
}

Expand Down
16 changes: 10 additions & 6 deletions crates/matrix-sdk/tests/integration/room/attachment/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ async fn test_room_attachment_send() {
.mount()
.await;

let room = mock.sync_joined_room(&DEFAULT_TEST_ROOM_ID).await;
let client = mock.make_client().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

let response = room
Expand Down Expand Up @@ -81,7 +82,8 @@ async fn test_room_attachment_send_info() {
.mount()
.await;

let room = mock.sync_joined_room(&DEFAULT_TEST_ROOM_ID).await;
let client = mock.make_client().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

let config = AttachmentConfig::new()
Expand Down Expand Up @@ -130,7 +132,8 @@ async fn test_room_attachment_send_wrong_info() {
.mount()
.await;

let room = mock.sync_joined_room(&DEFAULT_TEST_ROOM_ID).await;
let client = mock.make_client().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

// Here, using `AttachmentInfo::Video`…
Expand Down Expand Up @@ -188,7 +191,8 @@ async fn test_room_attachment_send_info_thumbnail() {
// Second request: return the media MXC.
mock.mock_upload().expect_mime_type("image/jpeg").ok(&media_mxc).mock_once().mount().await;

let room = mock.sync_joined_room(&DEFAULT_TEST_ROOM_ID).await;
let client = mock.make_client().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

// Preconditions: nothing is found in the cache.
Expand All @@ -199,7 +203,6 @@ async fn test_room_attachment_send_info_thumbnail() {
format: MediaFormat::Thumbnail(MediaThumbnailSettings::new(uint!(480), uint!(360))),
};

let client = mock.client();
let _ = client.media().get_media_content(&media_request, true).await.unwrap_err();
let _ = client.media().get_media_content(&thumbnail_request, true).await.unwrap_err();

Expand Down Expand Up @@ -283,7 +286,8 @@ async fn test_room_attachment_send_mentions() {
.mount()
.await;

let room = mock.sync_joined_room(&DEFAULT_TEST_ROOM_ID).await;
let client = mock.make_client().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

let response = room
Expand Down
8 changes: 5 additions & 3 deletions crates/matrix-sdk/tests/integration/room/joined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,10 +721,11 @@ async fn test_make_reply_event_doesnt_require_event_cache() {
// /event query to get details on an event.

let mock = MatrixMockServer::new().await;
let user_id = mock.client().user_id().unwrap().to_owned();
let client = mock.make_client().await;
let user_id = client.user_id().unwrap().to_owned();

let room_id = room_id!("!galette:saucisse.bzh");
let room = mock.sync_joined_room(room_id).await;
let room = mock.sync_joined_room(&client, room_id).await;

let event_id = event_id!("$1");
let f = EventFactory::new();
Expand All @@ -744,12 +745,13 @@ async fn test_make_reply_event_doesnt_require_event_cache() {
#[async_test]
async fn test_enable_encryption_doesnt_stay_unencrypted() {
let mock = MatrixMockServer::new().await;
let client = mock.make_client().await;

mock.mock_room_state_encryption().plain().mount().await;
mock.mock_set_room_state_encryption().ok(event_id!("$1")).mount().await;

let room_id = room_id!("!a:b.c");
let room = mock.sync_joined_room(room_id).await;
let room = mock.sync_joined_room(&client, room_id).await;

assert!(!room.is_encrypted().await.unwrap());

Expand Down
Loading

0 comments on commit 8e73592

Please sign in to comment.