如何使用python列出可用的测试? [英] How to list available tests with python?
问题描述
如何仅列出所有发现的测试? 我找到了以下命令:
How to just list all discovered tests? I found this command:
python3.4 -m unittest discover -s .
但这并不是我想要的,因为上面的命令执行测试.我的意思是让我们有一个包含大量测试的项目.执行时间为几分钟.这迫使我等到测试完成.
But it's not exactly what I want, because the above command executes tests. I mean let's have a project with a lot of tests. Execution time is a few minutes. This force me to wait until tests are finished.
我想要的是这样的东西(在命令的输出上方)
What I want is something like this (above command's output)
test_choice (test.TestSequenceFunctions) ... ok
test_sample (test.TestSequenceFunctions) ... ok
test_shuffle (test.TestSequenceFunctions) ... ok
或更妙的是,类似这样的东西(在上面编辑之后):
or even better, something more like this (after editing above):
test.TestSequenceFunctions.test_choice
test.TestSequenceFunctions.test_sample
test.TestSequenceFunctions.test_shuffle
但不执行,仅出于复制和粘贴目的而打印测试路径".
but without execution, only printing tests "paths" for copy&paste purpose.
推荐答案
Command line command discover
is implemented using unittest.TestLoader
. Here's the somewhat elegant solution
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
返回__iter__
方法,因此是可迭代的.
This works because TestLoader.discover
returns TestSuite
objects, that implement __iter__
method and therefore are iterable.
这篇关于如何使用python列出可用的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!