3

我将 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))

目录中的主要运行器 ,execall.py如下Maindir所示:

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给出了如何在测试用例中运行单个测试或测试的非常具体的示例,但在我的情况下这似乎不起作用。

4

1 回答 1

1

一种方法是编写自己的测试加载器。我强烈建议采用Flask 的 testsuite 模块中的机制。

基本思想是:

  1. 实现一个例程,该例程返回一个unittest.TestSuite()包含所需测试的所有 Python 模块的对象。这可以通过例如扫描目录中的test_XXX.py文件来完成(只需通过startswith('test')、regexp 等检查它们)。

  2. 使用 Step1 中生成的测试套件的子类unittest.TestLoader和覆盖。loadTestsFromName(self, name, module)例如,在 Flask 中:

     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 模块名称、测试套件(测试类)名称或仅通过测试用例名称加载测试。

于 2012-12-07T08:08:21.053 回答