use std::path::PathBuf;
use crate::connector::{ServiceConnector, ServiceInfo};
use super::helpers::detect_service;
pub struct MemoryConnector {
home_dir: Option<PathBuf>,
}
impl MemoryConnector {
pub fn new() -> Self {
Self { home_dir: None }
}
#[cfg(test)]
pub fn with_home(home_dir: PathBuf) -> Self {
Self {
home_dir: Some(home_dir),
}
}
fn addr_file_path(&self) -> PathBuf {
let home = self
.home_dir
.clone()
.or_else(dirs::home_dir)
.unwrap_or_else(|| PathBuf::from("/tmp"));
home.join(".trusty-memory").join("http_addr")
}
}
impl Default for MemoryConnector {
fn default() -> Self {
Self::new()
}
}
impl ServiceConnector for MemoryConnector {
fn id(&self) -> &'static str {
"trusty-memory"
}
fn display_name(&self) -> &'static str {
"Trusty Memory"
}
fn detect(&self) -> ServiceInfo {
detect_service(
self.id(),
self.display_name(),
"trusty-memory",
self.addr_file_path(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::connector::ServiceStatus;
use std::fs;
use tempfile::TempDir;
fn make_home_with_addr(rel_path: &str, content: &str) -> TempDir {
let tmp = TempDir::new().expect("tempdir");
let path = tmp.path().join(rel_path);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(&path, content).expect("write addr file");
tmp
}
#[test]
fn test_memory_connector_with_stale_addr_file() {
let tmp = make_home_with_addr(".trusty-memory/http_addr", "127.0.0.1:14997");
let connector = MemoryConnector::with_home(tmp.path().to_path_buf());
let info = connector.detect();
assert!(
info.status == ServiceStatus::Absent || info.status == ServiceStatus::Available,
"expected Absent or Available, got {:?}",
info.status
);
assert_eq!(info.id, "trusty-memory");
}
#[test]
fn test_memory_connector_no_addr_file() {
let tmp = TempDir::new().expect("tempdir");
let connector = MemoryConnector::with_home(tmp.path().to_path_buf());
let info = connector.detect();
assert!(
info.status == ServiceStatus::Absent || info.status == ServiceStatus::Available,
"expected Absent or Available without addr file, got {:?}",
info.status
);
}
}