我在这里查看了其他相关问题但未找到答案。我想简化我的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()
目前的输出是:
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)
我希望它看起来像这样:
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)
如果不解析输出,这可能吗? Traceback没有给我任何有用的信息,我正在进行1000次测试。
提前致谢!
答案 0 :(得分:2)
unittest
具有一种机制,可以在跟踪中隐藏TestCase.assert*
方法的内容,因为这些方法实际上不包含任何有关失败的有用信息。它在框架的全局变量中寻找__unittest
。
您可以通过在模块的顶部放置__unittest = True
来从追溯中隐藏整个模块。
答案 1 :(得分:1)
我不确定是否可以使用vanilla unittest模块。但是你应该看看py.test,你可以使用--tb
开关配置回溯中显示的信息量。
可能您对
感兴趣py.test --tb=line # only one line per failure
有关选项的完整列表,请参阅this page。
答案 2 :(得分:1)
诀窍是捕获异常,去除不需要的位并再次抛出......
根据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()
并生成以下内容......
./simple_unittest.py
F
======================================================================
FAIL: test_path (__main__.TestSequense)
----------------------------------------------------------------------
AssertionError: ERROR: /something/not/set/correctly is not a directory
----------------------------------------------------------------------
Ran 1 test in 0.000s