src/tests.rs

277 lines · 9319 bytes

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