简体   繁体   English

Python unittest output 仅在测试失败时

[英]Python unittest output only on test failures

Is there a way to write (or run) a set of Python unittest tests so that there is no output except when there is a test failure?有没有办法编写(或运行)一组unittest单元测试,以便除了测试失败之外没有 output?

For example, if tests/mytests.py contains some unittest tests, then running python3 test/mytests.py will only output to stdout (or stderr) if there is a test failure.例如,如果tests/mytests.py包含一些unittest测试,那么如果测试失败,运行python3 test/mytests.py只会 output 到 stdout(或 stderr)。

Yes there is.就在这里。 I was able to combine the techniques in the answers to these two questions to get it to work:我能够将这两个问题的答案中的技术结合起来使其发挥作用:

Python, unittest: Can one make the TestRunner completely quiet? Python,单元测试:可以让 TestRunner 完全安静吗?

argparse and unittest python argparse 和 unittest python

You can uncomment the test_should_fail() test to verify what happens when a test fails.您可以取消注释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.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM