有没有办法覆盖pytest(python)中的默认断言?
问题描述:
我想在每次调用断言时将一些信息记录到文件/数据库中.有没有办法在每次调用断言时覆盖断言或注册某种回调函数来执行此操作?
I'd like to a log some information to a file/database every time assert is invoked. Is there a way to override assert or register some sort of callback function to do this, every time assert is invoked?
问候沙拉德
答
尝试重载 AssertionError
而不是 assert
.原始断言错误在 python2 和 exceptions module 中可用python3 中的 href="https://docs.python.org/3/library/builtins.html" rel="nofollow">builtins 模块.
Try overload the AssertionError
instead of assert
. The original assertion error is available in exceptions module in python2 and builtins module in python3.
import exceptions
class AssertionError:
def __init__(self, *args, **kwargs):
print("Log me!")
raise exceptions.AssertionError