Unittest测试套件重复执行单测试脚本,需实现单次执行并生成报告
解决Unittest测试脚本重复执行两次的问题
嘿,我一眼就看出问题所在了——你把测试套件的构建和执行逻辑写在了一个继承自unittest.TestCase的类里面!这是Unittest使用中的典型误区:
Unittest框架会自动识别所有继承自TestCase的类作为测试用例类,而你在SmokeTestSuite类的定义里直接写了执行代码(不是在以test_开头的方法里),这就导致:
- 当测试加载器扫描到这个类时,会先执行类定义里的代码(也就是你写的构建套件、运行测试的逻辑);
- 如果这个类还被不小心加入到了测试集合中,或者框架本身对TestCase类的处理触发了额外执行,就会导致你的
xyz_test_class被跑两次。
修正方案
把测试套件的逻辑从TestCase类中抽出来,改成独立的执行入口,具体代码如下:
import unittest import os import time import HTMLTestRunner # 注意这里导入要小写,原代码的大写Import是错误的 def run_smoke_suite(): print('Running test suite') dir_path = os.getcwd() test_loader = unittest.TestLoader() # 要执行的测试类列表 test_classes_to_run = [xyz_test_class] suites_list = [] for test_class in test_classes_to_run: suite = test_loader.loadTestsFromTestCase(test_class) suites_list.append(suite) print(f"Loaded test suites: {suites_list}") combined_suite = unittest.TestSuite(suites_list) print(f"Total test cases to run: {combined_suite.countTestCases()}") # 生成带时间戳的报告文件 timestr = time.strftime("_%Y-%m-%d_%H.%M.%S") report_path = os.path.join(dir_path, f"TestReport{timestr}.html") with open(report_path, "w") as result_file: runner = HTMLTestRunner.HTMLTestRunner( stream=result_file, title='Test Report', description='Tests Execution Report' ) runner.run(combined_suite) if __name__ == '__main__': run_smoke_suite()
关键修改点说明
- 移除了不必要的
SmokeTestSuite(unittest.TestCase)类:测试套件不需要继承TestCase,TestCase是用来写单个测试用例的,而测试套件是用来组织多个测试用例/类的。 - 将套件逻辑封装到函数
run_smoke_suite中,并通过if __name__ == '__main__':作为入口:这样只有当你直接运行这个脚本时才会执行测试,避免被其他模块导入时意外触发执行。 - 修正了导入语句的大小写错误(原代码
Import→import),补充了缺失的unittest、os、time模块导入。 - 使用
with语句管理报告文件的打开:更安全,能自动处理文件关闭。
这样修改后,你的xyz_test_class就只会被加载并执行一次,同时能正常生成HTML测试报告啦!
内容的提问来源于stack exchange,提问作者Ramaajun
相关产品推荐
相关产品推荐

