src/tests.rs

284 lines · 10390 bytes

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