gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:50:28 25 4
gpt4 key购买 nike

我的 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's testsuite module 中的机制.

基本思路是:

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

  2. 子类 unittest.TestLoader 并覆盖 loadTestsFromName(self, name, module)这将使用在步骤 1 中生成的测试套件。例如,在 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 模块名称、测试套件(测试类)名称或仅通过测试用例名称加载测试。

关于python - 如何使用 Python 单元测试测试套件选择特定测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13758500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com