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

12

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

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

但是没有执行,只打印测试“路径”供复制&粘贴使用。

2个回答

25

使用unittest.TestLoader实现了命令行命令discover。这是一个相当优雅的解决方案。

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返回TestSuite对象,它们实现了__iter__方法,因此可以迭代。


1
我找不到@vaultah的电子邮件,所以我在这里写。我已经更新了许可证和归属。我希望您能原谅我的初犯 :)。我还要感谢BoltClock平静地解释我的错误。 - xliiv
@vaultah的解决方案中的代码应该放在哪里?在单元测试文件夹__main__.py中吗? - Sebastian

0
你可以这样做:
from your_tests import TestSequenceFunctions
print('\n'.join([f.__name__ for f in dir(TestSequenceFunctions) if f.__name__.startswith('test_')]))

我不确定是否有通过unittest.main公开的方法来实现这一点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接