matrix_sdk/test_utils/mocks/mod.rs
1// Copyright 2024 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Helpers to mock a server and have a client automatically connected to that
16//! server, for the purpose of integration tests.
17
18#![allow(missing_debug_implementations)]
19
20use std::{
21 collections::BTreeMap,
22 fmt,
23 sync::{Arc, Mutex, atomic::AtomicU32},
24};
25
26use as_variant::as_variant;
27use js_int::UInt;
28use matrix_sdk_base::deserialized_responses::TimelineEvent;
29#[cfg(feature = "experimental-element-recent-emojis")]
30use matrix_sdk_base::recent_emojis::RecentEmojisContent;
31use matrix_sdk_test::{
32 InvitedRoomBuilder, JoinedRoomBuilder, KnockedRoomBuilder, LeftRoomBuilder,
33 SyncResponseBuilder, TestAuthToken, TestDevice, User, event_factory::EventFactory, test_json,
34};
35use percent_encoding::{AsciiSet, CONTROLS};
36use ruma::{
37 DeviceId, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedDeviceId, OwnedEventId,
38 OwnedOneTimeKeyId, OwnedRoomId, OwnedUserId, RoomId, RoomOrAliasId, ServerName, UserId,
39 api::{
40 client::{
41 discovery::get_capabilities::v3::Capabilities,
42 receipt::create_receipt::v3::ReceiptType,
43 retention::{RoomIdOrAllRooms, get_retention_configuration::msc1763::RetentionLimits},
44 room::Visibility,
45 session::login::v3::{DiscoveryInfo, HomeserverInfo, IdentityServerInfo},
46 sync::sync_events::msc4186,
47 threads::get_thread_subscriptions_changes::msc4308::{
48 ThreadSubscription, ThreadUnsubscription,
49 },
50 uiaa,
51 },
52 error::StandardErrorBody,
53 },
54 device_id,
55 directory::PublicRoomsChunk,
56 encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
57 events::{
58 AnyGlobalAccountDataEventContent, AnyStateEvent, AnySyncTimelineEvent, AnyTimelineEvent,
59 GlobalAccountDataEventType, MessageLikeEventType, RoomAccountDataEventType, StateEventType,
60 receipt::ReceiptThread,
61 room::{
62 member::{MembershipState, RoomMemberEvent},
63 retention::RoomRetentionEventContent,
64 },
65 tag::TagName,
66 },
67 media::Method,
68 presence::PresenceState,
69 profile::{ProfileFieldName, ProfileFieldValue},
70 push::RuleKind,
71 serde::{JsonObject, Raw},
72 time::Duration,
73};
74use serde::{Deserialize, Serialize};
75use serde_json::{Value, from_value, json};
76use tokio::sync::oneshot::{self, Receiver};
77use wiremock::{
78 Mock, MockBuilder, MockGuard, MockServer, Request, Respond, ResponseTemplate, Times,
79 matchers::{
80 body_json, body_partial_json, header, method, path, path_regex, query_param,
81 query_param_is_missing,
82 },
83};
84
85#[cfg(feature = "e2e-encryption")]
86pub mod encryption;
87pub mod oauth;
88
89use super::client::MockClientBuilder;
90use crate::{
91 Client, OwnedServerName, Room, SlidingSyncBuilder, room::IncludeRelations, sync::SyncResponse,
92};
93
94/// Structure used to store the crypto keys uploaded to the server. They will be
95/// served back to clients when requested.
96#[derive(Debug, Default)]
97struct Keys {
98 device: BTreeMap<OwnedUserId, BTreeMap<String, Raw<DeviceKeys>>>,
99 master: BTreeMap<OwnedUserId, Raw<CrossSigningKey>>,
100 self_signing: BTreeMap<OwnedUserId, Raw<CrossSigningKey>>,
101 user_signing: BTreeMap<OwnedUserId, Raw<CrossSigningKey>>,
102 one_time_keys: BTreeMap<
103 OwnedUserId,
104 BTreeMap<OwnedDeviceId, BTreeMap<OwnedOneTimeKeyId, Raw<OneTimeKey>>>,
105 >,
106}
107
108/// A [`wiremock`] [`MockServer`] along with useful methods to help mocking
109/// Matrix client-server API endpoints easily.
110///
111/// It implements mock endpoints, limiting the shared code as much as possible,
112/// so the mocks are still flexible to use as scoped/unscoped mounts, named, and
113/// so on.
114///
115/// It works like this:
116///
117/// - start by saying which endpoint you'd like to mock, e.g.
118/// [`Self::mock_room_send()`]. This returns a specialized [`MockEndpoint`]
119/// data structure, with its own impl. For this example, it's
120/// `MockEndpoint<RoomSendEndpoint>`.
121/// - configure the response on the endpoint-specific mock data structure. For
122/// instance, if you want the sending to result in a transient failure, call
123/// [`MockEndpoint::error500`]; if you want it to succeed and return the event
124/// `$42`, call [`MockEndpoint::ok()`]. It's still possible to call
125/// [`MockEndpoint::respond_with()`], as we do with wiremock MockBuilder, for
126/// maximum flexibility when the helpers aren't sufficient.
127/// - once the endpoint's response is configured, for any mock builder, you get
128/// a [`MatrixMock`]; this is a plain [`wiremock::Mock`] with the server
129/// curried, so one doesn't have to pass it around when calling
130/// [`MatrixMock::mount()`] or [`MatrixMock::mount_as_scoped()`]. As such, it
131/// mostly defers its implementations to [`wiremock::Mock`] under the hood.
132///
133/// # Examples
134///
135/// ```
136/// # tokio_test::block_on(async {
137/// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
138/// use serde_json::json;
139///
140/// // First create the mock server and client pair.
141/// let mock_server = MatrixMockServer::new().await;
142/// let client = mock_server.client_builder().build().await;
143///
144/// // Let's say that our rooms are not encrypted.
145/// mock_server.mock_room_state_encryption().plain().mount().await;
146///
147/// // Let us get a room where we will send an event.
148/// let room = mock_server
149/// .sync_joined_room(&client, room_id!("!room_id:localhost"))
150/// .await;
151///
152/// // Now we mock the endpoint so we can actually send the event.
153/// let event_id = event_id!("$some_id");
154/// let send_guard = mock_server
155/// .mock_room_send()
156/// .ok(event_id)
157/// .expect(1)
158/// .mount_as_scoped()
159/// .await;
160///
161/// // And we send it out.
162/// let result = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
163///
164/// assert_eq!(
165/// event_id,
166/// result.response.event_id,
167/// "The event ID we mocked should match the one we received when we sent the event"
168/// );
169/// # anyhow::Ok(()) });
170/// ```
171pub struct MatrixMockServer {
172 server: MockServer,
173
174 /// Make the sync response builder stateful, to keep in memory the batch
175 /// token and avoid the client ignoring subsequent responses after the first
176 /// one.
177 sync_response_builder: Arc<Mutex<SyncResponseBuilder>>,
178
179 /// Make this mock server capable of mocking real end to end communications
180 keys: Arc<Mutex<Keys>>,
181
182 /// For crypto API end-points to work we need to be able to recognise what
183 /// client is doing the request by mapping the token to the user_id
184 token_to_user_id_map: Arc<Mutex<BTreeMap<String, OwnedUserId>>>,
185 token_counter: AtomicU32,
186}
187
188impl std::ops::Deref for MatrixMockServer {
189 type Target = MockServer;
190
191 fn deref(&self) -> &Self::Target {
192 &self.server
193 }
194}
195
196impl MatrixMockServer {
197 /// Create a new [`wiremock`] server specialized for Matrix usage.
198 pub async fn new() -> Self {
199 let server = MockServer::start().await;
200 let keys: Arc<Mutex<Keys>> = Default::default();
201 Self {
202 server,
203 sync_response_builder: Default::default(),
204 keys,
205 token_to_user_id_map: Default::default(),
206 token_counter: AtomicU32::new(0),
207 }
208 }
209
210 /// Creates a new [`MatrixMockServer`] from a [`wiremock`] server.
211 pub fn from_server(server: MockServer) -> Self {
212 let keys: Arc<Mutex<Keys>> = Default::default();
213 Self {
214 server,
215 sync_response_builder: Default::default(),
216 keys,
217 token_to_user_id_map: Default::default(),
218 token_counter: AtomicU32::new(0),
219 }
220 }
221
222 /// Creates a new [`MockClientBuilder`] configured to use this server,
223 /// preconfigured with a session expected by the server endpoints.
224 pub fn client_builder(&self) -> MockClientBuilder {
225 MockClientBuilder::new(Some(&self.server.uri()))
226 }
227
228 /// Return the underlying [`wiremock`] server.
229 pub fn server(&self) -> &MockServer {
230 &self.server
231 }
232
233 /// Return the URI of this server.
234 pub fn uri(&self) -> String {
235 self.server.uri()
236 }
237
238 /// Get an `OAuthMockServer` that uses the same mock server as this one.
239 pub fn oauth(&self) -> oauth::OAuthMockServer<'_> {
240 oauth::OAuthMockServer::new(self)
241 }
242
243 /// Mock the given endpoint.
244 fn mock_endpoint<T>(&self, mock: MockBuilder, endpoint: T) -> MockEndpoint<'_, T> {
245 MockEndpoint::new(&self.server, mock, endpoint)
246 }
247
248 /// Overrides the sync/ endpoint with knowledge that the given
249 /// invited/joined/knocked/left room exists, runs a sync and returns the
250 /// given room.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// # tokio_test::block_on(async {
256 /// use matrix_sdk::{
257 /// ruma::{event_id, room_id},
258 /// test_utils::mocks::MatrixMockServer,
259 /// };
260 /// use matrix_sdk_test::LeftRoomBuilder;
261 ///
262 /// let mock_server = MatrixMockServer::new().await;
263 /// let client = mock_server.client_builder().build().await;
264 ///
265 /// let left_room = mock_server
266 /// .sync_room(
267 /// &client,
268 /// LeftRoomBuilder::new(room_id!("!room_id:localhost")),
269 /// )
270 /// .await;
271 /// # anyhow::Ok(()) });
272 /// ```
273 pub async fn sync_room(&self, client: &Client, room_data: impl Into<AnyRoomBuilder>) -> Room {
274 let any_room = room_data.into();
275 let room_id = any_room.room_id().to_owned();
276
277 self.mock_sync()
278 .ok_and_run(client, move |builder| match any_room {
279 AnyRoomBuilder::Invited(invited) => {
280 builder.add_invited_room(invited);
281 }
282 AnyRoomBuilder::Joined(joined) => {
283 builder.add_joined_room(joined);
284 }
285 AnyRoomBuilder::Left(left) => {
286 builder.add_left_room(left);
287 }
288 AnyRoomBuilder::Knocked(knocked) => {
289 builder.add_knocked_room(knocked);
290 }
291 })
292 .await;
293
294 client.get_room(&room_id).expect("look at me, the room is known now")
295 }
296
297 /// Overrides the sync/ endpoint with knowledge that the given room exists
298 /// in the joined state, runs a sync and returns the given room.
299 ///
300 /// # Examples
301 ///
302 /// ```
303 /// # tokio_test::block_on(async {
304 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
305 ///
306 /// let mock_server = MatrixMockServer::new().await;
307 /// let client = mock_server.client_builder().build().await;
308 ///
309 /// let room = mock_server
310 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
311 /// .await;
312 /// # anyhow::Ok(()) });
313 /// ```
314 pub async fn sync_joined_room(&self, client: &Client, room_id: impl Into<OwnedRoomId>) -> Room {
315 self.sync_room(client, JoinedRoomBuilder::new(room_id)).await
316 }
317
318 /// Overrides the sync/ endpoint with knowledge that the room with the
319 /// default room ID
320 /// ([`TestRoom::Default`][matrix_sdk_test::TestRoom::Default])
321 /// exists in the joined state, runs a sync and returns the given room.
322 pub async fn sync_default_joined_room(&self, client: &Client) -> Room {
323 self.sync_room(client, JoinedRoomBuilder::default()).await
324 }
325
326 /// Verify that the previous mocks expected number of requests match
327 /// reality, and then cancels all active mocks.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// # tokio_test::block_on(async {
333 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
334 /// use serde_json::json;
335 ///
336 /// let mock_server = MatrixMockServer::new().await;
337 /// let client = mock_server.client_builder().build().await;
338 ///
339 /// mock_server.mock_room_state_encryption().plain().mount().await;
340 /// let room = mock_server
341 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
342 /// .await;
343 /// mock_server.mock_room_send().ok(event_id!("$some_id")).mount().await;
344 ///
345 /// // This will succeed.
346 /// let response = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
347 ///
348 /// // Now we reset the mocks.
349 /// mock_server.verify_and_reset().await;
350 ///
351 /// // And we can't send anymore.
352 /// let response = room
353 /// .send_raw("m.room.message", json!({ "body": "Hello world" }))
354 /// .await
355 /// .expect_err("We removed the mock so sending should now fail");
356 /// # anyhow::Ok(()) });
357 /// ```
358 pub async fn verify_and_reset(&self) {
359 self.server.verify().await;
360 self.server.reset().await;
361 }
362}
363
364// Specific mount endpoints.
365impl MatrixMockServer {
366 /// Mocks a sync endpoint.
367 ///
368 /// # Examples
369 ///
370 /// ```
371 /// # tokio_test::block_on(async {
372 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
373 /// use matrix_sdk_test::JoinedRoomBuilder;
374 ///
375 /// // First create the mock server and client pair.
376 /// let mock_server = MatrixMockServer::new().await;
377 /// let client = mock_server.client_builder().build().await;
378 /// let room_id = room_id!("!room_id:localhost");
379 ///
380 /// // Let's emulate what `MatrixMockServer::sync_joined_room()` does.
381 /// mock_server
382 /// .mock_sync()
383 /// .ok_and_run(&client, |builder| {
384 /// builder.add_joined_room(JoinedRoomBuilder::new(room_id));
385 /// })
386 /// .await;
387 ///
388 /// let room = client
389 /// .get_room(room_id)
390 /// .expect("The room should be available after we mocked the sync");
391 /// # anyhow::Ok(()) });
392 /// ```
393 pub fn mock_sync(&self) -> MockEndpoint<'_, SyncEndpoint> {
394 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/sync"));
395 self.mock_endpoint(
396 mock,
397 SyncEndpoint { sync_response_builder: self.sync_response_builder.clone() },
398 )
399 }
400
401 /// Mocks the sliding sync endpoint.
402 pub fn mock_sliding_sync(&self) -> MockEndpoint<'_, SlidingSyncEndpoint> {
403 let mock = Mock::given(method("POST"))
404 .and(path("/_matrix/client/unstable/org.matrix.simplified_msc3575/sync"));
405 self.mock_endpoint(mock, SlidingSyncEndpoint)
406 }
407
408 /// Creates a prebuilt mock for joining a room.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// # tokio_test::block_on(async {
414 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
415 /// use serde_json::json;
416 ///
417 /// let mock_server = MatrixMockServer::new().await;
418 /// let client = mock_server.client_builder().build().await;
419 /// let room_id = room_id!("!test:localhost");
420 ///
421 /// mock_server.mock_room_join(room_id).ok().mount();
422 ///
423 /// let room = client.join_room_by_id(room_id).await?;
424 ///
425 /// assert_eq!(
426 /// room_id,
427 /// room.room_id(),
428 /// "The room ID we mocked should match the one we received when we joined the room"
429 /// );
430 /// # anyhow::Ok(()) });
431 /// ```
432 pub fn mock_room_join(
433 &self,
434 room_id: impl Into<OwnedRoomId>,
435 ) -> MockEndpoint<'_, JoinRoomEndpoint> {
436 let room_id = room_id.into();
437 let mock = Mock::given(method("POST"))
438 .and(path(format!("/_matrix/client/v3/rooms/{room_id}/join")));
439 self.mock_endpoint(mock, JoinRoomEndpoint { room_id })
440 }
441
442 /// Creates a prebuilt mock for joining a room by ID or alias.
443 pub fn mock_room_join_by_id_or_alias<'a>(
444 &self,
445 room_id_or_alias: impl Into<&'a RoomOrAliasId>,
446 ) -> MockEndpoint<'_, JoinRoomByIdOrAliasEndpoint> {
447 let mock = Mock::given(method("POST")).and(path_regex(format!(
448 "^/_matrix/client/v3/join/{}$",
449 percent_encoded_path(room_id_or_alias.into().as_str())
450 )));
451 self.mock_endpoint(mock, JoinRoomByIdOrAliasEndpoint)
452 }
453
454 /// Creates a prebuilt mock for knocking on a room.
455 pub fn mock_room_knock<'b>(
456 &self,
457 room_or_alias_id: impl Into<&'b RoomOrAliasId>,
458 ) -> MockEndpoint<'_, RoomKnockEndpoint> {
459 let mock = Mock::given(method("POST")).and(path(format!(
460 "/_matrix/client/v3/knock/{}",
461 percent_encoded_path(room_or_alias_id.into().as_str())
462 )));
463 self.mock_endpoint(mock, RoomKnockEndpoint)
464 }
465
466 /// Creates a prebuilt mock for sending an event in a room.
467 ///
468 /// Note: works with _any_ room.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// # tokio_test::block_on(async {
474 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
475 /// use serde_json::json;
476 ///
477 /// let mock_server = MatrixMockServer::new().await;
478 /// let client = mock_server.client_builder().build().await;
479 ///
480 /// mock_server.mock_room_state_encryption().plain().mount().await;
481 ///
482 /// let room = mock_server
483 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
484 /// .await;
485 ///
486 /// let event_id = event_id!("$some_id");
487 /// mock_server
488 /// .mock_room_send()
489 /// .ok(event_id)
490 /// .expect(1)
491 /// .mount()
492 /// .await;
493 ///
494 /// let result = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
495 ///
496 /// assert_eq!(
497 /// event_id,
498 /// result.response.event_id,
499 /// "The event ID we mocked should match the one we received when we sent the event"
500 /// );
501 /// # anyhow::Ok(()) });
502 /// ```
503 pub fn mock_room_send(&self) -> MockEndpoint<'_, RoomSendEndpoint> {
504 let mock = Mock::given(method("PUT"))
505 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/send/.*".to_owned()));
506 self.mock_endpoint(mock, RoomSendEndpoint::default())
507 }
508
509 /// Creates a prebuilt mock for sending a state event in a room.
510 ///
511 /// Similar to: [`MatrixMockServer::mock_room_send`]
512 ///
513 /// Note: works with _any_ room. Note: works with _any_ event type.
514 ///
515 /// ```
516 /// # tokio_test::block_on(async {
517 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
518 /// use serde_json::json;
519 ///
520 /// let mock_server = MatrixMockServer::new().await;
521 /// let client = mock_server.client_builder().build().await;
522 ///
523 /// mock_server.mock_room_state_encryption().plain().mount().await;
524 ///
525 /// let room = mock_server
526 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
527 /// .await;
528 ///
529 /// let event_id = event_id!("$some_id");
530 /// mock_server
531 /// .mock_room_send_state()
532 /// .ok(event_id)
533 /// .expect(1)
534 /// .mount()
535 /// .await;
536 ///
537 /// let response_not_mocked = room.send_raw("m.room.create", json!({ "body": "Hello world" })).await;
538 /// // The `/send` endpoint should not be mocked by the server.
539 /// assert!(response_not_mocked.is_err());
540 ///
541 ///
542 /// let response = room.send_state_event_raw("m.room.message", "my_key", json!({ "body": "Hello world" })).await?;
543 /// // The `/state` endpoint should be mocked by the server.
544 /// assert_eq!(
545 /// event_id,
546 /// response.event_id,
547 /// "The event ID we mocked should match the one we received when we sent the event"
548 /// );
549 /// # anyhow::Ok(()) });
550 /// ```
551 pub fn mock_room_send_state(&self) -> MockEndpoint<'_, RoomSendStateEndpoint> {
552 let mock =
553 Mock::given(method("PUT")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/.*/.*"));
554 self.mock_endpoint(mock, RoomSendStateEndpoint::default()).expect_default_access_token()
555 }
556
557 /// Creates a prebuilt mock for asking whether _a_ room is encrypted or not.
558 ///
559 /// Note: Applies to all rooms.
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// # tokio_test::block_on(async {
565 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
566 ///
567 /// let mock_server = MatrixMockServer::new().await;
568 /// let client = mock_server.client_builder().build().await;
569 ///
570 /// mock_server.mock_room_state_encryption().encrypted().mount().await;
571 ///
572 /// let room = mock_server
573 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
574 /// .await;
575 ///
576 /// assert!(
577 /// room.latest_encryption_state().await?.is_encrypted(),
578 /// "The room should be marked as encrypted."
579 /// );
580 /// # anyhow::Ok(()) });
581 /// ```
582 pub fn mock_room_state_encryption(&self) -> MockEndpoint<'_, EncryptionStateEndpoint> {
583 let mock = Mock::given(method("GET"))
584 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.*room.*encryption.?"));
585 self.mock_endpoint(mock, EncryptionStateEndpoint).expect_default_access_token()
586 }
587
588 /// Creates a prebuilt mock for setting the room encryption state.
589 ///
590 /// Note: Applies to all rooms.
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// # tokio_test::block_on(async {
596 /// use matrix_sdk::{
597 /// ruma::{event_id, room_id},
598 /// test_utils::mocks::MatrixMockServer,
599 /// };
600 ///
601 /// let mock_server = MatrixMockServer::new().await;
602 /// let client = mock_server.client_builder().build().await;
603 ///
604 /// mock_server.mock_room_state_encryption().plain().mount().await;
605 /// mock_server
606 /// .mock_set_room_state_encryption()
607 /// .ok(event_id!("$id"))
608 /// .mock_once()
609 /// .mount()
610 /// .await;
611 ///
612 /// let room = mock_server
613 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
614 /// .await;
615 ///
616 /// room.enable_encryption()
617 /// .await
618 /// .expect("We should be able to enable encryption in the room");
619 /// # anyhow::Ok(()) });
620 /// ```
621 pub fn mock_set_room_state_encryption(&self) -> MockEndpoint<'_, SetEncryptionStateEndpoint> {
622 let mock = Mock::given(method("PUT"))
623 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.*room.*encryption.?"));
624 self.mock_endpoint(mock, SetEncryptionStateEndpoint).expect_default_access_token()
625 }
626
627 /// Creates a prebuilt mock for the room redact endpoint.
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// # tokio_test::block_on(async {
633 /// use matrix_sdk::{
634 /// ruma::{event_id, room_id},
635 /// test_utils::mocks::MatrixMockServer,
636 /// };
637 ///
638 /// let mock_server = MatrixMockServer::new().await;
639 /// let client = mock_server.client_builder().build().await;
640 /// let event_id = event_id!("$id");
641 ///
642 /// mock_server.mock_room_redact().ok(event_id).mock_once().mount().await;
643 ///
644 /// let room = mock_server
645 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
646 /// .await;
647 ///
648 /// room.redact(event_id, None, None)
649 /// .await
650 /// .expect("We should be able to redact events in the room");
651 /// # anyhow::Ok(()) });
652 /// ```
653 pub fn mock_room_redact(&self) -> MockEndpoint<'_, RoomRedactEndpoint> {
654 let mock = Mock::given(method("PUT"))
655 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/redact/.*?/.*?"));
656 self.mock_endpoint(mock, RoomRedactEndpoint).expect_default_access_token()
657 }
658
659 /// Creates a prebuilt mock for retrieving an event with /room/.../event.
660 pub fn mock_room_event(&self) -> MockEndpoint<'_, RoomEventEndpoint> {
661 let mock = Mock::given(method("GET"));
662 self.mock_endpoint(mock, RoomEventEndpoint { room: None, match_event_id: false })
663 .expect_default_access_token()
664 }
665
666 /// Creates a prebuilt mock for retrieving an event with /room/.../context.
667 pub fn mock_room_event_context(&self) -> MockEndpoint<'_, RoomEventContextEndpoint> {
668 let mock = Mock::given(method("GET"));
669 self.mock_endpoint(mock, RoomEventContextEndpoint { room: None, match_event_id: false })
670 .expect_default_access_token()
671 }
672
673 /// Create a prebuild mock for paginating room message with the `/messages`
674 /// endpoint.
675 pub fn mock_room_messages(&self) -> MockEndpoint<'_, RoomMessagesEndpoint> {
676 let mock =
677 Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/messages$"));
678 self.mock_endpoint(mock, RoomMessagesEndpoint).expect_default_access_token()
679 }
680
681 /// Create a prebuild mock for getting a state event.
682 pub fn mock_get_room_state_event(
683 &self,
684 event_type: &StateEventType,
685 state_key: impl fmt::Display,
686 ) -> MockEndpoint<'_, RoomStateEventEndpoint> {
687 let mock = Mock::given(method("GET")).and(path_regex(format!(
688 "^/_matrix/client/v3/rooms/.*/state/{event_type}/{state_key}$"
689 )));
690 self.mock_endpoint(mock, RoomStateEventEndpoint).expect_default_access_token()
691 }
692
693 /// Create a prebuilt mock for uploading media.
694 pub fn mock_upload(&self) -> MockEndpoint<'_, UploadEndpoint> {
695 let mock = Mock::given(method("POST")).and(path("/_matrix/media/v3/upload"));
696 self.mock_endpoint(mock, UploadEndpoint)
697 }
698
699 /// Create a prebuilt mock for resolving room aliases.
700 ///
701 /// # Examples
702 ///
703 /// ```
704 /// # tokio_test::block_on(async {
705 /// use matrix_sdk::{
706 /// ruma::{owned_room_id, room_alias_id},
707 /// test_utils::mocks::MatrixMockServer,
708 /// };
709 /// let mock_server = MatrixMockServer::new().await;
710 /// let client = mock_server.client_builder().build().await;
711 ///
712 /// mock_server
713 /// .mock_room_directory_resolve_alias()
714 /// .ok("!a:b.c", Vec::new())
715 /// .mock_once()
716 /// .mount()
717 /// .await;
718 ///
719 /// let res = client
720 /// .resolve_room_alias(room_alias_id!("#a:b.c"))
721 /// .await
722 /// .expect("We should be able to resolve the room alias");
723 /// assert_eq!(res.room_id, "!a:b.c");
724 /// # anyhow::Ok(()) });
725 /// ```
726 pub fn mock_room_directory_resolve_alias(&self) -> MockEndpoint<'_, ResolveRoomAliasEndpoint> {
727 let mock =
728 Mock::given(method("GET")).and(path_regex(r"/_matrix/client/v3/directory/room/.*"));
729 self.mock_endpoint(mock, ResolveRoomAliasEndpoint)
730 }
731
732 /// Create a prebuilt mock for publishing room aliases in the room
733 /// directory.
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// # tokio_test::block_on(async {
739 /// use matrix_sdk::{
740 /// ruma::{room_alias_id, room_id},
741 /// test_utils::mocks::MatrixMockServer,
742 /// };
743 ///
744 /// let mock_server = MatrixMockServer::new().await;
745 /// let client = mock_server.client_builder().build().await;
746 ///
747 /// mock_server
748 /// .mock_room_directory_create_room_alias()
749 /// .ok()
750 /// .mock_once()
751 /// .mount()
752 /// .await;
753 ///
754 /// client
755 /// .create_room_alias(room_alias_id!("#a:b.c"), room_id!("!a:b.c"))
756 /// .await
757 /// .expect("We should be able to create a room alias");
758 /// # anyhow::Ok(()) });
759 /// ```
760 pub fn mock_room_directory_create_room_alias(
761 &self,
762 ) -> MockEndpoint<'_, CreateRoomAliasEndpoint> {
763 let mock =
764 Mock::given(method("PUT")).and(path_regex(r"/_matrix/client/v3/directory/room/.*"));
765 self.mock_endpoint(mock, CreateRoomAliasEndpoint)
766 }
767
768 /// Create a prebuilt mock for removing room aliases from the room
769 /// directory.
770 ///
771 /// # Examples
772 ///
773 /// ```
774 /// # tokio_test::block_on(async {
775 /// use matrix_sdk::{
776 /// ruma::room_alias_id, test_utils::mocks::MatrixMockServer,
777 /// };
778 ///
779 /// let mock_server = MatrixMockServer::new().await;
780 /// let client = mock_server.client_builder().build().await;
781 ///
782 /// mock_server
783 /// .mock_room_directory_remove_room_alias()
784 /// .ok()
785 /// .mock_once()
786 /// .mount()
787 /// .await;
788 ///
789 /// client
790 /// .remove_room_alias(room_alias_id!("#a:b.c"))
791 /// .await
792 /// .expect("We should be able to remove the room alias");
793 /// # anyhow::Ok(()) });
794 /// ```
795 pub fn mock_room_directory_remove_room_alias(
796 &self,
797 ) -> MockEndpoint<'_, RemoveRoomAliasEndpoint> {
798 let mock =
799 Mock::given(method("DELETE")).and(path_regex(r"/_matrix/client/v3/directory/room/.*"));
800 self.mock_endpoint(mock, RemoveRoomAliasEndpoint)
801 }
802
803 /// Create a prebuilt mock for listing all public rooms.
804 pub fn mock_get_all_public_rooms(&self) -> MockEndpoint<'_, PublicRoomsEndpoint> {
805 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/publicRooms"));
806 self.mock_endpoint(mock, PublicRoomsEndpoint)
807 }
808
809 /// Create a prebuilt mock for listing filtered public rooms.
810 ///
811 /// # Examples
812 ///
813 /// ```
814 /// #
815 /// tokio_test::block_on(async {
816 /// use js_int::uint;
817 /// use ruma::directory::PublicRoomsChunkInit;
818 /// use matrix_sdk::room_directory_search::RoomDirectorySearch;
819 /// use matrix_sdk::{
820 /// ruma::{event_id, room_id},
821 /// test_utils::mocks::MatrixMockServer,
822 /// };
823 /// let mock_server = MatrixMockServer::new().await;
824 /// let client = mock_server.client_builder().build().await;
825 /// let event_id = event_id!("$id");
826 /// let room_id = room_id!("!room_id:localhost");
827 ///
828 /// let chunk = vec![PublicRoomsChunkInit {
829 /// num_joined_members: uint!(0),
830 /// room_id: room_id.to_owned(),
831 /// world_readable: true,
832 /// guest_can_join: true,
833 /// }.into()];
834 ///
835 /// mock_server.mock_get_filtered_public_rooms().ok(chunk, None, None, Some(20)).mock_once().mount().await;
836 /// let mut room_directory_search = RoomDirectorySearch::new(client);
837 ///
838 /// room_directory_search.search(Some("some-alias".to_owned()), 100, None)
839 /// .await
840 /// .expect("Room directory search failed");
841 ///
842 /// let (results, _) = room_directory_search.results();
843 /// assert_eq!(results.len(), 1);
844 /// assert_eq!(results.get(0).unwrap().room_id, room_id.to_owned());
845 /// # });
846 /// ```
847 pub fn mock_get_filtered_public_rooms(&self) -> MockEndpoint<'_, PublicRoomsEndpoint> {
848 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/publicRooms"));
849 self.mock_endpoint(mock, PublicRoomsEndpoint)
850 }
851
852 /// Create a prebuilt mock for setting a room's visibility in the room
853 /// directory.
854 ///
855 /// # Examples
856 ///
857 /// ```
858 /// # tokio_test::block_on(async {
859 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
860 /// use ruma::api::client::room::Visibility;
861 ///
862 /// let mock_server = MatrixMockServer::new().await;
863 /// let client = mock_server.client_builder().build().await;
864 ///
865 /// mock_server
866 /// .mock_room_directory_set_room_visibility()
867 /// .ok()
868 /// .mock_once()
869 /// .mount()
870 /// .await;
871 ///
872 /// let room = mock_server
873 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
874 /// .await;
875 ///
876 /// room.privacy_settings()
877 /// .update_room_visibility(Visibility::Private)
878 /// .await
879 /// .expect("We should be able to update the room's visibility");
880 /// # anyhow::Ok(()) });
881 /// ```
882 pub fn mock_room_directory_set_room_visibility(
883 &self,
884 ) -> MockEndpoint<'_, SetRoomVisibilityEndpoint> {
885 let mock = Mock::given(method("PUT"))
886 .and(path_regex(r"^/_matrix/client/v3/directory/list/room/.*$"));
887 self.mock_endpoint(mock, SetRoomVisibilityEndpoint)
888 }
889
890 /// Create a prebuilt mock for getting a room's visibility in the room
891 /// directory.
892 ///
893 /// # Examples
894 ///
895 /// ```
896 /// # tokio_test::block_on(async {
897 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
898 /// use ruma::api::client::room::Visibility;
899 ///
900 /// let mock_server = MatrixMockServer::new().await;
901 /// let client = mock_server.client_builder().build().await;
902 ///
903 /// mock_server
904 /// .mock_room_directory_get_room_visibility()
905 /// .ok(Visibility::Public)
906 /// .mock_once()
907 /// .mount()
908 /// .await;
909 ///
910 /// let room = mock_server
911 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
912 /// .await;
913 ///
914 /// let visibility = room
915 /// .privacy_settings()
916 /// .get_room_visibility()
917 /// .await
918 /// .expect("We should be able to get the room's visibility");
919 /// assert_eq!(visibility, Visibility::Public);
920 /// # anyhow::Ok(()) });
921 /// ```
922 pub fn mock_room_directory_get_room_visibility(
923 &self,
924 ) -> MockEndpoint<'_, GetRoomVisibilityEndpoint> {
925 let mock = Mock::given(method("GET"))
926 .and(path_regex(r"^/_matrix/client/v3/directory/list/room/.*$"));
927 self.mock_endpoint(mock, GetRoomVisibilityEndpoint)
928 }
929
930 /// Create a prebuilt mock for fetching information about key storage
931 /// backups.
932 ///
933 /// # Examples
934 ///
935 /// ```
936 /// # #[cfg(feature = "e2e-encryption")]
937 /// # {
938 /// # tokio_test::block_on(async {
939 /// use matrix_sdk::test_utils::mocks::MatrixMockServer;
940 ///
941 /// let mock_server = MatrixMockServer::new().await;
942 /// let client = mock_server.client_builder().build().await;
943 ///
944 /// mock_server.mock_room_keys_version().exists().expect(1).mount().await;
945 ///
946 /// let exists =
947 /// client.encryption().backups().fetch_exists_on_server().await.unwrap();
948 ///
949 /// assert!(exists);
950 /// # });
951 /// # }
952 /// ```
953 pub fn mock_room_keys_version(&self) -> MockEndpoint<'_, RoomKeysVersionEndpoint> {
954 let mock =
955 Mock::given(method("GET")).and(path_regex(r"_matrix/client/v3/room_keys/version"));
956 self.mock_endpoint(mock, RoomKeysVersionEndpoint).expect_default_access_token()
957 }
958
959 /// Create a prebuilt mock for adding key storage backups via POST
960 pub fn mock_add_room_keys_version(&self) -> MockEndpoint<'_, AddRoomKeysVersionEndpoint> {
961 let mock =
962 Mock::given(method("POST")).and(path_regex(r"_matrix/client/v3/room_keys/version"));
963 self.mock_endpoint(mock, AddRoomKeysVersionEndpoint).expect_any_access_token()
964 }
965
966 /// Create a prebuilt mock for adding key storage backups via POST
967 pub fn mock_delete_room_keys_version(&self) -> MockEndpoint<'_, DeleteRoomKeysVersionEndpoint> {
968 let mock = Mock::given(method("DELETE"))
969 .and(path_regex(r"_matrix/client/v3/room_keys/version/[^/]*"));
970 self.mock_endpoint(mock, DeleteRoomKeysVersionEndpoint).expect_default_access_token()
971 }
972
973 /// Creates a prebuilt mock for the `/sendToDevice` endpoint.
974 ///
975 /// This mock can be used to simulate sending to-device messages in tests.
976 ///
977 /// # Examples
978 ///
979 /// ```
980 /// # #[cfg(feature = "e2e-encryption")]
981 /// # {
982 /// # tokio_test::block_on(async {
983 /// use std::collections::BTreeMap;
984 /// use matrix_sdk::{
985 /// ruma::{
986 /// events::{AnyToDeviceEventContent, dummy::ToDeviceDummyEventContent},
987 /// serde::Raw,
988 /// api::client::to_device::send_event_to_device::v3::Request as ToDeviceRequest,
989 /// to_device::DeviceIdOrAllDevices,
990 /// owned_user_id, owned_device_id
991 /// },
992 /// test_utils::mocks::MatrixMockServer,
993 /// };
994 /// use serde_json::json;
995 ///
996 /// let mock_server = MatrixMockServer::new().await;
997 /// let client = mock_server.client_builder().build().await;
998 ///
999 /// mock_server.mock_send_to_device().ok().mock_once().mount().await;
1000 ///
1001 /// let request = ToDeviceRequest::new_raw(
1002 /// "m.custom.event".into(),
1003 /// "txn_id".into(),
1004 /// BTreeMap::from([(
1005 /// owned_user_id!("@alice:localhost"),
1006 /// BTreeMap::from([(
1007 /// DeviceIdOrAllDevices::AllDevices,
1008 /// Raw::new(&AnyToDeviceEventContent::Dummy(ToDeviceDummyEventContent {})).unwrap(),
1009 /// )])
1010 /// )]),
1011 /// );
1012 ///
1013 /// client
1014 /// .send(request)
1015 /// .await
1016 /// .expect("We should be able to send a to-device message");
1017 /// # anyhow::Ok(()) });
1018 /// # }
1019 /// ```
1020 pub fn mock_send_to_device(&self) -> MockEndpoint<'_, SendToDeviceEndpoint> {
1021 let mock =
1022 Mock::given(method("PUT")).and(path_regex(r"^/_matrix/client/v3/sendToDevice/.*/.*"));
1023 self.mock_endpoint(mock, SendToDeviceEndpoint).expect_default_access_token()
1024 }
1025
1026 /// Create a prebuilt mock for getting the room members in a room.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// # tokio_test::block_on(async {
1032 /// use matrix_sdk::{
1033 /// ruma::{event_id, room_id},
1034 /// test_utils::mocks::MatrixMockServer,
1035 /// };
1036 /// use matrix_sdk_base::RoomMemberships;
1037 /// use matrix_sdk_test::event_factory::EventFactory;
1038 /// use ruma::{
1039 /// events::room::member::{MembershipState, RoomMemberEventContent},
1040 /// user_id,
1041 /// };
1042 /// let mock_server = MatrixMockServer::new().await;
1043 /// let client = mock_server.client_builder().build().await;
1044 /// let event_id = event_id!("$id");
1045 /// let room_id = room_id!("!room_id:localhost");
1046 ///
1047 /// let f = EventFactory::new().room(room_id);
1048 /// let alice_user_id = user_id!("@alice:b.c");
1049 /// let alice_knock_event = f
1050 /// .event(RoomMemberEventContent::new(MembershipState::Knock))
1051 /// .event_id(event_id)
1052 /// .sender(alice_user_id)
1053 /// .state_key(alice_user_id)
1054 /// .into_raw();
1055 ///
1056 /// mock_server
1057 /// .mock_get_members()
1058 /// .ok(vec![alice_knock_event])
1059 /// .mock_once()
1060 /// .mount()
1061 /// .await;
1062 /// let room = mock_server.sync_joined_room(&client, room_id).await;
1063 ///
1064 /// let members = room.members(RoomMemberships::all()).await.unwrap();
1065 /// assert_eq!(members.len(), 1);
1066 /// # });
1067 /// ```
1068 pub fn mock_get_members(&self) -> MockEndpoint<'_, GetRoomMembersEndpoint> {
1069 let mock =
1070 Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/members$"));
1071 self.mock_endpoint(mock, GetRoomMembersEndpoint)
1072 }
1073
1074 /// Creates a prebuilt mock for inviting a user to a room by its id.
1075 ///
1076 /// # Examples
1077 ///
1078 /// ```
1079 /// # use ruma::user_id;
1080 /// tokio_test::block_on(async {
1081 /// use matrix_sdk::{
1082 /// ruma::room_id,
1083 /// test_utils::mocks::MatrixMockServer,
1084 /// };
1085 ///
1086 /// let mock_server = MatrixMockServer::new().await;
1087 /// let client = mock_server.client_builder().build().await;
1088 ///
1089 /// mock_server.mock_invite_user_by_id().ok().mock_once().mount().await;
1090 ///
1091 /// let room = mock_server
1092 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
1093 /// .await;
1094 ///
1095 /// room.invite_user_by_id(user_id!("@alice:localhost")).await.unwrap();
1096 /// # anyhow::Ok(()) });
1097 /// ```
1098 pub fn mock_invite_user_by_id(&self) -> MockEndpoint<'_, InviteUserByIdEndpoint> {
1099 let mock =
1100 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/invite$"));
1101 self.mock_endpoint(mock, InviteUserByIdEndpoint)
1102 }
1103
1104 /// Creates a prebuilt mock for kicking a user from a room.
1105 ///
1106 /// # Examples
1107 ///
1108 /// ```
1109 /// # use ruma::user_id;
1110 /// tokio_test::block_on(async {
1111 /// use matrix_sdk::{
1112 /// ruma::room_id,
1113 /// test_utils::mocks::MatrixMockServer,
1114 /// };
1115 ///
1116 /// let mock_server = MatrixMockServer::new().await;
1117 /// let client = mock_server.client_builder().build().await;
1118 ///
1119 /// mock_server.mock_kick_user().ok().mock_once().mount().await;
1120 ///
1121 /// let room = mock_server
1122 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
1123 /// .await;
1124 ///
1125 /// room.kick_user(user_id!("@alice:localhost"), None).await.unwrap();
1126 /// # anyhow::Ok(()) });
1127 /// ```
1128 pub fn mock_kick_user(&self) -> MockEndpoint<'_, KickUserEndpoint> {
1129 let mock =
1130 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/kick"));
1131 self.mock_endpoint(mock, KickUserEndpoint)
1132 }
1133
1134 /// Creates a prebuilt mock for banning a user from a room.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// # use ruma::user_id;
1140 /// tokio_test::block_on(async {
1141 /// use matrix_sdk::{
1142 /// ruma::room_id,
1143 /// test_utils::mocks::MatrixMockServer,
1144 /// };
1145 ///
1146 /// let mock_server = MatrixMockServer::new().await;
1147 /// let client = mock_server.client_builder().build().await;
1148 ///
1149 /// mock_server.mock_ban_user().ok().mock_once().mount().await;
1150 ///
1151 /// let room = mock_server
1152 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
1153 /// .await;
1154 ///
1155 /// room.ban_user(user_id!("@alice:localhost"), None).await.unwrap();
1156 /// # anyhow::Ok(()) });
1157 /// ```
1158 pub fn mock_ban_user(&self) -> MockEndpoint<'_, BanUserEndpoint> {
1159 let mock = Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/ban"));
1160 self.mock_endpoint(mock, BanUserEndpoint)
1161 }
1162
1163 /// Creates a prebuilt mock for unbanning a user from a room.
1164 pub fn mock_unban_user(&self) -> MockEndpoint<'_, UnbanUserEndpoint> {
1165 let mock =
1166 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/unban$"));
1167 self.mock_endpoint(mock, UnbanUserEndpoint)
1168 }
1169
1170 /// Creates a prebuilt mock for updating the typing notice in a room.
1171 pub fn mock_update_typing(&self) -> MockEndpoint<'_, UpdateTypingEndpoint> {
1172 let mock =
1173 Mock::given(method("PUT")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/typing/.*"));
1174 self.mock_endpoint(mock, UpdateTypingEndpoint)
1175 }
1176
1177 /// Creates a prebuilt mock for reporting an event in a room.
1178 pub fn mock_report_room_event(&self) -> MockEndpoint<'_, ReportRoomEventEndpoint> {
1179 let mock =
1180 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/report/.*"));
1181 self.mock_endpoint(mock, ReportRoomEventEndpoint)
1182 }
1183
1184 /// Creates a prebuilt mock for reporting a room.
1185 pub fn mock_report_room(&self) -> MockEndpoint<'_, ReportRoomEndpoint> {
1186 let mock =
1187 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/report$"));
1188 self.mock_endpoint(mock, ReportRoomEndpoint)
1189 }
1190
1191 /// Creates a prebuilt mock for reporting a user.
1192 pub fn mock_report_user(&self) -> MockEndpoint<'_, ReportUserEndpoint> {
1193 let mock = Mock::given(method("POST"));
1194 self.mock_endpoint(mock, ReportUserEndpoint::default())
1195 }
1196
1197 /// Creates a prebuilt mock for the `/_matrix/client/versions` endpoint.
1198 pub fn mock_versions(&self) -> MockEndpoint<'_, VersionsEndpoint> {
1199 let mock = Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/versions"));
1200 self.mock_endpoint(mock, VersionsEndpoint::default())
1201 }
1202
1203 /// Creates a prebuilt mock for the room summary endpoint [MSC3266](https://github.com/matrix-org/matrix-spec-proposals/pull/3266).
1204 pub fn mock_room_summary(&self) -> MockEndpoint<'_, RoomSummaryEndpoint> {
1205 let mock = Mock::given(method("GET"))
1206 .and(path_regex(r"^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary"));
1207 self.mock_endpoint(mock, RoomSummaryEndpoint)
1208 }
1209
1210 /// Creates a prebuilt mock for the endpoint used to set a room's pinned
1211 /// events.
1212 pub fn mock_set_room_pinned_events(&self) -> MockEndpoint<'_, SetRoomPinnedEventsEndpoint> {
1213 let mock = Mock::given(method("PUT"))
1214 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.room.pinned_events/.*?"));
1215 self.mock_endpoint(mock, SetRoomPinnedEventsEndpoint).expect_default_access_token()
1216 }
1217
1218 /// Creates a prebuilt mock for the endpoint used to get information about
1219 /// the owner of the given access token.
1220 ///
1221 /// If no access token is provided, the access token to match is
1222 /// [`TestAuthToken::AccessDefault`].
1223 pub fn mock_who_am_i(&self) -> MockEndpoint<'_, WhoAmIEndpoint> {
1224 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/account/whoami"));
1225 self.mock_endpoint(mock, WhoAmIEndpoint).expect_default_access_token()
1226 }
1227
1228 /// Creates a prebuilt mock for the endpoint used to publish end-to-end
1229 /// encryption keys.
1230 pub fn mock_upload_keys(&self) -> MockEndpoint<'_, UploadKeysEndpoint> {
1231 let mock = Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/keys/upload"));
1232 self.mock_endpoint(mock, UploadKeysEndpoint).expect_default_access_token()
1233 }
1234
1235 /// Creates a prebuilt mock for the endpoint used to query end-to-end
1236 /// encryption keys.
1237 pub fn mock_query_keys(&self) -> MockEndpoint<'_, QueryKeysEndpoint> {
1238 let mock = Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/keys/query"));
1239 self.mock_endpoint(mock, QueryKeysEndpoint).expect_default_access_token()
1240 }
1241
1242 /// Creates a prebuilt mock for the endpoint used to discover the URL of a
1243 /// homeserver.
1244 pub fn mock_well_known(&self) -> MockEndpoint<'_, WellKnownEndpoint> {
1245 let mock = Mock::given(method("GET")).and(path_regex(r"^/.well-known/matrix/client"));
1246 self.mock_endpoint(mock, WellKnownEndpoint)
1247 }
1248
1249 /// Creates a prebuilt mock for the endpoint used to publish cross-signing
1250 /// keys.
1251 pub fn mock_upload_cross_signing_keys(
1252 &self,
1253 ) -> MockEndpoint<'_, UploadCrossSigningKeysEndpoint> {
1254 let mock = Mock::given(method("POST"))
1255 .and(path_regex(r"^/_matrix/client/v3/keys/device_signing/upload"));
1256 self.mock_endpoint(mock, UploadCrossSigningKeysEndpoint).expect_default_access_token()
1257 }
1258
1259 /// Creates a prebuilt mock for the endpoint used to publish cross-signing
1260 /// signatures.
1261 pub fn mock_upload_cross_signing_signatures(
1262 &self,
1263 ) -> MockEndpoint<'_, UploadCrossSigningSignaturesEndpoint> {
1264 let mock = Mock::given(method("POST"))
1265 .and(path_regex(r"^/_matrix/client/v3/keys/signatures/upload"));
1266 self.mock_endpoint(mock, UploadCrossSigningSignaturesEndpoint).expect_default_access_token()
1267 }
1268
1269 /// Creates a prebuilt mock for the MSC3814 endpoint that fetches the
1270 /// currently stored dehydrated device.
1271 #[cfg(feature = "e2e-encryption")]
1272 pub fn mock_get_dehydrated_device(&self) -> MockEndpoint<'_, GetDehydratedDeviceEndpoint> {
1273 let mock = Mock::given(method("GET"))
1274 .and(path_regex(r"^/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device$"));
1275 self.mock_endpoint(mock, GetDehydratedDeviceEndpoint).expect_any_access_token()
1276 }
1277
1278 /// Creates a prebuilt mock for the MSC3814 endpoint that uploads a fresh
1279 /// dehydrated device.
1280 #[cfg(feature = "e2e-encryption")]
1281 pub fn mock_put_dehydrated_device(&self) -> MockEndpoint<'_, PutDehydratedDeviceEndpoint> {
1282 let mock = Mock::given(method("PUT"))
1283 .and(path_regex(r"^/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device$"));
1284 self.mock_endpoint(mock, PutDehydratedDeviceEndpoint).expect_any_access_token()
1285 }
1286
1287 /// Creates a prebuilt mock for the MSC3814 endpoint that deletes the
1288 /// current dehydrated device.
1289 #[cfg(feature = "e2e-encryption")]
1290 pub fn mock_delete_dehydrated_device(
1291 &self,
1292 ) -> MockEndpoint<'_, DeleteDehydratedDeviceEndpoint> {
1293 let mock = Mock::given(method("DELETE"))
1294 .and(path_regex(r"^/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device$"));
1295 self.mock_endpoint(mock, DeleteDehydratedDeviceEndpoint).expect_any_access_token()
1296 }
1297
1298 /// Creates a prebuilt mock for the MSC3814 endpoint that fetches the queued
1299 /// to-device events for a dehydrated device.
1300 #[cfg(feature = "e2e-encryption")]
1301 pub fn mock_dehydrated_device_events(
1302 &self,
1303 ) -> MockEndpoint<'_, DehydratedDeviceEventsEndpoint> {
1304 let mock = Mock::given(method("POST")).and(path_regex(
1305 r"^/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/[^/]+/events$",
1306 ));
1307 self.mock_endpoint(mock, DehydratedDeviceEventsEndpoint).expect_any_access_token()
1308 }
1309
1310 /// Creates a prebuilt mock for the endpoint used to leave a room.
1311 pub fn mock_room_leave(&self) -> MockEndpoint<'_, RoomLeaveEndpoint> {
1312 let mock =
1313 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/leave"));
1314 self.mock_endpoint(mock, RoomLeaveEndpoint).expect_default_access_token()
1315 }
1316
1317 /// Creates a prebuilt mock for the endpoint used to forget a room.
1318 pub fn mock_room_forget(&self) -> MockEndpoint<'_, RoomForgetEndpoint> {
1319 let mock =
1320 Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/forget"));
1321 self.mock_endpoint(mock, RoomForgetEndpoint).expect_default_access_token()
1322 }
1323
1324 /// Create a prebuilt mock for the endpoint use to log out a session.
1325 pub fn mock_logout(&self) -> MockEndpoint<'_, LogoutEndpoint> {
1326 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/logout"));
1327 self.mock_endpoint(mock, LogoutEndpoint).expect_default_access_token()
1328 }
1329
1330 /// Create a prebuilt mock for the endpoint used to get the list of thread
1331 /// roots.
1332 pub fn mock_room_threads(&self) -> MockEndpoint<'_, RoomThreadsEndpoint> {
1333 let mock =
1334 Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v1/rooms/.*/threads$"));
1335 self.mock_endpoint(mock, RoomThreadsEndpoint).expect_default_access_token()
1336 }
1337
1338 /// Create a prebuilt mock for the endpoint used to get the related events.
1339 pub fn mock_room_relations(&self) -> MockEndpoint<'_, RoomRelationsEndpoint> {
1340 // Routing happens in the final method ok(), since it can get
1341 // complicated.
1342 let mock = Mock::given(method("GET"));
1343 self.mock_endpoint(mock, RoomRelationsEndpoint::default()).expect_default_access_token()
1344 }
1345
1346 /// Create a prebuilt mock for the endpoint used to get the global account
1347 /// data.
1348 ///
1349 /// # Examples
1350 ///
1351 /// ```
1352 /// tokio_test::block_on(async {
1353 /// use js_int::uint;
1354 /// use matrix_sdk::test_utils::mocks::MatrixMockServer;
1355 ///
1356 /// let mock_server = MatrixMockServer::new().await;
1357 /// let client = mock_server.client_builder().build().await;
1358 ///
1359 /// mock_server.mock_get_recent_emojis().ok(
1360 /// client.user_id().unwrap(),
1361 /// vec![(":)".to_string(), uint!(1))]
1362 /// )
1363 /// .mock_once()
1364 /// .mount()
1365 /// .await;
1366 ///
1367 /// client.account().get_recent_emojis(true).await.unwrap();
1368 ///
1369 /// # anyhow::Ok(()) });
1370 /// ```
1371 #[cfg(feature = "experimental-element-recent-emojis")]
1372 pub fn mock_get_recent_emojis(&self) -> MockEndpoint<'_, GetRecentEmojisEndpoint> {
1373 let mock = Mock::given(method("GET"));
1374 self.mock_endpoint(mock, GetRecentEmojisEndpoint).expect_default_access_token()
1375 }
1376
1377 /// Create a prebuilt mock for the endpoint that updates the global account
1378 /// data.
1379 ///
1380 /// # Examples
1381 ///
1382 /// ```
1383 /// tokio_test::block_on(async {
1384 /// use js_int::uint;
1385 /// use matrix_sdk::test_utils::mocks::MatrixMockServer;
1386 /// use ruma::user_id;
1387 ///
1388 /// let mock_server = MatrixMockServer::new().await;
1389 /// let client = mock_server.client_builder().build().await;
1390 /// let user_id = client.user_id().unwrap();
1391 ///
1392 /// mock_server.mock_get_recent_emojis()
1393 /// .ok(user_id, vec![(":D".to_string(), uint!(1))])
1394 /// .mock_once()
1395 /// .mount()
1396 /// .await;
1397 ///
1398 /// mock_server.mock_add_recent_emojis()
1399 /// .ok(user_id)
1400 /// .mock_once()
1401 /// .mount()
1402 /// .await;
1403 /// // Calls both get and update recent emoji endpoints, with an update value
1404 /// client.account().add_recent_emoji(":D").await.unwrap();
1405 ///
1406 /// # anyhow::Ok(()) });
1407 /// ```
1408 #[cfg(feature = "experimental-element-recent-emojis")]
1409 pub fn mock_add_recent_emojis(&self) -> MockEndpoint<'_, UpdateRecentEmojisEndpoint> {
1410 let mock = Mock::given(method("PUT"));
1411 self.mock_endpoint(mock, UpdateRecentEmojisEndpoint::new()).expect_default_access_token()
1412 }
1413
1414 /// Create a prebuilt mock for the endpoint used to get the default secret
1415 /// storage key.
1416 ///
1417 /// # Examples
1418 ///
1419 /// ```
1420 /// tokio_test::block_on(async {
1421 /// use js_int::uint;
1422 /// use matrix_sdk::{
1423 /// encryption::secret_storage::SecretStorage,
1424 /// test_utils::mocks::MatrixMockServer,
1425 /// };
1426 ///
1427 /// let mock_server = MatrixMockServer::new().await;
1428 /// let client = mock_server.client_builder().build().await;
1429 ///
1430 /// mock_server.mock_get_default_secret_storage_key().ok(
1431 /// client.user_id().unwrap(),
1432 /// "abc", // key ID of default secret storage key
1433 /// )
1434 /// .mount()
1435 /// .await;
1436 ///
1437 /// client.encryption()
1438 /// .secret_storage()
1439 /// .fetch_default_key_id()
1440 /// .await
1441 /// .unwrap();
1442 ///
1443 /// # anyhow::Ok(()) });
1444 /// ```
1445 #[cfg(feature = "e2e-encryption")]
1446 pub fn mock_get_default_secret_storage_key(
1447 &self,
1448 ) -> MockEndpoint<'_, GetDefaultSecretStorageKeyEndpoint> {
1449 let mock = Mock::given(method("GET"));
1450 self.mock_endpoint(mock, GetDefaultSecretStorageKeyEndpoint).expect_default_access_token()
1451 }
1452
1453 /// Create a prebuilt mock for the endpoint used to get a secret storage
1454 /// key.
1455 ///
1456 /// # Examples
1457 ///
1458 /// ```
1459 /// tokio_test::block_on(async {
1460 /// use js_int::uint;
1461 /// use ruma::events::secret_storage::key;
1462 /// use ruma::serde::Base64;
1463 /// use matrix_sdk::{
1464 /// encryption::secret_storage::SecretStorage,
1465 /// test_utils::mocks::MatrixMockServer,
1466 /// };
1467 ///
1468 /// let mock_server = MatrixMockServer::new().await;
1469 /// let client = mock_server.client_builder().build().await;
1470 ///
1471 /// mock_server.mock_get_default_secret_storage_key().ok(
1472 /// client.user_id().unwrap(),
1473 /// "abc",
1474 /// )
1475 /// .mount()
1476 /// .await;
1477 /// mock_server.mock_get_secret_storage_key().ok(
1478 /// client.user_id().unwrap(),
1479 /// &key::SecretStorageKeyEventContent::new(
1480 /// "abc".into(),
1481 /// key::SecretStorageEncryptionAlgorithm::V1AesHmacSha2(key::SecretStorageV1AesHmacSha2Properties::new(
1482 /// Some(Base64::parse("xv5b6/p3ExEw++wTyfSHEg==").unwrap()),
1483 /// Some(Base64::parse("ujBBbXahnTAMkmPUX2/0+VTfUh63pGyVRuBcDMgmJC8=").unwrap()),
1484 /// )),
1485 /// ),
1486 /// )
1487 /// .mount()
1488 /// .await;
1489 ///
1490 /// client.encryption()
1491 /// .secret_storage()
1492 /// .open_secret_store("EsTj 3yST y93F SLpB jJsz eAXc 2XzA ygD3 w69H fGaN TKBj jXEd")
1493 /// .await
1494 /// .unwrap();
1495 ///
1496 /// # anyhow::Ok(()) });
1497 /// ```
1498 #[cfg(feature = "e2e-encryption")]
1499 pub fn mock_get_secret_storage_key(&self) -> MockEndpoint<'_, GetSecretStorageKeyEndpoint> {
1500 let mock = Mock::given(method("GET"));
1501 self.mock_endpoint(mock, GetSecretStorageKeyEndpoint).expect_default_access_token()
1502 }
1503
1504 /// Create a prebuilt mock for the endpoint used to get the default secret
1505 /// storage key.
1506 ///
1507 /// # Examples
1508 ///
1509 /// ```
1510 /// tokio_test::block_on(async {
1511 /// use js_int::uint;
1512 /// use serde_json::json;
1513 /// use ruma::events::GlobalAccountDataEventType;
1514 /// use matrix_sdk::test_utils::mocks::MatrixMockServer;
1515 ///
1516 /// let mock_server = MatrixMockServer::new().await;
1517 /// let client = mock_server.client_builder().build().await;
1518 ///
1519 /// mock_server.mock_get_master_signing_key().ok(
1520 /// client.user_id().unwrap(),
1521 /// json!({})
1522 /// )
1523 /// .mount()
1524 /// .await;
1525 ///
1526 /// client.account()
1527 /// .fetch_account_data(GlobalAccountDataEventType::from("m.cross_signing.master".to_owned()))
1528 /// .await
1529 /// .unwrap();
1530 ///
1531 /// # anyhow::Ok(()) });
1532 /// ```
1533 #[cfg(feature = "e2e-encryption")]
1534 pub fn mock_get_master_signing_key(&self) -> MockEndpoint<'_, GetMasterSigningKeyEndpoint> {
1535 let mock = Mock::given(method("GET"));
1536 self.mock_endpoint(mock, GetMasterSigningKeyEndpoint).expect_default_access_token()
1537 }
1538
1539 /// Create a prebuilt mock for the endpoint used to send a single receipt.
1540 pub fn mock_send_receipt(
1541 &self,
1542 receipt_type: ReceiptType,
1543 ) -> MockEndpoint<'_, ReceiptEndpoint> {
1544 let mock = Mock::given(method("POST"))
1545 .and(path_regex(format!("^/_matrix/client/v3/rooms/.*/receipt/{receipt_type}/")));
1546 self.mock_endpoint(mock, ReceiptEndpoint).expect_default_access_token()
1547 }
1548
1549 /// Create a prebuilt mock for the endpoint used to send multiple receipts.
1550 pub fn mock_send_read_markers(&self) -> MockEndpoint<'_, ReadMarkersEndpoint> {
1551 let mock = Mock::given(method("POST"))
1552 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/read_markers"));
1553 self.mock_endpoint(mock, ReadMarkersEndpoint).expect_default_access_token()
1554 }
1555
1556 /// Create a prebuilt mock for the endpoint used to set room account data.
1557 pub fn mock_set_room_account_data(
1558 &self,
1559 data_type: RoomAccountDataEventType,
1560 ) -> MockEndpoint<'_, RoomAccountDataEndpoint> {
1561 let mock = Mock::given(method("PUT")).and(path_regex(format!(
1562 "^/_matrix/client/v3/user/.*/rooms/.*/account_data/{data_type}"
1563 )));
1564 self.mock_endpoint(mock, RoomAccountDataEndpoint).expect_default_access_token()
1565 }
1566
1567 /// Create a prebuilt mock for the endpoint used to get the media config of
1568 /// the homeserver that requires authentication.
1569 pub fn mock_authenticated_media_config(
1570 &self,
1571 ) -> MockEndpoint<'_, AuthenticatedMediaConfigEndpoint> {
1572 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v1/media/config"));
1573 self.mock_endpoint(mock, AuthenticatedMediaConfigEndpoint)
1574 }
1575
1576 /// Create a prebuilt mock for the endpoint used to get the media config of
1577 /// the homeserver without requiring authentication.
1578 pub fn mock_media_config(&self) -> MockEndpoint<'_, MediaConfigEndpoint> {
1579 let mock = Mock::given(method("GET")).and(path("/_matrix/media/v3/config"));
1580 self.mock_endpoint(mock, MediaConfigEndpoint)
1581 }
1582
1583 /// Create a prebuilt mock for the endpoint used to get the supported legacy
1584 /// login types.
1585 pub fn mock_get_login_types(&self) -> MockEndpoint<'_, GetLoginTypesEndpoint> {
1586 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/login"));
1587 self.mock_endpoint(mock, GetLoginTypesEndpoint)
1588 }
1589
1590 /// Create a prebuilt mock for the endpoint used to log into a session.
1591 pub fn mock_login(&self) -> MockEndpoint<'_, LoginEndpoint> {
1592 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/login"));
1593 self.mock_endpoint(mock, LoginEndpoint)
1594 }
1595
1596 /// Create a prebuilt mock for the endpoint used to register a new account.
1597 pub fn mock_register(&self) -> MockEndpoint<'_, RegisterEndpoint> {
1598 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/register"));
1599 self.mock_endpoint(mock, RegisterEndpoint)
1600 }
1601
1602 /// Create a prebuilt mock for the endpoint used to refresh an access token,
1603 /// expecting the given refresh token, if any.
1604 pub fn mock_refresh<'b>(
1605 &self,
1606 refresh_token: Option<impl Into<&'b str>>,
1607 ) -> MockEndpoint<'_, RefreshEndpoint> {
1608 let mut mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/refresh"));
1609
1610 if let Some(refresh_token) = refresh_token {
1611 mock = mock.and(body_json(json!({ "refresh_token": refresh_token.into() })));
1612 }
1613
1614 self.mock_endpoint(mock, RefreshEndpoint)
1615 }
1616
1617 /// Create a prebuilt mock for the endpoint used to list the devices of a
1618 /// user.
1619 pub fn mock_devices(&self) -> MockEndpoint<'_, DevicesEndpoint> {
1620 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/devices"));
1621 self.mock_endpoint(mock, DevicesEndpoint).expect_default_access_token()
1622 }
1623
1624 /// Create a prebuilt mock for the endpoint used to query a single device.
1625 pub fn mock_get_device(&self) -> MockEndpoint<'_, GetDeviceEndpoint> {
1626 let mock = Mock::given(method("GET")).and(path_regex("/_matrix/client/v3/devices/.*"));
1627 self.mock_endpoint(mock, GetDeviceEndpoint).expect_default_access_token()
1628 }
1629
1630 /// Create a prebuilt mock for the endpoint used to delete several devices.
1631 pub fn mock_delete_devices(&self) -> MockEndpoint<'_, DeleteDevicesEndpoint> {
1632 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/delete_devices"));
1633 self.mock_endpoint(mock, DeleteDevicesEndpoint).expect_default_access_token()
1634 }
1635
1636 /// Create a prebuilt mock for the endpoint used to search in the user
1637 /// directory.
1638 pub fn mock_user_directory(&self) -> MockEndpoint<'_, UserDirectoryEndpoint> {
1639 let mock = Mock::given(method("POST"))
1640 .and(path("/_matrix/client/v3/user_directory/search"))
1641 .and(body_json(json!({
1642 "search_term": "test",
1643 "limit": 50
1644 })));
1645 self.mock_endpoint(mock, UserDirectoryEndpoint).expect_default_access_token()
1646 }
1647
1648 /// Create a prebuilt mock for the endpoint used to create a new room.
1649 pub fn mock_create_room(&self) -> MockEndpoint<'_, CreateRoomEndpoint> {
1650 let mock = Mock::given(method("POST")).and(path("/_matrix/client/v3/createRoom"));
1651 self.mock_endpoint(mock, CreateRoomEndpoint).expect_default_access_token()
1652 }
1653
1654 /// Create a prebuilt mock for the endpoint used to upgrade a room.
1655 pub fn mock_upgrade_room(&self) -> MockEndpoint<'_, UpgradeRoomEndpoint> {
1656 let mock =
1657 Mock::given(method("POST")).and(path_regex("/_matrix/client/v3/rooms/.*/upgrade"));
1658 self.mock_endpoint(mock, UpgradeRoomEndpoint).expect_default_access_token()
1659 }
1660
1661 /// Create a prebuilt mock for the endpoint used to pre-allocate a MXC URI
1662 /// for a media file.
1663 pub fn mock_media_allocate(&self) -> MockEndpoint<'_, MediaAllocateEndpoint> {
1664 let mock = Mock::given(method("POST")).and(path("/_matrix/media/v1/create"));
1665 self.mock_endpoint(mock, MediaAllocateEndpoint)
1666 }
1667
1668 /// Create a prebuilt mock for the endpoint used to upload a media file with
1669 /// a pre-allocated MXC URI.
1670 pub fn mock_media_allocated_upload(
1671 &self,
1672 server_name: &str,
1673 media_id: &str,
1674 ) -> MockEndpoint<'_, MediaAllocatedUploadEndpoint> {
1675 let mock = Mock::given(method("PUT"))
1676 .and(path(format!("/_matrix/media/v3/upload/{server_name}/{media_id}")));
1677 self.mock_endpoint(mock, MediaAllocatedUploadEndpoint)
1678 }
1679
1680 /// Create a prebuilt mock for the endpoint used to download a media file
1681 /// without requiring authentication.
1682 pub fn mock_media_download(&self) -> MockEndpoint<'_, MediaDownloadEndpoint> {
1683 let mock = Mock::given(method("GET")).and(path_regex("^/_matrix/media/v3/download/"));
1684 self.mock_endpoint(mock, MediaDownloadEndpoint)
1685 }
1686
1687 /// Create a prebuilt mock for the endpoint used to download a thumbnail of
1688 /// a media file without requiring authentication.
1689 pub fn mock_media_thumbnail(
1690 &self,
1691 resize_method: Method,
1692 width: u16,
1693 height: u16,
1694 animated: bool,
1695 ) -> MockEndpoint<'_, MediaThumbnailEndpoint> {
1696 let mock = Mock::given(method("GET"))
1697 .and(path_regex("^/_matrix/media/v3/thumbnail/"))
1698 .and(query_param("method", resize_method.as_str()))
1699 .and(query_param("width", width.to_string()))
1700 .and(query_param("height", height.to_string()))
1701 .and(query_param("animated", animated.to_string()));
1702 self.mock_endpoint(mock, MediaThumbnailEndpoint)
1703 }
1704
1705 /// Create a prebuilt mock for the endpoint used to download a media file
1706 /// that requires authentication.
1707 pub fn mock_authed_media_download(&self) -> MockEndpoint<'_, AuthedMediaDownloadEndpoint> {
1708 let mock =
1709 Mock::given(method("GET")).and(path_regex("^/_matrix/client/v1/media/download/"));
1710 self.mock_endpoint(mock, AuthedMediaDownloadEndpoint).expect_default_access_token()
1711 }
1712
1713 /// Create a prebuilt mock for the endpoint used to get a preview of a URL
1714 /// without requiring authentication.
1715 pub fn mock_media_preview(&self) -> MockEndpoint<'_, MediaPreviewEndpoint> {
1716 let mock = Mock::given(method("GET")).and(path("/_matrix/media/v3/preview_url"));
1717 self.mock_endpoint(mock, MediaPreviewEndpoint)
1718 }
1719
1720 /// Create a prebuilt mock for the endpoint used to get a preview of a URL
1721 /// that requires authentication.
1722 pub fn mock_authed_media_preview(&self) -> MockEndpoint<'_, AuthedMediaPreviewEndpoint> {
1723 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v1/media/preview_url"));
1724 self.mock_endpoint(mock, AuthedMediaPreviewEndpoint).expect_default_access_token()
1725 }
1726
1727 /// Create a prebuilt mock for the endpoint used to download a thumbnail of
1728 /// a media file that requires authentication.
1729 pub fn mock_authed_media_thumbnail(
1730 &self,
1731 resize_method: Method,
1732 width: u16,
1733 height: u16,
1734 animated: bool,
1735 ) -> MockEndpoint<'_, AuthedMediaThumbnailEndpoint> {
1736 let mock = Mock::given(method("GET"))
1737 .and(path_regex("^/_matrix/client/v1/media/thumbnail/"))
1738 .and(query_param("method", resize_method.as_str()))
1739 .and(query_param("width", width.to_string()))
1740 .and(query_param("height", height.to_string()))
1741 .and(query_param("animated", animated.to_string()));
1742 self.mock_endpoint(mock, AuthedMediaThumbnailEndpoint).expect_default_access_token()
1743 }
1744
1745 /// Create a prebuilt mock for the endpoint used to get a single thread
1746 /// subscription status in a given room.
1747 pub fn mock_room_get_thread_subscription(
1748 &self,
1749 ) -> MockEndpoint<'_, RoomGetThreadSubscriptionEndpoint> {
1750 let mock = Mock::given(method("GET"));
1751 self.mock_endpoint(mock, RoomGetThreadSubscriptionEndpoint::default())
1752 .expect_default_access_token()
1753 }
1754
1755 /// Create a prebuilt mock for the endpoint used to define a thread
1756 /// subscription in a given room.
1757 pub fn mock_room_put_thread_subscription(
1758 &self,
1759 ) -> MockEndpoint<'_, RoomPutThreadSubscriptionEndpoint> {
1760 let mock = Mock::given(method("PUT"));
1761 self.mock_endpoint(mock, RoomPutThreadSubscriptionEndpoint::default())
1762 .expect_default_access_token()
1763 }
1764
1765 /// Create a prebuilt mock for the endpoint used to delete a thread
1766 /// subscription in a given room.
1767 pub fn mock_room_delete_thread_subscription(
1768 &self,
1769 ) -> MockEndpoint<'_, RoomDeleteThreadSubscriptionEndpoint> {
1770 let mock = Mock::given(method("DELETE"));
1771 self.mock_endpoint(mock, RoomDeleteThreadSubscriptionEndpoint::default())
1772 .expect_default_access_token()
1773 }
1774
1775 /// Create a prebuilt mock for the endpoint used to enable a push rule.
1776 pub fn mock_enable_push_rule(
1777 &self,
1778 kind: RuleKind,
1779 rule_id: impl AsRef<str>,
1780 ) -> MockEndpoint<'_, EnablePushRuleEndpoint> {
1781 let rule_id = rule_id.as_ref();
1782 let mock = Mock::given(method("PUT")).and(path_regex(format!(
1783 "^/_matrix/client/v3/pushrules/global/{kind}/{rule_id}/enabled",
1784 )));
1785 self.mock_endpoint(mock, EnablePushRuleEndpoint).expect_default_access_token()
1786 }
1787
1788 /// Create a prebuilt mock for the endpoint used to set push rules actions.
1789 pub fn mock_set_push_rules_actions(
1790 &self,
1791 kind: RuleKind,
1792 rule_id: PushRuleIdSpec<'_>,
1793 ) -> MockEndpoint<'_, SetPushRulesActionsEndpoint> {
1794 let rule_id = rule_id.to_path();
1795 let mock = Mock::given(method("PUT")).and(path_regex(format!(
1796 "^/_matrix/client/v3/pushrules/global/{kind}/{rule_id}/actions",
1797 )));
1798 self.mock_endpoint(mock, SetPushRulesActionsEndpoint).expect_default_access_token()
1799 }
1800
1801 /// Create a prebuilt mock for the endpoint used to set push rules.
1802 pub fn mock_set_push_rules(
1803 &self,
1804 kind: RuleKind,
1805 rule_id: PushRuleIdSpec<'_>,
1806 ) -> MockEndpoint<'_, SetPushRulesEndpoint> {
1807 let rule_id = rule_id.to_path();
1808 let mock = Mock::given(method("PUT"))
1809 .and(path_regex(format!("^/_matrix/client/v3/pushrules/global/{kind}/{rule_id}$",)));
1810 self.mock_endpoint(mock, SetPushRulesEndpoint).expect_default_access_token()
1811 }
1812
1813 /// Create a prebuilt mock for the endpoint used to delete push rules.
1814 pub fn mock_delete_push_rules(
1815 &self,
1816 kind: RuleKind,
1817 rule_id: PushRuleIdSpec<'_>,
1818 ) -> MockEndpoint<'_, DeletePushRulesEndpoint> {
1819 let rule_id = rule_id.to_path();
1820 let mock = Mock::given(method("DELETE"))
1821 .and(path_regex(format!("^/_matrix/client/v3/pushrules/global/{kind}/{rule_id}$",)));
1822 self.mock_endpoint(mock, DeletePushRulesEndpoint).expect_default_access_token()
1823 }
1824
1825 /// Create a prebuilt mock for the federation version endpoint.
1826 pub fn mock_federation_version(&self) -> MockEndpoint<'_, FederationVersionEndpoint> {
1827 let mock = Mock::given(method("GET")).and(path("/_matrix/federation/v1/version"));
1828 self.mock_endpoint(mock, FederationVersionEndpoint)
1829 }
1830
1831 /// Create a prebuilt mock for the endpoint used to get all thread
1832 /// subscriptions across all rooms.
1833 pub fn mock_get_thread_subscriptions(
1834 &self,
1835 ) -> MockEndpoint<'_, GetThreadSubscriptionsEndpoint> {
1836 let mock = Mock::given(method("GET"))
1837 .and(path_regex(r"^/_matrix/client/unstable/io.element.msc4308/thread_subscriptions$"));
1838 self.mock_endpoint(mock, GetThreadSubscriptionsEndpoint::default())
1839 .expect_default_access_token()
1840 }
1841
1842 /// Create a prebuilt mock for the endpoint used to retrieve a space tree
1843 pub fn mock_get_hierarchy(&self) -> MockEndpoint<'_, GetHierarchyEndpoint> {
1844 let mock =
1845 Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v1/rooms/.*/hierarchy"));
1846 self.mock_endpoint(mock, GetHierarchyEndpoint).expect_default_access_token()
1847 }
1848
1849 /// Create a prebuilt mock for the endpoint used to set a space child.
1850 pub fn mock_set_space_child(&self) -> MockEndpoint<'_, SetSpaceChildEndpoint> {
1851 let mock = Mock::given(method("PUT"))
1852 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.space.child/.*?"));
1853 self.mock_endpoint(mock, SetSpaceChildEndpoint).expect_default_access_token()
1854 }
1855
1856 /// Create a prebuilt mock for the endpoint used to set a space parent.
1857 pub fn mock_set_space_parent(&self) -> MockEndpoint<'_, SetSpaceParentEndpoint> {
1858 let mock = Mock::given(method("PUT"))
1859 .and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.space.parent"));
1860 self.mock_endpoint(mock, SetSpaceParentEndpoint).expect_default_access_token()
1861 }
1862
1863 /// Create a prebuilt mock for the endpoint used to set a tag on a room.
1864 pub fn mock_set_tag(&self, tag: &TagName) -> MockEndpoint<'_, SetTagEndpoint> {
1865 let mock = Mock::given(method("PUT"))
1866 .and(path_regex(format!("^/_matrix/client/v3/user/.*/rooms/.*/tags/{tag}$")));
1867 self.mock_endpoint(mock, SetTagEndpoint).expect_default_access_token()
1868 }
1869
1870 /// Create a prebuilt mock for the endpoint used to remove a tag from a
1871 /// room.
1872 pub fn mock_delete_tag(&self, tag: &TagName) -> MockEndpoint<'_, DeleteTagEndpoint> {
1873 let mock = Mock::given(method("DELETE"))
1874 .and(path_regex(format!("^/_matrix/client/v3/user/.*/rooms/.*/tags/{tag}$")));
1875 self.mock_endpoint(mock, DeleteTagEndpoint).expect_default_access_token()
1876 }
1877
1878 /// Create a prebuilt mock for the endpoint used to get a profile field.
1879 pub fn mock_get_profile_field(
1880 &self,
1881 user_id: &UserId,
1882 field: ProfileFieldName,
1883 ) -> MockEndpoint<'_, GetProfileFieldEndpoint> {
1884 let mock = Mock::given(method("GET"))
1885 .and(path(format!("/_matrix/client/v3/profile/{user_id}/{field}")));
1886 self.mock_endpoint(mock, GetProfileFieldEndpoint { field })
1887 }
1888
1889 /// Create a prebuilt mock for the endpoint used to set a profile field.
1890 pub fn mock_set_profile_field(
1891 &self,
1892 user_id: &UserId,
1893 field: ProfileFieldName,
1894 ) -> MockEndpoint<'_, SetProfileFieldEndpoint> {
1895 let mock = Mock::given(method("PUT"))
1896 .and(path(format!("/_matrix/client/v3/profile/{user_id}/{field}")));
1897 self.mock_endpoint(mock, SetProfileFieldEndpoint).expect_default_access_token()
1898 }
1899
1900 /// Create a prebuilt mock for the endpoint used to delete a profile field.
1901 pub fn mock_delete_profile_field(
1902 &self,
1903 user_id: &UserId,
1904 field: ProfileFieldName,
1905 ) -> MockEndpoint<'_, DeleteProfileFieldEndpoint> {
1906 let mock = Mock::given(method("DELETE"))
1907 .and(path(format!("/_matrix/client/v3/profile/{user_id}/{field}")));
1908 self.mock_endpoint(mock, DeleteProfileFieldEndpoint).expect_default_access_token()
1909 }
1910
1911 /// Create a prebuilt mock for the endpoint used to get a profile.
1912 pub fn mock_get_profile(&self, user_id: &UserId) -> MockEndpoint<'_, GetProfileEndpoint> {
1913 let mock =
1914 Mock::given(method("GET")).and(path(format!("/_matrix/client/v3/profile/{user_id}")));
1915 self.mock_endpoint(mock, GetProfileEndpoint)
1916 }
1917
1918 /// Create a prebuilt mock for the endpoint used to query the profiles of
1919 /// multiple users (MSC4536).
1920 pub fn mock_query_profiles(&self) -> MockEndpoint<'_, QueryProfilesEndpoint> {
1921 let mock = Mock::given(method("POST"))
1922 .and(path("/_matrix/client/unstable/org.matrix.msc4536/profile/query"));
1923 self.mock_endpoint(mock, QueryProfilesEndpoint).expect_default_access_token()
1924 }
1925
1926 /// Create a prebuilt mock for the endpoint used to get the capabilities of
1927 /// the homeserver.
1928 pub fn mock_get_homeserver_capabilities(
1929 &self,
1930 ) -> MockEndpoint<'_, GetHomeserverCapabilitiesEndpoint> {
1931 let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/capabilities"));
1932 self.mock_endpoint(mock, GetHomeserverCapabilitiesEndpoint)
1933 }
1934
1935 /// Create a prebuilt mock for the endpoint used to get the message
1936 /// retention configuration of the homeserver
1937 /// ([MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)).
1938 ///
1939 /// # Examples
1940 ///
1941 /// ```
1942 /// # tokio_test::block_on(async {
1943 /// use std::{collections::BTreeMap, time::Duration};
1944 ///
1945 /// use matrix_sdk::{
1946 /// ruma::{
1947 /// api::client::retention::{
1948 /// RoomIdOrAllRooms,
1949 /// get_retention_configuration::msc1763::{
1950 /// LifetimeLimits, RetentionLimits,
1951 /// },
1952 /// },
1953 /// events::room::retention::RoomRetentionEventContent,
1954 /// },
1955 /// test_utils::mocks::MatrixMockServer,
1956 /// };
1957 ///
1958 /// let mock_server = MatrixMockServer::new().await;
1959 /// let client = mock_server.client_builder().build().await;
1960 ///
1961 /// let one_day = Duration::from_secs(24 * 60 * 60);
1962 ///
1963 /// mock_server
1964 /// .mock_get_retention_configuration()
1965 /// .ok(
1966 /// BTreeMap::from([(
1967 /// RoomIdOrAllRooms::AllRooms,
1968 /// RoomRetentionEventContent::new().at_most(one_day).unwrap(),
1969 /// )]),
1970 /// RetentionLimits::new(
1971 /// None,
1972 /// LifetimeLimits::from_range(..=one_day * 7),
1973 /// ),
1974 /// )
1975 /// .mock_once()
1976 /// .mount()
1977 /// .await;
1978 ///
1979 /// let config = client.fetch_retention_configuration().await?.unwrap();
1980 /// assert_eq!(config.policies.len(), 1);
1981 /// assert_eq!(config.limits.max_lifetime.unwrap().max(), Some(one_day * 7));
1982 /// # anyhow::Ok(()) });
1983 /// ```
1984 pub fn mock_get_retention_configuration(
1985 &self,
1986 ) -> MockEndpoint<'_, GetRetentionConfigurationEndpoint> {
1987 let mock = Mock::given(method("GET"))
1988 .and(path("/_matrix/client/unstable/org.matrix.msc1763/retention/configuration"));
1989 self.mock_endpoint(mock, GetRetentionConfigurationEndpoint).expect_default_access_token()
1990 }
1991
1992 /// Create a prebuilt mock for the endpoint used to deactivate an account
1993 /// with the given parameters.
1994 pub fn mock_deactivate_account(
1995 &self,
1996 id_server: Option<&str>,
1997 erase: bool,
1998 ) -> MockEndpoint<'_, DeactivateAccountEndpoint> {
1999 let mut body = JsonObject::new();
2000 if let Some(id_server) = id_server {
2001 body.insert("id_server".to_owned(), id_server.into());
2002 }
2003 if erase {
2004 body.insert("erase".to_owned(), erase.into());
2005 }
2006
2007 let mock = Mock::given(method("POST"))
2008 .and(path("/_matrix/client/v3/account/deactivate"))
2009 .and(body_json(body));
2010 self.mock_endpoint(mock, DeactivateAccountEndpoint)
2011 }
2012
2013 /// Create a prebuilt mock for the endpoint used to update the presence of a
2014 /// user.
2015 pub fn mock_update_presence(
2016 &self,
2017 presence: &PresenceState,
2018 status_msg: Option<&str>,
2019 ) -> MockEndpoint<'_, UpdatePresenceEndpoint> {
2020 let mut body = JsonObject::new();
2021 body.insert("presence".to_owned(), presence.as_str().into());
2022 if let Some(status_msg) = status_msg {
2023 body.insert("status_msg".to_owned(), status_msg.into());
2024 }
2025
2026 let mock = Mock::given(method("PUT"))
2027 .and(path_regex("^/_matrix/client/v3/presence/.*/status$"))
2028 .and(body_json(body));
2029 self.mock_endpoint(mock, UpdatePresenceEndpoint)
2030 }
2031
2032 /// Create a prebuilt mock for the endpoint used to get the presence of a
2033 /// user.
2034 pub fn mock_get_presence(&self, user_id: &UserId) -> MockEndpoint<'_, GetPresenceEndpoint> {
2035 let mock = Mock::given(method("GET"))
2036 .and(path(format!("/_matrix/client/v3/presence/{user_id}/status")));
2037 self.mock_endpoint(mock, GetPresenceEndpoint)
2038 }
2039
2040 /// Create a prebuilt mock for the endpoint used to discover the MatrixRTC
2041 /// transports.
2042 pub fn mock_get_rtc_transports(&self) -> MockEndpoint<'_, GetRtcTransportsEndpoint> {
2043 let mock = Mock::given(method("GET"))
2044 .and(path("/_matrix/client/unstable/org.matrix.msc4143/rtc/transports"));
2045 self.mock_endpoint(mock, GetRtcTransportsEndpoint)
2046 }
2047
2048 /// Creates a prebuilt mock for getting global account data.
2049 pub fn mock_get_global_account_data(
2050 &self,
2051 user_id: &UserId,
2052 account_data_type: &GlobalAccountDataEventType,
2053 ) -> MockEndpoint<'_, GetGlobalAccountDataEndpoint> {
2054 let mock = Mock::given(method("GET")).and(path(format!(
2055 "/_matrix/client/v3/user/{user_id}/account_data/{account_data_type}"
2056 )));
2057 self.mock_endpoint(mock, GetGlobalAccountDataEndpoint).expect_default_access_token()
2058 }
2059
2060 /// Creates a prebuilt mock for setting global account data.
2061 pub fn mock_set_global_account_data(
2062 &self,
2063 user_id: &UserId,
2064 account_data_type: &GlobalAccountDataEventType,
2065 ) -> MockEndpoint<'_, SetGlobalAccountDataEndpoint> {
2066 let mock = Mock::given(method("PUT")).and(path(format!(
2067 "/_matrix/client/v3/user/{user_id}/account_data/{account_data_type}"
2068 )));
2069 self.mock_endpoint(mock, SetGlobalAccountDataEndpoint).expect_default_access_token()
2070 }
2071}
2072
2073/// A specification for a push rule ID.
2074pub enum PushRuleIdSpec<'a> {
2075 /// A precise rule ID.
2076 Some(&'a str),
2077 /// Any rule ID should match.
2078 Any,
2079}
2080
2081impl<'a> PushRuleIdSpec<'a> {
2082 /// Convert this [`PushRuleIdSpec`] to a path.
2083 pub fn to_path(&self) -> &str {
2084 match self {
2085 PushRuleIdSpec::Some(id) => id,
2086 PushRuleIdSpec::Any => "[^/]*",
2087 }
2088 }
2089}
2090
2091/// Parameter to [`MatrixMockServer::sync_room`].
2092pub enum AnyRoomBuilder {
2093 /// A room we've been invited to.
2094 Invited(InvitedRoomBuilder),
2095 /// A room we've joined.
2096 Joined(JoinedRoomBuilder),
2097 /// A room we've left.
2098 Left(LeftRoomBuilder),
2099 /// A room we've knocked to.
2100 Knocked(KnockedRoomBuilder),
2101}
2102
2103impl AnyRoomBuilder {
2104 /// Get the [`RoomId`] of the room this [`AnyRoomBuilder`] will create.
2105 fn room_id(&self) -> &RoomId {
2106 match self {
2107 AnyRoomBuilder::Invited(r) => r.room_id(),
2108 AnyRoomBuilder::Joined(r) => r.room_id(),
2109 AnyRoomBuilder::Left(r) => r.room_id(),
2110 AnyRoomBuilder::Knocked(r) => r.room_id(),
2111 }
2112 }
2113}
2114
2115impl From<InvitedRoomBuilder> for AnyRoomBuilder {
2116 fn from(val: InvitedRoomBuilder) -> AnyRoomBuilder {
2117 AnyRoomBuilder::Invited(val)
2118 }
2119}
2120
2121impl From<JoinedRoomBuilder> for AnyRoomBuilder {
2122 fn from(val: JoinedRoomBuilder) -> AnyRoomBuilder {
2123 AnyRoomBuilder::Joined(val)
2124 }
2125}
2126
2127impl From<LeftRoomBuilder> for AnyRoomBuilder {
2128 fn from(val: LeftRoomBuilder) -> AnyRoomBuilder {
2129 AnyRoomBuilder::Left(val)
2130 }
2131}
2132
2133impl From<KnockedRoomBuilder> for AnyRoomBuilder {
2134 fn from(val: KnockedRoomBuilder) -> AnyRoomBuilder {
2135 AnyRoomBuilder::Knocked(val)
2136 }
2137}
2138
2139/// The [path percent-encode set] as defined in the WHATWG URL standard + `/`
2140/// since we always encode single segments of the path.
2141///
2142/// [path percent-encode set]: https://url.spec.whatwg.org/#path-percent-encode-set
2143///
2144/// Copied from Ruma:
2145/// https://github.com/ruma/ruma/blob/e4cb409ff3aaa16f31a7fe1e61fee43b2d144f7b/crates/ruma-common/src/percent_encode.rs#L7
2146const PATH_PERCENT_ENCODE_SET: &AsciiSet = &CONTROLS
2147 .add(b' ')
2148 .add(b'"')
2149 .add(b'#')
2150 .add(b'<')
2151 .add(b'>')
2152 .add(b'?')
2153 .add(b'`')
2154 .add(b'{')
2155 .add(b'}')
2156 .add(b'/');
2157
2158fn percent_encoded_path(path: &str) -> String {
2159 percent_encoding::utf8_percent_encode(path, PATH_PERCENT_ENCODE_SET).to_string()
2160}
2161
2162/// A wrapper for a [`Mock`] as well as a [`MockServer`], allowing us to call
2163/// [`Mock::mount`] or [`Mock::mount_as_scoped`] without having to pass the
2164/// [`MockServer`] reference (i.e. call `mount()` instead of `mount(&server)`).
2165pub struct MatrixMock<'a> {
2166 pub(super) mock: Mock,
2167 pub(super) server: &'a MockServer,
2168}
2169
2170impl MatrixMock<'_> {
2171 /// Set an expectation on the number of times this [`MatrixMock`] should
2172 /// match in the current test case.
2173 ///
2174 /// Expectations are verified when the server is shutting down: if the
2175 /// expectation is not satisfied, the [`MatrixMockServer`] will panic and
2176 /// the `error_message` is shown.
2177 ///
2178 /// By default, no expectation is set for [`MatrixMock`]s.
2179 pub fn expect<T: Into<Times>>(self, num_calls: T) -> Self {
2180 Self { mock: self.mock.expect(num_calls), ..self }
2181 }
2182
2183 /// Assign a name to your mock.
2184 ///
2185 /// The mock name will be used in error messages (e.g. if the mock
2186 /// expectation is not satisfied) and debug logs to help you identify what
2187 /// failed.
2188 pub fn named(self, name: impl Into<String>) -> Self {
2189 Self { mock: self.mock.named(name), ..self }
2190 }
2191
2192 /// Respond to a response of this endpoint exactly once.
2193 ///
2194 /// After it's been called, subsequent responses will hit the next handler
2195 /// or a 404.
2196 ///
2197 /// Also verifies that it's been called once.
2198 pub fn mock_once(self) -> Self {
2199 Self { mock: self.mock.up_to_n_times(1).expect(1), ..self }
2200 }
2201
2202 /// Makes sure the endpoint is never reached.
2203 pub fn never(self) -> Self {
2204 Self { mock: self.mock.expect(0), ..self }
2205 }
2206
2207 /// Specify an upper limit to the number of times you would like this
2208 /// [`MatrixMock`] to respond to incoming requests that satisfy the
2209 /// conditions imposed by your matchers.
2210 pub fn up_to_n_times(self, num: u64) -> Self {
2211 Self { mock: self.mock.up_to_n_times(num), ..self }
2212 }
2213
2214 /// Set the priority of this [`MatrixMock`].
2215 ///
2216 /// When several mocks match the same request, the one with the highest
2217 /// priority (i.e. the lowest value, 1 being the highest and 255 the lowest)
2218 /// responds to it. This is useful to mock the same endpoint differently for
2219 /// the first and the subsequent requests, by combining it with
2220 /// [`Self::up_to_n_times`].
2221 pub fn with_priority(self, priority: u8) -> Self {
2222 Self { mock: self.mock.with_priority(priority), ..self }
2223 }
2224
2225 /// Mount a [`MatrixMock`] on the attached server.
2226 ///
2227 /// The [`MatrixMock`] will remain active until the [`MatrixMockServer`] is
2228 /// shut down. If you want to control or limit how long your [`MatrixMock`]
2229 /// stays active, check out [`Self::mount_as_scoped`].
2230 pub async fn mount(self) {
2231 self.mock.mount(self.server).await;
2232 }
2233
2234 /// Mount a [`MatrixMock`] as **scoped** on the attached server.
2235 ///
2236 /// When using [`Self::mount`], your [`MatrixMock`]s will be active until
2237 /// the [`MatrixMockServer`] is shut down.
2238 ///
2239 /// When using `mount_as_scoped`, your [`MatrixMock`]s will be active as
2240 /// long as the returned [`MockGuard`] is not dropped.
2241 ///
2242 /// When the returned [`MockGuard`] is dropped, [`MatrixMockServer`] will
2243 /// verify that the expectations set on the scoped [`MatrixMock`] were
2244 /// verified - if not, it will panic.
2245 pub async fn mount_as_scoped(self) -> MockGuard {
2246 self.mock.mount_as_scoped(self.server).await
2247 }
2248}
2249
2250/// Generic mocked endpoint, with useful common helpers.
2251pub struct MockEndpoint<'a, T> {
2252 server: &'a MockServer,
2253 mock: MockBuilder,
2254 endpoint: T,
2255 delay: Option<Duration>,
2256 expected_access_token: ExpectedAccessToken,
2257}
2258
2259impl<'a, T> MockEndpoint<'a, T> {
2260 fn new(server: &'a MockServer, mock: MockBuilder, endpoint: T) -> Self {
2261 Self {
2262 server,
2263 mock,
2264 endpoint,
2265 expected_access_token: ExpectedAccessToken::Ignore,
2266 delay: None,
2267 }
2268 }
2269
2270 /// Expect authentication with the default access token on this endpoint.
2271 pub fn expect_default_access_token(mut self) -> Self {
2272 self.expected_access_token = ExpectedAccessToken::Default;
2273 self
2274 }
2275
2276 /// Expect authentication with the given access token on this endpoint.
2277 pub fn expect_access_token(mut self, access_token: impl Into<&'static str>) -> Self {
2278 self.expected_access_token = ExpectedAccessToken::Custom(access_token.into());
2279 self
2280 }
2281
2282 /// Expect authentication with any access token on this endpoint, regardless
2283 /// of its value.
2284 ///
2285 /// This is useful if we don't want to track the value of the access token.
2286 pub fn expect_any_access_token(mut self) -> Self {
2287 self.expected_access_token = ExpectedAccessToken::Any;
2288 self
2289 }
2290
2291 /// Expect no authentication on this endpoint.
2292 ///
2293 /// This means that the endpoint will not match if an `AUTHENTICATION`
2294 /// header is present.
2295 pub fn expect_missing_access_token(mut self) -> Self {
2296 self.expected_access_token = ExpectedAccessToken::Missing;
2297 self
2298 }
2299
2300 /// Ignore the access token on this endpoint.
2301 ///
2302 /// This should be used to override the default behavior of an endpoint that
2303 /// requires access tokens.
2304 pub fn ignore_access_token(mut self) -> Self {
2305 self.expected_access_token = ExpectedAccessToken::Ignore;
2306 self
2307 }
2308
2309 /// Expect the given UIAA auth data in the body of the request.
2310 pub fn expect_uiaa_auth_data(mut self, auth_data: &uiaa::AuthData) -> Self {
2311 self.mock = self.mock.and(body_partial_json(json!({
2312 "auth": auth_data,
2313 })));
2314 self
2315 }
2316
2317 /// Ensures that the body of the request is a superset of the provided
2318 /// `body` parameter.
2319 pub fn body_matches_partial_json(self, body: impl Serialize) -> Self {
2320 Self { mock: self.mock.and(body_partial_json(body)), ..self }
2321 }
2322
2323 /// Ensures that the body of the request is the exact provided `body`
2324 /// parameter.
2325 pub fn body_json(self, body: impl Serialize) -> Self {
2326 Self { mock: self.mock.and(body_json(body)), ..self }
2327 }
2328
2329 /// Specify how to respond to a query (viz., like
2330 /// [`MockBuilder::respond_with`] does), when other predefined responses
2331 /// aren't sufficient.
2332 ///
2333 /// If a delay has been specified with [`Self::with_delay`], it is applied
2334 /// to the [`ResponseTemplate`] obtained by responding to the request,
2335 /// overriding a preexisting one, if any.
2336 ///
2337 /// # Examples
2338 ///
2339 /// ```
2340 /// # tokio_test::block_on(async {
2341 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2342 /// use serde_json::json;
2343 /// use wiremock::ResponseTemplate;
2344 ///
2345 /// let mock_server = MatrixMockServer::new().await;
2346 /// let client = mock_server.client_builder().build().await;
2347 ///
2348 /// mock_server.mock_room_state_encryption().plain().mount().await;
2349 ///
2350 /// let room = mock_server
2351 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
2352 /// .await;
2353 ///
2354 /// let event_id = event_id!("$some_id");
2355 /// mock_server
2356 /// .mock_room_send()
2357 /// .respond_with(
2358 /// ResponseTemplate::new(429)
2359 /// .insert_header("Retry-After", "100")
2360 /// .set_body_json(json!({
2361 /// "errcode": "M_LIMIT_EXCEEDED",
2362 /// "custom_field": "with custom data",
2363 /// })))
2364 /// .expect(1)
2365 /// .mount()
2366 /// .await;
2367 ///
2368 /// room
2369 /// .send_raw("m.room.message", json!({ "body": "Hello world" }))
2370 /// .await
2371 /// .expect_err("The sending of the event should fail");
2372 /// # anyhow::Ok(()) });
2373 /// ```
2374 pub fn respond_with<R: Respond + 'static>(mut self, responder: R) -> MatrixMock<'a> {
2375 let delay = self.delay.take();
2376 let mock =
2377 self.mock.and(self.expected_access_token).respond_with(move |request: &Request| {
2378 let mut response_template = responder.respond(request);
2379 if let Some(delay) = delay {
2380 response_template = response_template.set_delay(delay);
2381 }
2382 response_template
2383 });
2384 MatrixMock { mock, server: self.server }
2385 }
2386
2387 /// For responses making use of [`ResponseTemplate`], add an additional
2388 /// delay before sending the response, to simulate server-side latency.
2389 ///
2390 /// Note: this will only work with [`MockEndpoint`]'s generic methods, or
2391 /// with specific implementations that take into account this delay when
2392 /// constructing the final mock.
2393 ///
2394 /// In particular, this will NOT work by default when using
2395 /// `Self::respond_with` with a custom function; in this case, the
2396 /// implementer must take the delay into account manually.
2397 pub fn with_delay(mut self, delay: Duration) -> Self {
2398 self.delay = Some(delay);
2399 self
2400 }
2401
2402 /// Returns a send endpoint that emulates a transient failure, i.e responds
2403 /// with error 500.
2404 ///
2405 /// # Examples
2406 ///
2407 /// ```
2408 /// # tokio_test::block_on(async {
2409 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2410 /// use serde_json::json;
2411 ///
2412 /// let mock_server = MatrixMockServer::new().await;
2413 /// let client = mock_server.client_builder().build().await;
2414 ///
2415 /// mock_server.mock_room_state_encryption().plain().mount().await;
2416 ///
2417 /// let room = mock_server
2418 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
2419 /// .await;
2420 ///
2421 /// mock_server
2422 /// .mock_room_send()
2423 /// .error500()
2424 /// .expect(1)
2425 /// .mount()
2426 /// .await;
2427 ///
2428 /// room
2429 /// .send_raw("m.room.message", json!({ "body": "Hello world" }))
2430 /// .await.expect_err("The sending of the event should have failed");
2431 /// # anyhow::Ok(()) });
2432 /// ```
2433 pub fn error500(self) -> MatrixMock<'a> {
2434 self.respond_with(ResponseTemplate::new(500))
2435 }
2436
2437 /// Returns an HTTP response with the given HTTP status code and JSON object
2438 /// as the body.
2439 pub fn respond_with_code_and_json<B: Serialize>(self, code: u16, json: B) -> MatrixMock<'a> {
2440 self.respond_with(ResponseTemplate::new(code).set_body_json(json))
2441 }
2442
2443 /// Returns a mocked endpoint that emulates an unimplemented endpoint, i.e
2444 /// responds with a 404 HTTP status code and an `M_UNRECOGNIZED` Matrix
2445 /// error code.
2446 ///
2447 /// Note that the default behavior of the mock server is to return a 404
2448 /// status code for endpoints that are not mocked with an empty response.
2449 ///
2450 /// This can be useful to check if an endpoint is called, even if it is not
2451 /// implemented by the server.
2452 pub fn error_unrecognized(self) -> MatrixMock<'a> {
2453 self.respond_with_code_and_json(
2454 404,
2455 json!({
2456 "errcode": "M_UNRECOGNIZED",
2457 "error": "Unrecognized request",
2458 }),
2459 )
2460 }
2461
2462 /// Returns a mocked endpoint that emulates an unknown token error, i.e
2463 /// responds with a 401 HTTP status code and an `M_UNKNOWN_TOKEN` Matrix
2464 /// error code.
2465 pub fn error_unknown_token(self, soft_logout: bool) -> MatrixMock<'a> {
2466 self.respond_with_code_and_json(
2467 401,
2468 json!({
2469 "errcode": "M_UNKNOWN_TOKEN",
2470 "error": "Unrecognized access token",
2471 "soft_logout": soft_logout,
2472 }),
2473 )
2474 }
2475
2476 /// Returns a mocked endpoint that emulates a rate-limited error.
2477 ///
2478 /// It responds with a 429 HTTP status code and an `M_LIMIT_EXCEEDED` Matrix
2479 /// error code.
2480 pub fn error_rate_limited(self) -> MatrixMock<'a> {
2481 self.respond_with_code_and_json(
2482 429,
2483 json!({
2484 "errcode": "M_LIMIT_EXCEEDED",
2485 "error": "Too many requests",
2486 "retry_after_ms": 2000
2487 }),
2488 )
2489 }
2490
2491 /// Returns a 200 OK response with the given JSON object as the body.
2492 pub fn ok_json<B: Serialize>(self, json: B) -> MatrixMock<'a> {
2493 self.respond_with_code_and_json(200, json)
2494 }
2495
2496 /// Returns an `{ event_id }` JSON struct along with a 200 ok response.
2497 pub fn ok_with_event_id(self, event_id: OwnedEventId) -> MatrixMock<'a> {
2498 self.ok_json(json!({ "event_id": event_id }))
2499 }
2500
2501 /// Returns a 200 OK response with an empty JSON object in the body.
2502 pub fn ok_empty_json(self) -> MatrixMock<'a> {
2503 self.ok_json(json!({}))
2504 }
2505
2506 /// Returns an endpoint that emulates a permanent failure error (e.g. event
2507 /// is too large).
2508 ///
2509 /// # Examples
2510 ///
2511 /// ```
2512 /// # tokio_test::block_on(async {
2513 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2514 /// use serde_json::json;
2515 ///
2516 /// let mock_server = MatrixMockServer::new().await;
2517 /// let client = mock_server.client_builder().build().await;
2518 ///
2519 /// mock_server.mock_room_state_encryption().plain().mount().await;
2520 ///
2521 /// let room = mock_server
2522 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
2523 /// .await;
2524 ///
2525 /// mock_server
2526 /// .mock_room_send()
2527 /// .error_too_large()
2528 /// .expect(1)
2529 /// .mount()
2530 /// .await;
2531 ///
2532 /// room
2533 /// .send_raw("m.room.message", json!({ "body": "Hello world" }))
2534 /// .await.expect_err("The sending of the event should have failed");
2535 /// # anyhow::Ok(()) });
2536 /// ```
2537 pub fn error_too_large(self) -> MatrixMock<'a> {
2538 self.respond_with_code_and_json(
2539 413,
2540 json!({
2541 // From https://spec.matrix.org/v1.10/client-server-api/#standard-error-response
2542 "errcode": "M_TOO_LARGE",
2543 "error": "Request body too large",
2544 }),
2545 )
2546 }
2547
2548 /// Returns a mocked endpoint that emulates a User-Interactive
2549 /// Authentication with a password stage.
2550 pub fn error_uiaa_password(self) -> MatrixMock<'a> {
2551 self.respond_with_code_and_json(
2552 401,
2553 json!({
2554 "flows": [
2555 {
2556 "stages": [
2557 "m.login.password"
2558 ]
2559 }
2560 ],
2561 "params": {},
2562 "session": "oFIJVvtEOCKmRUTYKTYIIPHL"
2563 }),
2564 )
2565 }
2566}
2567
2568/// The access token to expect on an endpoint.
2569enum ExpectedAccessToken {
2570 /// Ignore any access token or lack thereof.
2571 Ignore,
2572
2573 /// We expect the default access token.
2574 Default,
2575
2576 /// We expect the given access token.
2577 Custom(&'static str),
2578
2579 /// We expect any access token.
2580 Any,
2581
2582 /// We expect that there is no access token.
2583 Missing,
2584}
2585
2586impl ExpectedAccessToken {
2587 /// Get the access token from the given request.
2588 fn access_token(request: &Request) -> Option<&str> {
2589 request
2590 .headers
2591 .get(&http::header::AUTHORIZATION)?
2592 .to_str()
2593 .ok()?
2594 .strip_prefix("Bearer ")
2595 .filter(|token| !token.is_empty())
2596 }
2597}
2598
2599impl wiremock::Match for ExpectedAccessToken {
2600 fn matches(&self, request: &Request) -> bool {
2601 match self {
2602 Self::Ignore => true,
2603 Self::Default => Self::access_token(request)
2604 .is_some_and(|token| token == TestAuthToken::AccessDefault),
2605 Self::Custom(token) => Self::access_token(request) == Some(token),
2606 Self::Any => Self::access_token(request).is_some(),
2607 Self::Missing => request.headers.get(&http::header::AUTHORIZATION).is_none(),
2608 }
2609 }
2610}
2611
2612/// A prebuilt mock for sending a message like event in a room.
2613#[derive(Default)]
2614pub struct RoomSendEndpoint {
2615 room_id: Option<OwnedRoomId>,
2616 event_type: Option<MessageLikeEventType>,
2617}
2618
2619impl<'a> MockEndpoint<'a, RoomSendEndpoint> {
2620 fn generate_path_regexp(&self) -> String {
2621 let RoomSendEndpoint { room_id, event_type } = &self.endpoint;
2622 format!(
2623 r"^/_matrix/client/v3/rooms/{}/send/{}/",
2624 room_id.as_ref().map_or_else(|| ".*".to_owned(), |r| regex::escape(r.as_str())),
2625 event_type.as_ref().map_or_else(|| ".*".to_owned(), |t| regex::escape(&t.to_string())),
2626 )
2627 }
2628
2629 /// Ensures that the request marks the event as sticky (MSC4354) for
2630 /// exactly `duration`.
2631 pub fn with_sticky_duration(self, duration: Duration) -> Self {
2632 Self {
2633 mock: self.mock.and(query_param(
2634 "org.matrix.msc4354.sticky_duration_ms",
2635 duration.as_millis().to_string(),
2636 )),
2637 ..self
2638 }
2639 }
2640
2641 /// Ensures that the request does not mark the event as sticky (MSC4354).
2642 pub fn without_sticky_duration(self) -> Self {
2643 Self {
2644 mock: self.mock.and(query_param_is_missing("org.matrix.msc4354.sticky_duration_ms")),
2645 ..self
2646 }
2647 }
2648
2649 /// Ensures that the send endpoint request uses a specific event type.
2650 ///
2651 /// Important note: this should be called at most once, at the risk of
2652 /// confusing the path matching. The function will panic, if called
2653 /// multiple times.
2654 ///
2655 /// # Examples
2656 ///
2657 /// see also [`MatrixMockServer::mock_room_send`] for more context.
2658 ///
2659 /// ```
2660 /// # tokio_test::block_on(async {
2661 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2662 /// use serde_json::json;
2663 ///
2664 /// let mock_server = MatrixMockServer::new().await;
2665 /// let client = mock_server.client_builder().build().await;
2666 ///
2667 /// mock_server.mock_room_state_encryption().plain().mount().await;
2668 ///
2669 /// let room = mock_server
2670 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
2671 /// .await;
2672 ///
2673 /// let event_id = event_id!("$some_id");
2674 /// mock_server
2675 /// .mock_room_send()
2676 /// .for_type("m.room.message".into())
2677 /// .ok(event_id)
2678 /// .expect(1)
2679 /// .mount()
2680 /// .await;
2681 ///
2682 /// let response_not_mocked = room.send_raw("m.room.reaction", json!({ "body": "Hello world" })).await;
2683 /// // The `m.room.reaction` event type should not be mocked by the server.
2684 /// assert!(response_not_mocked.is_err());
2685 ///
2686 /// let result = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
2687 /// // The `m.room.message` event type should be mocked by the server.
2688 /// assert_eq!(
2689 /// event_id,
2690 /// result.response.event_id,
2691 /// "The event ID we mocked should match the one we received when we sent the event"
2692 /// );
2693 /// # anyhow::Ok(()) });
2694 /// ```
2695 pub fn for_type(mut self, event_type: MessageLikeEventType) -> Self {
2696 assert!(self.endpoint.event_type.is_none(), "you've called for_type() multiple times");
2697 self.endpoint.event_type = Some(event_type);
2698 // Note: we may have already defined a path, but this one ought to be
2699 // more specialized (unless for_room/for_type were called multiple
2700 // times).
2701 let path = self.generate_path_regexp();
2702 Self { mock: self.mock.and(path_regex(path)), ..self }
2703 }
2704
2705 /// Ensures that the send endpoint request targets a specific room.
2706 ///
2707 /// This composes with [`Self::for_type`], in any order.
2708 ///
2709 /// Important note: this should be called at most once, at the risk of
2710 /// confusing the path matching. The function will panic, if called
2711 /// multiple times.
2712 ///
2713 /// # Examples
2714 ///
2715 /// see also [`MatrixMockServer::mock_room_send`] for more context.
2716 ///
2717 /// ```
2718 /// # tokio_test::block_on(async {
2719 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2720 /// use serde_json::json;
2721 ///
2722 /// let mock_server = MatrixMockServer::new().await;
2723 /// let client = mock_server.client_builder().build().await;
2724 ///
2725 /// mock_server.mock_room_state_encryption().plain().mount().await;
2726 ///
2727 /// let room_id = room_id!("!room_id:localhost");
2728 /// let room = mock_server.sync_joined_room(&client, room_id).await;
2729 /// let other_room = mock_server
2730 /// .sync_joined_room(&client, room_id!("!other_room_id:localhost"))
2731 /// .await;
2732 ///
2733 /// let event_id = event_id!("$some_id");
2734 /// mock_server
2735 /// .mock_room_send()
2736 /// .for_type("m.room.message".into())
2737 /// .for_room(room_id)
2738 /// .ok(event_id)
2739 /// .expect(1)
2740 /// .mount()
2741 /// .await;
2742 ///
2743 /// let response_not_mocked = other_room.send_raw("m.room.message", json!({ "body": "Hello world" })).await;
2744 /// // Sending to another room should not be mocked by the server.
2745 /// assert!(response_not_mocked.is_err());
2746 ///
2747 /// let response_not_mocked = room.send_raw("m.room.reaction", json!({ "body": "Hello world" })).await;
2748 /// // The `m.room.reaction` event type should not be mocked by the server.
2749 /// assert!(response_not_mocked.is_err());
2750 ///
2751 /// let result = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
2752 /// // The `m.room.message` event type in this room should be mocked by the server.
2753 /// assert_eq!(
2754 /// event_id,
2755 /// result.response.event_id,
2756 /// "The event ID we mocked should match the one we received when we sent the event"
2757 /// );
2758 /// # anyhow::Ok(()) });
2759 /// ```
2760 pub fn for_room(mut self, room_id: impl Into<OwnedRoomId>) -> Self {
2761 assert!(self.endpoint.room_id.is_none(), "you've called for_room() multiple times");
2762 self.endpoint.room_id = Some(room_id.into());
2763 // Note: we may have already defined a path, but this one ought to be
2764 // more specialized (unless for_room/for_type were called multiple
2765 // times).
2766 let path = self.generate_path_regexp();
2767 Self { mock: self.mock.and(path_regex(path)), ..self }
2768 }
2769
2770 /// Ensures the event was sent as a delayed event.
2771 ///
2772 /// See also
2773 /// [the MSC](https://github.com/matrix-org/matrix-spec-proposals/pull/4140).
2774 ///
2775 /// Note: works with _any_ room.
2776 ///
2777 /// # Examples
2778 ///
2779 /// see also [`MatrixMockServer::mock_room_send`] for more context.
2780 ///
2781 /// ```
2782 /// # tokio_test::block_on(async {
2783 /// use matrix_sdk::{
2784 /// ruma::{
2785 /// api::client::delayed_events::{delayed_message_event, DelayParameters},
2786 /// events::{message::MessageEventContent, AnyMessageLikeEventContent},
2787 /// room_id,
2788 /// time::Duration,
2789 /// TransactionId,
2790 /// },
2791 /// test_utils::mocks::MatrixMockServer,
2792 /// };
2793 /// use serde_json::json;
2794 /// use wiremock::ResponseTemplate;
2795 ///
2796 /// let mock_server = MatrixMockServer::new().await;
2797 /// let client = mock_server.client_builder().build().await;
2798 ///
2799 /// mock_server.mock_room_state_encryption().plain().mount().await;
2800 ///
2801 /// let room = mock_server.sync_joined_room(&client, room_id!("!room_id:localhost")).await;
2802 ///
2803 /// mock_server
2804 /// .mock_room_send()
2805 /// .match_delayed_event(Duration::from_millis(500))
2806 /// .respond_with(ResponseTemplate::new(200).set_body_json(json!({"delay_id":"$some_id"})))
2807 /// .mock_once()
2808 /// .mount()
2809 /// .await;
2810 ///
2811 /// let response_not_mocked =
2812 /// room.send_raw("m.room.message", json!({ "body": "Hello world" })).await;
2813 ///
2814 /// // A non delayed event should not be mocked by the server.
2815 /// assert!(response_not_mocked.is_err());
2816 ///
2817 /// let r = delayed_message_event::msc4140::Request::new(
2818 /// room.room_id().to_owned(),
2819 /// TransactionId::new(),
2820 /// DelayParameters::Timeout { timeout: Duration::from_millis(500) },
2821 /// &AnyMessageLikeEventContent::Message(MessageEventContent::plain("hello world")),
2822 /// )
2823 /// .unwrap();
2824 ///
2825 /// let response = room.client().send(r).await.unwrap();
2826 /// // The delayed `m.room.message` event type should be mocked by the server.
2827 /// assert_eq!("$some_id", response.delay_id);
2828 /// # anyhow::Ok(()) });
2829 /// ```
2830 pub fn match_delayed_event(self, delay: Duration) -> Self {
2831 Self {
2832 mock: self
2833 .mock
2834 .and(query_param("org.matrix.msc4140.delay", delay.as_millis().to_string())),
2835 ..self
2836 }
2837 }
2838
2839 /// Returns a send endpoint that emulates success, i.e. the event has been
2840 /// sent with the given event id.
2841 ///
2842 /// # Examples
2843 ///
2844 /// ```
2845 /// # tokio_test::block_on(async {
2846 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
2847 /// use serde_json::json;
2848 ///
2849 /// let mock_server = MatrixMockServer::new().await;
2850 /// let client = mock_server.client_builder().build().await;
2851 ///
2852 /// mock_server.mock_room_state_encryption().plain().mount().await;
2853 ///
2854 /// let room = mock_server
2855 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
2856 /// .await;
2857 ///
2858 /// let event_id = event_id!("$some_id");
2859 /// let send_guard = mock_server
2860 /// .mock_room_send()
2861 /// .ok(event_id)
2862 /// .expect(1)
2863 /// .mount_as_scoped()
2864 /// .await;
2865 ///
2866 /// let result = room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
2867 ///
2868 /// assert_eq!(
2869 /// event_id,
2870 /// result.response.event_id,
2871 /// "The event ID we mocked should match the one we received when we sent the event"
2872 /// );
2873 /// # anyhow::Ok(()) });
2874 /// ```
2875 pub fn ok(self, returned_event_id: impl Into<OwnedEventId>) -> MatrixMock<'a> {
2876 self.ok_with_event_id(returned_event_id.into())
2877 }
2878
2879 /// Returns a send endpoint that emulates success, i.e. the event has been
2880 /// sent with the given event id.
2881 ///
2882 /// The sent event is captured and can be accessed using the returned
2883 /// [`Receiver`]. The [`Receiver`] is valid only for a send call. The given
2884 /// `event_sender` are added to the event JSON.
2885 ///
2886 /// # Examples
2887 ///
2888 /// ```no_run
2889 /// # tokio_test::block_on(async {
2890 /// use matrix_sdk::{
2891 /// ruma::{
2892 /// event_id, events::room::message::RoomMessageEventContent, room_id,
2893 /// },
2894 /// test_utils::mocks::MatrixMockServer,
2895 /// };
2896 /// use matrix_sdk_test::JoinedRoomBuilder;
2897 ///
2898 /// let room_id = room_id!("!room_id:localhost");
2899 /// let event_id = event_id!("$some_id");
2900 ///
2901 /// let server = MatrixMockServer::new().await;
2902 /// let client = server.client_builder().build().await;
2903 ///
2904 /// let user_id = client.user_id().expect("We should have a user ID by now");
2905 ///
2906 /// let (receiver, mock) =
2907 /// server.mock_room_send().ok_with_capture(event_id, user_id);
2908 ///
2909 /// server
2910 /// .mock_sync()
2911 /// .ok_and_run(&client, |builder| {
2912 /// builder.add_joined_room(JoinedRoomBuilder::new(room_id));
2913 /// })
2914 /// .await;
2915 ///
2916 /// // Mock any additional endpoints that might be needed to send the message.
2917 ///
2918 /// let room = client
2919 /// .get_room(room_id)
2920 /// .expect("We should have access to our room now");
2921 ///
2922 /// let event_id = room
2923 /// .send(RoomMessageEventContent::text_plain("It's a secret to everybody"))
2924 /// .await
2925 /// .expect("We should be able to send an initial message")
2926 /// .response
2927 /// .event_id;
2928 ///
2929 /// let event = receiver.await?;
2930 /// # anyhow::Ok(()) });
2931 /// ```
2932 pub fn ok_with_capture(
2933 self,
2934 returned_event_id: impl Into<OwnedEventId>,
2935 event_sender: impl Into<OwnedUserId>,
2936 ) -> (Receiver<Raw<AnySyncTimelineEvent>>, MatrixMock<'a>) {
2937 let event_id = returned_event_id.into();
2938 let event_sender = event_sender.into();
2939
2940 let (sender, receiver) = oneshot::channel();
2941 let sender = Arc::new(Mutex::new(Some(sender)));
2942
2943 let ret = self.respond_with(move |request: &Request| {
2944 if let Some(sender) = sender.lock().unwrap().take() {
2945 let uri = &request.url;
2946 let path_segments = uri.path_segments();
2947 let maybe_event_type = path_segments.and_then(|mut s| s.nth_back(1));
2948 let event_type = maybe_event_type
2949 .as_ref()
2950 .map(|&e| e.to_owned())
2951 .unwrap_or("m.room.message".to_owned());
2952
2953 let body: Value =
2954 request.body_json().expect("The received body should be valid JSON");
2955
2956 let event = json!({
2957 "event_id": event_id.clone(),
2958 "sender": event_sender,
2959 "type": event_type,
2960 "origin_server_ts": MilliSecondsSinceUnixEpoch::now(),
2961 "content": body,
2962 });
2963
2964 let event: Raw<AnySyncTimelineEvent> = from_value(event)
2965 .expect("We should be able to create a raw event from the content");
2966
2967 sender.send(event).expect("We should be able to send the event to the receiver");
2968 }
2969
2970 ResponseTemplate::new(200).set_body_json(json!({ "event_id": event_id.clone() }))
2971 });
2972
2973 (receiver, ret)
2974 }
2975}
2976
2977/// A prebuilt mock for sending a state event in a room.
2978#[derive(Default)]
2979pub struct RoomSendStateEndpoint {
2980 state_key: Option<String>,
2981 event_type: Option<StateEventType>,
2982}
2983
2984impl<'a> MockEndpoint<'a, RoomSendStateEndpoint> {
2985 fn generate_path_regexp(endpoint: &RoomSendStateEndpoint) -> String {
2986 format!(
2987 r"^/_matrix/client/v3/rooms/.*/state/{}/{}",
2988 endpoint.event_type.as_ref().map_or_else(|| ".*".to_owned(), |t| t.to_string()),
2989 endpoint.state_key.as_ref().map_or_else(|| ".*".to_owned(), |k| k.to_string())
2990 )
2991 }
2992
2993 /// Ensures that the send endpoint request uses a specific event type.
2994 ///
2995 /// Note: works with _any_ room.
2996 ///
2997 /// # Examples
2998 ///
2999 /// see also [`MatrixMockServer::mock_room_send`] for more context.
3000 ///
3001 /// ```
3002 /// # tokio_test::block_on(async {
3003 /// use matrix_sdk::{
3004 /// ruma::{
3005 /// event_id,
3006 /// events::room::{
3007 /// create::RoomCreateEventContent, power_levels::RoomPowerLevelsEventContent,
3008 /// },
3009 /// events::StateEventType,
3010 /// room_id,
3011 /// room_version_rules::AuthorizationRules,
3012 /// },
3013 /// test_utils::mocks::MatrixMockServer,
3014 /// };
3015 ///
3016 /// let mock_server = MatrixMockServer::new().await;
3017 /// let client = mock_server.client_builder().build().await;
3018 ///
3019 /// mock_server.mock_room_state_encryption().plain().mount().await;
3020 ///
3021 /// let room = mock_server.sync_joined_room(&client, room_id!("!room_id:localhost")).await;
3022 ///
3023 /// let event_id = event_id!("$some_id");
3024 ///
3025 /// mock_server
3026 /// .mock_room_send_state()
3027 /// .for_type(StateEventType::RoomPowerLevels)
3028 /// .ok(event_id)
3029 /// .expect(1)
3030 /// .mount()
3031 /// .await;
3032 ///
3033 /// let response_not_mocked = room.send_state_event(RoomCreateEventContent::new_v11()).await;
3034 /// // The `m.room.reaction` event type should not be mocked by the server.
3035 /// assert!(response_not_mocked.is_err());
3036 ///
3037 /// let response = room.send_state_event(RoomPowerLevelsEventContent::new(&AuthorizationRules::V1)).await?;
3038 /// // The `m.room.message` event type should be mocked by the server.
3039 /// assert_eq!(
3040 /// event_id, response.event_id,
3041 /// "The event ID we mocked should match the one we received when we sent the event"
3042 /// );
3043 ///
3044 /// # anyhow::Ok(()) });
3045 /// ```
3046 pub fn for_type(mut self, event_type: StateEventType) -> Self {
3047 self.endpoint.event_type = Some(event_type);
3048 // Note: we may have already defined a path, but this one ought to be
3049 // more specialized (unless for_key/for_type were called multiple
3050 // times).
3051 Self { mock: self.mock.and(path_regex(Self::generate_path_regexp(&self.endpoint))), ..self }
3052 }
3053
3054 /// Ensures the event was sent as a delayed event.
3055 ///
3056 /// See also
3057 /// [the MSC](https://github.com/matrix-org/matrix-spec-proposals/pull/4140).
3058 ///
3059 /// Note: works with _any_ room.
3060 ///
3061 /// # Examples
3062 ///
3063 /// see also [`MatrixMockServer::mock_room_send`] for more context.
3064 ///
3065 /// ```
3066 /// # tokio_test::block_on(async {
3067 /// use matrix_sdk::{
3068 /// ruma::{
3069 /// api::client::delayed_events::{delayed_state_event, DelayParameters},
3070 /// events::{room::create::RoomCreateEventContent, AnyStateEventContent},
3071 /// room_id,
3072 /// time::Duration,
3073 /// },
3074 /// test_utils::mocks::MatrixMockServer,
3075 /// };
3076 /// use wiremock::ResponseTemplate;
3077 /// use serde_json::json;
3078 ///
3079 /// let mock_server = MatrixMockServer::new().await;
3080 /// let client = mock_server.client_builder().build().await;
3081 ///
3082 /// mock_server.mock_room_state_encryption().plain().mount().await;
3083 ///
3084 /// let room = mock_server.sync_joined_room(&client, room_id!("!room_id:localhost")).await;
3085 ///
3086 /// mock_server
3087 /// .mock_room_send_state()
3088 /// .match_delayed_event(Duration::from_millis(500))
3089 /// .respond_with(ResponseTemplate::new(200).set_body_json(json!({"delay_id":"$some_id"})))
3090 /// .mock_once()
3091 /// .mount()
3092 /// .await;
3093 ///
3094 /// let response_not_mocked = room.send_state_event(RoomCreateEventContent::new_v11()).await;
3095 /// // A non delayed event should not be mocked by the server.
3096 /// assert!(response_not_mocked.is_err());
3097 ///
3098 /// let r = delayed_state_event::msc4140::Request::new(
3099 /// room.room_id().to_owned(),
3100 /// "".to_owned(),
3101 /// DelayParameters::Timeout { timeout: Duration::from_millis(500) },
3102 /// &AnyStateEventContent::RoomCreate(RoomCreateEventContent::new_v11()),
3103 /// )
3104 /// .unwrap();
3105 /// let response = room.client().send(r).await.unwrap();
3106 /// // The delayed `m.room.message` event type should be mocked by the server.
3107 /// assert_eq!("$some_id", response.delay_id);
3108 ///
3109 /// # anyhow::Ok(()) });
3110 /// ```
3111 pub fn match_delayed_event(self, delay: Duration) -> Self {
3112 Self {
3113 mock: self
3114 .mock
3115 .and(query_param("org.matrix.msc4140.delay", delay.as_millis().to_string())),
3116 ..self
3117 }
3118 }
3119
3120 /// ```
3121 /// # tokio_test::block_on(async {
3122 /// use matrix_sdk::{
3123 /// ruma::{
3124 /// event_id,
3125 /// events::{call::member::CallMemberEventContent, AnyStateEventContent},
3126 /// room_id,
3127 /// },
3128 /// test_utils::mocks::MatrixMockServer,
3129 /// };
3130 ///
3131 /// let mock_server = MatrixMockServer::new().await;
3132 /// let client = mock_server.client_builder().build().await;
3133 ///
3134 /// mock_server.mock_room_state_encryption().plain().mount().await;
3135 ///
3136 /// let room = mock_server.sync_joined_room(&client, room_id!("!room_id:localhost")).await;
3137 ///
3138 /// let event_id = event_id!("$some_id");
3139 ///
3140 /// mock_server
3141 /// .mock_room_send_state()
3142 /// .for_key("my_key".to_owned())
3143 /// .ok(event_id)
3144 /// .expect(1)
3145 /// .mount()
3146 /// .await;
3147 ///
3148 /// let response_not_mocked = room
3149 /// .send_state_event_for_key(
3150 /// "",
3151 /// AnyStateEventContent::CallMember(CallMemberEventContent::new_empty(None)),
3152 /// )
3153 /// .await;
3154 /// // The `m.room.reaction` event type should not be mocked by the server.
3155 /// assert!(response_not_mocked.is_err());
3156 ///
3157 /// let response = room
3158 /// .send_state_event_for_key(
3159 /// "my_key",
3160 /// AnyStateEventContent::CallMember(CallMemberEventContent::new_empty(None)),
3161 /// )
3162 /// .await
3163 /// .unwrap();
3164 ///
3165 /// // The `m.room.message` event type should be mocked by the server.
3166 /// assert_eq!(
3167 /// event_id, response.event_id,
3168 /// "The event ID we mocked should match the one we received when we sent the event"
3169 /// );
3170 /// # anyhow::Ok(()) });
3171 /// ```
3172 pub fn for_key(mut self, state_key: String) -> Self {
3173 self.endpoint.state_key = Some(state_key);
3174 // Note: we may have already defined a path, but this one ought to be
3175 // more specialized (unless for_key/for_type were called multiple
3176 // times).
3177 Self { mock: self.mock.and(path_regex(Self::generate_path_regexp(&self.endpoint))), ..self }
3178 }
3179
3180 /// Returns a send endpoint that emulates success, i.e. the event has been
3181 /// sent with the given event id.
3182 ///
3183 /// # Examples
3184 ///
3185 /// ```
3186 /// # tokio_test::block_on(async {
3187 /// use matrix_sdk::{ruma::{room_id, event_id}, test_utils::mocks::MatrixMockServer};
3188 /// use serde_json::json;
3189 ///
3190 /// let mock_server = MatrixMockServer::new().await;
3191 /// let client = mock_server.client_builder().build().await;
3192 ///
3193 /// mock_server.mock_room_state_encryption().plain().mount().await;
3194 ///
3195 /// let room = mock_server
3196 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
3197 /// .await;
3198 ///
3199 /// let event_id = event_id!("$some_id");
3200 /// let send_guard = mock_server
3201 /// .mock_room_send_state()
3202 /// .ok(event_id)
3203 /// .expect(1)
3204 /// .mount_as_scoped()
3205 /// .await;
3206 ///
3207 /// let response = room.send_state_event_raw("m.room.message", "my_key", json!({ "body": "Hello world" })).await?;
3208 ///
3209 /// assert_eq!(
3210 /// event_id,
3211 /// response.event_id,
3212 /// "The event ID we mocked should match the one we received when we sent the event"
3213 /// );
3214 /// # anyhow::Ok(()) });
3215 /// ```
3216 pub fn ok(self, returned_event_id: impl Into<OwnedEventId>) -> MatrixMock<'a> {
3217 self.ok_with_event_id(returned_event_id.into())
3218 }
3219}
3220
3221/// A prebuilt mock for running sync v2.
3222pub struct SyncEndpoint {
3223 sync_response_builder: Arc<Mutex<SyncResponseBuilder>>,
3224}
3225
3226impl<'a> MockEndpoint<'a, SyncEndpoint> {
3227 /// Expect the given timeout, or lack thereof, in the request.
3228 pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
3229 if let Some(timeout) = timeout {
3230 self.mock = self.mock.and(query_param("timeout", timeout.as_millis().to_string()));
3231 } else {
3232 self.mock = self.mock.and(query_param_is_missing("timeout"));
3233 }
3234
3235 self
3236 }
3237
3238 /// Expect the given `set_presence` value in the request.
3239 pub fn set_presence(mut self, presence: impl Into<String>) -> Self {
3240 self.mock = self.mock.and(query_param("set_presence", presence.into()));
3241 self
3242 }
3243
3244 /// Expect no explicit `set_presence` value in the request.
3245 pub fn set_presence_missing(mut self) -> Self {
3246 self.mock = self.mock.and(query_param_is_missing("set_presence"));
3247 self
3248 }
3249
3250 /// Mocks the sync endpoint, using the given function to generate the
3251 /// response.
3252 pub fn ok<F: FnOnce(&mut SyncResponseBuilder)>(self, func: F) -> MatrixMock<'a> {
3253 let response = {
3254 let mut builder = self.endpoint.sync_response_builder.lock().unwrap();
3255 func(&mut builder);
3256 builder.build_json_sync_response()
3257 };
3258 self.ok_json(response)
3259 }
3260
3261 /// Temporarily mocks the sync with the given endpoint and runs a client
3262 /// sync with it.
3263 ///
3264 /// After calling this function, the sync endpoint isn't mocked anymore.
3265 ///
3266 /// # Examples
3267 ///
3268 /// ```
3269 /// # tokio_test::block_on(async {
3270 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
3271 /// use matrix_sdk_test::JoinedRoomBuilder;
3272 ///
3273 /// // First create the mock server and client pair.
3274 /// let mock_server = MatrixMockServer::new().await;
3275 /// let client = mock_server.client_builder().build().await;
3276 /// let room_id = room_id!("!room_id:localhost");
3277 ///
3278 /// // Let's emulate what `MatrixMockServer::sync_joined_room()` does.
3279 /// mock_server
3280 /// .mock_sync()
3281 /// .ok_and_run(&client, |builder| {
3282 /// builder.add_joined_room(JoinedRoomBuilder::new(room_id));
3283 /// })
3284 /// .await;
3285 ///
3286 /// let room = client
3287 /// .get_room(room_id)
3288 /// .expect("The room should be available after we mocked the sync");
3289 /// # anyhow::Ok(()) });
3290 /// ```
3291 pub async fn ok_and_run<F: FnOnce(&mut SyncResponseBuilder)>(self, client: &Client, func: F) {
3292 self.ok_and_run_with_response(client, func).await;
3293 }
3294
3295 /// Temporarily mocks the sync with the given endpoint, runs a client
3296 /// sync with it and returns the response.
3297 ///
3298 /// After calling this function, the sync endpoint isn't mocked anymore.
3299 pub async fn ok_and_run_with_response<F: FnOnce(&mut SyncResponseBuilder)>(
3300 self,
3301 client: &Client,
3302 func: F,
3303 ) -> SyncResponse {
3304 let _scope = self.ok(func).mount_as_scoped().await;
3305
3306 client.sync_once(Default::default()).await.unwrap()
3307 }
3308}
3309
3310/// A prebuilt mock for reading the encryption state of a room.
3311pub struct EncryptionStateEndpoint;
3312
3313impl<'a> MockEndpoint<'a, EncryptionStateEndpoint> {
3314 /// Marks the room as encrypted.
3315 ///
3316 /// # Examples
3317 ///
3318 /// ```
3319 /// # tokio_test::block_on(async {
3320 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
3321 ///
3322 /// let mock_server = MatrixMockServer::new().await;
3323 /// let client = mock_server.client_builder().build().await;
3324 ///
3325 /// mock_server.mock_room_state_encryption().encrypted().mount().await;
3326 ///
3327 /// let room = mock_server
3328 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
3329 /// .await;
3330 ///
3331 /// assert!(
3332 /// room.latest_encryption_state().await?.is_encrypted(),
3333 /// "The room should be marked as encrypted."
3334 /// );
3335 /// # anyhow::Ok(()) });
3336 /// ```
3337 pub fn encrypted(self) -> MatrixMock<'a> {
3338 self.ok_json(EventFactory::new().room_encryption().into_content())
3339 }
3340
3341 /// Marks the room as encrypted, opting into experimental state event
3342 /// encryption.
3343 ///
3344 /// # Examples
3345 ///
3346 /// ```
3347 /// # tokio_test::block_on(async {
3348 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
3349 ///
3350 /// let mock_server = MatrixMockServer::new().await;
3351 /// let client = mock_server.client_builder().build().await;
3352 ///
3353 /// mock_server.mock_room_state_encryption().state_encrypted().mount().await;
3354 ///
3355 /// let room = mock_server
3356 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
3357 /// .await;
3358 ///
3359 /// assert!(
3360 /// room.latest_encryption_state().await?.is_state_encrypted(),
3361 /// "The room should be marked as state encrypted."
3362 /// );
3363 /// # anyhow::Ok(()) });
3364 /// ```
3365 #[cfg(feature = "experimental-encrypted-state-events")]
3366 pub fn state_encrypted(self) -> MatrixMock<'a> {
3367 self.ok_json(EventFactory::new().room_encryption_with_state_encryption().into_content())
3368 }
3369
3370 /// Marks the room as not encrypted.
3371 ///
3372 /// # Examples
3373 ///
3374 /// ```
3375 /// # tokio_test::block_on(async {
3376 /// use matrix_sdk::{ruma::room_id, test_utils::mocks::MatrixMockServer};
3377 ///
3378 /// let mock_server = MatrixMockServer::new().await;
3379 /// let client = mock_server.client_builder().build().await;
3380 ///
3381 /// mock_server.mock_room_state_encryption().plain().mount().await;
3382 ///
3383 /// let room = mock_server
3384 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
3385 /// .await;
3386 ///
3387 /// assert!(
3388 /// !room.latest_encryption_state().await?.is_encrypted(),
3389 /// "The room should not be marked as encrypted."
3390 /// );
3391 /// # anyhow::Ok(()) });
3392 /// ```
3393 pub fn plain(self) -> MatrixMock<'a> {
3394 self.respond_with_code_and_json(404, &*test_json::NOT_FOUND)
3395 }
3396}
3397
3398/// A prebuilt mock for setting the encryption state of a room.
3399pub struct SetEncryptionStateEndpoint;
3400
3401impl<'a> MockEndpoint<'a, SetEncryptionStateEndpoint> {
3402 /// Returns a mock for a successful setting of the encryption state event.
3403 pub fn ok(self, returned_event_id: impl Into<OwnedEventId>) -> MatrixMock<'a> {
3404 self.ok_with_event_id(returned_event_id.into())
3405 }
3406}
3407
3408/// A prebuilt mock for redacting an event in a room.
3409pub struct RoomRedactEndpoint;
3410
3411impl<'a> MockEndpoint<'a, RoomRedactEndpoint> {
3412 /// Only match a request that contains a specific `event_id` in its path.
3413 ///
3414 /// Without this, the mock would match the redaction of any event.
3415 ///
3416 /// # Examples
3417 ///
3418 /// ```
3419 /// # tokio_test::block_on(async {
3420 /// use matrix_sdk::{
3421 /// ruma::{event_id, room_id},
3422 /// test_utils::mocks::MatrixMockServer,
3423 /// };
3424 ///
3425 /// let mock_server = MatrixMockServer::new().await;
3426 /// let client = mock_server.client_builder().build().await;
3427 ///
3428 /// let redacted = event_id!("$redacted");
3429 /// let other = event_id!("$other");
3430 ///
3431 /// // This mock only answers redactions of `other`, so it's never hit.
3432 /// mock_server
3433 /// .mock_room_redact()
3434 /// .match_event_id(other)
3435 /// .ok(event_id!("$other_redaction"))
3436 /// .never()
3437 /// .mount()
3438 /// .await;
3439 /// mock_server
3440 /// .mock_room_redact()
3441 /// .match_event_id(redacted)
3442 /// .ok(event_id!("$redaction"))
3443 /// .mock_once()
3444 /// .mount()
3445 /// .await;
3446 ///
3447 /// let room = mock_server
3448 /// .sync_joined_room(&client, room_id!("!room_id:localhost"))
3449 /// .await;
3450 ///
3451 /// let response = room.redact(redacted, None, None).await?;
3452 /// assert_eq!(response.event_id, event_id!("$redaction"));
3453 /// # anyhow::Ok(()) });
3454 /// ```
3455 pub fn match_event_id(self, event_id: &EventId) -> Self {
3456 Self {
3457 mock: self.mock.and(path_regex(format!(
3458 r"^/_matrix/client/v3/rooms/.*/redact/{}/",
3459 regex::escape(event_id.as_str())
3460 ))),
3461 ..self
3462 }
3463 }
3464
3465 /// Returns a redact endpoint that emulates success, i.e. the redaction
3466 /// event has been sent with the given event id.
3467 pub fn ok(self, returned_event_id: impl Into<OwnedEventId>) -> MatrixMock<'a> {
3468 self.ok_with_event_id(returned_event_id.into())
3469 }
3470}
3471
3472/// A prebuilt mock for getting a single event in a room.
3473pub struct RoomEventEndpoint {
3474 room: Option<OwnedRoomId>,
3475 match_event_id: bool,
3476}
3477
3478impl<'a> MockEndpoint<'a, RoomEventEndpoint> {
3479 /// Limits the scope of this mock to a specific room.
3480 pub fn room(mut self, room: impl Into<OwnedRoomId>) -> Self {
3481 self.endpoint.room = Some(room.into());
3482 self
3483 }
3484
3485 /// Whether the mock checks for the event id from the event.
3486 pub fn match_event_id(mut self) -> Self {
3487 self.endpoint.match_event_id = true;
3488 self
3489 }
3490
3491 /// Returns a redact endpoint that emulates success, i.e. the redaction
3492 /// event has been sent with the given event id.
3493 pub fn ok(mut self, event: TimelineEvent) -> MatrixMock<'a> {
3494 let event_path = if self.endpoint.match_event_id {
3495 let event_id = event.event_id().expect("an event id is required");
3496 regex::escape(event_id.as_str())
3497 } else {
3498 // Event is at the end, so no need to add anything.
3499 "".to_owned()
3500 };
3501
3502 let room_path =
3503 self.endpoint.room.take().map_or_else(|| ".*".to_owned(), |room| room.to_string());
3504
3505 self.mock = self
3506 .mock
3507 .and(path_regex(format!(r"^/_matrix/client/v3/rooms/{room_path}/event/{event_path}")));
3508
3509 self.ok_json(event.into_raw().json())
3510 }
3511}
3512
3513/// A builder pattern for the response to a [`RoomEventContextEndpoint`]
3514/// request.
3515pub struct RoomContextResponseTemplate {
3516 event: TimelineEvent,
3517 events_before: Vec<TimelineEvent>,
3518 events_after: Vec<TimelineEvent>,
3519 start: Option<String>,
3520 end: Option<String>,
3521 state_events: Vec<Raw<AnyStateEvent>>,
3522}
3523
3524impl RoomContextResponseTemplate {
3525 /// Creates a new context response with the given focused event.
3526 pub fn new(event: TimelineEvent) -> Self {
3527 Self {
3528 event,
3529 events_before: Vec::new(),
3530 events_after: Vec::new(),
3531 start: None,
3532 end: None,
3533 state_events: Vec::new(),
3534 }
3535 }
3536
3537 /// Add some events before the target event.
3538 pub fn events_before(mut self, events: Vec<TimelineEvent>) -> Self {
3539 self.events_before = events;
3540 self
3541 }
3542
3543 /// Add some events after the target event.
3544 pub fn events_after(mut self, events: Vec<TimelineEvent>) -> Self {
3545 self.events_after = events;
3546 self
3547 }
3548
3549 /// Set the start token that could be used for paginating backwards.
3550 pub fn start(mut self, start: impl Into<String>) -> Self {
3551 self.start = Some(start.into());
3552 self
3553 }
3554
3555 /// Set the end token that could be used for paginating forwards.
3556 pub fn end(mut self, end: impl Into<String>) -> Self {
3557 self.end = Some(end.into());
3558 self
3559 }
3560
3561 /// Pass some extra state events to this response.
3562 pub fn state_events(mut self, state_events: Vec<Raw<AnyStateEvent>>) -> Self {
3563 self.state_events = state_events;
3564 self
3565 }
3566}
3567
3568/// A prebuilt mock for getting a single event with its context in a room.
3569pub struct RoomEventContextEndpoint {
3570 room: Option<OwnedRoomId>,
3571 match_event_id: bool,
3572}
3573
3574impl<'a> MockEndpoint<'a, RoomEventContextEndpoint> {
3575 /// Limits the scope of this mock to a specific room.
3576 pub fn room(mut self, room: impl Into<OwnedRoomId>) -> Self {
3577 self.endpoint.room = Some(room.into());
3578 self
3579 }
3580
3581 /// Whether the mock checks for the event id from the event.
3582 pub fn match_event_id(mut self) -> Self {
3583 self.endpoint.match_event_id = true;
3584 self
3585 }
3586
3587 /// Returns an endpoint that emulates a successful response.
3588 pub fn ok(mut self, response: RoomContextResponseTemplate) -> MatrixMock<'a> {
3589 let event_path = if self.endpoint.match_event_id {
3590 let event_id = response.event.event_id().expect("an event id is required");
3591 // The event id should begin with `$`, which would be taken as the
3592 // end of the regex so we need to escape it
3593 event_id.as_str().replace("$", "\\$")
3594 } else {
3595 // Event is at the end, so no need to add anything.
3596 "".to_owned()
3597 };
3598
3599 let room_path =
3600 self.endpoint.room.take().map_or_else(|| ".*".to_owned(), |room| room.to_string());
3601
3602 self.mock = self.mock.and(path_regex(format!(
3603 r"^/_matrix/client/v3/rooms/{room_path}/context/{event_path}"
3604 )));
3605
3606 self.ok_json(json!({
3607 "event": response.event.into_raw().json(),
3608 "events_before": response.events_before.into_iter().map(|event| event.into_raw().json().to_owned()).collect::<Vec<_>>(),
3609 "events_after": response.events_after.into_iter().map(|event| event.into_raw().json().to_owned()).collect::<Vec<_>>(),
3610 "end": response.end,
3611 "start": response.start,
3612 "state": response.state_events,
3613 }))
3614 }
3615}
3616
3617/// A prebuilt mock for the `/messages` endpoint.
3618pub struct RoomMessagesEndpoint;
3619
3620/// A prebuilt mock for getting a room messages in a room.
3621impl<'a> MockEndpoint<'a, RoomMessagesEndpoint> {
3622 /// Expects an optional limit to be set on the request.
3623 pub fn match_limit(self, limit: u32) -> Self {
3624 Self { mock: self.mock.and(query_param("limit", limit.to_string())), ..self }
3625 }
3626
3627 /// Expects an optional `from` to be set on the request.
3628 pub fn match_from(self, from: &str) -> Self {
3629 Self { mock: self.mock.and(query_param("from", from)), ..self }
3630 }
3631
3632 /// Returns a messages endpoint that emulates success, i.e. the messages
3633 /// provided as `response` could be retrieved.
3634 ///
3635 /// Note: pass `chunk` in the correct order: topological for forward
3636 /// pagination, reverse topological for backwards pagination.
3637 pub fn ok(self, response: RoomMessagesResponseTemplate) -> MatrixMock<'a> {
3638 self.ok_json(json!({
3639 "start": response.start,
3640 "end": response.end,
3641 "chunk": response.chunk,
3642 "state": response.state,
3643 }))
3644 }
3645}
3646
3647/// A response to a [`RoomMessagesEndpoint`] query.
3648pub struct RoomMessagesResponseTemplate {
3649 /// The start token for this /messages query.
3650 pub start: String,
3651 /// The end token for this /messages query (previous batch for back
3652 /// paginations, next batch for forward paginations).
3653 pub end: Option<String>,
3654 /// The set of timeline events returned by this query.
3655 pub chunk: Vec<Raw<AnyTimelineEvent>>,
3656 /// The set of state events returned by this query.
3657 pub state: Vec<Raw<AnyStateEvent>>,
3658}
3659
3660impl RoomMessagesResponseTemplate {
3661 /// Fill the events returned as part of this response.
3662 pub fn events(mut self, chunk: Vec<impl Into<Raw<AnyTimelineEvent>>>) -> Self {
3663 self.chunk = chunk.into_iter().map(Into::into).collect();
3664 self
3665 }
3666
3667 /// Fill the end token.
3668 pub fn end_token(mut self, token: impl Into<String>) -> Self {
3669 self.end = Some(token.into());
3670 self
3671 }
3672}
3673
3674impl Default for RoomMessagesResponseTemplate {
3675 fn default() -> Self {
3676 Self {
3677 start: "start-token-unused".to_owned(),
3678 end: Default::default(),
3679 chunk: Default::default(),
3680 state: Default::default(),
3681 }
3682 }
3683}
3684
3685/// A prebuilt mock for `GET
3686/// /_matrix/client/v3/rooms/{roomId}/state/{eventType}/{stateKey}`.
3687pub struct RoomStateEventEndpoint;
3688
3689impl<'a> MockEndpoint<'a, RoomStateEventEndpoint> {
3690 /// Returns a successful response with the given state event.
3691 pub fn ok(self, event: impl Into<Raw<AnyStateEvent>>) -> MatrixMock<'a> {
3692 self.ok_json(event.into())
3693 }
3694
3695 /// Returns an error response for a missing state event.
3696 pub fn error_not_found(self) -> MatrixMock<'a> {
3697 self.respond_with_code_and_json(
3698 404,
3699 json!({
3700 "errcode": "M_NOT_FOUND",
3701 "error": "State event not found."
3702 }),
3703 )
3704 }
3705}
3706
3707/// A prebuilt mock for uploading media.
3708pub struct UploadEndpoint;
3709
3710impl<'a> MockEndpoint<'a, UploadEndpoint> {
3711 /// Expect that the content type matches what's given here.
3712 pub fn expect_mime_type(self, content_type: &str) -> Self {
3713 Self { mock: self.mock.and(header("content-type", content_type)), ..self }
3714 }
3715
3716 /// Returns a upload endpoint that emulates success, i.e. the media has been
3717 /// uploaded to the media server and can be accessed using the given event
3718 /// has been sent with the given [`MxcUri`].
3719 ///
3720 /// The uploaded content is captured and can be accessed using the returned
3721 /// [`Receiver`]. The [`Receiver`] is valid only for a single media upload.
3722 ///
3723 /// # Examples
3724 ///
3725 /// ```no_run
3726 /// # tokio_test::block_on(async {
3727 /// use matrix_sdk::{
3728 /// ruma::{event_id, mxc_uri, room_id},
3729 /// test_utils::mocks::MatrixMockServer,
3730 /// };
3731 ///
3732 /// let mxid = mxc_uri!("mxc://localhost/12345");
3733 ///
3734 /// let server = MatrixMockServer::new().await;
3735 /// let (receiver, upload_mock) = server.mock_upload().ok_with_capture(mxid);
3736 /// let client = server.client_builder().build().await;
3737 ///
3738 /// client.media().upload(&mime::TEXT_PLAIN, vec![1, 2, 3, 4, 5], None).await?;
3739 ///
3740 /// let uploaded = receiver.await?;
3741 ///
3742 /// assert_eq!(uploaded, vec![1, 2, 3, 4, 5]);
3743 /// # anyhow::Ok(()) });
3744 /// ```
3745 pub fn ok_with_capture(self, mxc_id: &MxcUri) -> (Receiver<Vec<u8>>, MatrixMock<'a>) {
3746 let (sender, receiver) = oneshot::channel();
3747 let sender = Arc::new(Mutex::new(Some(sender)));
3748 let response_body = json!({"content_uri": mxc_id});
3749
3750 let ret = self.respond_with(move |request: &Request| {
3751 let maybe_sender = sender.lock().unwrap().take();
3752
3753 if let Some(sender) = maybe_sender {
3754 let body = request.body.clone();
3755 let _ = sender.send(body);
3756 }
3757
3758 ResponseTemplate::new(200).set_body_json(response_body.clone())
3759 });
3760
3761 (receiver, ret)
3762 }
3763
3764 /// Returns a upload endpoint that emulates success, i.e. the media has been
3765 /// uploaded to the media server and can be accessed using the given event
3766 /// has been sent with the given [`MxcUri`].
3767 pub fn ok(self, mxc_id: &MxcUri) -> MatrixMock<'a> {
3768 self.ok_json(json!({
3769 "content_uri": mxc_id
3770 }))
3771 }
3772}
3773
3774/// A prebuilt mock for resolving a room alias.
3775pub struct ResolveRoomAliasEndpoint;
3776
3777impl<'a> MockEndpoint<'a, ResolveRoomAliasEndpoint> {
3778 /// Sets up the endpoint to only intercept requests for the given room
3779 /// alias.
3780 pub fn for_alias(self, alias: impl Into<String>) -> Self {
3781 let alias = alias.into();
3782 Self {
3783 mock: self.mock.and(path_regex(format!(
3784 r"^/_matrix/client/v3/directory/room/{}",
3785 percent_encoded_path(&alias)
3786 ))),
3787 ..self
3788 }
3789 }
3790
3791 /// Returns a data endpoint with a resolved room alias.
3792 pub fn ok(self, room_id: &str, servers: Vec<String>) -> MatrixMock<'a> {
3793 self.ok_json(json!({
3794 "room_id": room_id,
3795 "servers": servers,
3796 }))
3797 }
3798
3799 /// Returns a data endpoint for a room alias that does not exit.
3800 pub fn not_found(self) -> MatrixMock<'a> {
3801 self.respond_with_code_and_json(
3802 404,
3803 json!({
3804 "errcode": "M_NOT_FOUND",
3805 "error": "Room alias not found."
3806 }),
3807 )
3808 }
3809}
3810
3811/// A prebuilt mock for creating a room alias.
3812pub struct CreateRoomAliasEndpoint;
3813
3814impl<'a> MockEndpoint<'a, CreateRoomAliasEndpoint> {
3815 /// Returns a data endpoint for creating a room alias.
3816 pub fn ok(self) -> MatrixMock<'a> {
3817 self.ok_empty_json()
3818 }
3819}
3820
3821/// A prebuilt mock for removing a room alias.
3822pub struct RemoveRoomAliasEndpoint;
3823
3824impl<'a> MockEndpoint<'a, RemoveRoomAliasEndpoint> {
3825 /// Returns a data endpoint for removing a room alias.
3826 pub fn ok(self) -> MatrixMock<'a> {
3827 self.ok_empty_json()
3828 }
3829}
3830
3831/// A prebuilt mock for paginating the public room list.
3832pub struct PublicRoomsEndpoint;
3833
3834impl<'a> MockEndpoint<'a, PublicRoomsEndpoint> {
3835 /// Returns a data endpoint for paginating the public room list.
3836 pub fn ok(
3837 self,
3838 chunk: Vec<PublicRoomsChunk>,
3839 next_batch: Option<String>,
3840 prev_batch: Option<String>,
3841 total_room_count_estimate: Option<u64>,
3842 ) -> MatrixMock<'a> {
3843 self.ok_json(json!({
3844 "chunk": chunk,
3845 "next_batch": next_batch,
3846 "prev_batch": prev_batch,
3847 "total_room_count_estimate": total_room_count_estimate,
3848 }))
3849 }
3850
3851 /// Returns a data endpoint for paginating the public room list with several
3852 /// `via` params.
3853 ///
3854 /// Each `via` param must be in the `server_map` parameter, otherwise it'll
3855 /// fail.
3856 pub fn ok_with_via_params(
3857 self,
3858 server_map: BTreeMap<OwnedServerName, Vec<PublicRoomsChunk>>,
3859 ) -> MatrixMock<'a> {
3860 self.respond_with(move |req: &Request| {
3861 #[derive(Deserialize)]
3862 struct PartialRequest {
3863 server: Option<OwnedServerName>,
3864 }
3865
3866 let (_, server) = req
3867 .url
3868 .query_pairs()
3869 .into_iter()
3870 .find(|(key, _)| key == "server")
3871 .expect("Server param not found in request URL");
3872 let server = ServerName::parse(server).expect("Couldn't parse server name");
3873 let chunk = server_map.get(&server).expect("Chunk for the server param not found");
3874 ResponseTemplate::new(200).set_body_json(json!({
3875 "chunk": chunk,
3876 "total_room_count_estimate": chunk.len(),
3877 }))
3878 })
3879 }
3880
3881 /// Returns an endpoint with a default successful response.
3882 pub fn ok_default(self) -> MatrixMock<'a> {
3883 self.ok_json(&*test_json::PUBLIC_ROOMS)
3884 }
3885}
3886
3887/// A prebuilt mock for getting the room's visibility in the room directory.
3888pub struct GetRoomVisibilityEndpoint;
3889
3890impl<'a> MockEndpoint<'a, GetRoomVisibilityEndpoint> {
3891 /// Returns an endpoint that get the room's public visibility.
3892 pub fn ok(self, visibility: Visibility) -> MatrixMock<'a> {
3893 self.ok_json(json!({
3894 "visibility": visibility,
3895 }))
3896 }
3897}
3898
3899/// A prebuilt mock for setting the room's visibility in the room directory.
3900pub struct SetRoomVisibilityEndpoint;
3901
3902impl<'a> MockEndpoint<'a, SetRoomVisibilityEndpoint> {
3903 /// Returns an endpoint that updates the room's visibility.
3904 pub fn ok(self) -> MatrixMock<'a> {
3905 self.ok_empty_json()
3906 }
3907}
3908
3909/// A prebuilt mock for `GET room_keys/version`: storage ("backup") of room
3910/// keys.
3911pub struct RoomKeysVersionEndpoint;
3912
3913impl<'a> MockEndpoint<'a, RoomKeysVersionEndpoint> {
3914 /// Returns an endpoint that says there is a single room keys backup
3915 pub fn exists(self) -> MatrixMock<'a> {
3916 self.ok_json(json!({
3917 "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
3918 "auth_data": {
3919 "public_key": "abcdefg",
3920 "signatures": {},
3921 },
3922 "count": 42,
3923 "etag": "anopaquestring",
3924 "version": "1",
3925 }))
3926 }
3927
3928 /// Returns an endpoint that says there is a single room keys backup
3929 pub fn exists_with_key(self, public_key: &str) -> MatrixMock<'a> {
3930 self.ok_json(json!({
3931 "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
3932 "auth_data": {
3933 "public_key": public_key,
3934 "signatures": {},
3935 },
3936 "count": 42,
3937 "etag": "anopaquestring",
3938 "version": "1",
3939 }))
3940 }
3941
3942 /// Returns an endpoint that says there is no room keys backup
3943 pub fn none(self) -> MatrixMock<'a> {
3944 self.respond_with_code_and_json(
3945 404,
3946 json!({
3947 "errcode": "M_NOT_FOUND",
3948 "error": "No current backup version"
3949 }),
3950 )
3951 }
3952
3953 /// Returns an endpoint that 429 errors when we get it
3954 pub fn error429(self) -> MatrixMock<'a> {
3955 self.error_rate_limited()
3956 }
3957
3958 /// Returns an endpoint that 404 errors when we get it
3959 pub fn error404(self) -> MatrixMock<'a> {
3960 self.respond_with(ResponseTemplate::new(404))
3961 }
3962}
3963
3964/// A prebuilt mock for `POST room_keys/version`: adding room key backups.
3965pub struct AddRoomKeysVersionEndpoint;
3966
3967impl<'a> MockEndpoint<'a, AddRoomKeysVersionEndpoint> {
3968 /// Returns an endpoint that may be used to add room key backups
3969 pub fn ok(self) -> MatrixMock<'a> {
3970 self.ok_json(json!({
3971 "version": "1"
3972 }))
3973 .named("POST for the backup creation")
3974 }
3975}
3976
3977/// A prebuilt mock for `DELETE room_keys/version/xxx`: deleting room key
3978/// backups.
3979pub struct DeleteRoomKeysVersionEndpoint;
3980
3981impl<'a> MockEndpoint<'a, DeleteRoomKeysVersionEndpoint> {
3982 /// Returns an endpoint that allows deleting room key backups
3983 pub fn ok(self) -> MatrixMock<'a> {
3984 self.ok_json(json!({})).named("DELETE for the backup deletion")
3985 }
3986}
3987
3988/// A prebuilt mock for the `/sendToDevice` endpoint.
3989///
3990/// This mock can be used to simulate sending to-device messages in tests.
3991pub struct SendToDeviceEndpoint;
3992impl<'a> MockEndpoint<'a, SendToDeviceEndpoint> {
3993 /// Returns a successful response with default data.
3994 pub fn ok(self) -> MatrixMock<'a> {
3995 self.ok_empty_json()
3996 }
3997}
3998
3999/// A prebuilt mock for `GET /members` request.
4000pub struct GetRoomMembersEndpoint;
4001
4002impl<'a> MockEndpoint<'a, GetRoomMembersEndpoint> {
4003 /// Returns a successful get members request with a list of members.
4004 pub fn ok(self, members: Vec<Raw<RoomMemberEvent>>) -> MatrixMock<'a> {
4005 self.ok_json(json!({
4006 "chunk": members,
4007 }))
4008 }
4009}
4010
4011/// A prebuilt mock for `POST /invite` request.
4012pub struct InviteUserByIdEndpoint;
4013
4014impl<'a> MockEndpoint<'a, InviteUserByIdEndpoint> {
4015 /// Returns a successful invite user by id request.
4016 pub fn ok(self) -> MatrixMock<'a> {
4017 self.ok_empty_json()
4018 }
4019}
4020
4021/// A prebuilt mock for `POST /kick` request.
4022pub struct KickUserEndpoint;
4023
4024impl<'a> MockEndpoint<'a, KickUserEndpoint> {
4025 /// Returns a successful kick user request.
4026 pub fn ok(self) -> MatrixMock<'a> {
4027 self.ok_empty_json()
4028 }
4029}
4030
4031/// A prebuilt mock for `POST /ban` request.
4032pub struct BanUserEndpoint;
4033
4034impl<'a> MockEndpoint<'a, BanUserEndpoint> {
4035 /// Returns a successful ban user request.
4036 pub fn ok(self) -> MatrixMock<'a> {
4037 self.ok_empty_json()
4038 }
4039}
4040
4041/// A prebuilt mock for a `POST /_matrix/client/v3/rooms/{roomId}/unban`
4042/// request.
4043pub struct UnbanUserEndpoint;
4044
4045impl<'a> MockEndpoint<'a, UnbanUserEndpoint> {
4046 /// Returns a successful unban user request.
4047 pub fn ok(self) -> MatrixMock<'a> {
4048 self.ok_empty_json()
4049 }
4050}
4051
4052/// A prebuilt mock for a `PUT
4053/// /_matrix/client/v3/rooms/{roomId}/typing/{userId}` request.
4054pub struct UpdateTypingEndpoint;
4055
4056impl<'a> MockEndpoint<'a, UpdateTypingEndpoint> {
4057 /// Returns a successful typing update request.
4058 pub fn ok(self) -> MatrixMock<'a> {
4059 self.ok_empty_json()
4060 }
4061}
4062
4063/// A prebuilt mock for a `POST
4064/// /_matrix/client/v3/rooms/{roomId}/report/{eventId} ` request.
4065pub struct ReportRoomEventEndpoint;
4066
4067impl<'a> MockEndpoint<'a, ReportRoomEventEndpoint> {
4068 /// Returns a successful typing update request.
4069 pub fn ok(self) -> MatrixMock<'a> {
4070 self.ok_empty_json()
4071 }
4072}
4073
4074/// A prebuilt mock for a `POST /_matrix/client/v3/rooms/{roomId}/report`
4075/// request.
4076pub struct ReportRoomEndpoint;
4077
4078impl<'a> MockEndpoint<'a, ReportRoomEndpoint> {
4079 /// Look for the given reason in the body.
4080 pub fn with_reason(self, reason: &str) -> Self {
4081 Self { mock: self.mock.and(body_partial_json(json!({ "reason": reason }))), ..self }
4082 }
4083
4084 /// Returns a successful room report request.
4085 pub fn ok(self) -> MatrixMock<'a> {
4086 self.ok_empty_json()
4087 }
4088}
4089
4090/// A prebuilt mock for a `POST /_matrix/client/v3/users/{userId}/report`
4091/// request.
4092#[derive(Default)]
4093pub struct ReportUserEndpoint {
4094 unstable_path: bool,
4095}
4096
4097impl<'a> MockEndpoint<'a, ReportUserEndpoint> {
4098 /// Expects the unstable MSC4260 path instead of the stable v3 one.
4099 pub fn match_unstable_path(mut self) -> Self {
4100 self.endpoint.unstable_path = true;
4101 self
4102 }
4103
4104 /// Looks for the given reason in the body.
4105 pub fn with_reason(self, reason: &str) -> Self {
4106 Self { mock: self.mock.and(body_partial_json(json!({ "reason": reason }))), ..self }
4107 }
4108
4109 /// Returns a successful user report request.
4110 pub fn ok(mut self) -> MatrixMock<'a> {
4111 let prefix = if self.endpoint.unstable_path { "unstable/org.matrix.msc4260" } else { "v3" };
4112 self.mock =
4113 self.mock.and(path_regex(format!(r"^/_matrix/client/{prefix}/users/[^/]+/report$")));
4114 self.ok_empty_json()
4115 }
4116}
4117
4118/// A prebuilt mock for `GET /versions` request.
4119pub struct VersionsEndpoint {
4120 versions: Vec<&'static str>,
4121 features: BTreeMap<&'static str, bool>,
4122}
4123
4124impl VersionsEndpoint {
4125 // Get a JSON array of commonly supported versions.
4126 fn commonly_supported_versions() -> Vec<&'static str> {
4127 vec![
4128 "r0.0.1", "r0.2.0", "r0.3.0", "r0.4.0", "r0.5.0", "r0.6.0", "r0.6.1", "v1.1", "v1.2",
4129 "v1.3", "v1.4", "v1.5", "v1.6", "v1.7", "v1.8", "v1.9", "v1.10", "v1.11",
4130 ]
4131 }
4132}
4133
4134impl Default for VersionsEndpoint {
4135 fn default() -> Self {
4136 Self { versions: Self::commonly_supported_versions(), features: BTreeMap::new() }
4137 }
4138}
4139
4140impl<'a> MockEndpoint<'a, VersionsEndpoint> {
4141 /// Returns a successful `/_matrix/client/versions` request.
4142 ///
4143 /// The response will return some commonly supported versions.
4144 pub fn ok(mut self) -> MatrixMock<'a> {
4145 let features = std::mem::take(&mut self.endpoint.features);
4146 let versions = std::mem::take(&mut self.endpoint.versions);
4147 self.ok_json(json!({
4148 "unstable_features": features,
4149 "versions": versions
4150 }))
4151 }
4152
4153 /// Set the supported flag for the given unstable feature in the response of
4154 /// this endpoint.
4155 pub fn with_feature(mut self, feature: &'static str, supported: bool) -> Self {
4156 self.endpoint.features.insert(feature, supported);
4157 self
4158 }
4159
4160 /// Indicate that push for encrypted events is supported by this homeserver.
4161 pub fn with_push_encrypted_events(self) -> Self {
4162 self.with_feature("org.matrix.msc4028", true)
4163 }
4164
4165 /// Indicate that thread subscriptions are supported by this homeserver.
4166 pub fn with_thread_subscriptions(self) -> Self {
4167 self.with_feature("org.matrix.msc4306", true)
4168 }
4169
4170 /// Indicate that simplified sliding sync is supported by this homeserver.
4171 pub fn with_simplified_sliding_sync(self) -> Self {
4172 self.with_feature("org.matrix.simplified_msc3575", true)
4173 }
4174
4175 /// Indicate that global profile sync is supported by this homeserver.
4176 pub fn with_profiles_sliding_sync_extension(self) -> Self {
4177 self.with_feature("org.matrix.msc4262", true)
4178 }
4179
4180 /// Indicate that querying multiple profiles (MSC4536) is supported by this
4181 /// homeserver.
4182 pub fn with_query_profiles(self) -> Self {
4183 self.with_feature("org.matrix.msc4536", true)
4184 }
4185
4186 /// Indicate that sticky events (MSC4354) are supported by this homeserver.
4187 pub fn with_sticky_events(self) -> Self {
4188 self.with_feature("org.matrix.msc4354", true)
4189 }
4190
4191 /// Set the supported versions in the response of this endpoint.
4192 pub fn with_versions(mut self, versions: Vec<&'static str>) -> Self {
4193 self.endpoint.versions = versions;
4194 self
4195 }
4196}
4197
4198/// A prebuilt mock for the room summary endpoint.
4199pub struct RoomSummaryEndpoint;
4200
4201impl<'a> MockEndpoint<'a, RoomSummaryEndpoint> {
4202 /// Returns a successful response with some default data and the given
4203 /// custom fields for the given room id.
4204 ///
4205 /// The custom fields may override the default data.
4206 fn ok_with_custom_fields<'b>(
4207 self,
4208 room_id: impl Into<&'b RoomId>,
4209 fields: Vec<(String, Value)>,
4210 ) -> MatrixMock<'a> {
4211 let mut body = as_variant!(
4212 json!({
4213 "room_id": room_id.into(),
4214 "guest_can_join": true,
4215 "num_joined_members": 1,
4216 "world_readable": true,
4217 "join_rule": "public",
4218 }),
4219 Value::Object
4220 )
4221 .unwrap();
4222 body.extend(fields);
4223
4224 self.ok_json(body)
4225 }
4226
4227 /// Returns a successful response with some default data for the given room
4228 /// id.
4229 pub fn ok<'b>(self, room_id: impl Into<&'b RoomId>) -> MatrixMock<'a> {
4230 self.ok_with_custom_fields(room_id, vec![])
4231 }
4232
4233 /// Returns a successful response with some default data and the given
4234 /// membership for the given room id.
4235 pub fn ok_with_membership<'b>(
4236 self,
4237 room_id: impl Into<&'b RoomId>,
4238 membership: MembershipState,
4239 ) -> MatrixMock<'a> {
4240 self.ok_with_custom_fields(
4241 room_id,
4242 vec![("membership".to_owned(), membership.as_str().into())],
4243 )
4244 }
4245}
4246
4247/// A prebuilt mock to set a room's pinned events.
4248pub struct SetRoomPinnedEventsEndpoint;
4249
4250impl<'a> MockEndpoint<'a, SetRoomPinnedEventsEndpoint> {
4251 /// Returns a successful response with a given event id. id.
4252 pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> {
4253 self.ok_with_event_id(event_id)
4254 }
4255
4256 /// Returns an error response with a generic error code indicating the
4257 /// client is not authorized to set pinned events.
4258 pub fn unauthorized(self) -> MatrixMock<'a> {
4259 self.respond_with(ResponseTemplate::new(400))
4260 }
4261}
4262
4263/// A prebuilt mock for `GET /account/whoami` request.
4264pub struct WhoAmIEndpoint;
4265
4266impl<'a> MockEndpoint<'a, WhoAmIEndpoint> {
4267 /// Returns a successful response with the default user ID and device ID.
4268 pub fn ok(self) -> MatrixMock<'a> {
4269 self.ok_with_ids(User::Alice, device_id!("D3V1C31D"))
4270 }
4271
4272 /// Returns a successful response with the given user ID, and the default
4273 /// device ID.
4274 pub fn ok_with_user_id<'b>(self, user_id: impl Into<&'b UserId>) -> MatrixMock<'a> {
4275 self.ok_with_ids(user_id, device_id!("D3V1C31D"))
4276 }
4277
4278 /// Returns a successful response with the given device ID, and the default
4279 /// user ID.
4280 pub fn ok_with_device_id(self, device_id: &DeviceId) -> MatrixMock<'a> {
4281 self.ok_with_ids(User::Alice, device_id)
4282 }
4283
4284 /// Returns a successful response with the given user ID and device ID.
4285 fn ok_with_ids<'b>(
4286 self,
4287 user_id: impl Into<&'b UserId>,
4288 device_id: &DeviceId,
4289 ) -> MatrixMock<'a> {
4290 self.ok_json(json!({
4291 "user_id": user_id.into(),
4292 "device_id": device_id,
4293 }))
4294 }
4295}
4296
4297/// A prebuilt mock for `POST /keys/upload` request.
4298pub struct UploadKeysEndpoint;
4299
4300impl<'a> MockEndpoint<'a, UploadKeysEndpoint> {
4301 /// Returns a successful response with counts of 10 curve25519 keys and 20
4302 /// signed curve25519 keys.
4303 pub fn ok(self) -> MatrixMock<'a> {
4304 self.ok_json(json!({
4305 "one_time_key_counts": {
4306 "curve25519": 10,
4307 "signed_curve25519": 20,
4308 },
4309 }))
4310 }
4311
4312 /// Returns a successful response with the given number of signed curve25519
4313 /// one-time keys.
4314 pub fn ok_with_signed_curve_key_count(self, n: u32) -> MatrixMock<'a> {
4315 self.ok_json(json!({
4316 "one_time_key_counts": {
4317 "signed_curve25519": n,
4318 },
4319 }))
4320 }
4321}
4322
4323/// A prebuilt mock for `POST /keys/query` request.
4324pub struct QueryKeysEndpoint;
4325
4326impl<'a> MockEndpoint<'a, QueryKeysEndpoint> {
4327 /// Returns a successful empty response.
4328 pub fn ok(self) -> MatrixMock<'a> {
4329 self.ok_empty_json()
4330 }
4331}
4332
4333/// A prebuilt mock for `GET /.well-known/matrix/client` request.
4334pub struct WellKnownEndpoint;
4335
4336impl<'a> MockEndpoint<'a, WellKnownEndpoint> {
4337 /// Returns a successful response with the URL for this homeserver.
4338 pub fn ok(self) -> MatrixMock<'a> {
4339 let server_uri = self.server.uri();
4340 self.ok_with_homeserver_url(&server_uri)
4341 }
4342
4343 /// Returns a successful response with the given homeserver URL.
4344 pub fn ok_with_homeserver_url(self, homeserver_url: &str) -> MatrixMock<'a> {
4345 self.ok_json(json!({
4346 "m.homeserver": {
4347 "base_url": homeserver_url,
4348 },
4349 "m.rtc_foci": [
4350 {
4351 "type": "m.livekit",
4352 "url": "wss://livekit.example.com",
4353 },
4354 ],
4355 }))
4356 }
4357
4358 /// Returns a 404 error response.
4359 pub fn error404(self) -> MatrixMock<'a> {
4360 self.respond_with(ResponseTemplate::new(404))
4361 }
4362}
4363
4364/// A prebuilt mock for `POST /keys/device_signing/upload` request.
4365pub struct UploadCrossSigningKeysEndpoint;
4366
4367impl<'a> MockEndpoint<'a, UploadCrossSigningKeysEndpoint> {
4368 /// Returns a successful empty response.
4369 pub fn ok(self) -> MatrixMock<'a> {
4370 self.ok_empty_json()
4371 }
4372
4373 /// Returns an error response with a UIAA stage that failed to authenticate
4374 /// because of an invalid password.
4375 pub fn uiaa_invalid_password(self) -> MatrixMock<'a> {
4376 self.respond_with_code_and_json(
4377 401,
4378 json!({
4379 "errcode": "M_FORBIDDEN",
4380 "error": "Invalid password",
4381 "flows": [
4382 {
4383 "stages": [
4384 "m.login.password"
4385 ]
4386 }
4387 ],
4388 "params": {},
4389 "session": "oFIJVvtEOCKmRUTYKTYIIPHL"
4390 }),
4391 )
4392 }
4393
4394 /// Returns an error response with an unstable OAuth 2.0 UIAA stage.
4395 pub fn uiaa_unstable_oauth(self) -> MatrixMock<'a> {
4396 let server_uri = self.server.uri();
4397 self.respond_with_code_and_json(
4398 401,
4399 json!({
4400 "session": "dummy",
4401 "flows": [{
4402 "stages": [ "org.matrix.cross_signing_reset" ]
4403 }],
4404 "params": {
4405 "org.matrix.cross_signing_reset": {
4406 "url": format!("{server_uri}/account/?action=org.matrix.cross_signing_reset"),
4407 }
4408 },
4409 "msg": "To reset your end-to-end encryption cross-signing identity, you first need to approve it and then try again."
4410 }),
4411 )
4412 }
4413
4414 /// Returns an error response with a stable OAuth 2.0 UIAA stage with the
4415 /// given session key and optional extra error message.
4416 pub fn uiaa_stable_oauth(
4417 self,
4418 session: &str,
4419 extra_error: Option<&StandardErrorBody>,
4420 ) -> MatrixMock<'a> {
4421 let mut json = json!({
4422 "session": session,
4423 "flows": [{
4424 "stages": [ "m.oauth" ]
4425 }],
4426 "params": {
4427 "m.oauth": {
4428 "url": format!("{}/account/?action=org.matrix.cross_signing_reset", self.server.uri()),
4429 }
4430 },
4431 "msg": "To reset your end-to-end encryption cross-signing identity, you first need to approve it and then try again."
4432 });
4433
4434 if let Some(extra_error) = extra_error {
4435 let extra_json = as_variant!(
4436 serde_json::to_value(extra_error)
4437 .expect("extra error should serialize successfully"),
4438 Value::Object
4439 )
4440 .expect("extra error should be a JSON object");
4441
4442 let json_object = json.as_object_mut().expect("UIAA response should be a JSON object");
4443 json_object.extend(extra_json);
4444 }
4445
4446 self.respond_with_code_and_json(401, json)
4447 }
4448}
4449
4450/// A prebuilt mock for `POST /keys/signatures/upload` request.
4451pub struct UploadCrossSigningSignaturesEndpoint;
4452
4453impl<'a> MockEndpoint<'a, UploadCrossSigningSignaturesEndpoint> {
4454 /// Returns a successful empty response.
4455 pub fn ok(self) -> MatrixMock<'a> {
4456 self.ok_empty_json()
4457 }
4458}
4459
4460/// A prebuilt mock for the MSC3814 `GET /dehydrated_device` request.
4461#[cfg(feature = "e2e-encryption")]
4462pub struct GetDehydratedDeviceEndpoint;
4463
4464#[cfg(feature = "e2e-encryption")]
4465impl<'a> MockEndpoint<'a, GetDehydratedDeviceEndpoint> {
4466 /// Returns a successful response carrying the given dehydrated device.
4467 pub fn ok(self, device_id: &DeviceId, device_data: Value) -> MatrixMock<'a> {
4468 self.ok_json(json!({
4469 "device_id": device_id,
4470 "device_data": device_data,
4471 }))
4472 }
4473
4474 /// Returns a 404 response with `M_NOT_FOUND`, signalling that no device is
4475 /// currently dehydrated for the user.
4476 pub fn not_found(self) -> MatrixMock<'a> {
4477 self.respond_with_code_and_json(
4478 404,
4479 json!({
4480 "errcode": "M_NOT_FOUND",
4481 "error": "No dehydrated device found",
4482 }),
4483 )
4484 }
4485}
4486
4487/// A prebuilt mock for the MSC3814 `PUT /dehydrated_device` request.
4488#[cfg(feature = "e2e-encryption")]
4489pub struct PutDehydratedDeviceEndpoint;
4490
4491#[cfg(feature = "e2e-encryption")]
4492impl<'a> MockEndpoint<'a, PutDehydratedDeviceEndpoint> {
4493 /// Returns a successful response echoing the supplied device ID.
4494 pub fn ok(self, device_id: &DeviceId) -> MatrixMock<'a> {
4495 self.ok_json(json!({
4496 "device_id": device_id,
4497 }))
4498 }
4499
4500 /// Returns a successful response, computing the response body from the
4501 /// `device_id` field in the request payload. Useful when the caller does
4502 /// not know the device ID ahead of time.
4503 pub fn ok_echo(self) -> MatrixMock<'a> {
4504 self.respond_with(|req: &Request| {
4505 #[derive(serde::Deserialize)]
4506 struct Body {
4507 device_id: OwnedDeviceId,
4508 }
4509 let body: Body = req.body_json().expect("dehydrated device PUT body");
4510 ResponseTemplate::new(200).set_body_json(json!({ "device_id": body.device_id }))
4511 })
4512 }
4513}
4514
4515/// A prebuilt mock for the MSC3814 `DELETE /dehydrated_device` request.
4516#[cfg(feature = "e2e-encryption")]
4517pub struct DeleteDehydratedDeviceEndpoint;
4518
4519#[cfg(feature = "e2e-encryption")]
4520impl<'a> MockEndpoint<'a, DeleteDehydratedDeviceEndpoint> {
4521 /// Returns a successful response echoing the deleted device ID.
4522 pub fn ok(self, device_id: &DeviceId) -> MatrixMock<'a> {
4523 self.ok_json(json!({
4524 "device_id": device_id,
4525 }))
4526 }
4527
4528 /// Returns a 404 with `M_NOT_FOUND`.
4529 pub fn not_found(self) -> MatrixMock<'a> {
4530 self.respond_with_code_and_json(
4531 404,
4532 json!({
4533 "errcode": "M_NOT_FOUND",
4534 "error": "No dehydrated device to delete",
4535 }),
4536 )
4537 }
4538}
4539
4540/// A prebuilt mock for the MSC3814 `POST /dehydrated_device/{device_id}/events`
4541/// request.
4542#[cfg(feature = "e2e-encryption")]
4543pub struct DehydratedDeviceEventsEndpoint;
4544
4545#[cfg(feature = "e2e-encryption")]
4546impl<'a> MockEndpoint<'a, DehydratedDeviceEventsEndpoint> {
4547 /// Returns a successful response with the supplied events array and an
4548 /// optional pagination cursor.
4549 pub fn ok(self, events: Vec<Value>, next_batch: Option<&str>) -> MatrixMock<'a> {
4550 self.ok_json(json!({
4551 "events": events,
4552 "next_batch": next_batch,
4553 }))
4554 }
4555
4556 /// Constrain the mock to only match requests whose `next_batch` body field
4557 /// equals the given token. Pair with [`Self::match_missing_next_batch`] for
4558 /// the initial request in a paginated flow.
4559 pub fn match_next_batch(mut self, token: &str) -> Self {
4560 self.mock = self.mock.and(body_partial_json(json!({ "next_batch": token })));
4561 self
4562 }
4563
4564 /// Constrain the mock to only match requests whose body has no `next_batch`
4565 /// field (i.e. the first call in a paginated flow).
4566 pub fn match_missing_next_batch(mut self) -> Self {
4567 self.mock = self.mock.and(body_json(json!({})));
4568 self
4569 }
4570}
4571
4572/// A prebuilt mock for the room leave endpoint.
4573pub struct RoomLeaveEndpoint;
4574
4575impl<'a> MockEndpoint<'a, RoomLeaveEndpoint> {
4576 /// Returns a successful response with some default data for the given room
4577 /// id.
4578 pub fn ok<'b>(self, room_id: impl Into<&'b RoomId>) -> MatrixMock<'a> {
4579 self.ok_json(json!({
4580 "room_id": room_id.into(),
4581 }))
4582 }
4583
4584 /// Returns a `M_FORBIDDEN` response.
4585 pub fn forbidden(self) -> MatrixMock<'a> {
4586 self.respond_with_code_and_json(
4587 403,
4588 json!({
4589 "errcode": "M_FORBIDDEN",
4590 "error": "sowwy",
4591 }),
4592 )
4593 }
4594}
4595
4596/// A prebuilt mock for the room forget endpoint.
4597pub struct RoomForgetEndpoint;
4598
4599impl<'a> MockEndpoint<'a, RoomForgetEndpoint> {
4600 /// Returns a successful response with some default data for the given room
4601 /// id.
4602 pub fn ok(self) -> MatrixMock<'a> {
4603 self.ok_empty_json()
4604 }
4605}
4606
4607/// A prebuilt mock for `POST /logout` request.
4608pub struct LogoutEndpoint;
4609
4610impl<'a> MockEndpoint<'a, LogoutEndpoint> {
4611 /// Returns a successful empty response.
4612 pub fn ok(self) -> MatrixMock<'a> {
4613 self.ok_empty_json()
4614 }
4615}
4616
4617/// A prebuilt mock for a `GET /rooms/{roomId}/threads` request.
4618pub struct RoomThreadsEndpoint;
4619
4620impl<'a> MockEndpoint<'a, RoomThreadsEndpoint> {
4621 /// Expects an optional `from` to be set on the request.
4622 pub fn match_from(self, from: &str) -> Self {
4623 Self { mock: self.mock.and(query_param("from", from)), ..self }
4624 }
4625
4626 /// Returns a successful response with some optional events and previous
4627 /// batch token.
4628 pub fn ok(
4629 self,
4630 chunk: Vec<Raw<AnyTimelineEvent>>,
4631 next_batch: Option<String>,
4632 ) -> MatrixMock<'a> {
4633 self.ok_json(json!({
4634 "chunk": chunk,
4635 "next_batch": next_batch
4636 }))
4637 }
4638}
4639
4640/// A prebuilt mock for a `GET /rooms/{roomId}/relations/{eventId}` family of
4641/// requests.
4642#[derive(Default)]
4643pub struct RoomRelationsEndpoint {
4644 event_id: Option<OwnedEventId>,
4645 spec: Option<IncludeRelations>,
4646}
4647
4648impl<'a> MockEndpoint<'a, RoomRelationsEndpoint> {
4649 /// Expects an optional `from` to be set on the request.
4650 pub fn match_from(self, from: &str) -> Self {
4651 Self { mock: self.mock.and(query_param("from", from)), ..self }
4652 }
4653
4654 /// Expects an optional `limit` to be set on the request.
4655 pub fn match_limit(self, limit: u32) -> Self {
4656 Self { mock: self.mock.and(query_param("limit", limit.to_string())), ..self }
4657 }
4658
4659 /// Match the given subrequest, according to the given specification.
4660 pub fn match_subrequest(mut self, spec: IncludeRelations) -> Self {
4661 self.endpoint.spec = Some(spec);
4662 self
4663 }
4664
4665 /// Expects the request to match a specific event id.
4666 pub fn match_target_event(mut self, event_id: OwnedEventId) -> Self {
4667 self.endpoint.event_id = Some(event_id);
4668 self
4669 }
4670
4671 /// Returns a successful response with some optional events and pagination
4672 /// tokens.
4673 pub fn ok(mut self, response: RoomRelationsResponseTemplate) -> MatrixMock<'a> {
4674 // Escape the leading $ to not confuse the regular expression engine.
4675 let event_spec = self
4676 .endpoint
4677 .event_id
4678 .take()
4679 .map(|event_id| event_id.as_str().replace("$", "\\$"))
4680 .unwrap_or_else(|| ".*".to_owned());
4681
4682 match self.endpoint.spec.take() {
4683 Some(IncludeRelations::RelationsOfType(rel_type)) => {
4684 self.mock = self.mock.and(path_regex(format!(
4685 r"^/_matrix/client/v1/rooms/.*/relations/{event_spec}/{rel_type}$"
4686 )));
4687 }
4688 Some(IncludeRelations::RelationsOfTypeAndEventType(rel_type, event_type)) => {
4689 self.mock = self.mock.and(path_regex(format!(
4690 r"^/_matrix/client/v1/rooms/.*/relations/{event_spec}/{rel_type}/{event_type}$"
4691 )));
4692 }
4693 _ => {
4694 self.mock = self.mock.and(path_regex(format!(
4695 r"^/_matrix/client/v1/rooms/.*/relations/{event_spec}",
4696 )));
4697 }
4698 }
4699
4700 self.ok_json(json!({
4701 "chunk": response.chunk,
4702 "next_batch": response.next_batch,
4703 "prev_batch": response.prev_batch,
4704 "recursion_depth": response.recursion_depth,
4705 }))
4706 }
4707}
4708
4709/// Helper function to set up a [`MockBuilder`] so it intercepts the account
4710/// data URLs.
4711fn global_account_data_mock_builder(
4712 builder: MockBuilder,
4713 user_id: &UserId,
4714 event_type: GlobalAccountDataEventType,
4715) -> MockBuilder {
4716 builder
4717 .and(path_regex(format!(r"^/_matrix/client/v3/user/{user_id}/account_data/{event_type}",)))
4718}
4719
4720/// A prebuilt mock for a
4721/// `GET /_matrix/client/v3/user/{userId}/account_data/io.element.recent_emoji`
4722/// request, which fetches the recently used emojis in the account data.
4723#[cfg(feature = "experimental-element-recent-emojis")]
4724pub struct GetRecentEmojisEndpoint;
4725
4726#[cfg(feature = "experimental-element-recent-emojis")]
4727impl<'a> MockEndpoint<'a, GetRecentEmojisEndpoint> {
4728 /// Returns a mock for a successful fetch of the recently used emojis in the
4729 /// account data.
4730 pub fn ok(mut self, user_id: &UserId, emojis: Vec<(String, UInt)>) -> MatrixMock<'a> {
4731 self.mock =
4732 global_account_data_mock_builder(self.mock, user_id, "io.element.recent_emoji".into());
4733 self.ok_json(json!({ "recent_emoji": emojis }))
4734 }
4735}
4736
4737/// A prebuilt mock for a
4738/// `PUT /_matrix/client/v3/user/{userId}/account_data/io.element.recent_emoji`
4739/// request, which updates the recently used emojis in the account data.
4740#[cfg(feature = "experimental-element-recent-emojis")]
4741pub struct UpdateRecentEmojisEndpoint {
4742 pub(crate) request_body: Option<Vec<(String, UInt)>>,
4743}
4744
4745#[cfg(feature = "experimental-element-recent-emojis")]
4746impl UpdateRecentEmojisEndpoint {
4747 /// Creates a new instance of the recent update recent emojis mock endpoint.
4748 fn new() -> Self {
4749 Self { request_body: None }
4750 }
4751}
4752
4753#[cfg(feature = "experimental-element-recent-emojis")]
4754impl<'a> MockEndpoint<'a, UpdateRecentEmojisEndpoint> {
4755 /// Returns a mock that will check the body of the request, making sure its
4756 /// contents match the provided list of emojis.
4757 pub fn match_emojis_in_request_body(self, emojis: Vec<(String, UInt)>) -> Self {
4758 Self::new(
4759 self.server,
4760 self.mock.and(body_json(json!(RecentEmojisContent::new(emojis)))),
4761 self.endpoint,
4762 )
4763 }
4764
4765 /// Returns a mock for a successful update of the recent emojis account data
4766 /// event. The request body contents should match the provided emoji list.
4767 #[cfg(feature = "experimental-element-recent-emojis")]
4768 pub fn ok(mut self, user_id: &UserId) -> MatrixMock<'a> {
4769 self.mock =
4770 global_account_data_mock_builder(self.mock, user_id, "io.element.recent_emoji".into());
4771 self.respond_with(ResponseTemplate::new(200).set_body_json(()))
4772 }
4773}
4774
4775/// A prebuilt mock for a
4776/// `GET /_matrix/client/v3/user/{userId}/account_data/m.secret_storage.
4777/// default_key` request, which fetches the ID of the default secret storage
4778/// key.
4779#[cfg(feature = "e2e-encryption")]
4780pub struct GetDefaultSecretStorageKeyEndpoint;
4781
4782#[cfg(feature = "e2e-encryption")]
4783impl<'a> MockEndpoint<'a, GetDefaultSecretStorageKeyEndpoint> {
4784 /// Returns a mock for a successful fetch of the default secret storage key.
4785 pub fn ok(mut self, user_id: &UserId, key_id: &str) -> MatrixMock<'a> {
4786 self.mock = global_account_data_mock_builder(
4787 self.mock,
4788 user_id,
4789 GlobalAccountDataEventType::SecretStorageDefaultKey,
4790 );
4791 self.ok_json(json!({
4792 "key": key_id
4793 }))
4794 }
4795}
4796
4797/// A prebuilt mock for a
4798/// `GET /_matrix/client/v3/user/{userId}/account_data/m.secret_storage.key.
4799/// {keyId}` request, which fetches information about a secret storage key.
4800#[cfg(feature = "e2e-encryption")]
4801pub struct GetSecretStorageKeyEndpoint;
4802
4803#[cfg(feature = "e2e-encryption")]
4804impl<'a> MockEndpoint<'a, GetSecretStorageKeyEndpoint> {
4805 /// Returns a mock for a successful fetch of the secret storage key
4806 pub fn ok(
4807 mut self,
4808 user_id: &UserId,
4809 secret_storage_key_event_content: &ruma::events::secret_storage::key::SecretStorageKeyEventContent,
4810 ) -> MatrixMock<'a> {
4811 self.mock = global_account_data_mock_builder(
4812 self.mock,
4813 user_id,
4814 GlobalAccountDataEventType::SecretStorageKey(
4815 secret_storage_key_event_content.key_id.clone(),
4816 ),
4817 );
4818 self.ok_json(secret_storage_key_event_content)
4819 }
4820}
4821
4822/// A prebuilt mock for a
4823/// `GET /_matrix/client/v3/user/{userId}/account_data/m.cross_signing.master`
4824/// request, which fetches information about the master signing key.
4825#[cfg(feature = "e2e-encryption")]
4826pub struct GetMasterSigningKeyEndpoint;
4827
4828#[cfg(feature = "e2e-encryption")]
4829impl<'a> MockEndpoint<'a, GetMasterSigningKeyEndpoint> {
4830 /// Returns a mock for a successful fetch of the master signing key
4831 pub fn ok<B: Serialize>(mut self, user_id: &UserId, key_json: B) -> MatrixMock<'a> {
4832 self.mock = global_account_data_mock_builder(
4833 self.mock,
4834 user_id,
4835 GlobalAccountDataEventType::from("m.cross_signing.master".to_owned()),
4836 );
4837 self.ok_json(key_json)
4838 }
4839}
4840
4841/// A response to a [`RoomRelationsEndpoint`] query.
4842#[derive(Default)]
4843pub struct RoomRelationsResponseTemplate {
4844 /// The set of timeline events returned by this query.
4845 pub chunk: Vec<Raw<AnyTimelineEvent>>,
4846
4847 /// An opaque string representing a pagination token, which semantics depend
4848 /// on the direction used in the request.
4849 pub next_batch: Option<String>,
4850
4851 /// An opaque string representing a pagination token, which semantics depend
4852 /// on the direction used in the request.
4853 pub prev_batch: Option<String>,
4854
4855 /// If `recurse` was set on the request, the depth to which the server
4856 /// recursed.
4857 ///
4858 /// If `recurse` was not set, this field must be absent.
4859 pub recursion_depth: Option<u32>,
4860}
4861
4862impl RoomRelationsResponseTemplate {
4863 /// Fill the events returned as part of this response.
4864 pub fn events(mut self, chunk: Vec<impl Into<Raw<AnyTimelineEvent>>>) -> Self {
4865 self.chunk = chunk.into_iter().map(Into::into).collect();
4866 self
4867 }
4868
4869 /// Fill the `next_batch` token returned as part of this response.
4870 pub fn next_batch(mut self, token: impl Into<String>) -> Self {
4871 self.next_batch = Some(token.into());
4872 self
4873 }
4874
4875 /// Fill the `prev_batch` token returned as part of this response.
4876 pub fn prev_batch(mut self, token: impl Into<String>) -> Self {
4877 self.prev_batch = Some(token.into());
4878 self
4879 }
4880
4881 /// Fill the recursion depth returned in this response.
4882 pub fn recursion_depth(mut self, depth: u32) -> Self {
4883 self.recursion_depth = Some(depth);
4884 self
4885 }
4886}
4887
4888/// A prebuilt mock for `POST /rooms/{roomId}/receipt/{receiptType}/{eventId}`
4889/// request.
4890pub struct ReceiptEndpoint;
4891
4892impl<'a> MockEndpoint<'a, ReceiptEndpoint> {
4893 /// Returns a successful empty response.
4894 pub fn ok(self) -> MatrixMock<'a> {
4895 self.ok_empty_json()
4896 }
4897
4898 /// Ensures that the request matches a specific receipt thread.
4899 pub fn match_thread(self, thread: ReceiptThread) -> Self {
4900 if let Some(thread_str) = thread.as_str() {
4901 self.body_matches_partial_json(json!({
4902 "thread_id": thread_str
4903 }))
4904 } else {
4905 self
4906 }
4907 }
4908
4909 /// Ensures that the request matches a specific event id.
4910 pub fn match_event_id(self, event_id: &EventId) -> Self {
4911 Self {
4912 mock: self.mock.and(path_regex(format!(
4913 r"^/_matrix/client/v3/rooms/.*/receipt/.*/{}$",
4914 event_id.as_str().replace("$", "\\$")
4915 ))),
4916 ..self
4917 }
4918 }
4919}
4920
4921/// A prebuilt mock for `POST /rooms/{roomId}/read_markers` request.
4922pub struct ReadMarkersEndpoint;
4923
4924impl<'a> MockEndpoint<'a, ReadMarkersEndpoint> {
4925 /// Returns a successful empty response.
4926 pub fn ok(self) -> MatrixMock<'a> {
4927 self.ok_empty_json()
4928 }
4929}
4930
4931/// A prebuilt mock for `PUT /user/{userId}/rooms/{roomId}/account_data/{type}`
4932/// request.
4933pub struct RoomAccountDataEndpoint;
4934
4935impl<'a> MockEndpoint<'a, RoomAccountDataEndpoint> {
4936 /// Returns a successful empty response.
4937 pub fn ok(self) -> MatrixMock<'a> {
4938 self.ok_empty_json()
4939 }
4940}
4941
4942/// A prebuilt mock for `GET /_matrix/client/v1/media/config` request.
4943pub struct AuthenticatedMediaConfigEndpoint;
4944
4945impl<'a> MockEndpoint<'a, AuthenticatedMediaConfigEndpoint> {
4946 /// Returns a successful response with the provided max upload size.
4947 pub fn ok(self, max_upload_size: UInt) -> MatrixMock<'a> {
4948 self.ok_json(json!({
4949 "m.upload.size": max_upload_size,
4950 }))
4951 }
4952
4953 /// Returns a successful response with a maxed out max upload size.
4954 pub fn ok_default(self) -> MatrixMock<'a> {
4955 self.ok_json(json!({
4956 "m.upload.size": UInt::MAX,
4957 }))
4958 }
4959}
4960
4961/// A prebuilt mock for `GET /_matrix/media/v3/config` request.
4962pub struct MediaConfigEndpoint;
4963
4964impl<'a> MockEndpoint<'a, MediaConfigEndpoint> {
4965 /// Returns a successful response with the provided max upload size.
4966 pub fn ok(self, max_upload_size: UInt) -> MatrixMock<'a> {
4967 self.ok_json(json!({
4968 "m.upload.size": max_upload_size,
4969 }))
4970 }
4971}
4972
4973/// A prebuilt mock for the `GET /_matrix/client/v3/login` endpoint.
4974pub struct GetLoginTypesEndpoint;
4975
4976impl<'a> MockEndpoint<'a, GetLoginTypesEndpoint> {
4977 /// Returns a successful response supporting password and SSO login.
4978 pub fn ok(self) -> MatrixMock<'a> {
4979 self.ok_json(json!({
4980 "flows": [
4981 { "type": "m.login.password" },
4982 { "type": "m.login.sso" },
4983 { "type": "m.login.token" },
4984 ],
4985 }))
4986 }
4987}
4988
4989/// A prebuilt mock for `POST /login` requests.
4990pub struct LoginEndpoint;
4991
4992impl<'a> MockEndpoint<'a, LoginEndpoint> {
4993 /// Returns a successful response.
4994 pub fn ok(self) -> MatrixMock<'a> {
4995 self.ok_with(LoginResponseTemplate200::with_default_fields())
4996 }
4997
4998 /// Returns a given response on POST /login requests
4999 ///
5000 /// # Arguments
5001 ///
5002 /// - `response` - The response that the mock server sends on POST /login
5003 /// requests.
5004 ///
5005 /// # Returns
5006 ///
5007 /// Returns a [`MatrixMock`] which can be mounted.
5008 ///
5009 /// # Examples
5010 ///
5011 /// ```
5012 /// use matrix_sdk::test_utils::mocks::{
5013 /// LoginResponseTemplate200, MatrixMockServer,
5014 /// };
5015 /// use matrix_sdk_test::async_test;
5016 /// use ruma::{device_id, time::Duration, user_id};
5017 ///
5018 /// #[async_test]
5019 /// async fn test_ok_with() {
5020 /// let server = MatrixMockServer::new().await;
5021 /// server
5022 /// .mock_login()
5023 /// .ok_with(LoginResponseTemplate200::new(
5024 /// "qwerty",
5025 /// device_id!("DEADBEEF"),
5026 /// user_id!("@cheeky_monkey:matrix.org"),
5027 /// ))
5028 /// .mount()
5029 /// .await;
5030 ///
5031 /// let client = server.client_builder().unlogged().build().await;
5032 ///
5033 /// let result = client
5034 /// .matrix_auth()
5035 /// .login_username("example", "wordpass")
5036 /// .send()
5037 /// .await
5038 /// .unwrap();
5039 ///
5040 /// assert!(
5041 /// result.access_tokesn.unwrap() == "qwerty",
5042 /// "wrong access token in response"
5043 /// );
5044 /// assert!(
5045 /// result.device_id.unwrap() == "DEADBEEF",
5046 /// "wrong device id in response"
5047 /// );
5048 /// assert!(
5049 /// result.user_id.unwrap() == "@cheeky_monkey:matrix.org",
5050 /// "wrong user id in response"
5051 /// );
5052 /// }
5053 /// ```
5054 pub fn ok_with(self, response: LoginResponseTemplate200) -> MatrixMock<'a> {
5055 self.ok_json(response)
5056 }
5057
5058 /// Returns a `M_FORBIDDEN` error response.
5059 pub fn error_forbidden(self) -> MatrixMock<'a> {
5060 self.respond_with_code_and_json(
5061 403,
5062 json!({
5063 "errcode": "M_FORBIDDEN",
5064 "error": "Invalid password",
5065 }),
5066 )
5067 }
5068}
5069
5070/// A response to a [`LoginEndpoint`] query with status code 200.
5071#[derive(Default, Serialize)]
5072pub struct LoginResponseTemplate200 {
5073 /// Required: An access token for the account. This access token can then be
5074 /// used to authorize other requests.
5075 #[serde(skip_serializing_if = "Option::is_none")]
5076 access_token: Option<String>,
5077
5078 /// Required: ID of the logged-in device. Will be the same as the
5079 /// corresponding parameter in the request, if one was specified.
5080 #[serde(skip_serializing_if = "Option::is_none")]
5081 device_id: Option<OwnedDeviceId>,
5082
5083 /// The lifetime of the access token, in milliseconds. Once the access token
5084 /// has expired a new access token can be obtained by using the provided
5085 /// refresh token. If no refresh token is provided, the client will need to
5086 /// re-log in to obtain a new access token. If not given, the client can
5087 /// assume that the access token will not expire.
5088 #[serde(
5089 rename = "expires_in_ms",
5090 with = "ruma::serde::duration::opt_ms",
5091 skip_serializing_if = "Option::is_none"
5092 )]
5093 expires_in: Option<Duration>,
5094
5095 /// A refresh token for the account. This token can be used to obtain a new
5096 /// access token when it expires by calling the /refresh endpoint.
5097 #[serde(skip_serializing_if = "Option::is_none")]
5098 refresh_token: Option<String>,
5099
5100 /// Required: The fully-qualified Matrix ID for the account.
5101 #[serde(skip_serializing_if = "Option::is_none")]
5102 user_id: Option<OwnedUserId>,
5103
5104 /// Optional client configuration provided by the server.
5105 #[serde(skip_serializing_if = "Option::is_none")]
5106 well_known: Option<DiscoveryInfo>,
5107}
5108
5109impl LoginResponseTemplate200 {
5110 /// Constructor for a response with the given minimal expected fields.
5111 pub fn new(
5112 access_token: impl Into<String>,
5113 device_id: impl Into<OwnedDeviceId>,
5114 user_id: impl Into<OwnedUserId>,
5115 ) -> Self {
5116 Self {
5117 access_token: Some(access_token.into()),
5118 device_id: Some(device_id.into()),
5119 user_id: Some(user_id.into()),
5120 ..Default::default()
5121 }
5122 }
5123
5124 /// Constructor for a response with default values for the minimal expected
5125 /// fields.
5126 pub fn with_default_fields() -> Self {
5127 Self {
5128 access_token: Some(TestAuthToken::AccessDefault.into()),
5129 device_id: Some(TestDevice::Default.into()),
5130 user_id: Some(User::Default.into()),
5131 ..Default::default()
5132 }
5133 }
5134
5135 /// sets expires_in
5136 pub fn expires_in(mut self, value: Duration) -> Self {
5137 self.expires_in = Some(value);
5138 self
5139 }
5140
5141 /// sets refresh_token
5142 pub fn refresh_token(mut self, value: impl Into<String>) -> Self {
5143 self.refresh_token = Some(value.into());
5144 self
5145 }
5146
5147 /// sets well_known which takes a homeserver_url and an optional
5148 /// identity_url
5149 pub fn well_known(mut self, homeserver_url: String, identity_url: Option<String>) -> Self {
5150 let mut well_known = DiscoveryInfo::new(HomeserverInfo::new(homeserver_url));
5151 well_known.identity_server = identity_url.map(IdentityServerInfo::new);
5152 self.well_known = Some(well_known);
5153 self
5154 }
5155}
5156
5157/// A prebuilt mock for the `POST /_matrix/client/v3/register` endpoint.
5158pub struct RegisterEndpoint;
5159
5160impl<'a> MockEndpoint<'a, RegisterEndpoint> {
5161 /// Returns a successful default response.
5162 pub fn ok(self) -> MatrixMock<'a> {
5163 self.ok_json(json!({
5164 "access_token": TestAuthToken::AccessDefault,
5165 "device_id": TestDevice::Default,
5166 "user_id": User::Default,
5167 }))
5168 }
5169
5170 /// Returns a successful default response including a refresh token.
5171 pub fn ok_with_refresh_token(self) -> MatrixMock<'a> {
5172 self.ok_json(json!({
5173 "access_token": TestAuthToken::AccessDefault,
5174 "device_id": TestDevice::Default,
5175 "user_id": User::Default,
5176 "refresh_token": TestAuthToken::RefreshDefault,
5177 }))
5178 }
5179
5180 /// Returns a `M_FORBIDDEN` error response.
5181 pub fn error_forbidden(self) -> MatrixMock<'a> {
5182 self.respond_with_code_and_json(
5183 403,
5184 json!({
5185 "errcode": "M_FORBIDDEN",
5186 "error": "Invalid password",
5187 }),
5188 )
5189 }
5190}
5191
5192/// A prebuilt mock for the `POST /_matrix/client/v3/refresh` endpoint.
5193pub struct RefreshEndpoint;
5194
5195impl<'a> MockEndpoint<'a, RefreshEndpoint> {
5196 /// Returns a successful default response.
5197 pub fn ok(self) -> MatrixMock<'a> {
5198 self.ok_with_both_tokens(TestAuthToken::AccessAlt1, TestAuthToken::RefreshAlt1)
5199 }
5200
5201 /// Returns a successful default response including both an access token and
5202 /// a refresh token.
5203 pub fn ok_with_both_tokens<'b, 'c>(
5204 self,
5205 access_token: impl Into<&'b str>,
5206 refresh_token: impl Into<&'c str>,
5207 ) -> MatrixMock<'a> {
5208 self.ok_json(json!({
5209 "access_token": access_token.into(),
5210 "refresh_token": refresh_token.into(),
5211 "expires_in_ms": 432_000_000,
5212 }))
5213 }
5214
5215 /// Returns a successful default response including only an access token.
5216 pub fn ok_with_access_token<'b>(self, access_token: impl Into<&'b str>) -> MatrixMock<'a> {
5217 self.ok_json(json!({
5218 "access_token": access_token.into(),
5219 "expires_in_ms": 432_000_000,
5220 }))
5221 }
5222}
5223
5224/// A prebuilt mock for `GET /devices` requests.
5225pub struct DevicesEndpoint;
5226
5227impl<'a> MockEndpoint<'a, DevicesEndpoint> {
5228 /// Returns a successful response.
5229 pub fn ok(self) -> MatrixMock<'a> {
5230 self.ok_json(json!({
5231 "devices": [
5232 {
5233 "device_id": "BNYQQWUMXO",
5234 "display_name": "Client 1",
5235 "last_seen_ip": "-",
5236 "last_seen_ts": 1596117733037u64,
5237 "user_id": "@example:localhost"
5238 },
5239 {
5240 "device_id": "LEBKSEUSNR",
5241 "display_name": "Client 2",
5242 "last_seen_ip": "-",
5243 "last_seen_ts": 1599057006985u64,
5244 "user_id": "@example:localhost"
5245 }
5246 ]
5247 }))
5248 }
5249}
5250
5251/// A prebuilt mock for `GET /devices/{deviceId}` requests.
5252pub struct GetDeviceEndpoint;
5253
5254impl<'a> MockEndpoint<'a, GetDeviceEndpoint> {
5255 /// Returns a successful response.
5256 pub fn ok(self) -> MatrixMock<'a> {
5257 self.ok_json(json!({
5258 "device_id": "QBUAZIFURK",
5259 "display_name": "android",
5260 "last_seen_ip": "1.2.3.4",
5261 "last_seen_ts": 1474491775024u64
5262 }))
5263 }
5264}
5265
5266/// A prebuilt mock for the `POST /_matrix/client/v3/delete_devices` endpoint.
5267pub struct DeleteDevicesEndpoint;
5268
5269impl<'a> MockEndpoint<'a, DeleteDevicesEndpoint> {
5270 /// Returns a successful empty response.
5271 pub fn ok(self) -> MatrixMock<'a> {
5272 self.ok_empty_json()
5273 }
5274}
5275
5276/// A prebuilt mock for `POST /user_directory/search` requests.
5277pub struct UserDirectoryEndpoint;
5278
5279impl<'a> MockEndpoint<'a, UserDirectoryEndpoint> {
5280 /// Returns a successful response.
5281 pub fn ok(self) -> MatrixMock<'a> {
5282 self.ok_json(json!({
5283 "limited": false,
5284 "results": [
5285 {
5286 "user_id": "@test:example.me",
5287 "display_name": "Test",
5288 "avatar_url": "mxc://example.me/someid"
5289 }
5290 ]
5291 }))
5292 }
5293}
5294
5295/// A prebuilt mock for `POST /createRoom` requests.
5296pub struct CreateRoomEndpoint;
5297
5298impl<'a> MockEndpoint<'a, CreateRoomEndpoint> {
5299 /// Returns a successful response.
5300 pub fn ok(self) -> MatrixMock<'a> {
5301 self.ok_json(json!({ "room_id": "!room:example.org"}))
5302 }
5303}
5304
5305/// A prebuilt mock for `POST /rooms/{roomId}/upgrade` requests.
5306pub struct UpgradeRoomEndpoint;
5307
5308impl<'a> MockEndpoint<'a, UpgradeRoomEndpoint> {
5309 /// Returns a successful response with desired replacement_room ID.
5310 pub fn ok_with<'b>(self, new_room_id: impl Into<&'b RoomId>) -> MatrixMock<'a> {
5311 self.ok_json(json!({ "replacement_room": new_room_id.into() }))
5312 }
5313}
5314
5315/// A prebuilt mock for `POST /media/v1/create` requests.
5316pub struct MediaAllocateEndpoint;
5317
5318impl<'a> MockEndpoint<'a, MediaAllocateEndpoint> {
5319 /// Returns a successful response.
5320 pub fn ok(self) -> MatrixMock<'a> {
5321 self.ok_json(json!({
5322 "content_uri": "mxc://example.com/AQwafuaFswefuhsfAFAgsw"
5323 }))
5324 }
5325}
5326
5327/// A prebuilt mock for `PUT /media/v3/upload/{server_name}/{media_id}`
5328/// requests.
5329pub struct MediaAllocatedUploadEndpoint;
5330
5331impl<'a> MockEndpoint<'a, MediaAllocatedUploadEndpoint> {
5332 /// Returns a successful response.
5333 pub fn ok(self) -> MatrixMock<'a> {
5334 self.ok_empty_json()
5335 }
5336}
5337
5338/// A prebuilt mock for `GET /media/v3/download` requests.
5339pub struct MediaDownloadEndpoint;
5340
5341impl<'a> MockEndpoint<'a, MediaDownloadEndpoint> {
5342 /// Returns a successful response with a plain text content.
5343 pub fn ok_plain_text(self) -> MatrixMock<'a> {
5344 self.respond_with(ResponseTemplate::new(200).set_body_string("Hello, World!"))
5345 }
5346
5347 /// Returns a successful response with a fake image content.
5348 pub fn ok_image(self) -> MatrixMock<'a> {
5349 self.respond_with(
5350 ResponseTemplate::new(200).set_body_raw(b"binaryjpegfullimagedata", "image/jpeg"),
5351 )
5352 }
5353}
5354
5355/// A prebuilt mock for `GET /media/v3/thumbnail` requests.
5356pub struct MediaThumbnailEndpoint;
5357
5358impl<'a> MockEndpoint<'a, MediaThumbnailEndpoint> {
5359 /// Returns a successful response with a fake image content.
5360 pub fn ok(self) -> MatrixMock<'a> {
5361 self.respond_with(
5362 ResponseTemplate::new(200).set_body_raw(b"binaryjpegthumbnaildata", "image/jpeg"),
5363 )
5364 }
5365}
5366
5367/// A prebuilt mock for `GET /media/v3/preview_url` requests.
5368pub struct MediaPreviewEndpoint;
5369
5370impl<'a> MockEndpoint<'a, MediaPreviewEndpoint> {
5371 /// Returns a successful response with OpenGraph-like data for the URL.
5372 pub fn ok(self) -> MatrixMock<'a> {
5373 self.ok_json(json!({
5374 "og:title": "Matrix Blog Post",
5375 "og:description": "This is a really cool blog post from matrix.org",
5376 "og:image": "mxc://example.com/ascERGshawAWawugaAcauga",
5377 "og:image:type": "image/png",
5378 "og:image:height": 48,
5379 "og:image:width": 48,
5380 "matrix:image:size": 102_400,
5381 }))
5382 }
5383
5384 /// Returns a successful but empty response.
5385 ///
5386 /// Homeservers legitimately return an empty object when they could not
5387 /// extract any metadata from the URL.
5388 pub fn ok_empty(self) -> MatrixMock<'a> {
5389 self.ok_empty_json()
5390 }
5391}
5392
5393/// A prebuilt mock for `GET /client/v1/media/preview_url` requests.
5394pub struct AuthedMediaPreviewEndpoint;
5395
5396impl<'a> MockEndpoint<'a, AuthedMediaPreviewEndpoint> {
5397 /// Returns a successful response with OpenGraph-like data for the URL.
5398 pub fn ok(self) -> MatrixMock<'a> {
5399 self.ok_json(json!({
5400 "og:title": "Matrix Blog Post",
5401 "og:description": "This is a really cool blog post from matrix.org",
5402 "og:image": "mxc://example.com/ascERGshawAWawugaAcauga",
5403 "og:image:type": "image/png",
5404 "og:image:height": 48,
5405 "og:image:width": 48,
5406 "matrix:image:size": 102_400,
5407 }))
5408 }
5409
5410 /// Returns a successful but empty response.
5411 ///
5412 /// Homeservers legitimately return an empty object when they could not
5413 /// extract any metadata from the URL.
5414 pub fn ok_empty(self) -> MatrixMock<'a> {
5415 self.ok_empty_json()
5416 }
5417}
5418
5419/// A prebuilt mock for `GET /client/v1/media/download` requests.
5420pub struct AuthedMediaDownloadEndpoint;
5421
5422impl<'a> MockEndpoint<'a, AuthedMediaDownloadEndpoint> {
5423 /// Returns a successful response with a plain text content.
5424 pub fn ok_plain_text(self) -> MatrixMock<'a> {
5425 self.respond_with(ResponseTemplate::new(200).set_body_string("Hello, World!"))
5426 }
5427
5428 /// Returns a successful response with the given bytes.
5429 pub fn ok_bytes(self, bytes: Vec<u8>) -> MatrixMock<'a> {
5430 self.respond_with(
5431 ResponseTemplate::new(200).set_body_raw(bytes, "application/octet-stream"),
5432 )
5433 }
5434
5435 /// Returns a successful response with a fake image content.
5436 pub fn ok_image(self) -> MatrixMock<'a> {
5437 self.respond_with(
5438 ResponseTemplate::new(200).set_body_raw(b"binaryjpegfullimagedata", "image/jpeg"),
5439 )
5440 }
5441}
5442
5443/// A prebuilt mock for `GET /client/v1/media/thumbnail` requests.
5444pub struct AuthedMediaThumbnailEndpoint;
5445
5446impl<'a> MockEndpoint<'a, AuthedMediaThumbnailEndpoint> {
5447 /// Returns a successful response with a fake image content.
5448 pub fn ok(self) -> MatrixMock<'a> {
5449 self.respond_with(
5450 ResponseTemplate::new(200).set_body_raw(b"binaryjpegthumbnaildata", "image/jpeg"),
5451 )
5452 }
5453}
5454
5455/// A prebuilt mock for `GET /client/v3/rooms/{room_id}/join` requests.
5456pub struct JoinRoomEndpoint {
5457 room_id: OwnedRoomId,
5458}
5459
5460impl<'a> MockEndpoint<'a, JoinRoomEndpoint> {
5461 /// Returns a successful response using the provided [`RoomId`].
5462 pub fn ok(self) -> MatrixMock<'a> {
5463 let room_id = self.endpoint.room_id.to_owned();
5464
5465 self.ok_json(json!({
5466 "room_id": room_id,
5467 }))
5468 }
5469}
5470
5471/// A prebuilt mock for `POST /_matrix/client/v3/join/{roomIdOrAlias}` requests.
5472pub struct JoinRoomByIdOrAliasEndpoint;
5473
5474impl<'a> MockEndpoint<'a, JoinRoomByIdOrAliasEndpoint> {
5475 /// Returns a successful response using the given [`RoomId`].
5476 pub fn ok<'b>(self, room_id: impl Into<&'b RoomId>) -> MatrixMock<'a> {
5477 self.ok_json(json!({
5478 "room_id": room_id.into(),
5479 }))
5480 }
5481}
5482
5483/// A prebuilt mock for `POST /_matrix/client/v3/knock/{roomIdOrAlias}`
5484/// requests.
5485pub struct RoomKnockEndpoint;
5486
5487impl<'a> MockEndpoint<'a, RoomKnockEndpoint> {
5488 /// Returns a successful response using the given [`RoomId`].
5489 pub fn ok<'b>(self, room_id: impl Into<&'b RoomId>) -> MatrixMock<'a> {
5490 self.ok_json(json!({
5491 "room_id": room_id.into(),
5492 }))
5493 }
5494}
5495
5496#[derive(Default)]
5497struct ThreadSubscriptionMatchers {
5498 /// Optional room id to match in the query.
5499 room_id: Option<OwnedRoomId>,
5500 /// Optional thread root event id to match in the query.
5501 thread_root: Option<OwnedEventId>,
5502}
5503
5504impl ThreadSubscriptionMatchers {
5505 /// Match the request parameter against a specific room id.
5506 fn match_room_id(mut self, room_id: OwnedRoomId) -> Self {
5507 self.room_id = Some(room_id);
5508 self
5509 }
5510
5511 /// Match the request parameter against a specific thread root event id.
5512 fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self {
5513 self.thread_root = Some(thread_root);
5514 self
5515 }
5516
5517 /// Compute the final URI for the thread subscription endpoint.
5518 fn endpoint_regexp_uri(&self) -> String {
5519 if self.room_id.is_some() || self.thread_root.is_some() {
5520 format!(
5521 "^/_matrix/client/unstable/io.element.msc4306/rooms/{}/thread/{}/subscription$",
5522 self.room_id.as_deref().map(|s| s.as_str()).unwrap_or(".*"),
5523 self.thread_root.as_deref().map(|s| s.as_str()).unwrap_or(".*").replace("$", "\\$")
5524 )
5525 } else {
5526 "^/_matrix/client/unstable/io.element.msc4306/rooms/.*/thread/.*/subscription$"
5527 .to_owned()
5528 }
5529 }
5530}
5531
5532/// A prebuilt mock for
5533/// `GET /client/*/rooms/{room_id}/threads/{thread_root}/subscription`
5534#[derive(Default)]
5535pub struct RoomGetThreadSubscriptionEndpoint {
5536 matchers: ThreadSubscriptionMatchers,
5537}
5538
5539impl<'a> MockEndpoint<'a, RoomGetThreadSubscriptionEndpoint> {
5540 /// Returns a successful response for the given thread subscription.
5541 pub fn ok(mut self, automatic: bool) -> MatrixMock<'a> {
5542 self.mock = self.mock.and(path_regex(self.endpoint.matchers.endpoint_regexp_uri()));
5543 self.ok_json(json!({
5544 "automatic": automatic
5545 }))
5546 }
5547
5548 /// Match the request parameter against a specific room id.
5549 pub fn match_room_id(mut self, room_id: impl Into<OwnedRoomId>) -> Self {
5550 self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id.into());
5551 self
5552 }
5553 /// Match the request parameter against a specific thread root event id.
5554 pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self {
5555 self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root);
5556 self
5557 }
5558}
5559
5560/// A prebuilt mock for
5561/// `PUT /client/*/rooms/{room_id}/threads/{thread_root}/subscription`
5562#[derive(Default)]
5563pub struct RoomPutThreadSubscriptionEndpoint {
5564 matchers: ThreadSubscriptionMatchers,
5565}
5566
5567impl<'a> MockEndpoint<'a, RoomPutThreadSubscriptionEndpoint> {
5568 /// Returns a successful response for the given setting of thread
5569 /// subscription.
5570 pub fn ok(mut self) -> MatrixMock<'a> {
5571 self.mock = self.mock.and(path_regex(self.endpoint.matchers.endpoint_regexp_uri()));
5572 self.respond_with(ResponseTemplate::new(200))
5573 }
5574
5575 /// Returns that the server skipped an automated thread subscription,
5576 /// because the user unsubscribed to the thread after the event id passed in
5577 /// the automatic subscription.
5578 pub fn conflicting_unsubscription(mut self) -> MatrixMock<'a> {
5579 self.mock = self.mock.and(path_regex(self.endpoint.matchers.endpoint_regexp_uri()));
5580 self.respond_with_code_and_json(
5581 409,
5582 json!({
5583 "errcode": "IO.ELEMENT.MSC4306.M_CONFLICTING_UNSUBSCRIPTION",
5584 "error": "the user unsubscribed after the subscription event id"
5585 }),
5586 )
5587 }
5588
5589 /// Match the request parameter against a specific room id.
5590 pub fn match_room_id(mut self, room_id: impl Into<OwnedRoomId>) -> Self {
5591 self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id.into());
5592 self
5593 }
5594 /// Match the request parameter against a specific thread root event id.
5595 pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self {
5596 self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root);
5597 self
5598 }
5599 /// Match the request body's `automatic` field against a specific event id.
5600 pub fn match_automatic_event_id(mut self, up_to_event_id: &EventId) -> Self {
5601 self.mock = self.mock.and(body_json(json!({
5602 "automatic": up_to_event_id
5603 })));
5604 self
5605 }
5606}
5607
5608/// A prebuilt mock for
5609/// `DELETE /client/*/rooms/{room_id}/threads/{thread_root}/subscription`
5610#[derive(Default)]
5611pub struct RoomDeleteThreadSubscriptionEndpoint {
5612 matchers: ThreadSubscriptionMatchers,
5613}
5614
5615impl<'a> MockEndpoint<'a, RoomDeleteThreadSubscriptionEndpoint> {
5616 /// Returns a successful response for the deletion of a given thread
5617 /// subscription.
5618 pub fn ok(mut self) -> MatrixMock<'a> {
5619 self.mock = self.mock.and(path_regex(self.endpoint.matchers.endpoint_regexp_uri()));
5620 self.respond_with(ResponseTemplate::new(200))
5621 }
5622
5623 /// Match the request parameter against a specific room id.
5624 pub fn match_room_id(mut self, room_id: impl Into<OwnedRoomId>) -> Self {
5625 self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id.into());
5626 self
5627 }
5628 /// Match the request parameter against a specific thread root event id.
5629 pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self {
5630 self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root);
5631 self
5632 }
5633}
5634
5635/// A prebuilt mock for
5636/// `PUT /_matrix/client/v3/pushrules/global/{kind}/{ruleId}/enabled`.
5637pub struct EnablePushRuleEndpoint;
5638
5639impl<'a> MockEndpoint<'a, EnablePushRuleEndpoint> {
5640 /// Returns a successful empty JSON response.
5641 pub fn ok(self) -> MatrixMock<'a> {
5642 self.ok_empty_json()
5643 }
5644}
5645
5646/// A prebuilt mock for
5647/// `PUT /_matrix/client/v3/pushrules/global/{kind}/{ruleId}/actions`.
5648pub struct SetPushRulesActionsEndpoint;
5649
5650impl<'a> MockEndpoint<'a, SetPushRulesActionsEndpoint> {
5651 /// Returns a successful empty JSON response.
5652 pub fn ok(self) -> MatrixMock<'a> {
5653 self.ok_empty_json()
5654 }
5655}
5656
5657/// A prebuilt mock for
5658/// `PUT /_matrix/client/v3/pushrules/global/{kind}/{ruleId}`.
5659pub struct SetPushRulesEndpoint;
5660
5661impl<'a> MockEndpoint<'a, SetPushRulesEndpoint> {
5662 /// Returns a successful empty JSON response.
5663 pub fn ok(self) -> MatrixMock<'a> {
5664 self.ok_empty_json()
5665 }
5666}
5667
5668/// A prebuilt mock for
5669/// `DELETE /_matrix/client/v3/pushrules/global/{kind}/{ruleId}`.
5670pub struct DeletePushRulesEndpoint;
5671
5672impl<'a> MockEndpoint<'a, DeletePushRulesEndpoint> {
5673 /// Returns a successful empty JSON response.
5674 pub fn ok(self) -> MatrixMock<'a> {
5675 self.ok_empty_json()
5676 }
5677}
5678
5679/// A prebuilt mock for the federation version endpoint.
5680pub struct FederationVersionEndpoint;
5681
5682impl<'a> MockEndpoint<'a, FederationVersionEndpoint> {
5683 /// Returns a successful response with the given server name and version.
5684 pub fn ok(self, server_name: &str, version: &str) -> MatrixMock<'a> {
5685 let response_body = json!({
5686 "server": {
5687 "name": server_name,
5688 "version": version
5689 }
5690 });
5691 self.ok_json(response_body)
5692 }
5693
5694 /// Returns a successful response with empty/missing server information.
5695 pub fn ok_empty(self) -> MatrixMock<'a> {
5696 let response_body = json!({});
5697 self.ok_json(response_body)
5698 }
5699}
5700
5701/// A prebuilt mock for `GET ^/_matrix/client/v3/thread_subscriptions`.
5702#[derive(Default)]
5703pub struct GetThreadSubscriptionsEndpoint {
5704 /// New thread subscriptions per (room id, thread root event id).
5705 subscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadSubscription>>,
5706 /// New thread unsubscriptions per (room id, thread root event id).
5707 unsubscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadUnsubscription>>,
5708}
5709
5710impl<'a> MockEndpoint<'a, GetThreadSubscriptionsEndpoint> {
5711 /// Add a single thread subscription to the response.
5712 pub fn add_subscription(
5713 mut self,
5714 room_id: OwnedRoomId,
5715 thread_root: OwnedEventId,
5716 subscription: ThreadSubscription,
5717 ) -> Self {
5718 self.endpoint.subscribed.entry(room_id).or_default().insert(thread_root, subscription);
5719 self
5720 }
5721
5722 /// Add a single thread unsubscription to the response.
5723 pub fn add_unsubscription(
5724 mut self,
5725 room_id: OwnedRoomId,
5726 thread_root: OwnedEventId,
5727 unsubscription: ThreadUnsubscription,
5728 ) -> Self {
5729 self.endpoint.unsubscribed.entry(room_id).or_default().insert(thread_root, unsubscription);
5730 self
5731 }
5732
5733 /// Match the `from` query parameter to a given value.
5734 pub fn match_from(self, from: &str) -> Self {
5735 Self { mock: self.mock.and(query_param("from", from)), ..self }
5736 }
5737
5738 /// Match the `to` query parameter to a given value.
5739 pub fn match_to(self, to: &str) -> Self {
5740 Self { mock: self.mock.and(query_param("to", to)), ..self }
5741 }
5742
5743 /// Returns a successful response with the given thread subscriptions, and
5744 /// "end" parameter to be used in the next query.
5745 pub fn ok(self, end: Option<String>) -> MatrixMock<'a> {
5746 let response = json!({
5747 "subscribed": self.endpoint.subscribed,
5748 "unsubscribed": self.endpoint.unsubscribed,
5749 "end": end,
5750 });
5751 self.ok_json(response)
5752 }
5753}
5754
5755/// A prebuilt mock for `GET /client/*/rooms/{roomId}/hierarchy`
5756#[derive(Default)]
5757pub struct GetHierarchyEndpoint;
5758
5759impl<'a> MockEndpoint<'a, GetHierarchyEndpoint> {
5760 /// Returns a successful response containing the given room IDs.
5761 pub fn ok_with_room_ids(self, room_ids: Vec<&RoomId>) -> MatrixMock<'a> {
5762 let rooms = room_ids
5763 .iter()
5764 .map(|id| {
5765 json!({
5766 "room_id": id,
5767 "num_joined_members": 1,
5768 "world_readable": false,
5769 "guest_can_join": false,
5770 "children_state": []
5771 })
5772 })
5773 .collect::<Vec<_>>();
5774
5775 self.ok_json(json!({
5776 "rooms": rooms,
5777 }))
5778 }
5779
5780 /// Returns a successful response containing the given room IDs and children
5781 /// states
5782 pub fn ok_with_room_ids_and_children_state(
5783 self,
5784 room_ids: Vec<&RoomId>,
5785 children_state: Vec<(&RoomId, Vec<&ServerName>)>,
5786 ) -> MatrixMock<'a> {
5787 let children_state = children_state
5788 .into_iter()
5789 .map(|(id, via)| {
5790 json!({
5791 "type":
5792 "m.space.child",
5793 "state_key": id,
5794 "content": { "via": via },
5795 "sender": "@bob:matrix.org",
5796 "origin_server_ts": MilliSecondsSinceUnixEpoch::now()
5797 })
5798 })
5799 .collect::<Vec<_>>();
5800
5801 let rooms = room_ids
5802 .iter()
5803 .map(|id| {
5804 json!({
5805 "room_id": id,
5806 "num_joined_members": 1,
5807 "world_readable": false,
5808 "guest_can_join": false,
5809 "children_state": children_state
5810 })
5811 })
5812 .collect::<Vec<_>>();
5813
5814 self.ok_json(json!({
5815 "rooms": rooms,
5816 }))
5817 }
5818
5819 /// Returns a successful response with an empty list of rooms.
5820 pub fn ok(self) -> MatrixMock<'a> {
5821 self.ok_json(json!({
5822 "rooms": []
5823 }))
5824 }
5825}
5826
5827/// A prebuilt mock for
5828/// `PUT /_matrix/client/v3/rooms/{roomId}/state/m.space.child/{stateKey}`
5829pub struct SetSpaceChildEndpoint;
5830
5831impl<'a> MockEndpoint<'a, SetSpaceChildEndpoint> {
5832 /// Returns a successful response with a given event id.
5833 pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> {
5834 self.ok_with_event_id(event_id)
5835 }
5836
5837 /// Returns an error response with a generic error code indicating the
5838 /// client is not authorized to set space children.
5839 pub fn unauthorized(self) -> MatrixMock<'a> {
5840 self.respond_with(ResponseTemplate::new(400))
5841 }
5842}
5843
5844/// A prebuilt mock for
5845/// `PUT /_matrix/client/v3/rooms/{roomId}/state/m.space.parent/{stateKey}`
5846pub struct SetSpaceParentEndpoint;
5847
5848impl<'a> MockEndpoint<'a, SetSpaceParentEndpoint> {
5849 /// Returns a successful response with a given event id.
5850 pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> {
5851 self.ok_with_event_id(event_id)
5852 }
5853
5854 /// Returns an error response with a generic error code indicating the
5855 /// client is not authorized to set space parents.
5856 pub fn unauthorized(self) -> MatrixMock<'a> {
5857 self.respond_with(ResponseTemplate::new(400))
5858 }
5859}
5860
5861/// A prebuilt mock for `PUT
5862/// /_matrix/client/v3/user/{userId}/rooms/{roomId}/tags/{tag}`.
5863pub struct SetTagEndpoint;
5864
5865impl<'a> MockEndpoint<'a, SetTagEndpoint> {
5866 /// Returns a successful empty response.
5867 pub fn ok(self) -> MatrixMock<'a> {
5868 self.ok_empty_json()
5869 }
5870}
5871
5872/// A prebuilt mock for `DELETE
5873/// /_matrix/client/v3/user/{userId}/rooms/{roomId}/tags/{tag}`.
5874pub struct DeleteTagEndpoint;
5875
5876impl<'a> MockEndpoint<'a, DeleteTagEndpoint> {
5877 /// Returns a successful empty response.
5878 pub fn ok(self) -> MatrixMock<'a> {
5879 self.ok_empty_json()
5880 }
5881}
5882
5883/// A prebuilt mock for running simplified sliding sync.
5884pub struct SlidingSyncEndpoint;
5885
5886impl<'a> MockEndpoint<'a, SlidingSyncEndpoint> {
5887 /// Mocks the sliding sync endpoint with the given response.
5888 pub fn ok(self, response: msc4186::Response) -> MatrixMock<'a> {
5889 // A bit silly that we need to destructure all the fields ourselves, but
5890 // Response isn't serializable :'(
5891 self.ok_json(json!({
5892 "txn_id": response.txn_id,
5893 "pos": response.pos,
5894 "lists": response.lists,
5895 "rooms": response.rooms,
5896 "extensions": response.extensions,
5897 }))
5898 }
5899
5900 /// Temporarily mocks the sync with the given endpoint and runs a client
5901 /// sync with it.
5902 ///
5903 /// After calling this function, the sync endpoint isn't mocked anymore.
5904 pub async fn ok_and_run<F: FnOnce(SlidingSyncBuilder) -> SlidingSyncBuilder>(
5905 self,
5906 client: &Client,
5907 on_builder: F,
5908 response: msc4186::Response,
5909 ) {
5910 let _scope = self.ok(response).mount_as_scoped().await;
5911
5912 let sliding_sync =
5913 on_builder(client.sliding_sync("test_id").unwrap()).build().await.unwrap();
5914
5915 let _summary = sliding_sync.sync_once().await.unwrap();
5916 }
5917}
5918
5919/// A prebuilt mock for `GET /_matrix/client/*/profile/{user_id}/{key_name}`.
5920pub struct GetProfileFieldEndpoint {
5921 field: ProfileFieldName,
5922}
5923
5924impl<'a> MockEndpoint<'a, GetProfileFieldEndpoint> {
5925 /// Returns a successful response containing the given value, if any.
5926 pub fn ok_with_value(self, value: Option<Value>) -> MatrixMock<'a> {
5927 if let Some(value) = value {
5928 let field = self.endpoint.field.to_string();
5929 self.ok_json(json!({
5930 field: value,
5931 }))
5932 } else {
5933 self.ok_empty_json()
5934 }
5935 }
5936}
5937
5938/// A prebuilt mock for `PUT /_matrix/client/*/profile/{user_id}/{key_name}`.
5939pub struct SetProfileFieldEndpoint;
5940
5941impl<'a> MockEndpoint<'a, SetProfileFieldEndpoint> {
5942 /// Returns a successful empty response.
5943 pub fn ok(self) -> MatrixMock<'a> {
5944 self.ok_empty_json()
5945 }
5946
5947 /// Expect the request body to set the given [`ProfileFieldValue`].
5948 pub fn expect_field_value(mut self, value: ProfileFieldValue) -> Self {
5949 let body = BTreeMap::from([(value.field_name(), value.value())]);
5950 self.mock = self.mock.and(body_json(body));
5951 self
5952 }
5953}
5954
5955/// A prebuilt mock for `DELETE /_matrix/client/*/profile/{user_id}/{key_name}`.
5956pub struct DeleteProfileFieldEndpoint;
5957
5958impl<'a> MockEndpoint<'a, DeleteProfileFieldEndpoint> {
5959 /// Returns a successful empty response.
5960 pub fn ok(self) -> MatrixMock<'a> {
5961 self.ok_empty_json()
5962 }
5963}
5964
5965/// A prebuilt mock for `GET /_matrix/client/*/profile/{user_id}`.
5966pub struct GetProfileEndpoint;
5967
5968impl<'a> MockEndpoint<'a, GetProfileEndpoint> {
5969 /// Returns a successful empty response.
5970 pub fn ok_with_fields(self, fields: Vec<ProfileFieldValue>) -> MatrixMock<'a> {
5971 let profile = fields
5972 .iter()
5973 .map(|field| (field.field_name(), field.value()))
5974 .collect::<BTreeMap<_, _>>();
5975 self.ok_json(profile)
5976 }
5977}
5978
5979/// A prebuilt mock for `POST /_matrix/client/*/profile/query` (MSC4536).
5980pub struct QueryProfilesEndpoint;
5981
5982impl<'a> MockEndpoint<'a, QueryProfilesEndpoint> {
5983 /// Expect the request to query exactly the given users, in that order.
5984 pub fn expect_users(mut self, users: &[OwnedUserId]) -> Self {
5985 self.mock = self.mock.and(body_json(json!({ "users": users })));
5986 self
5987 }
5988
5989 /// Returns a successful response containing the given profiles.
5990 pub fn ok_with_profiles(
5991 self,
5992 profiles: Vec<(OwnedUserId, Vec<ProfileFieldValue>)>,
5993 ) -> MatrixMock<'a> {
5994 let profiles = profiles
5995 .into_iter()
5996 .map(|(user_id, fields)| {
5997 let profile = fields
5998 .iter()
5999 .map(|field| (field.field_name(), field.value()))
6000 .collect::<BTreeMap<_, _>>();
6001 (user_id, json!(profile))
6002 })
6003 .collect::<BTreeMap<_, _>>();
6004 self.ok_json(profiles)
6005 }
6006}
6007
6008/// A prebuilt mock for `GET /_matrix/client/*/capabilities`.
6009pub struct GetHomeserverCapabilitiesEndpoint;
6010
6011impl<'a> MockEndpoint<'a, GetHomeserverCapabilitiesEndpoint> {
6012 /// Returns a successful empty response.
6013 pub fn ok_with_capabilities(self, capabilities: Capabilities) -> MatrixMock<'a> {
6014 self.ok_json(json!({
6015 "capabilities": capabilities,
6016 }))
6017 }
6018}
6019
6020/// A prebuilt mock for `GET
6021/// /_matrix/client/unstable/org.matrix.msc1763/retention/configuration`.
6022pub struct GetRetentionConfigurationEndpoint;
6023
6024impl<'a> MockEndpoint<'a, GetRetentionConfigurationEndpoint> {
6025 /// Returns a successful response without any policies or limits.
6026 pub fn ok_empty(self) -> MatrixMock<'a> {
6027 self.ok(BTreeMap::new(), RetentionLimits::default())
6028 }
6029
6030 /// Returns a successful response with the given policies and limits.
6031 ///
6032 /// `policies` maps a room ID (or all rooms) to its retention policy, and
6033 /// `limits` are the limits to apply to the policies defined in
6034 /// `m.room.retention` state events.
6035 pub fn ok(
6036 self,
6037 policies: BTreeMap<RoomIdOrAllRooms, RoomRetentionEventContent>,
6038 limits: RetentionLimits,
6039 ) -> MatrixMock<'a> {
6040 self.ok_json(json!({
6041 "policies": policies,
6042 "limits": limits,
6043 }))
6044 }
6045}
6046
6047/// A prebuilt mock for `POST /_matrix/client/*/account/deactivate`.
6048pub struct DeactivateAccountEndpoint;
6049
6050impl<'a> MockEndpoint<'a, DeactivateAccountEndpoint> {
6051 /// Returns a successful response with a successful 3PID unbind.
6052 pub fn ok_with_success(self) -> MatrixMock<'a> {
6053 self.respond_with(ResponseTemplate::new(200).set_body_json(json!({
6054 "id_server_unbind_result": "success",
6055 })))
6056 }
6057}
6058
6059/// A prebuilt mock for `PUT /_matrix/client/v3/presence/{userId}/status`.
6060pub struct UpdatePresenceEndpoint;
6061
6062impl<'a> MockEndpoint<'a, UpdatePresenceEndpoint> {
6063 /// Returns a successful empty response.
6064 pub fn ok(self) -> MatrixMock<'a> {
6065 self.ok_empty_json()
6066 }
6067}
6068
6069/// A prebuilt mock for `GET /_matrix/client/v3/presence/{userId}/status`.
6070pub struct GetPresenceEndpoint;
6071
6072impl<'a> MockEndpoint<'a, GetPresenceEndpoint> {
6073 /// Returns a successful response with the given presence state.
6074 pub fn ok(self, presence: &PresenceState) -> MatrixMock<'a> {
6075 self.ok_json(json!({ "presence": presence.as_str() }))
6076 }
6077}
6078
6079/// A prebuilt mock for `GET
6080/// /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`.
6081pub struct GetRtcTransportsEndpoint;
6082
6083impl<'a> MockEndpoint<'a, GetRtcTransportsEndpoint> {
6084 /// Returns a successful response with a single `m.livekit` transport.
6085 pub fn ok(self) -> MatrixMock<'a> {
6086 self.respond_with(ResponseTemplate::new(200).set_body_json(json!({
6087 "rtc_transports": [
6088 { "type": "m.livekit", "url": "wss://livekit.example.com" }
6089 ]
6090 })))
6091 }
6092}
6093
6094/// A prebuilt mock for `GET
6095/// /_matrix/client/v3/user/{userId}/account_data/{type}`.
6096pub struct GetGlobalAccountDataEndpoint;
6097
6098impl<'a> MockEndpoint<'a, GetGlobalAccountDataEndpoint> {
6099 /// Returns a successful response with the given account data.
6100 pub fn ok(self, account_data: impl Into<AnyGlobalAccountDataEventContent>) -> MatrixMock<'a> {
6101 self.ok_json(account_data.into())
6102 }
6103}
6104
6105/// A prebuilt mock for `PUT
6106/// /_matrix/client/v3/user/{userId}/account_data/{type}`.
6107pub struct SetGlobalAccountDataEndpoint;
6108
6109impl<'a> MockEndpoint<'a, SetGlobalAccountDataEndpoint> {
6110 /// Expect the request body to contain the given account data.
6111 pub fn expect_account_data(
6112 self,
6113 account_data: impl Into<AnyGlobalAccountDataEventContent>,
6114 ) -> Self {
6115 self.body_json(account_data.into())
6116 }
6117
6118 /// Returns a successful empty response.
6119 pub fn ok(self) -> MatrixMock<'a> {
6120 self.ok_empty_json()
6121 }
6122}