如何从测试套件中提取测试用例列表?

2024-06-28 19:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的unittest,代码如下:

suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2))

但是,我想在每个测试被套件收集之后对它们做一些定制的事情。我想我可以做一些类似的事情来迭代suite中的测试用例:

^{pr2}$

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

3
<class 'unittest.suite.TestSuite'>

有没有办法可以从套件中获取TestCase类的所有对象?有没有其他方法可以帮助我加载测试用例?在


Tags: 代码套件测试用例unittest事情classsuitemodule1
3条回答

获取测试列表的一个简单方法是使用nose2 collect插件。在

$ nose2 -s <testdir> -v  plugin nose2.plugins.collect  collect-only 
test_1 (test_test.TestClass1)
Test Desc 1 ... ok
test_2 (test_test.TestClass1)
Test Desc 2 ... ok
test_3 (test_test.TestClass1)
Test Desc 3 ... ok
test_2_1 (test_test.TestClass2)
Test Desc 2_1 ... ok
test_2_2 (test_test.TestClass2)
Test Desc 2_2 ... ok

                                   
Ran 5 tests in 0.001s

OK

它不能真正运行测试。在

你可以这样安装nos2(以及它的插件):

^{pr2}$

当然,您可以使用nose2运行单元测试,例如这样或这样:

# run tests from testfile.py
$ nose2 -v -s . testfile

# generate junit xml results:
$ nose2 -v  plugin nose2.plugins.junitxml -X testfile  junit-xml 
$ mv nose2-junit.xml results_testfile.xml

试试看

  for test in suite:
    print test._tests

我将此函数用作suite中的一些元素。\ u测试本身就是套件:

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

相关问题 更多 >