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

1 投票
1 回答
1127 浏览
提问于 2025-04-29 08:24

我正在尝试对一些复杂的网络功能进行单元测试,每当出现错误时,我的网络库会输出成百上千行的日志信息。我其实只关心错误的具体追踪信息,但我得往上翻那些日志才能看到追踪信息。

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

那我们来聊聊使用 logging 模块吧。

老实说,我不太确定你应该用哪个函数才能得到最好的效果。

不过,有一个函数叫 logging.exception

举个例子:

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

撰写回答