使Python unittest显示AssertionError但不显示Traceb

2024-10-01 15:35:41 发布

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

我已经看了其他相关的问题,但没有找到我的答案。我想简化Python(2.7)unittests的输出。{cd1>没有成功。在

下面是我的代码片段(真实的代码生成了许多类似的测试):

#!/usr/bin/python -E
import unittest
import os
import sys

class TestSequense(unittest.TestCase):
    pass

def test_dir_exists(dir):
    def test(self):
        self.assertTrue(os.path.isdir(dir),"ERROR: " + dir + " is not a directory")
    return test

if __name__ == '__main__':
    test = test_dir_exists("/something/not/set/correctly")
    setattr(TestSequense, "test_path",  test)
    #TODO trying remove unnecessary traceback info... still not working
    sys.tracebacklimit = 0
    unittest.main()

目前的输出是:

^{pr2}$

我希望它看起来像这样:

F
======================================================================
FAIL: test_path (__main__.TestSequense)
----------------------------------------------------------------------
AssertionError: ERROR: /something/not/set/correctly is not a directory

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

在不解析输出的情况下,这是可能的吗?回溯没有给我任何有用的信息,我正在运行1000个测试。在

提前谢谢!在


Tags: pathtestimportselfisosmaindef
3条回答

unittest有一种机制,可以在回溯中隐藏TestCase.assert*方法的内容,因为这些方法实际上不包含任何有用的失败信息。它在框架的全局参数中查找__unittest。 您可以通过将__unittest = True放在模块顶部来隐藏整个模块。在

我不确定是否可以使用vanilla unittest模块。但是您应该看看py.test,有了它,您可以使用 tb开关配置回溯中显示的信息量。在

也许你对

py.test  tb=line    # only one line per failure

有关选项的完整列表,请参见this page。在

诀窍是捕捉异常,去掉不需要的部分并再次抛出。。。在

基于this答案-下面的代码可以工作。。。在

#!/usr/bin/python -E
import unittest
import os
import sys

class TestSequense(unittest.TestCase):
    pass

def test_dir_exists(dir):
    def test(self):
       try:
           self.assertTrue(os.path.isdir(dir),"ERROR: " + dir + " is not a directory")
       except:
           # Remove traceback info as we don't need it
           unittest_exception = sys.exc_info()
           raise unittest_exception[0], unittest_exception[1], unittest_exception[2].tb_next
    return test

if __name__ == '__main__':
    test = test_dir_exists("/something/not/set/correctly")
    setattr(TestSequense, "test_path",  test)
    unittest.main()

并生成以下内容。。。在

^{pr2}$

相关问题 更多 >

    热门问题