src/tests.rs

267 lines · 9291 bytes

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