【问题标题】:Python unittest output only on test failuresPython unittest 仅在测试失败时输出
【发布时间】:2020-06-17 01:25:40
【问题描述】:

有没有办法编写(或运行)一组 Python unittest 测试,以便在测试失败时没有输出except

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

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

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

    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.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多