Skip to content

Commit

Permalink
task(tests): add a MockClientBuilder to help with creating Client
Browse files Browse the repository at this point in the history
…s connected to a `MatrixMockServer`
  • Loading branch information
bnjbvr committed Nov 12, 2024
1 parent c097989 commit 1358d6a
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 61 deletions.
74 changes: 66 additions & 8 deletions crates/matrix-sdk/src/test_utils/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,23 @@

use std::sync::{Arc, Mutex};

use matrix_sdk_base::deserialized_responses::TimelineEvent;
use matrix_sdk_base::{deserialized_responses::TimelineEvent, store::StoreConfig, SessionMeta};
use matrix_sdk_test::{
test_json, InvitedRoomBuilder, JoinedRoomBuilder, KnockedRoomBuilder, LeftRoomBuilder,
SyncResponseBuilder,
};
use ruma::{MxcUri, OwnedEventId, OwnedRoomId, RoomId};
use ruma::{api::MatrixVersion, device_id, user_id, MxcUri, OwnedEventId, OwnedRoomId, RoomId};
use serde_json::json;
use wiremock::{
matchers::{body_partial_json, header, method, path, path_regex},
Mock, MockBuilder, MockGuard, MockServer, Respond, ResponseTemplate, Times,
};

use super::logged_in_client;
use crate::{Client, Room};
use crate::{
config::RequestConfig,
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client, ClientBuilder, Room,
};

/// A `wiremock` [`MockServer`] along with useful methods to help mocking Matrix
/// client-server API endpoints easily.
Expand Down Expand Up @@ -80,10 +83,10 @@ impl MatrixMockServer {
Self { server, sync_response_builder: Default::default() }
}

/// 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
/// Creates a new [`MockClientBuilder`] configured to use this server,
/// preconfigured with a session expected by the server endpoints.
pub fn client_builder(&self) -> MockClientBuilder {
MockClientBuilder::new(self.server.uri())
}

/// Return the underlying server.
Expand Down Expand Up @@ -543,3 +546,58 @@ impl<'a> MockEndpoint<'a, CreateRoomAliasEndpoint> {
MatrixMock { server: self.server, mock }
}
}

/// An augmented [`ClientBuilder`] that also allows for handling session login.
pub struct MockClientBuilder {
builder: ClientBuilder,
logged_in: bool,
}

impl MockClientBuilder {
fn new(homeserver: String) -> Self {
let default_builder = Client::builder()
.homeserver_url(homeserver)
.server_versions([MatrixVersion::V1_0])
.request_config(RequestConfig::new().disable_retry());

Self { builder: default_builder, logged_in: true }
}

/// Doesn't log-in a user.
///
/// Authenticated requests will fail if this is called.
pub fn unlogged(mut self) -> Self {
self.logged_in = false;
self
}

/// Provides another [`StoreConfig`] for the underlying [`ClientBuilder`].
pub fn store_config(mut self, store_config: StoreConfig) -> Self {
self.builder = self.builder.store_config(store_config);
self
}

/// Finish building the client into the final [`Client`] instance.
pub async fn build(self) -> Client {
let client = self.builder.build().await.expect("building client failed");

if self.logged_in {
client
.matrix_auth()
.restore_session(MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),
},
tokens: MatrixSessionTokens {
access_token: "1234".to_owned(),
refresh_token: None,
},
})
.await
.unwrap();
}

client
}
}
10 changes: 5 additions & 5 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,7 @@ async fn test_room_attachment_send() {
.mount()
.await;

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

Expand Down Expand Up @@ -82,7 +82,7 @@ async fn test_room_attachment_send_info() {
.mount()
.await;

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

Expand Down Expand Up @@ -132,7 +132,7 @@ async fn test_room_attachment_send_wrong_info() {
.mount()
.await;

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

Expand Down Expand Up @@ -191,7 +191,7 @@ 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 client = mock.make_client().await;
let client = mock.client_builder().build().await;
let room = mock.sync_joined_room(&client, &DEFAULT_TEST_ROOM_ID).await;
mock.mock_room_state_encryption().plain().mount().await;

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

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

Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk/tests/integration/room/joined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,7 @@ async fn test_make_reply_event_doesnt_require_event_cache() {
// /event query to get details on an event.

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

let room_id = room_id!("!galette:saucisse.bzh");
Expand All @@ -745,7 +745,7 @@ 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;
let client = mock.client_builder().build().await;

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

0 comments on commit 1358d6a

Please sign in to comment.