use crate::handlers::node_id::NodeId;
use crate::objects::github::GitHub;
use crate::objects::user::User;
use chrono::{DateTime, Utc};
use serde_json::{Number, Value};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use uuid::Uuid;
#[derive(Clone)]
pub struct FakeHub {
pub github: Arc<Mutex<GitHub>>,
pub started: DateTime<Utc>,
pub address: String,
}
impl Default for FakeHub {
fn default() -> FakeHub {
FakeHub {
github: Arc::new(Mutex::new(create_github())),
started: Utc::now(),
address: String::from("localhost"),
}
}
}
fn create_github() -> GitHub {
let mut users: HashMap<String, User> = HashMap::new();
let name = String::from("jeff");
let mut jeff = User::new(name.clone());
jeff.extra
.insert(String::from("id"), Value::Number(Number::from(1)));
let mut second = User::new(String::from("h1alexbel"));
second
.extra
.insert(String::from("id"), Value::Number(Number::from(2)));
users.insert(String::from("h1alexbel"), second);
users.insert(name, jeff);
GitHub {
id: Uuid::new_v4(),
name: String::from("main"),
users,
}
}
impl FakeHub {
pub fn new(started: DateTime<Utc>) -> FakeHub {
FakeHub {
github: Arc::new(Mutex::new(create_github())),
started,
address: String::from("localhost"),
}
}
pub fn with_addr(address: String) -> FakeHub {
FakeHub {
github: Arc::new(Mutex::new(create_github())),
started: Utc::now(),
address,
}
}
pub fn main(&self) -> Arc<Mutex<GitHub>> {
Arc::clone(&self.github)
}
pub fn coords(&self) -> String {
format!(
"{};node:{}",
self.address,
NodeId { from: self.started }.as_string()
)
}
}
#[cfg(test)]
mod tests {
use crate::objects::fakehub::FakeHub;
use anyhow::Result;
use chrono::{TimeZone, Utc};
use hamcrest::{equal_to, is, HamcrestMatcher};
#[test]
fn returns_default_fakehub_instance() -> Result<()> {
let fakehub = FakeHub::default();
let github = fakehub.main();
let locked = github.lock().expect("Failed to lock");
assert_that!(locked.id.is_nil(), is(equal_to(false)));
Ok(())
}
#[test]
fn returns_default_github() -> Result<()> {
let fakehub = FakeHub::default();
let github = fakehub.main();
let locked = github.lock().expect("Failed to lock");
let users = locked.clone().users();
assert_that!(&locked.name, is(equal_to("main")));
assert_that!(users.len(), is(equal_to(2)));
Ok(())
}
#[test]
#[allow(clippy::unwrap_used)]
fn returns_coords() -> Result<()> {
let fakehub = FakeHub::new(Utc.with_ymd_and_hms(2024, 9, 1, 9, 10, 11).unwrap());
assert_that!(
fakehub.coords(),
is(equal_to(String::from(
"localhost;node:305be946d516494d20c7c10f6d0020f9"
)))
);
Ok(())
}
}