如何在错误日志后强制我的Python单元测试打印回溯?

时间:2014-10-23 20:44:42

标签: python unit-testing python-2.7

我试图对一些复杂的网络内容进行单元测试,每次出现错误时,我的网络库都会输出数百行日志消息。我唯一感兴趣的是错误的实际回溯,但我必须向上滚动所有这些日志消息以查看回溯。

有没有办法强制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

1 个答案:

答案 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