如何使用Python单元测试测试套件选择特定测试

2024-06-01 03:26:29 发布

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

我将Python单元测试代码组织如下:

Maindir
   |
   |--Dir1
   |  |
   |  |-- test_A.py
   |  |-- test_B.py
   |  |-- test_C.py
   |
   |--Dir2
       | ...

我想你明白了。在每个Dirx目录中,我都有一个名为suite.py的文件,它将给定目录中的测试集合在一起(因此您可以选择特定测试,省略其他测试,等等)。这些文件看起来如下(在选择所有测试的情况下,它们也可能只选择一个子集测试)[也考虑测试& lt;-& gt;单元测试]:

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


Tags: 文件pytestimport目录单元测试suitetestsuite
1条回答
网友
1楼 · 发布于 2024-06-01 03:26:29

一种方法是编写自己的测试加载程序。我强烈建议采用Flask's testsuite module中的机制

基本思想是:

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

  2. 子类unittest.TestLoader和重写loadTestsFromName(self, name, module) 这将使用步骤1中生成的testsuite。例如,在烧瓶中:

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

相关问题 更多 >