src/tests.rs

264 lines · 8848 bytes

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