我有如下组织的Python单元测试代码:
Maindir
|
|--Dir1
| |
| |-- test_A.py
| |-- test_B.py
| |-- test_C.py
|
|--Dir2
| ...
我想你明白了。在每个Dirx
目录中,我都有一个名为suite.py
的文件,它将给定目录中测试的一组测试放在一起(这样你就可以选择特定的测试,省略其他测试等)
import test_A
import test_B
import test_C
suite1 = test.TestSuite()
suite1.addTests(test.TestLoader().loadTestsFromTestCase(test_A.MyTest))
suite1.addTests(test.TestLoader().loadTestsFromTestCase(test_B.MyTest))
suite1.addTests(test.TestLoader().loadTestsFromTestCase(test_C.MyTest))
Maindir
目录中的主运行程序execall.py
如下所示:
from Dir1.suite import suite1
from Dir2.suite import suite2
suite_all = test.TestSuite([
suite1,
suite2])
if __name__ == '__main__':
test.main(defaultTest='suite_all')
现在我可以做以下事情:
- 运行所有测试:'execall.py'(如文档所示)
- 运行特定套件:
execall.py suite1
(如文档所示)
但是我如何才能只运行特定的单个测试?如何运行特定文件的所有测试?我尝试了以下操作,但没有成功,出现了相同的错误:'TestSuite' object has no attribute 'xxx'
execall.py suite1.test_A
execall.py suite1.test_A.test1
execall.py test_A
execall.py test_A.test1
execall.py -h
给出了关于如何在测试用例中运行单个测试或测试的非常具体的示例,但在我的情况下,这似乎不起作用。
一种方法是编写自己的测试加载程序。我强烈建议采用Flask的测试套件模块中的机制。
基本思想是:
-
实现一个例程,该例程返回一个
unittest.TestSuite()
对象以及包含所需测试的所有Python模块。这可以通过扫描目录中的test_XXX.py
文件来完成(只需通过startswith('test')
、regexp等进行检查) -
子类
unittest.TestLoader
和覆盖loadTestsFromName(self, name, module)
其将使用在步骤1中生成的测试套件。例如,在烧瓶中:for testcase, testname in find_all_tests(suite): if testname == name or testname.endswith('.' + name) or ('.' + name + '.') in testname or testname.startswith(name + '.'): all_tests.append(testcase)
这允许按Python模块名称、测试套件(测试类)名称或仅按测试用例名称加载测试。