use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::collections::HashMap;
use tokio::sync::Mutex;
pub struct MockDao {
data: Mutex<HashMap<String, String>>,
}
impl MockDao {
pub fn new() -> Self {
Self {
data: Mutex::new(HashMap::new()),
}
}
}
#[async_trait]
impl GarrisonDao for MockDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let data = self.data.lock().await;
Ok(data.get(key).cloned())
}
async fn set(&self, key: &str, value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
let mut data = self.data.lock().await;
data.insert(key.to_string(), value.to_string());
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let mut data = self.data.lock().await;
if data.contains_key(key) {
data.insert(key.to_string(), value.to_string());
Ok(())
} else {
Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key)))
}
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
let mut data = self.data.lock().await;
data.remove(key);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn update_existing_key_overwrites_value() {
let dao = MockDao::new();
dao.set("k1", "v1", 60).await.unwrap();
dao.update("k1", "v2").await.unwrap();
assert_eq!(dao.get("k1").await.unwrap(), Some("v2".to_string()));
}
#[tokio::test]
async fn update_missing_key_returns_dao_error() {
let dao = MockDao::new();
let result = dao.update("missing", "v").await;
assert!(matches!(result, Err(GarrisonError::Dao(_))));
}
#[tokio::test]
async fn expire_is_noop_ok() {
let dao = MockDao::new();
dao.set("k1", "v1", 60).await.unwrap();
assert!(dao.expire("k1", 120).await.is_ok());
}
#[tokio::test]
async fn delete_removes_key() {
let dao = MockDao::new();
dao.set("k1", "v1", 60).await.unwrap();
dao.delete("k1").await.unwrap();
assert_eq!(dao.get("k1").await.unwrap(), None);
}
}