Skip to content

Commit fa8efa8

Browse files
author
Michel von Czettritz
committed
mock NCTalk and add test to users with Mock
1 parent b18cf5e commit fa8efa8

File tree

6 files changed

+124
-18
lines changed

6 files changed

+124
-18
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ exclude = [
2020
"tags",
2121
]
2222

23+
[dev-dependencies]
24+
mockall = { version = "0.13.0" }
25+
mockall_derive = { version = "0.13.0"}
26+
2327
[dependencies]
2428
reqwest = { version = "0.12", features = ["json"] }
2529
tokio = { version = "1", features = ["full"] }

src/backend/nc_message.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::backend::nc_request::NCReqDataMessage;
22
use chrono::prelude::*;
33

44
/// `NextCloud` message interface
5-
#[derive(Debug)]
5+
#[derive(Debug, Default)]
66
pub struct NCMessage(NCReqDataMessage);
77

88
impl From<NCReqDataMessage> for NCMessage {

src/backend/nc_request.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use reqwest::{
1212
use serde::{Deserialize, Deserializer, Serialize};
1313
use std::{collections::HashMap, error::Error};
1414

15-
#[derive(Debug, Clone)]
15+
#[derive(Debug, Clone, Default)]
1616
pub struct NCRequest {
1717
base_url: String,
1818
client: Client,

src/backend/nc_room.rs

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,17 @@ pub enum NCRoomTypes {
1919
NoteToSelf,
2020
}
2121

22+
impl Default for NCRoomTypes {
23+
fn default() -> Self {
24+
NCRoomTypes::OneToOne
25+
}
26+
}
27+
#[cfg(test)]
28+
use mockall::{automock, predicate::*};
29+
30+
#[cfg_attr(test, automock)]
2231
#[async_trait]
23-
pub trait NCRoomInterface: Debug + Send + Display + Ord {
32+
pub trait NCRoomInterface: Debug + Send + Display + Ord + Default{
2433
fn get_last_room_level_message_id(&self) -> Option<i32>;
2534
fn has_unread(&self) -> bool;
2635
fn is_dm(&self) -> bool;
@@ -39,17 +48,17 @@ pub trait NCRoomInterface: Debug + Send + Display + Ord {
3948
async fn update_if_id_is_newer(
4049
&mut self,
4150
message_id: i32,
42-
data_option: Option<&NCReqDataRoom>,
51+
data_option: Option<NCReqDataRoom>,
4352
) -> Result<(), Box<dyn std::error::Error>>;
4453
async fn send(&self, message: String) -> Result<String, Box<dyn std::error::Error>>;
4554
async fn update(
4655
&mut self,
47-
data_option: Option<&NCReqDataRoom>,
56+
data_option: Option<NCReqDataRoom>,
4857
) -> Result<(), Box<dyn std::error::Error>>;
4958
async fn mark_as_read(&self) -> Result<(), Box<dyn std::error::Error>>;
5059
}
5160

52-
#[derive(Debug)]
61+
#[derive(Debug, Default)]
5362
pub struct NCRoom {
5463
requester: NCRequest,
5564
notifier: NCNotify,
@@ -239,7 +248,7 @@ impl NCRoomInterface for NCRoom {
239248

240249
async fn update(
241250
&mut self,
242-
data_option: Option<&NCReqDataRoom>,
251+
data_option: Option<NCReqDataRoom>,
243252
) -> Result<(), Box<dyn std::error::Error>> {
244253
if let Some(data) = data_option {
245254
self.room_data = data.clone();
@@ -289,7 +298,7 @@ impl NCRoomInterface for NCRoom {
289298
async fn update_if_id_is_newer(
290299
&mut self,
291300
message_id: i32,
292-
data_option: Option<&NCReqDataRoom>,
301+
data_option: Option<NCReqDataRoom>,
293302
) -> Result<(), Box<dyn std::error::Error>> {
294303
use std::cmp::Ordering;
295304

@@ -352,3 +361,39 @@ impl std::ops::Deref for NCRoom {
352361
&self.room_data.displayName
353362
}
354363
}
364+
365+
#[cfg(test)]
366+
mod tests {
367+
use super::*;
368+
static BUTZ: &str = "Butz";
369+
impl std::ops::Deref for MockNCRoomInterface {
370+
type Target = str;
371+
fn deref(&self) -> &Self::Target {
372+
BUTZ
373+
}
374+
}
375+
impl Ord for MockNCRoomInterface {
376+
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
377+
self.to_string().cmp(&other.to_string())
378+
}
379+
}
380+
381+
impl PartialOrd for MockNCRoomInterface {
382+
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
383+
Some(self.cmp(other))
384+
}
385+
}
386+
387+
impl PartialEq for MockNCRoomInterface {
388+
fn eq(&self, other: &Self) -> bool {
389+
self == other
390+
}
391+
}
392+
393+
impl Eq for MockNCRoomInterface {}
394+
impl std::fmt::Display for MockNCRoomInterface {
395+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396+
write!(f, "{}", self)
397+
}
398+
}
399+
}

src/backend/nc_talk.rs

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ use crate::{
77
config::{self},
88
};
99
use async_trait::async_trait;
10-
use core::panic;
1110
use itertools::Itertools;
1211
use std::{collections::HashMap, error::Error, fmt::Debug, path::PathBuf};
1312

1413
use super::nc_room::{NCRoom, NCRoomTypes};
1514

15+
1616
#[async_trait]
17-
pub trait NCBackend: Debug + Send {
17+
pub trait NCBackend: Debug + Send + Default {
1818
type Room: NCRoomInterface;
1919
fn write_to_log(&mut self) -> Result<(), std::io::Error>;
2020
fn get_current_room_token(&self) -> &str;
@@ -24,14 +24,14 @@ pub trait NCBackend: Debug + Send {
2424
fn get_room_by_displayname(&self, name: &str) -> &str;
2525
fn get_dm_keys_display_name_mapping(&self) -> Vec<(String, String)>;
2626
fn get_group_keys_display_name_mapping(&self) -> Vec<(String, String)>;
27-
fn get_room_keys(&self) -> Vec<&String>;
27+
fn get_room_keys(&self) -> Vec<&'_ String>;
2828
async fn send_message(&mut self, message: String) -> Result<(), Box<dyn Error>>;
2929
async fn select_room(&mut self, token: String) -> Result<(), Box<dyn Error>>;
3030
async fn update_rooms(&mut self, force_update: bool) -> Result<(), Box<dyn Error>>;
3131
fn add_room(&mut self, room_option: Option<Self::Room>);
3232
}
3333

34-
#[derive(Debug)]
34+
#[derive(Debug, Default)]
3535
pub struct NCTalk {
3636
rooms: HashMap<String, NCRoom>,
3737
chat_data_path: PathBuf,
@@ -136,7 +136,7 @@ impl NCTalk {
136136
json_room
137137
.update_if_id_is_newer(
138138
message_id,
139-
Some(initial_message_ids.get(token).unwrap()),
139+
Some((*initial_message_ids.get(token).unwrap()).clone()),
140140
)
141141
.await?;
142142
rooms.insert(token.clone(), json_room);
@@ -361,10 +361,10 @@ impl NCBackend for NCTalk {
361361
.get_mut(room.token.as_str())
362362
.ok_or("Failed to get Room ref.")?;
363363
if force_update {
364-
room_ref.update(Some(&room)).await?;
364+
room_ref.update(Some(room)).await?;
365365
} else {
366366
room_ref
367-
.update_if_id_is_newer(room.lastMessage.id, Some(&room))
367+
.update_if_id_is_newer(room.lastMessage.id, Some(room))
368368
.await?;
369369
}
370370
} else {
@@ -389,10 +389,51 @@ impl NCBackend for NCTalk {
389389
}
390390
}
391391
}
392+
393+
#[cfg(test)]
394+
use mockall::{mock, predicate::*};
395+
#[cfg(test)]
396+
use crate::backend::nc_room::MockNCRoomInterface;
397+
398+
399+
#[cfg(test)]
400+
mock!{
401+
#[derive(Debug)]
402+
pub NCTalk{}
403+
#[async_trait]
404+
impl NCBackend for NCTalk{
405+
type Room = MockNCRoomInterface;
406+
fn write_to_log(&mut self) -> Result<(), std::io::Error>;
407+
fn get_current_room_token(&self) -> &str;
408+
fn get_room(&self, token: &str) -> &<MockNCTalk as NCBackend>::Room;
409+
fn get_current_room(&self) -> &<MockNCTalk as NCBackend>::Room;
410+
fn get_unread_rooms(&self) -> Vec<String>;
411+
fn get_room_by_displayname(&self, name: &str) -> &str;
412+
fn get_dm_keys_display_name_mapping(&self) -> Vec<(String, String)>;
413+
fn get_group_keys_display_name_mapping(&self) -> Vec<(String, String)>;
414+
fn get_room_keys<'a>(&'a self) -> Vec<&'a String>;
415+
async fn send_message(& mut self, message: String) -> Result<(), Box<dyn Error>>;
416+
async fn select_room(&mut self, token: String) -> Result<(), Box<dyn Error>>;
417+
async fn update_rooms(& mut self, force_update: bool) -> Result<(), Box<dyn Error>>;
418+
fn add_room(&mut self, room_option: Option<<MockNCTalk as NCBackend>::Room>);
419+
}
420+
}
421+
#[cfg(test)]
422+
impl std::fmt::Display for MockNCTalk {
423+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424+
write!(f, "{}", self)
425+
}
426+
}
427+
428+
392429
#[cfg(test)]
393430
mod tests {
431+
// use crate::backend::nc_room::MockNCRoomInterface;
432+
433+
// use super::*;
434+
435+
394436

395-
// use super::*;
396437

397438
// #[derive(Debug, Default)]
398439
// pub struct MockBackend {

src/ui/users.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,20 +75,32 @@ impl<'a> StatefulWidget for &Users<'a> {
7575
#[cfg(test)]
7676
mod tests {
7777
use backend::TestBackend;
78+
use crate::backend::{nc_request::NCReqDataParticipants, nc_room::MockNCRoomInterface, nc_talk::MockNCTalk};
7879

7980
use super::*;
8081

8182
#[test]
8283
fn render_users() {
84+
let mut mock_nc_backend = MockNCTalk::new();
8385
let backend = TestBackend::new(10, 10);
8486
let mut terminal = Terminal::new(backend).unwrap();
85-
let users = Users::new();
87+
let mut users = Users::new();
88+
89+
let mut mock_room = MockNCRoomInterface::new();
90+
let mut dummy_user = NCReqDataParticipants::default();
91+
dummy_user.displayName = "Butz".to_string();
92+
mock_room.expect_get_users().return_const(vec![dummy_user]);
93+
mock_nc_backend.expect_get_current_room().once().return_const(mock_room);
94+
users.update(&mock_nc_backend);
95+
96+
8697
terminal
8798
.draw(|frame| users.render_area(frame, Rect::new(0, 0, 8, 8)))
8899
.unwrap();
100+
89101
let mut expected = Buffer::with_lines([
90102
"│Users ",
91-
"│ ",
103+
"│Butz ",
92104
"│ ",
93105
"│ ",
94106
"│ ",
@@ -103,7 +115,11 @@ mod tests {
103115
for x in 1..=7 {
104116
expected[(x, 0)].set_style(Style::new().green().on_black().bold());
105117
}
118+
for x in 1..=7 {
119+
expected[(x, 1)].set_style(Style::new().white().on_black().bold());
120+
}
106121

107122
terminal.backend().assert_buffer(&expected);
123+
108124
}
109125
}

0 commit comments

Comments
 (0)