【发布时间】:2020-06-17 01:25:40
【问题描述】:
有没有办法编写(或运行)一组 Python unittest 测试,以便在测试失败时没有输出except?
例如,如果tests/mytests.py 包含一些unittest 测试,那么运行python3 test/mytests.py 只会在测试失败时输出到stdout(或stderr)。
【问题讨论】:
有没有办法编写(或运行)一组 Python unittest 测试,以便在测试失败时没有输出except?
例如,如果tests/mytests.py 包含一些unittest 测试,那么运行python3 test/mytests.py 只会在测试失败时输出到stdout(或stderr)。
【问题讨论】:
是的,有。我能够将这两个问题的答案中的技术结合起来使其发挥作用:
Python, unittest: Can one make the TestRunner completely quiet?
您可以取消注释 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.')
【讨论】: