-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_tests.py
More file actions
91 lines (74 loc) · 2.71 KB
/
Copy pathrun_tests.py
File metadata and controls
91 lines (74 loc) · 2.71 KB
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
"""运行所有测试的脚本。"""
import argparse
import importlib
import os
import sys
from dotenv import load_dotenv
def run_test(test_name: str) -> bool:
"""运行指定的测试
Args:
test_name: 测试名称
Returns:
是否成功
"""
try:
# 导入测试模块
module_name = f"tests.{test_name}"
# 使用 unittest 运行测试
import unittest
# 尝试加载测试模块
try:
# 先尝试作为 unittest 测试运行
test_suite = unittest.defaultTestLoader.loadTestsFromName(module_name)
test_runner = unittest.TextTestRunner(verbosity=2)
result = test_runner.run(test_suite)
return result.wasSuccessful()
except (ImportError, AttributeError):
# 如果不是 unittest 测试,尝试作为普通模块运行
module = importlib.import_module(module_name)
if hasattr(module, "main"):
module.main()
return True
else:
print(f"错误: 测试模块 {module_name} 没有 main 函数,也不是 unittest 测试")
return False
except ImportError as e:
print(f"错误: 无法导入测试模块 {module_name}: {str(e)}")
return False
except Exception as e:
print(f"错误: 运行测试 {test_name} 失败: {str(e)}")
return False
def main() -> None:
"""主函数"""
# 解析命令行参数
parser = argparse.ArgumentParser(description="运行测试")
parser.add_argument("--test", type=str, help="要运行的测试名称,不包含 'test_' 前缀和 '.py' 后缀")
parser.add_argument("--all", action="store_true", help="运行所有测试")
args = parser.parse_args()
# 加载环境变量
load_dotenv()
# 确保当前目录在 Python 路径中
sys.path.insert(0, os.path.abspath("."))
# 运行测试
if args.test:
# 运行指定的测试
test_name = f"test_{args.test}" if not args.test.startswith("test_") else args.test
success = run_test(test_name)
sys.exit(0 if success else 1)
elif args.all:
# 运行所有测试
test_dir = os.path.join(os.path.dirname(__file__), "tests")
test_files = [f[:-3] for f in os.listdir(test_dir) if f.startswith("test_") and f.endswith(".py")]
success = True
for test_file in test_files:
print(f"\n运行测试: {test_file}")
print("=" * 80)
if not run_test(test_file):
success = False
print("=" * 80)
sys.exit(0 if success else 1)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()