【发布时间】:2015-05-16 04:16:53
【问题描述】:
我想将 pytest 断言的结果放入日志中。
首先我尝试了这个解决方案
def logged_assert(self, testval, msg=None):
if not testval:
if msg is None:
try:
assert testval
except AssertionError as e:
self.logger.exception(e)
raise e
self.logger.error(msg)
assert testval, msg
它工作得很好,但是如果内置,我需要为每个断言使用我自己的 msg。问题是 testval 会在它传递给函数时进行评估,而错误 msg 是
AssertionError: False
我在第一条评论中找到了解决问题http://code.activestate.com/recipes/577074-logging-asserts/ 的好方法。
我在我的记录器包装模块中编写了这个函数
def logged_excepthook(er_type, value, trace):
print('HOOK!')
if isinstance(er_type, AssertionError):
current = sys.modules[sys._getframe(1).f_globals['__name__']]
if 'logger' in sys.modules[current]:
sys.__excepthook__(er_type, value, trace)
sys.modules[current].error(exc_info=(er_type, value, trace))
else:
sys.__excepthook__(er_type, value, trace)
else:
sys.__excepthook__(er_type, value, trace)
然后
sys.excepthook = logged_excepthook
在测试模块中,我有断言输出
import sys
print(sys.excepthook, sys.__excepthook__, logged_excepthook)
是
<function logged_excepthook at 0x02D672B8> <built-in function excepthook> <function logged_excepthook at 0x02D672B8>
但我的输出中没有“Hook”消息。而且我的日志文件中也没有错误消息。所有的作品都与内置的 sys.excepthook 一样。
我查看了 pytest 源,但 sys.excepthook 并没有改变。 但是如果我用 Cntrl-C 中断我的代码执行,我会在标准输出中收到“Hook”消息。
主要问题是为什么内置 sys.excepthook 调用而不是我的自定义函数,我该如何解决这个问题。 但如果存在另一种记录断言错误的方法,我也很感兴趣。
我在 64 位 windows 8.1 上使用 python3.2(32 位)。
【问题讨论】: