| .. | ||
| services/risk_detection/engine | ||
| conftest.py | ||
| demo_test_success.py | ||
| demo_test.py | ||
| README.md | ||
| run_tests.py | ||
| run_tests.sh | ||
| setup_tests.sh | ||
| test_http_api.py | ||
| TEST_README.md | ||
| test_risk_detection_workflow.py | ||
| TEST_SUMMARY.md | ||
风险检测系统单元测试
本目录包含风险检测系统的所有单元测试。
测试结构
tests/
├── conftest.py # pytest配置和共享fixtures
├── services/
│ └── risk_detection/
│ └── engine/ # 风险检测引擎测试
│ ├── test_dependency_resolver.py # 依赖解析器测试
│ ├── test_execution_plan.py # 执行计划器测试
│ ├── test_result_processor.py # 结果处理器测试
│ └── test_rule_engine.py # 规则引擎测试
└── README.md # 本文件
测试范围
1. 依赖解析器测试 (test_dependency_resolver.py)
- DependencyNode:依赖节点的基本功能
- DependencyGraph:依赖图构建、循环检测、层级计算
- DependencyResolver:依赖分析、验证、执行顺序生成
2. 执行计划器测试 (test_execution_plan.py)
- ExecutionNode:执行节点转换
- ExecutionStage:执行阶段管理
- ExecutionPlan:执行计划构建
- ExecutionPlanner:计划生成(串行/并行/混合模式)
- ExecutionPlanBuilder:手动计划构建
3. 结果处理器测试 (test_result_processor.py)
- DetectionResult:检测结果管理
- RiskEvidence:风险证据管理
- ResultAggregator:结果聚合
- RiskScoreCalculator:风险评分计算
- EvidenceBuilder:证据链构建
- SuggestionGenerator:整改建议生成
- ResultProcessor:结果处理流程
4. 规则引擎测试 (test_rule_engine.py)
- AlgorithmRegistry:算法注册表
- RuleEngine:规则引擎核心功能
- 全局规则引擎实例管理
运行测试
运行所有测试
# 在项目根目录执行
cd backend
python -m pytest tests/ -v
运行特定模块测试
# 运行依赖解析器测试
python -m pytest tests/services/risk_detection/engine/test_dependency_resolver.py -v
# 运行执行计划器测试
python -m pytest tests/services/risk_detection/engine/test_execution_plan.py -v
# 运行结果处理器测试
python -m pytest tests/services/risk_detection/engine/test_result_processor.py -v
# 运行规则引擎测试
python -m pytest tests/services/risk_detection/engine/test_rule_engine.py -v
运行特定测试用例
# 运行特定测试类
python -m pytest tests/services/risk_detection/engine/test_dependency_resolver.py::TestDependencyGraph -v
# 运行特定测试方法
python -m pytest tests/services/risk_detection/engine/test_dependency_resolver.py::TestDependencyGraph::test_has_cycle_with_cycle -v
生成覆盖率报告
# 安装coverage
pip install coverage
# 运行测试并生成覆盖率报告
coverage run -m pytest tests/
# 查看覆盖率报告
coverage report
# 生成HTML覆盖率报告
coverage html
测试数据
测试使用了以下模拟数据:
- 模拟数据库会话 (mock_db_session)
- 模拟检测规则列表 (sample_detection_rules)
- 模拟检测结果 (mock_detection_results)
- 模拟实体信息 (sample_entity_info)
- 模拟充值数据 (sample_recharge_data)
- 模拟申报数据 (sample_declaration_data)
- 模拟合同数据 (sample_contract_data)
- 模拟风险阈值 (sample_risk_thresholds)
测试工具和库
测试使用的主要工具:
- pytest:测试框架
- pytest-asyncio:异步测试支持
- unittest.mock:模拟对象和函数
- coverage:代码覆盖率测试
测试原则
- 独立性:每个测试用例独立运行,不依赖其他测试
- 可重复性:测试结果稳定,多次运行结果一致
- 可读性:测试代码清晰,注释完整
- 覆盖率:核心逻辑覆盖率≥80%
- 边界测试:包含正常、异常、边界值测试
注意事项
- 测试使用模拟对象,不依赖真实数据库
- 异步测试使用pytest.mark.asyncio标记
- 所有测试用例都有断言验证结果
- 测试文件名规范:test_<模块名>.py
- 测试类名规范:Test<组件名>
- 测试方法名规范:test_<功能描述>
添加新测试
添加新测试时,请遵循以下步骤:
- 在相应模块的测试文件中添加测试类
- 使用conftest.py中提供的fixtures
- 添加适当的模拟数据和断言
- 运行测试确保通过
- 检查代码覆盖率
示例:
class TestNewComponent:
def test_new_functionality(self):
"""测试新功能"""
# 准备测试数据
# 执行测试
# 断言结果
assert True