Python unittest仅在测试失败时输出

2024-09-27 17:55:05 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以编写(或运行)一组Python unittest测试,以便在测试失败时除了之外没有任何输出

例如,如果tests/mytests.py包含一些unittest测试,那么运行python3 test/mytests.py只会在测试失败时输出到stdout(或stderr)


Tags: 方法pyteststderrstdouttestsunittestpython3
1条回答
网友
1楼 · 发布于 2024-09-27 17:55:05

有。我能够将这两个问题的答案中的技巧结合起来,使其发挥作用:

Python, unittest: Can one make the TestRunner completely quiet?

argparse and unittest python

您可以取消对test_should_fail()测试的注释,以验证测试失败时会发生什么

# mymodule.py

def myfunc():
    return True

import unittest
import os

class TestMyFunc(unittest.TestCase):
    def test_myfunc(self):
        self.assertEqual(myfunc(), True)

    # def test_should_fail(self):
    #     self.assertEqual(True, False)

if __name__ == '__main__':
    alltests = unittest.TestLoader().loadTestsFromTestCase(TestMyFunc)
    runner = unittest.TextTestRunner(stream=open(os.devnull, 'w'))
    result = runner.run(alltests)
    if len(result.failures) or len(result.errors):
        print('There were failures or errors.')

相关问题 更多 >

    热门问题