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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 管理器层集成测试模块(`cfg(test)`)。
//!
//! 覆盖 `GarrisonManager` 的初始化、端到端流程、Strategy 注册表、DisableRepository
//! 集成、cleanup task 生命周期等场景。

use super::mock::MockInterface;
use super::*;
use crate::config::GarrisonConfig;
use crate::context::tenant::with_default_tenant;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::session::GarrisonSession;
use crate::stp::util::spawn_cleanup_task;
use crate::stp::{GarrisonInterface, GarrisonUtil, LoginParams, SessionLogic};
use crate::strategy::{GarrisonPermissionStrategy, GarrisonPermissionStrategyDefault};
use async_trait::async_trait;
use serial_test::serial;

// 辅助函数

/// 创建默认测试配置(timeout=3600,throw_on_not_login=false 便于断言)。
fn make_config() -> GarrisonConfig {
    let mut config = GarrisonConfig::default_config();
    config.timeout = 3600;
    config.active_timeout = -1;
    config.throw_on_not_login = false;
    config
}

/// 在 task_local 上下文中执行 future(设置当前 token)。
async fn with_token<R>(token: String, f: impl std::future::Future<Output = R>) -> R {
    crate::stp::with_current_token(token, f).await
}

// 未初始化场景测试

/// 验证未初始化时 `GarrisonManager::logic()` 返回 Session 错误。
#[test]
#[serial]
fn logic_returns_error_when_not_initialized() {
    GarrisonManager::reset_for_test();
    let result = GarrisonManager::logic();
    assert!(result.is_err());
    match result {
        Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init") => {},
        other => panic!("应返回 manager-not-init,实际: {:?}", other.map(|_| ())),
    }
}

/// 验证未初始化时 `GarrisonManager::is_initialized()` 返回 false。
#[test]
#[serial]
fn is_initialized_returns_false_when_not_initialized() {
    GarrisonManager::reset_for_test();
    assert!(!GarrisonManager::is_initialized());
}

// 初始化场景测试

/// 验证 init 后 `is_initialized()` 返回 true。
#[tokio::test]
#[serial]
async fn init_sets_initialized_flag() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(result.is_ok(), "init 应成功: {:?}", result.map(|_| ()));
    assert!(GarrisonManager::is_initialized());
    GarrisonManager::reset_for_test();
}

/// 验证 init 校验配置:timeout=0 抛 Config 错误。
#[tokio::test]
#[serial]
async fn init_rejects_invalid_config() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = GarrisonConfig::default_config();
    config.timeout = 0; // 非法
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        GarrisonError::Config(ref msg) if msg.contains("config-timeout-must-positive")
    ));
    assert!(!GarrisonManager::is_initialized());
    GarrisonManager::reset_for_test();
}

/// 验证 init 处理 active_timeout=-1 的兜底语义(使用 timeout 兜底)。
#[tokio::test]
#[serial]
async fn init_handles_negative_active_timeout() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config()); // active_timeout = -1
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(result.is_ok(), "active_timeout=-1 应使用 timeout 兜底");
    assert!(GarrisonManager::is_initialized());
    GarrisonManager::reset_for_test();
}

// 端到端流程测试(login → check_login → check_permission → logout)

/// 验证完整端到端流程:init → login → check_login → logout → check_login 失败。
#[tokio::test]
#[serial]
async fn end_to_end_login_check_logout() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();
    assert!(GarrisonManager::is_initialized());

    let token = GarrisonUtil::login_simple("1001").await.unwrap();
    assert!(!token.is_empty());

    let is_logged_in = with_token(token.clone(), async { GarrisonUtil::check_login().await })
        .await
        .unwrap();
    assert!(is_logged_in, "登录后 check_login 应返回 true");

    let logout_result = with_token(token.clone(), async { GarrisonUtil::logout().await }).await;
    assert!(
        logout_result.is_ok(),
        "logout 应成功: {:?}",
        logout_result.map(|_| ())
    );

    let is_still_logged_in = with_token(token.clone(), async { GarrisonUtil::check_login().await })
        .await
        .unwrap();
    assert!(!is_still_logged_in, "logout 后 check_login 应返回 false");

    GarrisonManager::reset_for_test();
}

/// 验证权限校验端到端流程:login → check_permission 持有/未持有。
#[tokio::test]
#[serial]
async fn end_to_end_check_permission() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> =
        Arc::new(MockInterface::new().with_permission("1001", &["user:read", "user:write"]));
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    // 持有权限
    let check_result = with_token(token.clone(), async {
        with_default_tenant(async { GarrisonUtil::check_permission("user:read").await }).await
    })
    .await;
    assert!(
        check_result.is_ok(),
        "持有权限应通过: {:?}",
        check_result.map(|_| ())
    );

    // 未持有权限
    let check_result = with_token(token.clone(), async {
        with_default_tenant(async { GarrisonUtil::check_permission("user:delete").await }).await
    })
    .await;
    assert!(check_result.is_err());
    assert!(matches!(
        check_result.unwrap_err(),
        GarrisonError::NotPermission(ref p) if p == "user:delete"
    ));

    GarrisonManager::reset_for_test();
}

/// 验证角色校验端到端流程:login → check_role 持有/未持有。
#[tokio::test]
#[serial]
async fn end_to_end_check_role() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> =
        Arc::new(MockInterface::new().with_role("1001", &["admin"]));
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    // 持有角色
    let check_result = with_token(
        token.clone(),
        with_default_tenant(async { GarrisonUtil::check_role("admin").await }),
    )
    .await;
    assert!(
        check_result.is_ok(),
        "持有角色应通过: {:?}",
        check_result.map(|_| ())
    );

    // 未持有角色
    let check_result = with_token(
        token.clone(),
        with_default_tenant(async { GarrisonUtil::check_role("superadmin").await }),
    )
    .await;
    assert!(check_result.is_err());
    assert!(matches!(
        check_result.unwrap_err(),
        GarrisonError::NotRole(ref r) if r == "superadmin"
    ));

    GarrisonManager::reset_for_test();
}

/// 验证 GarrisonUtil::login 未初始化时抛错。
#[tokio::test]
#[serial]
async fn util_login_fails_when_not_initialized() {
    GarrisonManager::reset_for_test();
    let result = GarrisonUtil::login_simple("1001").await;
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        GarrisonError::Session(ref msg) if msg.contains("manager-not-init")
    ));
}

/// 验证重复 init 覆盖式更新(不抛错)。
#[tokio::test]
#[serial]
async fn init_overwrites_existing() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao.clone())
        .config(config.clone())
        .interface(interface.clone())
        .build()
        .await
        .unwrap();
    assert!(GarrisonManager::is_initialized());

    // 重复 init 应覆盖式更新,不抛错
    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(
        result.is_ok(),
        "重复 init 应覆盖式更新: {:?}",
        result.map(|_| ())
    );
    assert!(GarrisonManager::is_initialized());

    GarrisonManager::reset_for_test();
}

// 验证 inventory 已注册 default factory(编译期 `inventory::submit!` + 运行时单例枚举)。
#[serial]
#[test]
fn default_factory_registered_via_inventory() {
    use std::iter::Iterator;
    let found = inventory::iter::<GarrisonLogicFactoryEntry>()
        .filter(|e| e.name == "default")
        .count();
    assert!(
        found >= 1,
        "应至少注册一个 name='default' 的 factory,实际: {}",
        found
    );
}

/// 验证 default factory 构造的 logic 可正常 login。
#[serial]
#[tokio::test]
async fn default_factory_builds_working_logic() {
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    let timeout = u64::try_from(config.timeout).unwrap();
    let session = Arc::new(GarrisonSession::new(dao, timeout, timeout, 0));
    let firewall: Arc<dyn GarrisonPermissionStrategy> =
        Arc::new(GarrisonPermissionStrategyDefault::new(interface));

    // 构造各字段为 None 的空 context 调用 factory
    #[cfg(feature = "listener")]
    let ctx = GarrisonLogicFactoryContext {
        plugin_manager: None,
        listener_manager: None,
        auth_logic: None,
        permission_checker: None,
        disable_repository: None,
        #[cfg(feature = "three-tier-cache")]
        user_cache_service: None,
    };
    #[cfg(not(feature = "listener"))]
    let ctx = GarrisonLogicFactoryContext {
        plugin_manager: None,
        auth_logic: None,
        permission_checker: None,
        disable_repository: None,
        #[cfg(feature = "three-tier-cache")]
        user_cache_service: None,
    };
    let logic = garrison_logic_factory_default(session, config, firewall, &ctx).unwrap();
    let token = logic.login("1001", &LoginParams::default()).await.unwrap();
    assert!(!token.is_empty());
}

// init 配置分支补充测试

// 验证 builder 处理 active_timeout > 0 的非负值(覆盖 `build_logic` 中 else 分支,不走 timeout 兜底)。
#[tokio::test]
#[serial]
async fn init_with_positive_active_timeout() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = GarrisonConfig::default_config();
    config.timeout = 3600;
    config.active_timeout = 1800; // 正值,走 else 分支
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(
        result.is_ok(),
        "active_timeout=1800 应走 else 分支并成功: {:?}",
        result.map(|_| ())
    );
    assert!(GarrisonManager::is_initialized());

    let token = GarrisonUtil::login_simple("1001").await.unwrap();
    assert!(!token.is_empty());

    GarrisonManager::reset_for_test();
}

// 验证 builder 处理 active_timeout = 0 的边界值(覆盖 `build_logic` 中 else 分支)。
#[tokio::test]
#[serial]
async fn init_with_zero_active_timeout() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = GarrisonConfig::default_config();
    config.timeout = 3600;
    config.active_timeout = 0; // 边界值 0,走 else 分支
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(result.is_ok(), "active_timeout=0 应走 else 分支并成功");
    assert!(GarrisonManager::is_initialized());

    GarrisonManager::reset_for_test();
}

// 验证 builder 校验配置:非法 token_style 抛 Config 错误(覆盖 `build_logic` 中
// `config.validate()?` 的错误分支)。
#[tokio::test]
#[serial]
async fn init_rejects_invalid_token_style() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = GarrisonConfig::default_config();
    config.token_style = "unknown_style".to_string(); // 非法
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(result.is_err());
    assert!(
        matches!(result.unwrap_err(), GarrisonError::Config(ref msg) if msg.contains("config-unknown-token-style")),
        "应返回 'config-unknown-token-style' 错误"
    );
    assert!(!GarrisonManager::is_initialized());

    GarrisonManager::reset_for_test();
}

// builder 兜底路径测试

// 验证 builder 构建成功且后续 login 可正常工作(兜底路径由 `build_logic_via_builder_chain` 单测覆盖)。
#[tokio::test]
#[serial]
async fn builder_build_succeeds_and_login_works() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    let result = GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await;
    assert!(
        result.is_ok(),
        "builder 构建应成功: {:?}",
        result.map(|_| ())
    );
    assert!(GarrisonManager::is_initialized());

    let token = GarrisonUtil::login_simple("1001").await.unwrap();
    assert!(!token.is_empty());

    GarrisonManager::reset_for_test();
}

// MockDao 方法覆盖测试

// 验证 MockDao::expire 和 delete 方法可正常调用(补充此前未直接调用的 trait 方法覆盖)。
#[tokio::test]
async fn mock_dao_expire_and_delete_work() {
    let dao = MockDao::new();
    dao.set("key1", "value1", 3600).await.unwrap();

    dao.expire("key1", 7200).await.unwrap();
    let got = dao.get("key1").await.unwrap();
    assert_eq!(got, Some("value1".to_string()));

    let result = dao.expire("missing", 3600).await;
    assert!(
        matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-key-missing")),
        "expire 不存在的键应返回 Dao(dao-key-missing),实际: {:?}",
        result
    );

    dao.delete("key1").await.unwrap();
    let got = dao.get("key1").await.unwrap();
    assert!(got.is_none());
}

// Strategy 注册表集成测试

/// 验证未初始化时 `GarrisonManager::strategy()` 返回 Session 错误。
#[tokio::test]
#[serial]
async fn strategy_returns_error_when_not_initialized() {
    GarrisonManager::reset_for_test();
    let result = GarrisonManager::strategy();
    match result {
        Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init") => {},
        other => panic!("应返回 manager-not-init,实际: {:?}", other.map(|_| ())),
    }
}

/// 验证 init 后 `strategy()` 返回 `Arc<RwLock<Strategy>>`。
#[tokio::test]
#[serial]
async fn strategy_available_after_init() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let strategy = GarrisonManager::strategy();
    assert!(strategy.is_ok(), "init 后应能获取 strategy");

    GarrisonManager::reset_for_test();
}

// 语义守卫:`logic()` / `strategy()` 多次调用返回同一 Arc 实例,`with_strategy()` 替换后返回新实例。
#[tokio::test]
#[serial]
async fn singleton_arc_identity_preserved() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let a = GarrisonManager::logic().unwrap();
    let b = GarrisonManager::logic().unwrap();
    assert!(Arc::ptr_eq(&a, &b), "logic() 应返回同一 Arc 实例");

    let sa = GarrisonManager::strategy().unwrap();
    let sb = GarrisonManager::strategy().unwrap();
    assert!(Arc::ptr_eq(&sa, &sb), "strategy() 应返回同一 Arc 实例");

    // with_strategy 替换后返回新实例
    let logic = GarrisonManager::logic().unwrap();
    let replacement = Arc::new(RwLock::new(Strategy::new(logic)));
    GarrisonManager::with_strategy(replacement.clone()).unwrap();
    let sc = GarrisonManager::strategy().unwrap();
    assert!(!Arc::ptr_eq(&sa, &sc), "替换后应返回新 Arc 实例");

    GarrisonManager::reset_for_test();
}

/// 验证 `with_strategy()` 整体替换 Strategy 注册表。
#[tokio::test]
#[serial]
async fn with_strategy_replaces_registry() {
    use crate::strategy::LoginHandler;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let logic = GarrisonManager::logic().unwrap();
    let custom_strategy = Arc::new(RwLock::new(Strategy::new(logic)));

    struct CustomLogin;
    #[async_trait]
    impl LoginHandler for CustomLogin {
        async fn handle_login(&self, id: &str) -> GarrisonResult<String> {
            Ok(format!("custom-{}", id))
        }
    }
    custom_strategy
        .write()
        .register_login_handler(Arc::new(CustomLogin));

    GarrisonManager::with_strategy(custom_strategy).unwrap();

    let strategy = GarrisonManager::strategy().unwrap();
    let login_handler = strategy.read().login_handler().clone();
    let token = login_handler.handle_login("1001").await.unwrap();
    assert_eq!(token, "custom-1001", "with_strategy 后应使用自定义策略");

    GarrisonManager::reset_for_test();
}

/// 验证运行时通过 `strategy().write().register_*()` 替换策略立即生效。
#[tokio::test]
#[serial]
async fn runtime_strategy_replacement_takes_effect_immediately() {
    use crate::strategy::LoginHandler;

    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    // 替换前:默认策略生成 token(先 clone Arc 再 await,避免跨 await 持锁)
    let strategy = GarrisonManager::strategy().unwrap();
    let default_handler = strategy.read().login_handler().clone();
    let default_token = default_handler.handle_login("1001").await.unwrap();
    assert!(!default_token.is_empty());

    struct CustomLogin;
    #[async_trait]
    impl LoginHandler for CustomLogin {
        async fn handle_login(&self, id: &str) -> GarrisonResult<String> {
            Ok(format!("runtime-{}", id))
        }
    }
    strategy
        .write()
        .register_login_handler(Arc::new(CustomLogin));

    // 替换后立即生效(先 clone Arc 再 await)
    let custom_handler = strategy.read().login_handler().clone();
    let token = custom_handler.handle_login("1001").await.unwrap();
    assert_eq!(token, "runtime-1001", "运行时替换策略后应立即生效");

    GarrisonManager::reset_for_test();
}

// GarrisonManager 注册 DisableRepository 集成测试

// 验证 init 后 `disable_repository()` 返回 Some,未注册时返回 None。
#[tokio::test]
#[serial]
async fn test_manager_registers_disable_repository() {
    GarrisonManager::reset_for_test();

    assert!(
        GarrisonManager::disable_repository().is_none(),
        "未 init 时 disable_repository() 应返回 None"
    );

    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let repo = GarrisonManager::disable_repository();
    assert!(repo.is_some(), "init 后 disable_repository() 应返回 Some");

    GarrisonManager::reset_for_test();
}

/// 验证通过 disable_repository 封禁用户后,check_disable 返回 DisableService 错误。
#[tokio::test]
#[serial]
async fn test_disable_then_check_disable_errors() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let repo = GarrisonManager::disable_repository().expect("init 后应返回 Some");
    let until = chrono::Utc::now() + chrono::Duration::seconds(3600);
    repo.disable("1001", "default", Some(until), 0, 3600)
        .await
        .unwrap();

    let result = with_token(token, async { GarrisonUtil::check_disable().await }).await;
    match result {
        Err(GarrisonError::DisableService { service, .. }) => {
            assert_eq!(service, "default");
        },
        other => panic!(
            "封禁后 check_disable 应返回 Err(DisableService),实际: {:?}",
            other
        ),
    }

    GarrisonManager::reset_for_test();
}

/// 验证封禁后解封,check_disable 返回 Ok。
#[tokio::test]
#[serial]
async fn test_untie_disable_then_check_disable_ok() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let token = GarrisonUtil::login_simple("1002").await.unwrap();

    let repo = GarrisonManager::disable_repository().expect("init 后应返回 Some");
    repo.disable("1002", "default", None, 0, 0).await.unwrap();

    repo.untie_disable("1002", "default").await.unwrap();

    let result = with_token(token, async { GarrisonUtil::check_disable().await }).await;
    assert!(
        result.is_ok(),
        "解封后 check_disable 应返回 Ok,实际: {:?}",
        result
    );

    GarrisonManager::reset_for_test();
}

/// 验证 disable_repository() 多次调用返回同一实例(Arc 指针相等)。
#[tokio::test]
#[serial]
async fn test_manager_disable_repository_persists() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config());
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let repo1 = GarrisonManager::disable_repository().expect("init 后应返回 Some");
    let repo2 = GarrisonManager::disable_repository().expect("init 后应返回 Some");

    assert!(
        Arc::ptr_eq(&repo1, &repo2),
        "disable_repository() 多次调用应返回同一实例(Arc 指针相等)"
    );

    GarrisonManager::reset_for_test();
}

// spawn_cleanup_task 集成到 GarrisonManager::builder()

// 验证 interval > 0 时 init 后 cleanup task 启动(`cleanup_task_handle` 为 Some)。
#[tokio::test]
#[serial]
async fn manager_init_positive_interval_starts_cleanup_task() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = make_config();
    config.token_map_cleanup_interval_secs = 1;
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    assert!(
        GARRISON_MANAGER.cleanup_task_handle.read().is_some(),
        "interval > 0 时 init 后应启动 cleanup task"
    );

    GarrisonManager::reset_for_test();
}

// 验证 interval = -1 时 init 不启动 cleanup task(`cleanup_task_handle` 为 None)。
#[tokio::test]
#[serial]
async fn manager_init_negative_interval_no_cleanup_task() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = make_config();
    config.token_map_cleanup_interval_secs = -1;
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    assert!(
        GARRISON_MANAGER.cleanup_task_handle.read().is_none(),
        "interval = -1 时 init 不应启动 cleanup task"
    );

    GarrisonManager::reset_for_test();
}

// 验证 init 后 cleanup task 实际运行(timeout=1 TTL + interval=1 每秒清理,login
// 创建 token 后轮询等待其从 `login_token_map` 移除)。
#[tokio::test]
#[serial]
async fn manager_init_cleanup_task_runs_after_init() {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let mut config = make_config();
    config.timeout = 1; // TTL = 1 秒
    config.active_timeout = -1;
    config.token_map_cleanup_interval_secs = 1; // 每秒清理
    let config = Arc::new(config);
    let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());

    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();

    let token = GarrisonUtil::login_simple("1001").await.unwrap();
    assert!(!token.is_empty());

    let logic = GarrisonManager::logic().unwrap();
    assert!(
        logic.session.get_token_by_login_id("1001").is_some(),
        "清理前 token 应存在于 login_token_map"
    );

    // 等待 token TTL 过期 + 清理周期。
    // 不用固定 sleep(CI 慢机器上 3s 余量不足导致 flaky),
    // 改为轮询断言:最长等 10s,token 被清理即提前返回。
    let mut cleaned = false;
    for _ in 0..50 {
        if logic.session.get_token_by_login_id("1001").is_none() {
            cleaned = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    }
    assert!(
        cleaned,
        "清理后 token 应从 login_token_map 移除(TTL=1s + 每秒清理)"
    );

    GarrisonManager::reset_for_test();
}

// 验证 manager drop 时 cleanup task 被取消(局部实例存入 handle,drop 后计数器不再显著增长)。
#[tokio::test]
async fn manager_drop_cancels_cleanup_task() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    // 计数 DAO:get 始终返回 Err,cleanup 每次循环都会调用 get 并计数
    struct CountingDao {
        counter: Arc<AtomicUsize>,
    }
    #[async_trait]
    impl GarrisonDao for CountingDao {
        async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
            self.counter.fetch_add(1, Ordering::SeqCst);
            Err(GarrisonError::Dao("test counting".to_string()))
        }
        async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn delete(&self, _key: &str) -> GarrisonResult<()> {
            Ok(())
        }
        crate::atomic_test_fallback!();
    }

    let counter = Arc::new(AtomicUsize::new(0));
    let dao: Arc<dyn GarrisonDao> = Arc::new(CountingDao {
        counter: counter.clone(),
    });
    let session = Arc::new(GarrisonSession::new(dao, 3600, 86400, 0));
    // 添加 token 到 login_token_map,确保 cleanup 有内容可遍历
    session.add_login_token("user1", "token1");

    let handle = spawn_cleanup_task(session, 1).unwrap();

    let manager = GarrisonManager::new();
    *manager.cleanup_task_handle.write() = Some(Arc::new(handle));

    // 等待 2 个 cleanup 周期(tokio::time::interval 首次 tick 立即返回,第二次在 1 秒后)
    tokio::time::sleep(Duration::from_millis(1500)).await;
    let count_before = counter.load(Ordering::SeqCst);
    assert!(
        count_before >= 2,
        "drop 前 cleanup task 应已运行至少 2 次,实际: {}",
        count_before
    );

    // drop manager — 应 abort cleanup task
    drop(manager);

    // 等待 2 个周期,验证 task 已停止(计数不应显著增长)
    tokio::time::sleep(Duration::from_millis(1500)).await;
    let count_after = counter.load(Ordering::SeqCst);
    assert!(
        count_after <= count_before + 1,
        "drop 后 cleanup task 应已取消,计数不应显著增长。before={}, after={}",
        count_before,
        count_after
    );
}

/// 调用 MockInterface 的默认委托方法以覆盖 async_trait wrapper。
#[tokio::test]
async fn mock_interface_default_methods_with_type_coverage() {
    let iface = MockInterface::new();
    let _ = iface
        .get_permission_list_with_type("u1", "default")
        .await
        .unwrap();
    let _ = iface
        .get_role_list_with_type("u1", "default")
        .await
        .unwrap();
}

/// 调用 CountingDao 的 atomic + 默认 trait 方法以覆盖 async_trait wrapper。
#[tokio::test]
async fn counting_dao_atomic_and_default_methods_coverage() {
    use std::sync::atomic::AtomicUsize;
    struct CountingDao {
        _counter: Arc<AtomicUsize>,
    }
    #[async_trait]
    impl GarrisonDao for CountingDao {
        async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
            Ok(None)
        }
        async fn set(&self, _key: &str, _value: &str, _ttl: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn delete(&self, _key: &str) -> GarrisonResult<()> {
            Ok(())
        }
        crate::atomic_test_fallback!();
    }
    let dao = CountingDao {
        _counter: Arc::new(AtomicUsize::new(0)),
    };
    let _ = dao.set_if_absent("a", "v", 60).await;
    let _ = dao.get_and_delete("a").await;
    let _ = dao.incr("c", 60).await;
    let _ = dao.decr("c").await;
    let _ = dao.rename("a", "b").await;
    let _ = dao.compare_and_swap("b", Some("v"), "v2", 60).await;
    let _ = dao.set_permanent("p", "v").await;
    let _ = dao.get_timeout("k").await;
    let _ = dao.get_with_ttl("k").await;
    let _ = dao.keys("*").await;
    let _ = dao.find_social_binding(0, "w", "o").await;
    let _ = dao.insert_social_binding(0, "u", "w", "o", None, 0).await;
    let _ = dao.compare_and_update_if_greater("k", 1, 60).await;
    let _ = dao.eval_lua("r", vec![], vec![]).await;
    #[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
    {
        let _ = dao.insert_credit_consumption(0, "r", 1, 1, 1, 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, "c", "p").await;
        let _ = dao.delete_role_hierarchy_edge(0, "c", "p").await;
    }
}