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

2024-06-26 18:00:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有没有什么方法可以强制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 << --------------------

我希望看到这样的情况,以便在运行测试后快速看到错误:

^{pr2}$

Tags: offrom网络消息librariesmy错误etc
1条回答
网友
1楼 · 发布于 2024-06-26 18:00:48

使用logging模块怎么样?在

老实说,我不知道你会使用什么函数来获得最佳结果。在

但是,有logging.exception

例如:

import logging

try:
    print blah

except Exception, e:
    logging.exception("\n\n !!!!!! \n\n  {} \n\n !!!!!! \n\n".format(e))

出现异常的输出非常明显:

^{pr2}$

相关问题 更多 >