我试图对一些复杂的网络内容进行单元测试,每次出现错误时,我的网络库都会输出数百行日志消息。我唯一感兴趣的是错误的实际回溯,但我必须向上滚动所有这些日志消息以查看回溯。
有没有办法强制Python的unittest模块在日志之后输出回溯而不是相反?
例如,我目前看到以下内容:
======================================================================
ERROR: my_test (tests.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_code_file.py", line 39, in my_function
my_module.my_function()
File "my_code_file.py", line 78, in my_function
raise Exception("My exception here")
Exception: My exception here
-------------------- >> begin captured logging << --------------------
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
-------------------- >> end captured logging << --------------------
我希望看到这样的内容,以便在运行测试后能够快速查看错误:
======================================================================
-------------------- >> begin captured logging << --------------------
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
<<< hundreds of lines of logs from networking libraries/wiretraces/etc>>>
-------------------- >> end captured logging << --------------------
ERROR: my_test (tests.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_code_file.py", line 39, in my_function
my_module.my_function()
File "my_code_file.py", line 78, in my_function
raise Exception("My exception here")
Exception: My exception here
答案 0 :(得分:0)
使用logging
模块怎么样?
老实说,我不确定您将使用哪种功能来获得最佳效果。
但是,有logging.exception
<强> EX:强>
import logging
try:
print blah
except Exception, e:
logging.exception("\n\n !!!!!! \n\n {} \n\n !!!!!! \n\n".format(e))
该异常的输出很明显:
ERROR:root:
!!!!!!
name 'blah' is not defined
!!!!!!
Traceback (most recent call last):
File "<ipython-input-39-99d79696f33a>", line 2, in <module>
print blah
NameError: name 'blah' is not defined