如果您可以在测试中添加 __init__.py 文件,您可以在其中放置一个 load_tests 函数来为您处理发现。
如果测试包名称(带有__init__.py 的目录)与
模式,然后将检查包是否有“load_tests”功能。如果
this 存在,然后它会被 loader、tests、pattern 调用。
如果 load_tests 存在,则发现不递归到包中,
load_tests 负责加载包中的所有测试。
我不太确定这是最好的方法,但编写该函数的一种方法是:
import os
import pkgutil
import inspect
import unittest
# Add *all* subdirectories to this module's path
__path__ = [x[0] for x in os.walk(os.path.dirname(__file__))]
def load_tests(loader, suite, pattern):
for imp, modname, _ in pkgutil.walk_packages(__path__):
mod = imp.find_module(modname).load_module(modname)
for memname, memobj in inspect.getmembers(mod):
if inspect.isclass(memobj):
if issubclass(memobj, unittest.TestCase):
print("Found TestCase: {}".format(memobj))
for test in loader.loadTestsFromTestCase(memobj):
print(" Found Test: {}".format(test))
suite.addTest(test)
print("=" * 70)
return suite
很丑,我同意。
首先将所有子目录添加到测试包的路径 (Docs)。
然后,您使用pkgutil 走路径,寻找包或模块。
当它找到一个时,它会检查模块成员以查看它们是否是类,如果它们是类,它们是否是unittest.TestCase 的子类。如果是,则将类中的测试加载到测试套件中。
现在,您可以在项目根目录中键入
python -m unittest discover -p tests
使用-p 模式开关。如果一切顺利,你会看到我所看到的,类似于:
Found TestCase: <class 'test_tc.TestCase'>
Found Test: testBar (test_tc.TestCase)
Found Test: testFoo (test_tc.TestCase)
Found TestCase: <class 'test_employee.TestCase'>
Found Test: testBar (test_employee.TestCase)
Found Test: testFoo (test_employee.TestCase)
======================================================================
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
这是预期的,我的两个示例文件中的每一个都包含两个测试,testFoo 和 testBar 每个。
编辑:经过更多挖掘,看起来您可以将此函数指定为:
def load_tests(loader, suite, pattern):
for imp, modname, _ in pkgutil.walk_packages(__path__):
mod = imp.find_module(modname).load_module(modname)
for test in loader.loadTestsFromModule(mod):
print("Found Tests: {}".format(test._tests))
suite.addTests(test)
这使用loader.loadTestsFromModule() 方法而不是我上面使用的loader.loadTestsFromTestCase() 方法。它仍然修改 tests 包路径并遍历它寻找模块,我认为这是这里的关键。
现在的输出看起来有点不同,因为我们一次将找到的测试套件添加到我们的主测试套件suite:
python -m unittest discover -p tests
Found Tests: [<test_tc.TestCase testMethod=testBar>, <test_tc.TestCase testMethod=testFoo>]
Found Tests: [<test_employee.TestCase testMethod=testBar>, <test_employee.TestCase testMethod=testFoo>]
======================================================================
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OK
但我们仍然在两个类和两个子目录中得到了我们预期的 4 个测试。