Struct MatrixMockServer

Source
pub struct MatrixMockServer { /* private fields */ }
Available on crate feature testing and non-target_family="wasm" only.
Expand description

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 so on.

It works like this:

  • start by saying which endpoint you’d like to mock, e.g. Self::mock_room_send(). This returns a specialized MockEndpoint data structure, with its own impl. For this example, it’s MockEndpoint<RoomSendEndpoint>.
  • configure the response on the endpoint-specific mock data structure. For instance, if you want the sending to result in a transient failure, call MockEndpoint::error500; if you want it to succeed and return the event $42, call MockEndpoint::ok(). It’s still possible to call MockEndpoint::respond_with(), as we do with wiremock MockBuilder, for maximum flexibility when the helpers aren’t sufficient.
  • once the endpoint’s response is configured, for any mock builder, you get a MatrixMock; this is a plain wiremock::Mock with the server curried, so one doesn’t have to pass it around when calling MatrixMock::mount() or MatrixMock::mount_as_scoped(). As such, it mostly defers its implementations to wiremock::Mock under the hood.

§Examples

use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use serde_json::json;

// First create the mock server and client pair.
let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

// Let's say that our rooms are not encrypted.
mock_server.mock_room_state_encryption().plain().mount().await;

// Let us get a room where we will send an event.
let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

// Now we mock the endpoint so we can actually send the event.
let event_id = event_id!("$some_id");
let send_guard = mock_server
    .mock_room_send()
    .ok(event_id)
    .expect(1)
    .mount_as_scoped()
    .await;

// And we send it out.
let response = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;

assert_eq!(
    event_id,
    response.event_id,
    "The event ID we mocked should match the one we received when we sent the event"
);

Implementations§

Source§

impl MatrixMockServer

Extends the MatrixMockServer with useful methods to help mocking matrix crypto API and perform integration test with encryption.

It implements mock endpoints for the keys/upload, will store the uploaded devices and serves them back for incoming keys/query. It is also storing and claiming one-time-keys, allowing to set up working olm sessions.

Adds some helpers like exhaust_one_time_keys that allows to simulate a client running out of otks. More can be added if needed later.

It works like this:

The MatrixMockServer::set_up_alice_and_bob_for_encryption will set up two olm machines aware of each other and ready to communicate.

Source

pub fn client_builder_for_crypto_end_to_end( &self, user_id: &UserId, device_id: &DeviceId, ) -> MockClientBuilder

Available on crate feature e2e-encryption only.

Creates a new MockClientBuilder configured to use this server and suitable for usage of the crypto API end points. Will create a specific access token and some mapping to the associated user_id.

Source

pub fn exhaust_one_time_keys( &self, user_id: OwnedUserId, device_id: OwnedDeviceId, )

Available on crate feature e2e-encryption only.

Makes the server forget about all the one-time-keys for that device.

Source

pub async fn exchange_e2ee_identities(&self, alice: &Client, bob: &Client)

Available on crate feature e2e-encryption only.

Ensure that the given clients are aware of each others public identities.

Source

pub async fn set_up_alice_and_bob_for_encryption(&self) -> (Client, Client)

Available on crate feature e2e-encryption only.

Utility to properly setup two clients. These two clients will know about each others (alice will have downloaded bob device keys).

Source

pub async fn set_up_carl_for_encryption( &self, alice: &Client, bob: &Client, ) -> Client

Available on crate feature e2e-encryption only.

Creates a third client for e2e tests.

Source

pub async fn set_up_new_device_for_encryption( &self, existing_client: &Client, device_id: &DeviceId, clients_to_update: Vec<&Client>, ) -> Client

Available on crate feature e2e-encryption only.

Creates a new device and returns a new client for it. The new and old clients will be aware of each other.

§Arguments
  • existing_client - The original client for which a new device will be created
  • device_id - The device ID to use for the new client
  • clients_to_update - A vector of client references that should be notified about the new device. These clients will receive a device list change notification during their next sync.
§Returns

Returns the newly created client instance configured for the new device.

Source

pub async fn mock_crypto_endpoints_preset(&self)

Available on crate feature e2e-encryption only.

Mock up the various crypto API so that it can serve back keys when needed

Source

pub async fn mock_capture_put_to_device( &self, sender_user_id: &UserId, ) -> (MockGuard, impl Future<Output = Raw<EncryptedToDeviceEvent>>)

Available on crate feature e2e-encryption only.

Creates a response handler for mocking encrypted to-device message requests.

This function creates a response handler that captures encrypted to-device messages sent via the /sendToDevice endpoint.

§Arguments
  • sender - The user ID of the message sender
§Returns

Returns a tuple containing:

  • A MockGuard the end-point mock is scoped to this guard
  • A Future that resolves to a Raw<EncryptedToDeviceEvent>> containing the captured encrypted to-device message.
§Examples

#[async_test]
async fn test_mock_capture_put_to_device() {
    let server = MatrixMockServer::new().await;
    server.mock_crypto_endpoints_preset().await;

    let (alice, bob) = server.set_up_alice_and_bob_for_encryption().await;
    let bob_user_id = bob.user_id().unwrap();
    let bob_device_id = bob.device_id().unwrap();

    // From the point of view of Alice, Bob now has a device.
    let alice_bob_device = alice
        .encryption()
        .get_device(bob_user_id, bob_device_id)
        .await
        .unwrap()
        .expect("alice sees bob's device");

    let content_raw = Raw::new(&json!({ /*...*/ })).unwrap().cast();

    // Set up the mock to capture encrypted to-device messages
    let (guard, captured) =
        server.mock_capture_put_to_device(alice.user_id().unwrap()).await;

    alice
        .encryption()
        .encrypt_and_send_raw_to_device(
            vec![&alice_bob_device],
            "call.keys",
            content_raw,
        )
        .await
        .unwrap();

    // this is the captured event as sent by alice!
    let sent_event = captured.await;
    drop(guard);
}
Source

pub async fn mock_capture_put_to_device_then_sync_back<'a>( &'a self, sender_user_id: &UserId, recipient: &'a Client, ) -> impl Future<Output = Raw<EncryptedToDeviceEvent>> + 'a

Available on crate feature e2e-encryption only.

Captures a to-device message when it is sent to the mock server and then injects it into the recipient’s sync response.

This is a utility function that combines capturing an encrypted to-device message and delivering it to the recipient through a sync response. It’s useful for testing end-to-end encryption scenarios where you need to verify message delivery and processing.

§Arguments
  • sender_user_id - The user ID of the message sender
  • recipient - The client that will receive the message through sync
§Returns

Returns a Future that will resolve when the captured event has been fed back down the recipient sync.

Source

pub async fn capture_put_to_device_traffic( &self, sender_user_id: &UserId, to_device_queue: Arc<Mutex<PendingToDeviceMessages>>, ) -> MockGuard

Available on crate feature e2e-encryption only.

Utility to capture all the /toDevice upload traffic and store it in a queue to be later used with MatrixMockServer::sync_back_pending_to_device_messages.

Source

pub async fn sync_back_pending_to_device_messages( &self, to_device_queue: Arc<Mutex<PendingToDeviceMessages>>, recipient: &Client, )

Available on crate feature e2e-encryption only.

Sync the pending to-device messages for this client.

To be used in connection with MatrixMockServer::capture_put_to_device_traffic that is capturing the traffic.

Source§

impl MatrixMockServer

Source

pub async fn new() -> Self

Create a new wiremock server specialized for Matrix usage.

Source

pub fn from_server(server: MockServer) -> Self

Creates a new MatrixMockServer from a wiremock server.

Source

pub fn client_builder(&self) -> MockClientBuilder

Creates a new MockClientBuilder configured to use this server, preconfigured with a session expected by the server endpoints.

Source

pub fn server(&self) -> &MockServer

Return the underlying wiremock server.

Source

pub fn uri(&self) -> String

Return the URI of this server.

Source

pub fn oauth(&self) -> OAuthMockServer<'_>

Get an OAuthMockServer that uses the same mock server as this one.

Source

pub async fn sync_room( &self, client: &Client, room_data: impl Into<AnyRoomBuilder>, ) -> Room

Overrides the sync/ endpoint with knowledge that the given invited/joined/knocked/left room exists, runs a sync and returns the given room.

§Examples
use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use matrix_sdk_test::LeftRoomBuilder;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

let left_room = mock_server
    .sync_room(&client, LeftRoomBuilder::new(room_id!("!room_id:localhost")))
    .await;
Source

pub async fn sync_joined_room(&self, client: &Client, room_id: &RoomId) -> Room

Overrides the sync/ endpoint with knowledge that the given room exists in the joined state, runs a sync and returns the given room.

§Examples
use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;
Source

pub async fn verify_and_reset(&self)

Verify that the previous mocks expected number of requests match reality, and then cancels all active mocks.

§Examples
use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use serde_json::json;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_state_encryption().plain().mount().await;
let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;
mock_server.mock_room_send().ok(event_id!("$some_id")).mount().await;

// This will succeed.
let response = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;

// Now we reset the mocks.
mock_server.verify_and_reset().await;

// And we can't send anymore.
let response = room
    .send_raw("m.room.message", json!({ "body": "Hello world" }))
    .await
    .expect_err("We removed the mock so sending should now fail");
Source§

impl MatrixMockServer

Source

pub fn mock_sync(&self) -> MockEndpoint<'_, SyncEndpoint>

Mocks a sync endpoint.

§Examples
use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
use matrix_sdk_test::JoinedRoomBuilder;

// First create the mock server and client pair.
let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;
let room_id = room_id!("!room_id:localhost");

// Let's emulate what `MatrixMockServer::sync_joined_room()` does.
mock_server
    .mock_sync()
    .ok_and_run(&client, |builder| {
        builder.add_joined_room(JoinedRoomBuilder::new(room_id));
    })
    .await;

let room = client
    .get_room(room_id)
    .expect("The room should be available after we mocked the sync");
Source

pub fn mock_room_join( &self, room_id: &RoomId, ) -> MockEndpoint<'_, JoinRoomEndpoint>

Creates a prebuilt mock for joining a room.

§Examples
use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use serde_json::json;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;
let room_id = room_id!("!test:localhost");

mock_server.mock_room_join(room_id).ok().mount();

let room = client.join_room_by_id(room_id).await?;

assert_eq!(
    room_id,
    room.room_id(),
    "The room ID we mocked should match the one we received when we joined the room"
);
Source

pub fn mock_room_send(&self) -> MockEndpoint<'_, RoomSendEndpoint>

Creates a prebuilt mock for sending an event in a room.

Note: works with any room.

§Examples
use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use serde_json::json;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_state_encryption().plain().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

let event_id = event_id!("$some_id");
mock_server
    .mock_room_send()
    .ok(event_id)
    .expect(1)
    .mount()
    .await;

let response = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;

assert_eq!(
    event_id,
    response.event_id,
    "The event ID we mocked should match the one we received when we sent the event"
);
Source

pub fn mock_room_send_state(&self) -> MockEndpoint<'_, RoomSendStateEndpoint>

Creates a prebuilt mock for sending a state event in a room.

Similar to: MatrixMockServer::mock_room_send

Note: works with any room. Note: works with any event type.

use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
use serde_json::json;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_state_encryption().plain().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

let event_id = event_id!("$some_id");
mock_server
    .mock_room_send_state()
    .ok(event_id)
    .expect(1)
    .mount()
    .await;

let response_not_mocked = room.send_raw("m.room.create", json!({ "body": "Hello world" })).await;
// The `/send` endpoint should not be mocked by the server.
assert!(response_not_mocked.is_err());


let response = room.send_state_event_raw("m.room.message", "my_key", json!({ "body": "Hello world" })).await?;
// The `/state` endpoint should be mocked by the server.
assert_eq!(
    event_id,
    response.event_id,
    "The event ID we mocked should match the one we received when we sent the event"
);
Source

pub fn mock_room_state_encryption( &self, ) -> MockEndpoint<'_, EncryptionStateEndpoint>

Creates a prebuilt mock for asking whether a room is encrypted or not.

Note: Applies to all rooms.

§Examples
use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_state_encryption().encrypted().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

assert!(
    room.latest_encryption_state().await?.is_encrypted(),
    "The room should be marked as encrypted."
);
Source

pub fn mock_set_room_state_encryption( &self, ) -> MockEndpoint<'_, SetEncryptionStateEndpoint>

Creates a prebuilt mock for setting the room encryption state.

Note: Applies to all rooms.

§Examples
use matrix_sdk::{
    ruma::{event_id, room_id},
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_state_encryption().plain().mount().await;
mock_server
    .mock_set_room_state_encryption()
    .ok(event_id!("$id"))
    .mock_once()
    .mount()
    .await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.enable_encryption()
    .await
    .expect("We should be able to enable encryption in the room");
Source

pub fn mock_room_redact(&self) -> MockEndpoint<'_, RoomRedactEndpoint>

Creates a prebuilt mock for the room redact endpoint.

§Examples
use matrix_sdk::{
    ruma::{event_id, room_id},
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;
let event_id = event_id!("$id");

mock_server.mock_room_redact().ok(event_id).mock_once().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.redact(event_id, None, None)
    .await
    .expect("We should be able to redact events in the room");
Source

pub fn mock_room_event(&self) -> MockEndpoint<'_, RoomEventEndpoint>

Creates a prebuilt mock for retrieving an event with /room/…/event.

Source

pub fn mock_room_event_context( &self, ) -> MockEndpoint<'_, RoomEventContextEndpoint>

Creates a prebuilt mock for retrieving an event with /room/…/context.

Source

pub fn mock_room_messages(&self) -> MockEndpoint<'_, RoomMessagesEndpoint>

Create a prebuild mock for paginating room message with the /messages endpoint.

Source

pub fn mock_upload(&self) -> MockEndpoint<'_, UploadEndpoint>

Create a prebuilt mock for uploading media.

Source

pub fn mock_room_directory_resolve_alias( &self, ) -> MockEndpoint<'_, ResolveRoomAliasEndpoint>

Create a prebuilt mock for resolving room aliases.

§Examples
use matrix_sdk::{
    ruma::{owned_room_id, room_alias_id},
    test_utils::mocks::MatrixMockServer,
};
let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server
    .mock_room_directory_resolve_alias()
    .ok("!a:b.c", Vec::new())
    .mock_once()
    .mount()
    .await;

let res = client
    .resolve_room_alias(room_alias_id!("#a:b.c"))
    .await
    .expect("We should be able to resolve the room alias");
assert_eq!(res.room_id, owned_room_id!("!a:b.c"));
Source

pub fn mock_room_directory_create_room_alias( &self, ) -> MockEndpoint<'_, CreateRoomAliasEndpoint>

Create a prebuilt mock for publishing room aliases in the room directory.

§Examples
use matrix_sdk::{
    ruma::{room_alias_id, room_id},
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server
    .mock_room_directory_create_room_alias()
    .ok()
    .mock_once()
    .mount()
    .await;

client
    .create_room_alias(room_alias_id!("#a:b.c"), room_id!("!a:b.c"))
    .await
    .expect("We should be able to create a room alias");
Source

pub fn mock_room_directory_remove_room_alias( &self, ) -> MockEndpoint<'_, RemoveRoomAliasEndpoint>

Create a prebuilt mock for removing room aliases from the room directory.

§Examples
use matrix_sdk::{
    ruma::room_alias_id, test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server
    .mock_room_directory_remove_room_alias()
    .ok()
    .mock_once()
    .mount()
    .await;

client
    .remove_room_alias(room_alias_id!("#a:b.c"))
    .await
    .expect("We should be able to remove the room alias");
Source

pub fn mock_public_rooms(&self) -> MockEndpoint<'_, PublicRoomsEndpoint>

Create a prebuilt mock for listing public rooms.

§Examples
tokio_test::block_on(async {
use js_int::uint;
use ruma::directory::PublicRoomsChunkInit;
use matrix_sdk::room_directory_search::RoomDirectorySearch;
use matrix_sdk::{
    ruma::{event_id, room_id},
    test_utils::mocks::MatrixMockServer,
};
let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;
let event_id = event_id!("$id");
let room_id = room_id!("!room_id:localhost");

let chunk = vec![PublicRoomsChunkInit {
    num_joined_members: uint!(0),
    room_id: room_id.to_owned(),
    world_readable: true,
    guest_can_join: true,
}.into()];

mock_server.mock_public_rooms().ok(chunk, None, None, Some(20)).mock_once().mount().await;
let mut room_directory_search = RoomDirectorySearch::new(client);

room_directory_search.search(Some("some-alias".to_owned()), 100, None)
    .await
    .expect("Room directory search failed");

let (results, _) = room_directory_search.results();
assert_eq!(results.len(), 1);
assert_eq!(results.get(0).unwrap().room_id, room_id.to_owned());
Source

pub fn mock_room_directory_set_room_visibility( &self, ) -> MockEndpoint<'_, SetRoomVisibilityEndpoint>

Create a prebuilt mock for setting a room’s visibility in the room directory.

§Examples
use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
use ruma::api::client::room::Visibility;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server
    .mock_room_directory_set_room_visibility()
    .ok()
    .mock_once()
    .mount()
    .await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.privacy_settings()
    .update_room_visibility(Visibility::Private)
    .await
    .expect("We should be able to update the room's visibility");
Source

pub fn mock_room_directory_get_room_visibility( &self, ) -> MockEndpoint<'_, GetRoomVisibilityEndpoint>

Create a prebuilt mock for getting a room’s visibility in the room directory.

§Examples
use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
use ruma::api::client::room::Visibility;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server
    .mock_room_directory_get_room_visibility()
    .ok(Visibility::Public)
    .mock_once()
    .mount()
    .await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

let visibility = room
    .privacy_settings()
    .get_room_visibility()
    .await
    .expect("We should be able to get the room's visibility");
assert_eq!(visibility, Visibility::Public);
Source

pub fn mock_room_keys_version( &self, ) -> MockEndpoint<'_, RoomKeysVersionEndpoint>

Create a prebuilt mock for fetching information about key storage backups.

§Examples
use matrix_sdk::test_utils::mocks::MatrixMockServer;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_room_keys_version().exists().expect(1).mount().await;

let exists =
    client.encryption().backups().fetch_exists_on_server().await.unwrap();

assert!(exists);
Source

pub fn mock_add_room_keys_version( &self, ) -> MockEndpoint<'_, AddRoomKeysVersionEndpoint>

Create a prebuilt mock for adding key storage backups via POST

Source

pub fn mock_delete_room_keys_version( &self, ) -> MockEndpoint<'_, DeleteRoomKeysVersionEndpoint>

Create a prebuilt mock for adding key storage backups via POST

Source

pub fn mock_send_to_device(&self) -> MockEndpoint<'_, SendToDeviceEndpoint>

Creates a prebuilt mock for the /sendToDevice endpoint.

This mock can be used to simulate sending to-device messages in tests.

§Examples
use std::collections::BTreeMap;
use matrix_sdk::{
    ruma::{
        serde::Raw,
        api::client::to_device::send_event_to_device::v3::Request as ToDeviceRequest,
        to_device::DeviceIdOrAllDevices,
        user_id,owned_device_id
    },
    test_utils::mocks::MatrixMockServer,
};
use serde_json::json;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_send_to_device().ok().mock_once().mount().await;

let request = ToDeviceRequest::new_raw(
    "m.custom.event".into(),
    "txn_id".into(),
BTreeMap::from([
(user_id!("@alice:localhost").to_owned(), BTreeMap::from([(
    DeviceIdOrAllDevices::AllDevices,
    Raw::new(&ruma::events::AnyToDeviceEventContent::Dummy(ruma::events::dummy::ToDeviceDummyEventContent {})).unwrap(),
)])),
])
);

client
    .send(request)
    .await
    .expect("We should be able to send a to-device message");
Source

pub fn mock_get_members(&self) -> MockEndpoint<'_, GetRoomMembersEndpoint>

Create a prebuilt mock for getting the room members in a room.

§Examples
use matrix_sdk::{
    ruma::{event_id, room_id},
    test_utils::mocks::MatrixMockServer,
};
use matrix_sdk_base::RoomMemberships;
use matrix_sdk_test::event_factory::EventFactory;
use ruma::{
    events::room::member::{MembershipState, RoomMemberEventContent},
    user_id,
};
let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;
let event_id = event_id!("$id");
let room_id = room_id!("!room_id:localhost");

let f = EventFactory::new().room(room_id);
let alice_user_id = user_id!("@alice:b.c");
let alice_knock_event = f
    .event(RoomMemberEventContent::new(MembershipState::Knock))
    .event_id(event_id)
    .sender(alice_user_id)
    .state_key(alice_user_id)
    .into_raw();

mock_server
    .mock_get_members()
    .ok(vec![alice_knock_event])
    .mock_once()
    .mount()
    .await;
let room = mock_server.sync_joined_room(&client, room_id).await;

let members = room.members(RoomMemberships::all()).await.unwrap();
assert_eq!(members.len(), 1);
Source

pub fn mock_invite_user_by_id(&self) -> MockEndpoint<'_, InviteUserByIdEndpoint>

Creates a prebuilt mock for inviting a user to a room by its id.

§Examples
tokio_test::block_on(async {
use matrix_sdk::{
    ruma::room_id,
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_invite_user_by_id().ok().mock_once().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.invite_user_by_id(user_id!("@alice:localhost")).await.unwrap();
Source

pub fn mock_kick_user(&self) -> MockEndpoint<'_, KickUserEndpoint>

Creates a prebuilt mock for kicking a user from a room.

§Examples
tokio_test::block_on(async {
use matrix_sdk::{
    ruma::room_id,
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_kick_user().ok().mock_once().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.kick_user(user_id!("@alice:localhost"), None).await.unwrap();
Source

pub fn mock_ban_user(&self) -> MockEndpoint<'_, BanUserEndpoint>

Creates a prebuilt mock for banning a user from a room.

§Examples
tokio_test::block_on(async {
use matrix_sdk::{
    ruma::room_id,
    test_utils::mocks::MatrixMockServer,
};

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_ban_user().ok().mock_once().mount().await;

let room = mock_server
    .sync_joined_room(&client, room_id!("!room_id:localhost"))
    .await;

room.ban_user(user_id!("@alice:localhost"), None).await.unwrap();
Source

pub fn mock_versions(&self) -> MockEndpoint<'_, VersionsEndpoint>

Creates a prebuilt mock for the /_matrix/client/versions endpoint.

Source

pub fn mock_room_summary(&self) -> MockEndpoint<'_, RoomSummaryEndpoint>

Creates a prebuilt mock for the room summary endpoint MSC3266.

Source

pub fn mock_set_room_pinned_events( &self, ) -> MockEndpoint<'_, SetRoomPinnedEventsEndpoint>

Creates a prebuilt mock for the endpoint used to set a room’s pinned events.

Source

pub fn mock_who_am_i(&self) -> MockEndpoint<'_, WhoAmIEndpoint>

Creates a prebuilt mock for the endpoint used to get information about the owner of the given access token.

If no access token is provided, the access token to match is "1234", which matches the default value in the mock data.

Source

pub fn mock_upload_keys(&self) -> MockEndpoint<'_, UploadKeysEndpoint>

Creates a prebuilt mock for the endpoint used to publish end-to-end encryption keys.

Source

pub fn mock_query_keys(&self) -> MockEndpoint<'_, QueryKeysEndpoint>

Creates a prebuilt mock for the endpoint used to query end-to-end encryption keys.

Source

pub fn mock_well_known(&self) -> MockEndpoint<'_, WellKnownEndpoint>

Creates a prebuilt mock for the endpoint used to discover the URL of a homeserver.

Source

pub fn mock_upload_cross_signing_keys( &self, ) -> MockEndpoint<'_, UploadCrossSigningKeysEndpoint>

Creates a prebuilt mock for the endpoint used to publish cross-signing keys.

Source

pub fn mock_upload_cross_signing_signatures( &self, ) -> MockEndpoint<'_, UploadCrossSigningSignaturesEndpoint>

Creates a prebuilt mock for the endpoint used to publish cross-signing signatures.

Source

pub fn mock_room_leave(&self) -> MockEndpoint<'_, RoomLeaveEndpoint>

Creates a prebuilt mock for the endpoint used to leave a room.

Source

pub fn mock_room_forget(&self) -> MockEndpoint<'_, RoomForgetEndpoint>

Creates a prebuilt mock for the endpoint used to forget a room.

Source

pub fn mock_logout(&self) -> MockEndpoint<'_, LogoutEndpoint>

Create a prebuilt mock for the endpoint use to log out a session.

Source

pub fn mock_room_threads(&self) -> MockEndpoint<'_, RoomThreadsEndpoint>

Create a prebuilt mock for the endpoint used to get the list of thread roots.

Source

pub fn mock_room_relations(&self) -> MockEndpoint<'_, RoomRelationsEndpoint>

Create a prebuilt mock for the endpoint used to get the related events.

Source

pub fn mock_global_account_data( &self, ) -> MockEndpoint<'_, GlobalAccountDataEndpoint>

Create a prebuilt mock for the endpoint used to get the global account data.

§Examples
tokio_test::block_on(async {
use matrix_sdk::test_utils::mocks::MatrixMockServer;
use serde_json::json;
use ruma::events::media_preview_config::MediaPreviews;

let mock_server = MatrixMockServer::new().await;
let client = mock_server.client_builder().build().await;

mock_server.mock_global_account_data().ok(
    client.user_id().unwrap(),
    ruma::events::GlobalAccountDataEventType::MediaPreviewConfig,
    json!({
        "media_previews": "private",
        "invite_avatars": "off"
    })
)
.mock_once()
.mount()
.await;

client.account().fetch_media_preview_config_event_content().await.unwrap();
Source

pub fn mock_send_receipt( &self, receipt_type: ReceiptType, ) -> MockEndpoint<'_, ReceiptEndpoint>

Create a prebuilt mock for the endpoint used to send a single receipt.

Source

pub fn mock_send_read_markers(&self) -> MockEndpoint<'_, ReadMarkersEndpoint>

Create a prebuilt mock for the endpoint used to send multiple receipts.

Source

pub fn mock_set_room_account_data( &self, data_type: RoomAccountDataEventType, ) -> MockEndpoint<'_, RoomAccountDataEndpoint>

Create a prebuilt mock for the endpoint used to set room account data.

Source

pub fn mock_authenticated_media_config( &self, ) -> MockEndpoint<'_, AuthenticatedMediaConfigEndpoint>

Create a prebuilt mock for the endpoint used to get the media config of the homeserver that requires authentication.

Source

pub fn mock_media_config(&self) -> MockEndpoint<'_, MediaConfigEndpoint>

Create a prebuilt mock for the endpoint used to get the media config of the homeserver without requiring authentication.

Source

pub fn mock_login(&self) -> MockEndpoint<'_, LoginEndpoint>

Create a prebuilt mock for the endpoint used to log into a session.

Source

pub fn mock_devices(&self) -> MockEndpoint<'_, DevicesEndpoint>

Create a prebuilt mock for the endpoint used to list the devices of a user.

Source

pub fn mock_user_directory(&self) -> MockEndpoint<'_, UserDirectoryEndpoint>

Create a prebuilt mock for the endpoint used to search in the user directory.

Source

pub fn mock_create_room(&self) -> MockEndpoint<'_, CreateRoomEndpoint>

Create a prebuilt mock for the endpoint used to create a new room.

Source

pub fn mock_upgrade_room(&self) -> MockEndpoint<'_, UpgradeRoomEndpoint>

Create a prebuilt mock for the endpoint used to upgrade a room.

Source

pub fn mock_media_allocate(&self) -> MockEndpoint<'_, MediaAllocateEndpoint>

Create a prebuilt mock for the endpoint used to pre-allocate a MXC URI for a media file.

Source

pub fn mock_media_allocated_upload( &self, server_name: &str, media_id: &str, ) -> MockEndpoint<'_, MediaAllocatedUploadEndpoint>

Create a prebuilt mock for the endpoint used to upload a media file with a pre-allocated MXC URI.

Source

pub fn mock_media_download(&self) -> MockEndpoint<'_, MediaDownloadEndpoint>

Create a prebuilt mock for the endpoint used to download a media file without requiring authentication.

Source

pub fn mock_media_thumbnail( &self, resize_method: Method, width: u16, height: u16, animated: bool, ) -> MockEndpoint<'_, MediaThumbnailEndpoint>

Create a prebuilt mock for the endpoint used to download a thumbnail of a media file without requiring authentication.

Source

pub fn mock_authed_media_download( &self, ) -> MockEndpoint<'_, AuthedMediaDownloadEndpoint>

Create a prebuilt mock for the endpoint used to download a media file that requires authentication.

Source

pub fn mock_authed_media_thumbnail( &self, resize_method: Method, width: u16, height: u16, animated: bool, ) -> MockEndpoint<'_, AuthedMediaThumbnailEndpoint>

Create a prebuilt mock for the endpoint used to download a thumbnail of a media file that requires authentication.

Source

pub fn mock_room_get_thread_subscription( &self, ) -> MockEndpoint<'_, RoomGetThreadSubscriptionEndpoint>

Create a prebuilt mock for the endpoint used to get a single thread subscription status in a given room.

Source

pub fn mock_room_put_thread_subscription( &self, ) -> MockEndpoint<'_, RoomPutThreadSubscriptionEndpoint>

Create a prebuilt mock for the endpoint used to define a thread subscription in a given room.

Source

pub fn mock_room_delete_thread_subscription( &self, ) -> MockEndpoint<'_, RoomDeleteThreadSubscriptionEndpoint>

Create a prebuilt mock for the endpoint used to delete a thread subscription in a given room.

Source

pub fn mock_enable_push_rule( &self, kind: RuleKind, rule_id: impl AsRef<str>, ) -> MockEndpoint<'_, EnablePushRuleEndpoint>

Create a prebuilt mock for the endpoint used to enable a push rule.

Source

pub fn mock_set_push_rules_actions( &self, kind: RuleKind, rule_id: PushRuleIdSpec<'_>, ) -> MockEndpoint<'_, SetPushRulesActionsEndpoint>

Create a prebuilt mock for the endpoint used to set push rules actions.

Source

pub fn mock_set_push_rules( &self, kind: RuleKind, rule_id: PushRuleIdSpec<'_>, ) -> MockEndpoint<'_, SetPushRulesEndpoint>

Create a prebuilt mock for the endpoint used to set push rules.

Source

pub fn mock_delete_push_rules( &self, kind: RuleKind, rule_id: PushRuleIdSpec<'_>, ) -> MockEndpoint<'_, DeletePushRulesEndpoint>

Create a prebuilt mock for the endpoint used to delete push rules.

Source

pub fn mock_federation_version( &self, ) -> MockEndpoint<'_, FederationVersionEndpoint>

Create a prebuilt mock for the federation version endpoint.

Source

pub fn mock_get_thread_subscriptions( &self, ) -> MockEndpoint<'_, GetThreadSubscriptionsEndpoint>

Create a prebuilt mock for the endpoint used to get all thread subscriptions across all rooms.

Source

pub fn mock_get_hierarchy(&self) -> MockEndpoint<'_, GetHierarchyEndpoint>

Create a prebuilt mock for the endpoint used to retrieve a space tree

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

Source§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
Source§

fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
Source§

fn consume_handle(handle: Handle) -> Arc<T>

Consume a handle, getting back the initial Arc<>
Source§

fn get_arc(handle: Handle) -> Arc<Self>

Get a clone of the Arc<> using a “borrowed” handle. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> Any for T
where T: Any,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fruit for T
where T: Send + Downcast,

§

impl<T> JsonCastable<CanonicalJsonValue> for T

§

impl<T> JsonCastable<Value> for T

Source§

impl<T> MaybeSendSync for T

Source§

impl<T> SendOutsideWasm for T
where T: Send,

Source§

impl<T> SyncOutsideWasm for T
where T: Sync,