use super::GarrisonInterface;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::time::{Duration, Instant};
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::dao::repository::{NewUser, UpdateUser, UserListRow, UserRepository, UserRow};
pub struct MockDao {
store: Mutex<HashMap<String, (String, Option<Instant>)>>,
}
impl MockDao {
pub fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
}
}
}
#[async_trait]
impl GarrisonDao for MockDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let mut store = self.store.lock();
match store.get(key) {
Some((value, expire_at)) => {
if let Some(deadline) = expire_at {
if Instant::now() >= *deadline {
store.remove(key);
return Ok(None);
}
}
Ok(Some(value.clone()))
},
None => Ok(None),
}
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
let expire_at = if ttl_seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(ttl_seconds))
};
self.store
.lock()
.insert(key.to_string(), (value.to_string(), expire_at));
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((existing, _)) => {
*existing = value.to_string();
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((_, expire_at)) => {
*expire_at = if seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(seconds))
};
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.store.lock().remove(key);
Ok(())
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
let store = self.store.lock();
match store.get(key) {
Some((_, Some(deadline))) => {
let now = Instant::now();
if *deadline <= now {
Ok(None)
} else {
Ok(Some(*deadline - now))
}
},
_ => Ok(None),
}
}
crate::atomic_test_fallback!();
}
pub struct MockFirewall {
pub has_permission: bool,
pub has_role: bool,
}
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
Ok(self.has_permission)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(self.has_role)
}
async fn check_role_any(&self, _login_id: &str, _roles: &[&str]) -> GarrisonResult<bool> {
Ok(self.has_role)
}
async fn check_role_all(&self, _login_id: &str, _roles: &[&str]) -> GarrisonResult<bool> {
Ok(self.has_role)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(self.has_permission)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(self.has_role)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
pub struct MockInterface;
#[async_trait]
impl GarrisonInterface for MockInterface {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
}
pub struct MockInterfaceWithPerms {
pub permissions: Vec<String>,
pub roles: Vec<String>,
}
#[async_trait]
impl GarrisonInterface for MockInterfaceWithPerms {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.permissions.clone())
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.roles.clone())
}
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
pub struct MockUserRepository {
users: Mutex<HashMap<String, UserRow>>,
update_error: Mutex<Option<String>>,
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
impl MockUserRepository {
pub fn new() -> Self {
Self {
users: Mutex::new(HashMap::new()),
update_error: Mutex::new(None),
}
}
pub fn insert(&self, user: UserRow) {
self.users.lock().insert(user.username.clone(), user);
}
#[cfg_attr(not(feature = "listener"), allow(dead_code))]
pub fn set_update_error(&self, msg: &str) {
*self.update_error.lock() = Some(msg.to_string());
}
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[async_trait]
impl UserRepository for MockUserRepository {
async fn find_by_id(&self, _tenant_id: i64, id: &str) -> GarrisonResult<Option<UserRow>> {
Ok(self.users.lock().values().find(|u| u.id == id).cloned())
}
async fn find_by_username(
&self,
_tenant_id: i64,
username: &str,
) -> GarrisonResult<Option<UserRow>> {
Ok(self.users.lock().get(username).cloned())
}
async fn create(&self, _tenant_id: i64, _user: NewUser) -> GarrisonResult<String> {
Err(GarrisonError::Internal(
"stp-mock-not-implemented::".to_string(),
))
}
async fn update(&self, _tenant_id: i64, id: &str, user: UpdateUser) -> GarrisonResult<()> {
if let Some(msg) = self.update_error.lock().clone() {
return Err(GarrisonError::Internal(msg));
}
let mut users = self.users.lock();
let key = users
.values()
.find(|u| u.id == id)
.map(|u| u.username.clone());
if let Some(row) = key.as_deref().and_then(|k| users.get_mut(k)) {
if let Some(username) = user.username {
row.username = username;
}
if let Some(password_hash) = user.password_hash {
row.password_hash = password_hash;
}
if let Some(status) = user.status {
row.status = status;
}
if let Some(last_login_at) = user.last_login_at {
row.last_login_at = Some(last_login_at);
}
}
Ok(())
}
async fn delete(&self, _tenant_id: i64, _id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn list(
&self,
_tenant_id: i64,
_offset: i64,
_limit: i64,
) -> GarrisonResult<Vec<UserListRow>> {
Ok(vec![])
}
}
pub struct MockInterfaceWithLoginType {
pub perms: HashMap<String, Vec<String>>,
pub roles: HashMap<String, Vec<String>>,
}
#[async_trait]
impl GarrisonInterface for MockInterfaceWithLoginType {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.perms.get("default").cloned().unwrap_or_default())
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.roles.get("default").cloned().unwrap_or_default())
}
async fn get_permission_list_with_type(
&self,
_login_id: &str,
login_type: &str,
) -> GarrisonResult<Vec<String>> {
Ok(self.perms.get(login_type).cloned().unwrap_or_default())
}
async fn get_role_list_with_type(
&self,
_login_id: &str,
login_type: &str,
) -> GarrisonResult<Vec<String>> {
Ok(self.roles.get(login_type).cloned().unwrap_or_default())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[tokio::test]
async fn mock_dao_default_trait_methods_coverage() {
use crate::dao::GarrisonDao;
let dao = MockDao::new();
dao.set("k1", "v1", 60).await.unwrap();
let _ = dao.set_if_absent("a1", "v1", 60).await;
let _ = dao.get_and_delete("a1").await;
let _ = dao.incr("ctr", 60).await;
let _ = dao.decr("ctr").await;
let _ = dao.rename("k1", "k2").await;
let _ = dao.compare_and_swap("k2", Some("v1"), "v2", 60).await;
let _ = dao.set_permanent("perm", "val").await;
let _ = dao.get_with_ttl("k1").await;
let _ = dao.keys("*").await;
let _ = dao.find_social_binding(0, "wechat", "openid").await;
let _ = dao
.insert_social_binding(0, "1001", "wechat", "openid", None, 0)
.await;
let _ = dao.compare_and_update_if_greater("k1", 10, 60).await;
let _ = dao.eval_lua("return 1", vec![], vec![]).await;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
{
let _ = dao
.insert_credit_consumption(0, "meter", 1, 100, 100, 0)
.await;
let _ = dao.query_credit_consumption(0, 0, 0).await;
let _ = dao.query_role_hierarchy_edges(0).await;
let _ = dao.insert_role_hierarchy_edge(0, "child", "parent").await;
let _ = dao.delete_role_hierarchy_edge(0, "child", "parent").await;
}
}
#[tokio::test]
async fn mock_dao_set_then_get_returns_value() {
let dao = MockDao::new();
dao.set("k1", "v1", 0).await.unwrap();
let v = dao.get("k1").await.unwrap();
assert_eq!(v.as_deref(), Some("v1"));
}
#[tokio::test]
async fn mock_dao_get_missing_returns_none() {
let dao = MockDao::new();
let v = dao.get("no-such-key").await.unwrap();
assert!(v.is_none(), "不存在的 key 应返回 None");
}
#[tokio::test]
async fn mock_dao_update_existing_key() {
let dao = MockDao::new();
dao.set("k1", "v1", 0).await.unwrap();
dao.update("k1", "v2").await.unwrap();
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("v2"));
}
#[tokio::test]
async fn mock_dao_update_missing_key_returns_error() {
let dao = MockDao::new();
let result = dao.update("missing", "v").await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("missing")),
"update 不存在的 key 应返回 Dao 错误包含 key 名,实际: {:?}",
result
);
}
#[tokio::test]
async fn mock_dao_expire_missing_key_returns_error() {
let dao = MockDao::new();
let result = dao.expire("missing", 60).await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"expire 不存在的 key 应返回 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn mock_dao_expire_zero_seconds_clears_ttl() {
let dao = MockDao::new();
dao.set("k1", "v1", 60).await.unwrap();
dao.expire("k1", 0).await.unwrap();
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("v1"));
let t = dao.get_timeout("k1").await.unwrap();
assert!(
t.is_none(),
"expire 0 后应无 deadline,get_timeout 返回 None"
);
}
#[tokio::test]
async fn mock_dao_delete_removes_key() {
let dao = MockDao::new();
dao.set("k1", "v1", 0).await.unwrap();
dao.delete("k1").await.unwrap();
assert!(dao.get("k1").await.unwrap().is_none());
}
#[tokio::test]
async fn mock_dao_delete_missing_key_is_idempotent() {
let dao = MockDao::new();
assert!(dao.delete("missing").await.is_ok());
}
#[tokio::test]
async fn mock_dao_get_timeout_missing_returns_none() {
let dao = MockDao::new();
let t = dao.get_timeout("missing").await.unwrap();
assert!(t.is_none());
}
#[tokio::test]
async fn mock_dao_get_timeout_permanent_key_returns_none() {
let dao = MockDao::new();
dao.set("perm", "v", 0).await.unwrap();
assert!(dao.get_timeout("perm").await.unwrap().is_none());
}
#[tokio::test]
async fn mock_dao_get_timeout_returns_some_for_ttl_key() {
let dao = MockDao::new();
dao.set("k1", "v1", 3600).await.unwrap();
let t = dao.get_timeout("k1").await.unwrap();
assert!(t.is_some(), "带 TTL 的 key get_timeout 应返回 Some");
let d = t.unwrap();
assert!(d.as_secs() <= 3600, "剩余时间应 <= 3600s,实际: {:?}", d);
}
#[tokio::test]
async fn mock_dao_get_expired_key_returns_none() {
let dao = MockDao::new();
dao.set("expiring", "v", 1).await.unwrap();
assert_eq!(dao.get("expiring").await.unwrap().as_deref(), Some("v"));
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
assert!(
dao.get("expiring").await.unwrap().is_none(),
"过期 key 应返回 None"
);
}
#[tokio::test]
async fn mock_dao_get_timeout_expired_returns_none() {
let dao = MockDao::new();
dao.set("k1", "v1", 1).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
let t = dao.get_timeout("k1").await.unwrap();
assert!(
t.is_none(),
"deadline <= now 时 get_timeout 应返回 None,实际: {:?}",
t
);
}
#[tokio::test]
async fn mock_dao_expire_extends_ttl() {
let dao = MockDao::new();
dao.set("k1", "v1", 1).await.unwrap();
dao.expire("k1", 3600).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
assert_eq!(
dao.get("k1").await.unwrap().as_deref(),
Some("v1"),
"expire 续期后 key 应仍可读"
);
}
#[tokio::test]
async fn mock_firewall_returns_configured_booleans() {
let fw = MockFirewall {
has_permission: true,
has_role: false,
};
assert!(fw.check_permission("u1", "p1").await.unwrap());
assert!(!fw.check_role("u1", "r1").await.unwrap());
}
#[tokio::test]
async fn mock_firewall_check_role_any_returns_has_role() {
let fw = MockFirewall {
has_permission: false,
has_role: true,
};
assert!(fw.check_role_any("u1", &["a", "b"]).await.unwrap());
}
#[tokio::test]
async fn mock_firewall_check_role_all_returns_has_role() {
let fw = MockFirewall {
has_permission: false,
has_role: false,
};
assert!(!fw.check_role_all("u1", &["a", "b"]).await.unwrap());
}
#[tokio::test]
async fn mock_firewall_get_lists_return_empty() {
let fw = MockFirewall {
has_permission: true,
has_role: true,
};
assert_eq!(
fw.get_permission_list("u1").await.unwrap(),
Vec::<String>::new()
);
assert_eq!(fw.get_role_list("u1").await.unwrap(), Vec::<String>::new());
}
#[tokio::test]
async fn mock_interface_returns_empty_lists() {
let iface = MockInterface;
assert_eq!(
iface.get_permission_list("u1").await.unwrap(),
Vec::<String>::new()
);
assert_eq!(
iface.get_role_list("u1").await.unwrap(),
Vec::<String>::new()
);
let _ = iface
.get_permission_list_with_type("u1", "default")
.await
.unwrap();
let _ = iface
.get_role_list_with_type("u1", "default")
.await
.unwrap();
}
#[tokio::test]
async fn mock_interface_with_perms_returns_configured_lists() {
let iface = MockInterfaceWithPerms {
permissions: vec!["user:read".to_string(), "user:write".to_string()],
roles: vec!["admin".to_string()],
};
assert_eq!(
iface.get_permission_list("u1").await.unwrap(),
vec!["user:read".to_string(), "user:write".to_string()]
);
assert_eq!(
iface.get_role_list("u1").await.unwrap(),
vec!["admin".to_string()]
);
let _ = iface
.get_permission_list_with_type("u1", "default")
.await
.unwrap();
let _ = iface
.get_role_list_with_type("u1", "default")
.await
.unwrap();
}
#[tokio::test]
async fn mock_interface_with_login_type_returns_perms_by_type() {
let mut perms = HashMap::new();
perms.insert(
"admin".to_string(),
vec!["admin:read".to_string(), "admin:write".to_string()],
);
perms.insert("user".to_string(), vec!["user:read".to_string()]);
let iface = MockInterfaceWithLoginType {
perms,
roles: HashMap::new(),
};
assert_eq!(
iface
.get_permission_list_with_type("u1", "admin")
.await
.unwrap(),
vec!["admin:read".to_string(), "admin:write".to_string()]
);
assert_eq!(
iface
.get_permission_list_with_type("u1", "user")
.await
.unwrap(),
vec!["user:read".to_string()]
);
assert_eq!(
iface
.get_permission_list_with_type("u1", "unknown")
.await
.unwrap(),
Vec::<String>::new()
);
}
#[tokio::test]
async fn mock_interface_with_login_type_returns_roles_by_type() {
let mut roles = HashMap::new();
roles.insert("admin".to_string(), vec!["super-admin".to_string()]);
let iface = MockInterfaceWithLoginType {
perms: HashMap::new(),
roles,
};
assert_eq!(
iface.get_role_list_with_type("u1", "admin").await.unwrap(),
vec!["super-admin".to_string()]
);
assert_eq!(
iface.get_role_list_with_type("u1", "user").await.unwrap(),
Vec::<String>::new()
);
}
#[tokio::test]
async fn mock_interface_with_login_type_default_uses_default_key() {
let mut perms = HashMap::new();
perms.insert("default".to_string(), vec!["default:perm".to_string()]);
let iface = MockInterfaceWithLoginType {
perms,
roles: HashMap::new(),
};
assert_eq!(
iface.get_permission_list("u1").await.unwrap(),
vec!["default:perm".to_string()]
);
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
mod user_repo_tests {
use super::*;
fn make_row(id: &str, username: &str) -> UserRow {
UserRow {
id: id.to_string(),
username: username.to_string(),
password_hash: "hash".to_string(),
status: "active".to_string(),
tenant_id: 0,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
last_login_at: None,
}
}
#[tokio::test]
async fn mock_user_repo_find_by_username_returns_some() {
let repo = MockUserRepository::new();
repo.insert(make_row("u-1", "alice"));
let r = repo.find_by_username(0, "alice").await.unwrap();
assert!(r.is_some(), "插入后 find_by_username 应返回 Some");
assert_eq!(r.unwrap().id, "u-1");
}
#[tokio::test]
async fn mock_user_repo_find_by_username_missing_returns_none() {
let repo = MockUserRepository::new();
let r = repo.find_by_username(0, "nobody").await.unwrap();
assert!(r.is_none(), "未插入用户 find_by_username 应返回 None");
}
#[tokio::test]
async fn mock_user_repo_find_by_id_returns_some() {
let repo = MockUserRepository::new();
repo.insert(make_row("u-42", "alice"));
let r = repo.find_by_id(0, "u-42").await.unwrap();
assert!(r.is_some(), "插入后 find_by_id 应返回 Some");
assert_eq!(r.unwrap().username, "alice");
}
#[tokio::test]
async fn mock_user_repo_find_by_id_missing_returns_none() {
let repo = MockUserRepository::new();
let r = repo.find_by_id(0, "missing").await.unwrap();
assert!(r.is_none());
}
#[tokio::test]
async fn mock_user_repo_create_returns_internal_error() {
let repo = MockUserRepository::new();
let new_user = NewUser {
username: "new".to_string(),
password_hash: "hash".to_string(),
status: "active".to_string(),
};
let result = repo.create(0, new_user).await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("stp-mock-not-implemented")),
"create 应返回 Internal 错误包含 'stp-mock-not-implemented',实际: {:?}",
result
);
}
#[tokio::test]
async fn mock_user_repo_update_returns_ok() {
let repo = MockUserRepository::new();
let update = UpdateUser {
username: None,
password_hash: Some("new-hash".to_string()),
status: Some("inactive".to_string()),
last_login_at: None,
};
repo.update(0, "any-id", update).await.unwrap();
}
#[tokio::test]
async fn mock_user_repo_delete_returns_ok() {
let repo = MockUserRepository::new();
repo.delete(0, "any-id").await.unwrap();
}
#[tokio::test]
async fn mock_user_repo_list_returns_empty() {
let repo = MockUserRepository::new();
let v = repo.list(0, 0, 10).await.unwrap();
assert!(v.is_empty(), "list 应返回空 Vec,实际长度: {}", v.len());
}
}
}