如何仅从指定存在的文件加载Python unittest单元测试?
问题:仅针对存在的文件运行指定单元测试
原本使用以下代码运行tests文件夹中的全部单元测试:
suite = unittest.defaultTestLoader.discover('tests')
需要实现逻辑:当e1.py存在时运行test_e1,e5.py存在时运行test_e5,跳过不存在的e2.py、e11.py对应的测试。尝试discover()的pattern参数无法满足需求,改用unittest.TestLoader().loadTestsFromNames()后出现失败测试,输出类似:
<unittest.suite.TestSuite tests=[<unittest.loader._FailedTest testMethod=tests/test_>]>
解决方案
问题核心是loadTestsFromNames()要求的测试名称格式错误,正确格式应为**包名.模块名.测试类名**,而非文件路径格式。以下是两种可行的实现方式:
方式一:基于源文件列表筛选测试
确保tests文件夹是Python包(需包含__init__.py文件),然后调整代码如下:
import os import unittest # 配置源文件所在目录和需要检查的源文件列表 source_dir = "./" target_source_files = ["e1.py", "e5.py", "e2.py", "e11.py"] test_names = [] for source_file in target_source_files: source_full_path = os.path.join(source_dir, source_file) if not os.path.exists(source_full_path): continue # 提取源文件名(不带.py),拼接成正确的测试名称格式 source_base = os.path.splitext(source_file)[0] test_module = f"tests.test_{source_base}" test_names.append(f"{test_module}.TestDocs") # 加载并运行测试套件 suite = unittest.TestLoader().loadTestsFromNames(test_names) runner = unittest.TextTestRunner() runner.run(suite)
方式二:遍历测试文件反向匹配源文件
如果不确定目标源文件列表,可先遍历tests目录下的测试文件,再匹配对应的源文件是否存在:
import os import unittest source_dir = "./" test_names = [] # 遍历tests目录下的所有测试文件 for test_file in os.listdir("tests"): if not (test_file.startswith("test_") and test_file.endswith(".py")): continue # 从测试文件名提取对应源文件的名称(如test_e1.py -> e1.py) source_base = test_file[5:-3] # 去掉前缀"test_"和后缀".py" source_file = f"{source_base}.py" source_full_path = os.path.join(source_dir, source_file) if os.path.exists(source_full_path): test_module = f"tests.{os.path.splitext(test_file)[0]}" test_names.append(f"{test_module}.TestDocs") # 加载并运行测试套件 suite = unittest.TestLoader().loadTestsFromNames(test_names) runner = unittest.TextTestRunner() runner.run(suite)
关键注意点
- 测试名称必须遵循
包.模块.类的格式,例如tests.test_e1.TestDocs,其中tests是包名,test_e1是tests包下的模块文件,TestDocs是模块中的测试类。 - tests文件夹必须是Python包,即包含
__init__.py(空文件即可),否则Python无法识别为模块。 - 如果需要运行特定测试方法,可将测试名称细化为
tests.test_e1.TestDocs.test_specific_method。
内容的提问来源于stack exchange,提问作者ginjaemocoes
相关产品推荐
相关产品推荐

