我想用一个固定装置包装所有测试,在其中检查使用 loguru 记录的日志是否有错误消息。
我试过这个:
@pytest.fixture(autouse=True)
def assert_no_log_error(caplog):
yield
assert "ERROR" not in caplog.text
但 caplog.text 始终为空。我假设,在测试之后、夹具实际检查日志之前,caplog 已被清除。 我怎样才能做到这一点?
您可以为此使用 io 和 contextlib
@pytest.fixture(autouse=True)
def assert_no_log_error():
with io.StringIO() as buf, contextlib.redirect_stdout(buf):
yield
value = buf.getvalue()
assert "ERROR" not in value
buf.truncate()