#!/usr/bin/env python3 """ 收入完整性检测算法测试运行脚本 用法: python run_tests.py # 运行所有测试 python run_tests.py -v # 详细输出 python run_tests.py test_revenue_integrity.py # 只运行收入检测测试 python run_tests.py -k "normal" # 运行名称包含"normal"的测试 python run_tests.py --html=report.html # 生成HTML报告 """ import os import sys import subprocess import argparse from pathlib import Path # 设置Python路径 PROJECT_ROOT = Path(__file__).parent sys.path.insert(0, str(PROJECT_ROOT)) def main(): parser = argparse.ArgumentParser(description="运行收入完整性检测算法测试") parser.add_argument( "test_path", nargs="?", default="app/tests/test_revenue_integrity.py", help="测试文件路径(默认为收入完整性测试)" ) parser.add_argument( "-v", "--verbose", action="store_true", help="详细输出" ) parser.add_argument( "-k", "--keyword", help="运行名称包含关键字的测试" ) parser.add_argument( "--html", help="生成HTML测试报告" ) parser.add_argument( "--cov", action="store_true", help="生成代码覆盖率报告" ) parser.add_argument( "--no-header", action="store_true", help="不显示头部信息" ) args = parser.parse_args() # 显示头部信息 if not args.no_header: print("=" * 80) print("收入完整性检测算法测试运行器") print("=" * 80) print() # 构建pytest命令 pytest_cmd = ["python", "-m", "pytest"] # 添加测试路径 pytest_cmd.append(args.test_path) # 添加详细输出 if args.verbose: pytest_cmd.append("-v") pytest_cmd.append("-s") else: pytest_cmd.append("-v") # 添加关键字过滤 if args.keyword: pytest_cmd.append(f"-k {args.keyword}") # 添加HTML报告 if args.html: pytest_cmd.append(f"--html={args.html}") pytest_cmd.append("--self-contained-html") # 添加覆盖率报告 if args.cov: pytest_cmd.append("--cov=app/services/risk_detection/algorithms/revenue_integrity") pytest_cmd.append("--cov-report=html:htmlcov") pytest_cmd.append("--cov-report=term-missing") # 添加更多有用的选项 pytest_cmd.extend([ "--tb=short", # 简短的错误回溯 "--strict-markers", # 严格标记模式 "--disable-warnings", # 禁用警告(如果需要可以移除) ]) # 显示要执行的命令 if not args.no_header: print(f"执行命令: {' '.join(pytest_cmd)}") print() # 运行测试 try: result = subprocess.run(pytest_cmd, cwd=PROJECT_ROOT) # 显示结果摘要 print() print("=" * 80) if result.returncode == 0: print("✓ 所有测试通过!") else: print("✗ 部分测试失败") print("=" * 80) sys.exit(result.returncode) except KeyboardInterrupt: print("\n测试被用户中断") sys.exit(1) except Exception as e: print(f"运行测试时出错: {e}") sys.exit(1) if __name__ == "__main__": main()