如何使用 python 列出可用的测试?

2024-02-25

如何列出所有发现的测试? 我发现这个命令:

python3.4 -m unittest discover -s .

但这并不完全是我想要的,因为上面的命令执行测试。我的意思是让我们有一个包含大量测试的项目。执行时间为几分钟。这迫使我必须等到测试完成。

我想要的是这样的(上面命令的输出)

test_choice (test.TestSequenceFunctions) ... ok
test_sample (test.TestSequenceFunctions) ... ok
test_shuffle (test.TestSequenceFunctions) ... ok

或者更好的是,更像这样(在上面编辑之后):

test.TestSequenceFunctions.test_choice
test.TestSequenceFunctions.test_sample
test.TestSequenceFunctions.test_shuffle

但没有执行,仅打印测试“路径”以用于复制粘贴目的。


命令行命令discover是使用实现的unittest.TestLoader https://docs.python.org/3/library/unittest.html?highlight=discover#unittest.TestLoader。这是有点优雅的解决方案

import unittest

def print_suite(suite):
    if hasattr(suite, '__iter__'):
        for x in suite:
            print_suite(x)
    else:
        print(suite)

print_suite(unittest.defaultTestLoader.discover('.'))

运行示例:

In [5]: print_suite(unittest.defaultTestLoader.discover('.'))
test_accounts (tests.TestAccounts)
test_counters (tests.TestAccounts)
# More of this ...
test_full (tests.TestImages)

这有效是因为TestLoader.discover https://docs.python.org/3/library/unittest.html?highlight=discover#unittest.TestLoader.discover回报TestSuite对象,实现__iter__方法,因此是可迭代的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 python 列出可用的测试? 的相关文章

随机推荐