src/tests.rs

271 lines · 9868 bytes

  1use std::iter::FromIterator as _;
  2
  3use lazy_static::lazy_static;
  4use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
  5use matrix_sdk::ruma::{UInt, event_id, server_name, user_id};
  6use matrix_sdk::ruma::{assign, owned_room_alias_id};
  7use serde_json::{Map, Value};
  8use tokio::sync::mpsc::unbounded_channel;
  9
 10use crate::base::EventLocation;
 11use crate::config::*;
 12use crate::prelude::*;
 13
 14lazy_static! {
 15    pub static ref TEST_ROOM1_ALIAS: OwnedRoomAliasId = owned_room_alias_id!("#room1:example.com");
 16    pub static ref TEST_ROOM1_ID: OwnedRoomId =
 17        RoomId::new_v1(server_name!("example.com")).to_owned();
 18    pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
 19    pub static ref TEST_USER2: OwnedUserId = user_id!("@user2:example.com").to_owned();
 20    pub static ref TEST_USER3: OwnedUserId = user_id!("@user3:example.com").to_owned();
 21    pub static ref TEST_USER4: OwnedUserId = user_id!("@user4:example.com").to_owned();
 22    pub static ref TEST_USER5: OwnedUserId = user_id!("@user5:example.com").to_owned();
 23    pub static ref MSG1_EVID: OwnedEventId = EventId::new_v1(server_name!("example.com"));
 24    pub static ref MSG2_EVID: OwnedEventId = EventId::new_v1(server_name!("example.com"));
 25    pub static ref MSG3_EVID: OwnedEventId =
 26        event_id!("$5jRz3KfVhaUzXtVj7k:example.com").to_owned();
 27    pub static ref MSG4_EVID: OwnedEventId =
 28        event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned();
 29    pub static ref MSG5_EVID: OwnedEventId = EventId::new_v1(server_name!("example.com"));
 30    pub static ref MSG1_KEY: MessageKey = MessageKey {
 31        // 2000-01-01T00:00:00
 32        ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(946681200).unwrap())),
 33        id: MSG1_EVID.clone().into()
 34    };
 35    pub static ref MSG2_KEY: MessageKey = MessageKey {
 36        ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(1).unwrap())),
 37        id: MSG2_EVID.clone().into()
 38    };
 39    pub static ref MSG3_KEY: MessageKey = MessageKey {
 40        ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(2).unwrap())),
 41        id: MSG3_EVID.clone().into()
 42    };
 43    pub static ref MSG4_KEY: MessageKey = MessageKey {
 44        ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(2).unwrap())),
 45        id: MSG4_EVID.clone().into()
 46    };
 47    pub static ref MSG5_KEY: MessageKey = MessageKey {
 48        ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(8).unwrap())),
 49        id: MSG5_EVID.clone().into()
 50    };
 51}
 52
 53pub fn mock_room1_message(
 54    content: RoomMessageEventContent,
 55    sender: OwnedUserId,
 56    key: MessageKey,
 57) -> Message {
 58    let timestamp = key.ts.0;
 59    let event_id = key.id.as_origin().unwrap();
 60
 61    let event = serde_json::from_value(Value::Object(Map::from_iter([
 62        ("type".to_owned(), Value::String("m.room.message".into())),
 63        ("content".to_owned(), serde_json::to_value(&content).unwrap()),
 64        ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
 65        ("sender".to_owned(), serde_json::to_value(&sender).unwrap()),
 66        ("origin_server_ts".to_owned(), serde_json::to_value(timestamp).unwrap()),
 67        ("room_id".to_owned(), serde_json::to_value(&*TEST_ROOM1_ID).unwrap()),
 68    ])))
 69    .unwrap();
 70
 71    Message::new(MessageEvent::Original(event, Default::default()), sender, timestamp.into())
 72}
 73
 74pub fn mock_message1() -> Message {
 75    let content = RoomMessageEventContent::text_plain("writhe");
 76
 77    mock_room1_message(content, TEST_USER1.clone(), MSG1_KEY.clone())
 78}
 79
 80pub fn mock_message2() -> Message {
 81    let content = RoomMessageEventContent::text_plain("helium");
 82
 83    mock_room1_message(content, TEST_USER2.clone(), MSG2_KEY.clone())
 84}
 85
 86pub fn mock_message3() -> Message {
 87    let content = RoomMessageEventContent::text_plain("this\nis\na\nmultiline\nmessage");
 88
 89    mock_room1_message(content, TEST_USER2.clone(), MSG3_KEY.clone())
 90}
 91
 92pub fn mock_message4() -> Message {
 93    let content = RoomMessageEventContent::text_plain("help");
 94
 95    mock_room1_message(content, TEST_USER1.clone(), MSG4_KEY.clone())
 96}
 97
 98pub fn mock_message5() -> Message {
 99    let content = RoomMessageEventContent::text_plain("character");
100
101    mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
102}
103
104pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> {
105    let mut keys = HashMap::new();
106
107    keys.insert(MSG1_EVID.clone(), EventLocation::Message(None, MSG1_KEY.clone()));
108    keys.insert(MSG2_EVID.clone(), EventLocation::Message(None, MSG2_KEY.clone()));
109    keys.insert(MSG3_EVID.clone(), EventLocation::Message(None, MSG3_KEY.clone()));
110    keys.insert(MSG4_EVID.clone(), EventLocation::Message(None, MSG4_KEY.clone()));
111    keys.insert(MSG5_EVID.clone(), EventLocation::Message(None, MSG5_KEY.clone()));
112
113    keys
114}
115
116pub fn mock_messages() -> Messages {
117    let mut messages = Messages::main();
118
119    messages.insert(MSG1_KEY.clone(), mock_message1());
120    messages.insert(MSG2_KEY.clone(), mock_message2());
121    messages.insert(MSG3_KEY.clone(), mock_message3());
122    messages.insert(MSG4_KEY.clone(), mock_message4());
123    messages.insert(MSG5_KEY.clone(), mock_message5());
124
125    messages
126}
127
128pub fn mock_room() -> RoomInfo {
129    let mut room = RoomInfo::default();
130    room.name = Some("Watercooler Discussion".into());
131    room.keys = mock_keys();
132    *room.get_thread_mut(None) = mock_messages();
133
134    let user_id = TEST_USER2.clone();
135    let name = "User 2";
136    room.display_names.set(user_id.clone(), Some(name.to_string()), true);
137
138    room
139}
140
141pub fn mock_dirs() -> DirectoryValues {
142    DirectoryValues {
143        cache: PathBuf::new(),
144        data: PathBuf::new(),
145        logs: PathBuf::new(),
146        downloads: None,
147    }
148}
149
150pub fn mock_tunables() -> TunableValues {
151    TunableValues {
152        default_markup: Default::default(),
153        ignorecase: false,
154        default_register: None,
155        default_room: None,
156        default_via: Default::default(),
157        encryption: Encryption::default().values(),
158        input_prompt: None,
159        log_level: "warn".into(),
160        max_log_files: 7,
161        message_formatted_display: true,
162        message_shortcode_display: false,
163        normal_after_send: true,
164        proxy: Proxy::default().values(),
165        reaction_display: true,
166        reaction_shortcode_display: false,
167        read_receipt_send: true,
168        read_receipt_trigger: Default::default(),
169        read_receipt_display: true,
170        room_labels: Default::default(),
171        request_timeout: 120,
172        sort: SortOverrides::default().values(),
173        state_event_display: true,
174        sync_delay_ms: 1000,
175        terminal: Terminal::default().values(),
176        theme: "default".into(),
177        typing_notice_send: true,
178        typing_notice_display: true,
179        users: vec![(TEST_USER5.clone(), UserDisplayTunables {
180            color: Some(Color::Black),
181            name: Some("USER 5".into()),
182        })]
183        .into_iter()
184        .collect::<HashMap<_, _>>(),
185        open_command: None,
186        external_edit_file_suffix: String::from(".md"),
187        username_display: UserDisplayStyle::Username,
188        message_user_color: false,
189        mouse: Default::default(),
190        notifications: Notifications {
191            enabled: false,
192            via: NotifyVia::default(),
193            show_message: true,
194            sound_hint: None,
195        },
196        image_preview: assign!(ImagePreview::default().values(), {enabled: false}),
197        user_gutter_width: 30,
198        tabstop: 4,
199        members_split: Default::default(),
200        default_split: Default::default(),
201        ssl_verify: true,
202        cache_policy: Default::default(),
203        send_on_enter: true,
204        date_format: "%A, %B %d %Y".to_string(),
205        time_format: "  [%T]".to_string(),
206        time_gutter_width: 12,
207    }
208}
209
210pub fn mock_settings() -> ApplicationSettings {
211    ApplicationSettings {
212        layout_json: PathBuf::new(),
213        session_json: PathBuf::new(),
214        device_json: PathBuf::new(),
215        session_json_old: PathBuf::new(),
216        sled_dir: PathBuf::new(),
217        sqlite_dir: PathBuf::new(),
218        sqlite_cache_dir: PathBuf::new(),
219
220        profile_name: "test".into(),
221        profile: ProfileConfig {
222            user_id: user_id!("@user:example.com").to_owned(),
223            password_file: None,
224            url: None,
225            settings: None,
226            dirs: None,
227            layout: None,
228            macros: None,
229            aliases: None,
230            theme: None,
231        },
232        tunables: mock_tunables(),
233        dirs: mock_dirs(),
234        layout: Default::default(),
235        macros: HashMap::default(),
236        aliases: Aliases::default(),
237        theme: crate::config::theme::default_theme().values().into(),
238        themes: Default::default(),
239        enable_enhanced_keys: false,
240    }
241}
242
243pub async fn mock_store() -> ProgramStore {
244    let (tx, _) = unbounded_channel();
245    let (receipts, _) = unbounded_channel();
246    let client = matrix_sdk::Client::builder()
247        .homeserver_url("https://localhost")
248        // don't panic if no certs are available like in a nix build sandbox
249        .disable_ssl_verification()
250        .build()
251        .await
252        .unwrap();
253    let worker = Requester { tx, receipts, client };
254
255    let mut store = ChatStore::new(worker, mock_settings()).unwrap();
256
257    // Add presence information.
258    store.presences.get_or_default(TEST_USER1.clone());
259    store.presences.get_or_default(TEST_USER2.clone());
260    store.presences.get_or_default(TEST_USER3.clone());
261    store.presences.get_or_default(TEST_USER4.clone());
262    store.presences.get_or_default(TEST_USER5.clone());
263
264    let room_id = TEST_ROOM1_ID.clone();
265    let info = mock_room();
266
267    store.rooms.insert(room_id.clone(), info);
268    store.aliases.insert(TEST_ROOM1_ALIAS.clone(), room_id);
269
270    ProgramStore::new(store)
271}