使Python单元测试显示AssertionError但没有Traceback

int*_*ter 5 python unit-testing

我在这里查看了其他相关问题,但没有找到答案。我想简化我的Python(2.7)单元测试的输出。尝试sys.tracebacklimit = 0不起作用。

这是我的代码片段(实际代码会生成许多类似的测试):

#!/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()
Run Code Online (Sandbox Code Playgroud)

当前输出为:

F
======================================================================
FAIL: test_path (__main__.TestSequense)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./simple_unittest.py", line 11, in test
    self.assertTrue(os.path.isdir(dir),"ERROR: " + dir + " is not a directory")
AssertionError: ERROR: /something/not/set/correctly is not a directory

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

FAILED (failures=1)
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

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)
Run Code Online (Sandbox Code Playgroud)

不解析输出就可以吗?追溯没有给我任何有用的信息,并且我正在运行1000多个测试。

提前致谢!

小智 7

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

  • 这个答案的简化版本:将 `__unittest = True` 放在包含测试用例的文件的顶部。 (2认同)

mem*_*lyk 5

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

可能你感兴趣

py.test --tb=line    # only one line per failure
Run Code Online (Sandbox Code Playgroud)

有关选项的完整列表,请参阅此页面