garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 健康检查模块单元测试。
//!
//! 通过 `mod.rs` 中的 `#[cfg(test)] mod tests;` 引入。

use super::mock::{AlwaysDegraded, AlwaysHealthy, AlwaysUnhealthy, HangingCheck, PanickingCheck};
use super::*;
use crate::config::GarrisonConfig;
use std::sync::Arc;

// 测试 fixture:HangDao(探测路径超时测试共享)

/// Hang DAO:`get` sleep 10s(远超 `HEALTH_PROBE_TIMEOUT` 2s)模拟数据库/Redis 后端
/// 网络不可达,其他方法返回 `Ok`;仅探测路径(db-postgres / db-mysql / cache-redis)编译。
#[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(())
    }

    crate::atomic_test_fallback!();
}

// HealthStatus 测试

#[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);
}

// HealthRegistry 测试

#[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);
}

/// `with_check_timeout` 覆盖默认 5 秒护栏,供超时测试压到毫秒级。
#[test]
fn with_check_timeout_overrides_default() {
    let registry = HealthRegistry::new().with_check_timeout(std::time::Duration::from_millis(50));
    assert_eq!(registry.check_timeout, std::time::Duration::from_millis(50));
}

/// 检查体 panic 按 Unhealthy 聚合(panic 隔离),不拖垮其余检查项。
#[tokio::test]
async fn registry_panicking_check_is_isolated_as_unhealthy() {
    let mut registry = HealthRegistry::new();
    registry.register(Box::new(AlwaysHealthy));
    registry.register(Box::new(PanickingCheck));
    let report = registry.check_all().await;
    assert_eq!(report.overall, HealthStatus::Unhealthy);
    let panicked = report
        .checks
        .iter()
        .find(|c| c.name == "panicking")
        .expect("应有 panicking 检查项");
    assert_eq!(panicked.status, HealthStatus::Unhealthy);
    assert_eq!(
        panicked.message.as_deref(),
        Some("check failed"),
        "HTTP 响应只暴露通用描述,不泄漏 panic 细节"
    );
}

/// 超时护栏:挂起的检查超过 `check_timeout` 按 Unhealthy 聚合,readiness 不被拖住。
#[tokio::test]
async fn registry_hanging_check_times_out_as_unhealthy() {
    let mut registry =
        HealthRegistry::new().with_check_timeout(std::time::Duration::from_millis(20));
    registry.register(Box::new(HangingCheck));
    let report = registry.check_all().await;
    assert_eq!(report.overall, HealthStatus::Unhealthy);
    assert_eq!(report.checks.len(), 1);
    assert_eq!(report.checks[0].status, HealthStatus::Unhealthy);
}

#[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);
}

// ConfigHealthCheck 测试

#[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());
}

// CacheHealthCheck 测试(feature-gated)

/// 快路径下(仅 `cache-memory`):进程存活即 Healthy(oxcache 内存后端无网络 I/O,无需
/// 探测);探测路径(`cache-redis`)行为由超时/manager 未初始化测试覆盖。
#[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);
}

// DbHealthCheck 测试(feature-gated)

/// 快路径下(仅 `db-sqlite`):进程存活即 Healthy(SQLite 嵌入式数据库无独立服务进程,
/// 无需探测);探测路径(`db-postgres`/`db-mysql`)行为由 manager 未初始化/超时测试覆盖。
#[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);
}

// 健康检查真实探测 + 超时测试(探测路径专属)

/// 探测路径下(`db-postgres` / `db-mysql`),`GarrisonManager` 未初始化时
/// `DbHealthCheck` 返回 `Ok(Unhealthy)`——不误报 `Healthy`,也避免 `Err` 被
/// HealthRegistry 转为通用 "check failed";`db-sqlite-only` 快路径不适用。
#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
#[tokio::test]
#[serial_test::serial]
async fn db_health_check_unhealthy_when_manager_uninitialized() {
    // 确保 manager 未初始化(reset 任何前序测试残留状态)
    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)"
    );
}

/// 探测路径下未注入连接池(`new()` 默认)时返回 `Degraded`(诚实降级,不误报 `Healthy`)。
#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
#[tokio::test]
#[serial_test::serial]
async fn db_health_check_degraded_without_pool() {
    use crate::manager::GarrisonManager;
    use crate::stp::GarrisonInterface;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let config = Arc::new(GarrisonConfig::default_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .expect("init manager 应成功");

    let checker = DbHealthCheck::new();
    let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
    assert_eq!(
        status,
        HealthStatus::Degraded,
        "未注入连接池时 DbHealthCheck 应返回 Degraded(不误报 Healthy)"
    );

    GarrisonManager::reset_for_test();
}

/// 注入连接池后执行真实 ping——数据库可达 → `Healthy`;用 sqlite 内存池验证 `with_pool`
/// 的接线与 ping 调用本身(真实 pg/mysql 连通性由 e2e_matrix 覆盖)。
#[cfg(all(
    any(feature = "db-postgres", feature = "db-mysql"),
    feature = "db-sqlite"
))]
#[tokio::test]
async fn db_health_check_with_pool_pings_real_db() {
    use crate::manager::GarrisonManager;
    use crate::stp::GarrisonInterface;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let config = Arc::new(GarrisonConfig::default_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .expect("init manager 应成功");

    let pool = crate::dao::init_dbnexus("sqlite::memory:")
        .await
        .expect("sqlite 内存池应创建成功");
    let checker = DbHealthCheck::with_pool(pool);
    let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
    assert_eq!(
        status,
        HealthStatus::Healthy,
        "注入连接池且数据库可达时应返回 Healthy(真实 ping 通过)"
    );

    GarrisonManager::reset_for_test();
}

/// 探测路径下(`cache-redis`),`dao.get` hang 时 `CacheHealthCheck` 在
/// `HEALTH_PROBE_TIMEOUT`(2s)内返回 `Unhealthy`,而非等 dao 返回(10s)。
#[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::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .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();
}

/// 探测路径下(`cache-redis`),`GarrisonManager` 未初始化时 `CacheHealthCheck` 返回
/// `Unhealthy`(不误报 `Healthy`);与 `db_health_check_unhealthy_when_manager_uninitialized` 对称。
#[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)"
    );
}

/// 未注入连接池时,即使 manager 的 DAO hang,`DbHealthCheck::check` 也立即返回
/// `Degraded`(诚实降级,不再探测 dao.get);仅在 `db-postgres` / `db-mysql` 探测路径编译。
#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
#[tokio::test]
#[serial_test::serial]
async fn db_health_check_returns_degraded_without_pool_even_when_dao_hangs() {
    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::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .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(无池映射为 Degraded,不是 Err)");
    let elapsed = start.elapsed();

    assert_eq!(
        status,
        HealthStatus::Degraded,
        "未注入连接池时 DbHealthCheck 应诚实降级为 Degraded(不探测 dao.get,不误报 Healthy)"
    );
    assert!(
        elapsed < Duration::from_secs(1),
        "无池分支应立即返回(不等待 dao),实际耗时: {:?}",
        elapsed
    );

    GarrisonManager::reset_for_test();
}

// HealthReport 序列化测试

#[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"));
}

// axum_routes 测试(feature = "web-axum")

/// 测试 axum liveness 探针始终返回 200。
#[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);
}

/// 测试 axum readiness 探针在所有检查健康时返回 200。
#[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);
}

/// 测试 axum readiness 探针在 Degraded 状态时返回 200(降级但可用)。
#[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);
}

/// 测试 axum readiness 探针在 Unhealthy 状态时返回 503。
#[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);
}

// warp_routes 测试(feature = "web-warp")

/// 测试 warp liveness 探针返回 200。
#[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);
}

/// 测试 warp readiness 探针在健康时返回 200。
#[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);
}

/// 测试 warp readiness 探针在 Unhealthy 时返回 503。
#[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);
}

// HealthRegistry Default / register 链式调用测试

/// 测试 HealthRegistry 的 Default 实现返回空 registry。
#[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());
}

/// 测试 HealthReport::empty() 返回空报告且整体状态为 Healthy。
#[test]
fn test_health_report_empty() {
    let report = HealthReport::empty();
    assert_eq!(report.overall, HealthStatus::Healthy);
    assert!(report.checks.is_empty());
}

/// 测试 HealthRegistry::register 链式调用(返回 &mut Self)。
#[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);
}

// 覆盖率补测:Default 实现 + 探测成功分支 + warp 合并 filter

/// 探测路径下(`cache-redis`):`CacheHealthCheck::default()` 与 `new()` 等价,manager
/// 已初始化且 `dao.get` 可达时返回 `Healthy`(覆盖 `Default` 与探测成功分支)。
#[cfg(feature = "cache-redis")]
#[tokio::test]
#[serial_test::serial]
async fn cache_health_check_default_returns_healthy_when_probe_succeeds() {
    use crate::dao::GarrisonDao;
    use crate::manager::GarrisonManager;
    use crate::stp::GarrisonInterface;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let config = Arc::new(GarrisonConfig::default_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .expect("init with InMemoryDao 应成功");

    // Default 实现与 new() 等价(allow:本测试目的就是执行 Default impl,改写为单元结构体字面量会使覆盖失效)
    #[allow(clippy::default_constructed_unit_structs)]
    let checker = CacheHealthCheck::default();
    assert_eq!(checker.name(), "cache");
    let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
    assert_eq!(
        status,
        HealthStatus::Healthy,
        "dao.get 可达(Ok(Ok(_)))时探测应返回 Healthy"
    );

    GarrisonManager::reset_for_test();
}

/// 快路径下(仅 `cache-memory`):`CacheHealthCheck::default()` 等价于 `new()`,
/// 进程存活即 Healthy。
#[cfg(all(feature = "cache-memory", not(feature = "cache-redis")))]
#[tokio::test]
async fn cache_health_check_default_impl_fast_path() {
    //(allow:本测试的目的就是执行 Default impl,改写为单元结构体字面量会使覆盖失效)
    #[allow(clippy::default_constructed_unit_structs)]
    let checker = CacheHealthCheck::default();
    assert_eq!(checker.name(), "cache");
    let result = checker.check().await.unwrap();
    assert_eq!(result, HealthStatus::Healthy);
}

/// 快路径下(仅 `db-sqlite`):`DbHealthCheck::default()` 等价于 `new()`,SQLite 进程存活
/// 即 Healthy;覆盖 `Default` 实现(既有测试仅覆盖 `new()`)。
#[cfg(all(
    feature = "db-sqlite",
    not(any(feature = "db-postgres", feature = "db-mysql"))
))]
#[tokio::test]
async fn db_health_check_default_impl_returns_healthy() {
    //(allow:本测试的目的就是执行 Default impl,改写为单元结构体字面量会使覆盖失效)
    #[allow(clippy::default_constructed_unit_structs)]
    let checker = DbHealthCheck::default();
    assert_eq!(checker.name(), "database");
    let result = checker.check().await.unwrap();
    assert_eq!(result, HealthStatus::Healthy);
}

/// 测试 warp 合并 filter(`health_filters` = live OR ready):
/// `/health/live` 与 `/health/ready` 均可经同一 filter 服务。
#[cfg(feature = "web-warp")]
#[tokio::test]
async fn test_warp_health_filters_serves_live_and_ready() {
    use super::warp_routes::health_filters;
    use warp::http::StatusCode;

    let mut registry = HealthRegistry::new();
    registry.register(Box::new(AlwaysHealthy));
    let filter = health_filters(Arc::new(registry));

    let resp = warp::test::request()
        .method("GET")
        .path("/health/live")
        .reply(&filter)
        .await;
    assert_eq!(resp.status(), StatusCode::OK, "合并 filter 应放行 live");

    let resp = warp::test::request()
        .method("GET")
        .path("/health/ready")
        .reply(&filter)
        .await;
    assert_eq!(resp.status(), StatusCode::OK, "合并 filter 应放行 ready");
}

/// 测试 warp readiness 探针在 Degraded 状态时返回 200(降级但可用)。
///
/// 覆盖 `warp_routes.rs` 中 `Healthy | Degraded => OK` match 臂的 Degraded 半边。
#[cfg(feature = "web-warp")]
#[tokio::test]
async fn test_warp_ready_filter_returns_200_when_degraded() {
    use super::warp_routes::ready_filter;
    use warp::http::StatusCode;

    let mut registry = HealthRegistry::new();
    registry.register(Box::new(AlwaysDegraded));
    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);
}

/// Error DAO:`get` 直接返回 `Err`,用于覆盖探测的 `Ok(Err(_)) → Unhealthy` 分支。
#[cfg(feature = "cache-redis")]
struct ErrorDao;

#[cfg(feature = "cache-redis")]
#[async_trait::async_trait]
impl crate::dao::GarrisonDao for ErrorDao {
    async fn get(&self, _key: &str) -> crate::error::GarrisonResult<Option<String>> {
        Err(crate::error::GarrisonError::Dao(
            "health-probe-error".to_string(),
        ))
    }
    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(())
    }

    crate::atomic_test_fallback!();
}

/// 探测路径下,`dao.get` 返回 `Err` 时 `CacheHealthCheck` 映射为 `Unhealthy`。
///
/// 覆盖 `checks.rs` 中 `Ok(Err(_)) => Unhealthy` 分支(后端显式报错,区别于超时)。
#[cfg(feature = "cache-redis")]
#[tokio::test]
#[serial_test::serial]
async fn cache_health_check_unhealthy_when_probe_errors() {
    use crate::dao::GarrisonDao;
    use crate::manager::GarrisonManager;
    use crate::stp::GarrisonInterface;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(ErrorDao);
    let config = Arc::new(GarrisonConfig::default_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(crate::stp::mock::MockInterface);
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .expect("init with ErrorDao 应成功(init 不调用 dao.get)");

    let checker = CacheHealthCheck::new();
    let status = checker.check().await.expect("check 应返回 Ok 而非 Err");
    assert_eq!(
        status,
        HealthStatus::Unhealthy,
        "dao.get 返回 Err 时探测应映射为 Unhealthy(而非 Err)"
    );

    GarrisonManager::reset_for_test();
}

// actix_routes 测试(feature = "web-actix")

/// actix 健康路由:`/health/live` 恒 200,`/health/ready` 按聚合状态 200 / 503。
#[cfg(feature = "web-actix")]
#[tokio::test]
async fn test_actix_health_routes_serve_live_and_ready() {
    use actix_web::test::{call_service, init_service, TestRequest};
    use actix_web::{http::StatusCode, web, App};

    let healthy = Arc::new(HealthRegistry::new());
    let app = init_service(
        App::new()
            .app_data(web::Data::new(healthy))
            .configure(super::actix_routes::configure_health_routes),
    )
    .await;

    let live = call_service(&app, TestRequest::get().uri("/health/live").to_request()).await;
    assert_eq!(live.status(), StatusCode::OK, "liveness 进程存活即 200");

    let ready = call_service(&app, TestRequest::get().uri("/health/ready").to_request()).await;
    assert_eq!(
        ready.status(),
        StatusCode::OK,
        "空 registry 聚合为 Healthy,readiness 应 200"
    );

    let mut unhealthy = HealthRegistry::new();
    unhealthy.register(Box::new(AlwaysUnhealthy));
    let app = init_service(
        App::new()
            .app_data(web::Data::new(Arc::new(unhealthy)))
            .configure(super::actix_routes::configure_health_routes),
    )
    .await;
    let ready = call_service(&app, TestRequest::get().uri("/health/ready").to_request()).await;
    assert_eq!(
        ready.status(),
        StatusCode::SERVICE_UNAVAILABLE,
        "任一检查项 Unhealthy 时 readiness 应 503"
    );
}