如何从TestSuite中提取TestCase列表?

ely*_*aie 6 python unit-testing

我正在使用Python的unittest和简单的代码,如下所示:

suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2))
Run Code Online (Sandbox Code Playgroud)

但是,我希望在套件收集后对每个测试做一些自定义的事情.我以为我可以做这样的事情来迭代套件中的测试用例:

print suite.countTestCases()
for test in suite:             # Also tried with suite.__iter__()
    # Do something with test
    print test.__class__
Run Code Online (Sandbox Code Playgroud)

但是,对于我加载的测试用例数量,它只会打印

3
<class 'unittest.suite.TestSuite'>
Run Code Online (Sandbox Code Playgroud)

有没有办法从套件中获取TestCase类的所有对象?还有其他方法我应该加载测试用例来促进这个吗?

Dor*_*mer 5

尝试

  for test in suite:
    print test._tests
Run Code Online (Sandbox Code Playgroud)


Tot*_*oro 5

我使用这个函数是因为suite._tests 中的一些元素本身就是套件:

def list_of_tests_gen(s):
  """ a generator of tests from a suite

  """
  for test in s:
    if unittest.suite._isnotsuite(test):
      yield test
    else:
      for t in list_of_tests_gen(test):
        yield t
Run Code Online (Sandbox Code Playgroud)