matrix_sdk/test_utils/client.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//! Augmented [`ClientBuilder`] that can set up an already logged-in user.
16
17use matrix_sdk_base::{store::StoreConfig, SessionMeta};
18use ruma::{api::MatrixVersion, device_id, user_id};
19
20use crate::{
21 authentication::matrix::{MatrixSession, MatrixSessionTokens},
22 config::RequestConfig,
23 Client, ClientBuilder,
24};
25
26/// An augmented [`ClientBuilder`] that also allows for handling session login.
27#[allow(missing_debug_implementations)]
28pub struct MockClientBuilder {
29 builder: ClientBuilder,
30 logged_in: bool,
31}
32
33impl MockClientBuilder {
34 /// Create a new [`MockClientBuilder`] connected to the given homeserver,
35 /// using Matrix V1.12, and which will not attempt any network retry (by
36 /// default).
37 pub(crate) fn new(homeserver: String) -> Self {
38 let default_builder = Client::builder()
39 .homeserver_url(homeserver)
40 .server_versions([MatrixVersion::V1_12])
41 .request_config(RequestConfig::new().disable_retry());
42
43 Self { builder: default_builder, logged_in: true }
44 }
45
46 /// Doesn't log-in a user.
47 ///
48 /// Authenticated requests will fail if this is called.
49 pub fn unlogged(mut self) -> Self {
50 self.logged_in = false;
51 self
52 }
53
54 /// Provides another [`StoreConfig`] for the underlying [`ClientBuilder`].
55 pub fn store_config(mut self, store_config: StoreConfig) -> Self {
56 self.builder = self.builder.store_config(store_config);
57 self
58 }
59
60 /// Finish building the client into the final [`Client`] instance.
61 pub async fn build(self) -> Client {
62 let client = self.builder.build().await.expect("building client failed");
63
64 if self.logged_in {
65 client
66 .matrix_auth()
67 .restore_session(MatrixSession {
68 meta: SessionMeta {
69 user_id: user_id!("@example:localhost").to_owned(),
70 device_id: device_id!("DEVICEID").to_owned(),
71 },
72 tokens: MatrixSessionTokens {
73 access_token: "1234".to_owned(),
74 refresh_token: None,
75 },
76 })
77 .await
78 .unwrap();
79 }
80
81 client
82 }
83}