如何列出可用的Python测试?

12 投票
2 回答
6929 浏览
提问于 2025-04-18 11:30

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

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 个回答

0

你可以这样做:

from your_tests import TestSequenceFunctions
print('\n'.join([f.__name__ for f in dir(TestSequenceFunctions) if f.__name__.startswith('test_')]))

我不太确定通过 unittest.main 有没有公开的方法可以做到这一点。

25

命令行中的 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 返回的是 TestSuite 对象,这些对象实现了 __iter__ 方法,因此可以被遍历。

撰写回答