在 pytest 的自动使用装置中使用 caplog

问题描述 投票:0回答:1

我想用一个固定装置包装所有测试,在其中检查使用 loguru 记录的日志是否有错误消息。

我试过这个:

@pytest.fixture(autouse=True)
def assert_no_log_error(caplog):
    yield
    assert "ERROR" not in caplog.text

但 caplog.text 始终为空。我假设,在测试之后、夹具实际检查日志之前,caplog 已被清除。 我怎样才能做到这一点?

python pytest pytest-fixtures loguru caplog
1个回答
0
投票

您可以为此使用 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()
© www.soinside.com 2019 - 2024. All rights reserved.