use super::mock::{AlwaysDegraded, AlwaysHealthy, AlwaysUnhealthy};
use super::*;
use crate::config::GarrisonConfig;
use std::sync::Arc;
#[cfg(any(feature = "db-postgres", feature = "db-mysql", feature = "cache-redis"))]
struct HangDao;
#[cfg(any(feature = "db-postgres", feature = "db-mysql", feature = "cache-redis"))]
#[async_trait::async_trait]
impl crate::dao::GarrisonDao for HangDao {
async fn get(&self, _key: &str) -> crate::error::GarrisonResult<Option<String>> {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
Ok(None)
}
async fn set(
&self,
_key: &str,
_value: &str,
_ttl_seconds: u64,
) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn update(&self, _key: &str, _value: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
}
#[test]
fn health_status_serializes_to_lowercase() {
assert_eq!(
serde_json::to_string(&HealthStatus::Healthy).unwrap(),
"\"healthy\""
);
assert_eq!(
serde_json::to_string(&HealthStatus::Degraded).unwrap(),
"\"degraded\""
);
assert_eq!(
serde_json::to_string(&HealthStatus::Unhealthy).unwrap(),
"\"unhealthy\""
);
}
#[test]
fn health_status_deserializes_from_lowercase() {
let s: HealthStatus = serde_json::from_str("\"healthy\"").unwrap();
assert_eq!(s, HealthStatus::Healthy);
let s: HealthStatus = serde_json::from_str("\"degraded\"").unwrap();
assert_eq!(s, HealthStatus::Degraded);
let s: HealthStatus = serde_json::from_str("\"unhealthy\"").unwrap();
assert_eq!(s, HealthStatus::Unhealthy);
}
#[test]
fn health_status_equality() {
assert_ne!(HealthStatus::Healthy, HealthStatus::Unhealthy);
assert_eq!(HealthStatus::Healthy, HealthStatus::Healthy);
}
#[tokio::test]
async fn empty_registry_returns_healthy() {
let registry = HealthRegistry::new();
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Healthy);
assert!(report.checks.is_empty());
}
#[tokio::test]
async fn registry_all_healthy_returns_healthy() {
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysHealthy));
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Healthy);
assert_eq!(report.checks.len(), 1);
assert_eq!(report.checks[0].name, "always-healthy");
assert_eq!(report.checks[0].status, HealthStatus::Healthy);
}
#[tokio::test]
async fn registry_with_unhealthy_returns_unhealthy() {
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysHealthy));
registry.register(Box::new(AlwaysUnhealthy));
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Unhealthy);
assert_eq!(report.checks.len(), 2);
let unhealthy_check = report
.checks
.iter()
.find(|c| c.name == "always-unhealthy")
.expect("should have always-unhealthy check");
assert_eq!(unhealthy_check.status, HealthStatus::Unhealthy);
assert!(unhealthy_check.message.is_some());
}
#[tokio::test]
async fn registry_with_degraded_and_no_unhealthy_returns_degraded() {
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysHealthy));
registry.register(Box::new(AlwaysDegraded));
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Degraded);
}
#[tokio::test]
async fn registry_unhealthy_overrides_degraded() {
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysDegraded));
registry.register(Box::new(AlwaysUnhealthy));
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Unhealthy);
}
#[tokio::test]
async fn config_health_check_returns_healthy_for_valid_config() {
let config = Arc::new(GarrisonConfig::default_config());
let checker = ConfigHealthCheck::new(config);
assert_eq!(checker.name(), "config");
let result = checker.check().await.unwrap();
assert_eq!(result, HealthStatus::Healthy);
}
#[tokio::test]
async fn config_health_check_returns_unhealthy_for_invalid_config() {
let mut config = GarrisonConfig::default_config();
config.timeout = -1; let checker = ConfigHealthCheck::new(Arc::new(config));
let result = checker.check().await;
assert!(result.is_err());
}
#[cfg(all(feature = "cache-memory", not(feature = "cache-redis")))]
#[tokio::test]
async fn cache_health_check_returns_healthy() {
let checker = CacheHealthCheck::new();
assert_eq!(checker.name(), "cache");
let result = checker.check().await.unwrap();
assert_eq!(result, HealthStatus::Healthy);
}
#[cfg(all(
feature = "db-sqlite",
not(any(feature = "db-postgres", feature = "db-mysql"))
))]
#[tokio::test]
async fn db_health_check_returns_healthy() {
let checker = DbHealthCheck::new();
assert_eq!(checker.name(), "database");
let result = checker.check().await.unwrap();
assert_eq!(result, HealthStatus::Healthy);
}
#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
#[tokio::test]
#[serial_test::serial]
async fn db_health_check_unhealthy_when_manager_uninitialized() {
crate::manager::GarrisonManager::reset_for_test();
assert!(
!crate::manager::GarrisonManager::is_initialized(),
"测试前置:manager 必须未初始化"
);
let checker = DbHealthCheck::new();
let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
assert_eq!(
status,
HealthStatus::Unhealthy,
"manager 未初始化时 DbHealthCheck 应返回 Unhealthy(而非误报 Healthy)"
);
}
#[cfg(feature = "cache-redis")]
#[tokio::test]
#[serial_test::serial]
async fn cache_health_check_returns_unhealthy_on_probe_timeout() {
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::stp::GarrisonInterface;
use std::time::{Duration, Instant};
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(HangDao);
let config = Arc::new(GarrisonConfig::default_config());
let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
GarrisonManager::init(dao, config, interface)
.expect("init with HangDao 应成功(init 不调用 dao.get)");
assert!(
GarrisonManager::is_initialized(),
"测试前置:manager 必须已初始化"
);
let checker = CacheHealthCheck::new();
let start = Instant::now();
let status = checker
.check()
.await
.expect("check 应返回 Ok 而非 Err(超时映射为 Unhealthy,不是 Err)");
let elapsed = start.elapsed();
assert_eq!(
status,
HealthStatus::Unhealthy,
"dao hang 时 CacheHealthCheck 应在 HEALTH_PROBE_TIMEOUT 内返回 Unhealthy"
);
assert!(
elapsed < Duration::from_secs(5),
"应在 HEALTH_PROBE_TIMEOUT(2s)附近返回,实际耗时: {:?}",
elapsed
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "cache-redis")]
#[tokio::test]
#[serial_test::serial]
async fn cache_health_check_unhealthy_when_manager_uninitialized() {
crate::manager::GarrisonManager::reset_for_test();
assert!(
!crate::manager::GarrisonManager::is_initialized(),
"测试前置:manager 必须未初始化"
);
let checker = CacheHealthCheck::new();
let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
assert_eq!(
status,
HealthStatus::Unhealthy,
"manager 未初始化时 CacheHealthCheck 应返回 Unhealthy(而非误报 Healthy)"
);
}
#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
#[tokio::test]
#[serial_test::serial]
async fn db_health_check_returns_unhealthy_on_probe_timeout() {
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::stp::GarrisonInterface;
use std::time::{Duration, Instant};
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(HangDao);
let config = Arc::new(GarrisonConfig::default_config());
let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
GarrisonManager::init(dao, config, interface)
.expect("init with HangDao 应成功(init 不调用 dao.get)");
assert!(
GarrisonManager::is_initialized(),
"测试前置:manager 必须已初始化"
);
let checker = DbHealthCheck::new();
let start = Instant::now();
let status = checker
.check()
.await
.expect("check 应返回 Ok 而非 Err(超时映射为 Unhealthy,不是 Err)");
let elapsed = start.elapsed();
assert_eq!(
status,
HealthStatus::Unhealthy,
"dao hang 时 DbHealthCheck 应在 HEALTH_PROBE_TIMEOUT 内返回 Unhealthy"
);
assert!(
elapsed < Duration::from_secs(5),
"应在 HEALTH_PROBE_TIMEOUT(2s)附近返回,实际耗时: {:?}",
elapsed
);
GarrisonManager::reset_for_test();
}
#[test]
fn health_report_serializes_correctly() {
let report = HealthReport {
overall: HealthStatus::Degraded,
checks: vec![CheckResult {
name: "cache".to_string(),
status: HealthStatus::Degraded,
message: Some("high latency".to_string()),
}],
};
let json = serde_json::to_string(&report).unwrap();
assert!(json.contains("\"overall\":\"degraded\""));
assert!(json.contains("\"name\":\"cache\""));
assert!(json.contains("\"status\":\"degraded\""));
assert!(json.contains("\"message\":\"high latency\""));
}
#[test]
fn health_report_skips_none_message() {
let report = HealthReport {
overall: HealthStatus::Healthy,
checks: vec![CheckResult {
name: "config".to_string(),
status: HealthStatus::Healthy,
message: None,
}],
};
let json = serde_json::to_string(&report).unwrap();
assert!(!json.contains("message"));
}
#[cfg(feature = "web-axum")]
#[tokio::test]
async fn test_axum_live_returns_200() {
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
let registry = Arc::new(HealthRegistry::new());
let app = super::axum_routes::health_routes(registry);
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/health/live")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[cfg(feature = "web-axum")]
#[tokio::test]
async fn test_axum_ready_returns_200_when_healthy() {
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysHealthy));
let app = super::axum_routes::health_routes(Arc::new(registry));
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[cfg(feature = "web-axum")]
#[tokio::test]
async fn test_axum_ready_returns_200_when_degraded() {
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysDegraded));
let app = super::axum_routes::health_routes(Arc::new(registry));
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[cfg(feature = "web-axum")]
#[tokio::test]
async fn test_axum_ready_returns_503_when_unhealthy() {
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysUnhealthy));
let app = super::axum_routes::health_routes(Arc::new(registry));
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[cfg(feature = "web-warp")]
#[tokio::test]
async fn test_warp_live_filter_returns_200() {
use super::warp_routes::live_filter;
use warp::http::StatusCode;
let resp = warp::test::request()
.method("GET")
.path("/health/live")
.reply(&live_filter())
.await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[cfg(feature = "web-warp")]
#[tokio::test]
async fn test_warp_ready_filter_returns_200_when_healthy() {
use super::warp_routes::ready_filter;
use warp::http::StatusCode;
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysHealthy));
let filter = ready_filter(Arc::new(registry));
let resp = warp::test::request()
.method("GET")
.path("/health/ready")
.reply(&filter)
.await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[cfg(feature = "web-warp")]
#[tokio::test]
async fn test_warp_ready_filter_returns_503_when_unhealthy() {
use super::warp_routes::ready_filter;
use warp::http::StatusCode;
let mut registry = HealthRegistry::new();
registry.register(Box::new(AlwaysUnhealthy));
let filter = ready_filter(Arc::new(registry));
let resp = warp::test::request()
.method("GET")
.path("/health/ready")
.reply(&filter)
.await;
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn test_health_registry_default() {
let registry = HealthRegistry::default();
let report = registry.check_all().await;
assert_eq!(report.overall, HealthStatus::Healthy);
assert!(report.checks.is_empty());
}
#[test]
fn test_health_report_empty() {
let report = HealthReport::empty();
assert_eq!(report.overall, HealthStatus::Healthy);
assert!(report.checks.is_empty());
}
#[tokio::test]
async fn test_health_registry_register_chain() {
let mut registry = HealthRegistry::new();
registry
.register(Box::new(AlwaysHealthy))
.register(Box::new(AlwaysDegraded));
let report = registry.check_all().await;
assert_eq!(report.checks.len(), 2);
assert_eq!(report.overall, HealthStatus::Degraded);
}