为什么pytest无法识别loguru的AssertionError?

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

conftest.py
中,我根据 loguru 的文档重新定义了 caplog。我有
enqueue=True
,因为我的一些代码使用了多重处理。

@pytest.fixture
def caplog(caplog: LogCaptureFixture):
    """Redefine caplog to work with loguru, taken from their docs
    """
    handler_id = logger.add(
        caplog.handler,
        format="{message}",
        level=0,
        filter=lambda record: record["level"].no >= caplog.handler.level,
        enqueue=True,  # Set to 'True' if your test is spawning child processes.
    )
    yield caplog
    logger.remove(handler_id)

我有一个基本测试,在

enqueue=False
时有效,但在
enqueue=True
时无效。如果我将
assert_no_errors_logged
的内容复制/粘贴到测试下方,它就会起作用。但如果我调用
assert_no_errors_logged
,pytest 就会抱怨。如果
enqueue=False
,这不是问题。

def test_errors_are_caught(caplog):
    logger.debug("debug message")
    logger.info("an info")
    logger.error("an error")
    logger.critical("a very bad thing")
    with pytest.raises(AssertionError):
        assert_no_errors_logged(caplog)

def assert_no_errors_logged(caplog):
    error_messages = [record for record in caplog.records if record.levelno >= logging.ERROR]
    num_errors = len(error_messages)
    assert num_errors == 0

错误

============================== 1 failed in 0.28s ==============================
FAILED                [100%]2024-07-15 14:38:33.327 | DEBUG    | test_compute_statistics:test_errors_are_caught:440 - debug message
2024-07-15 14:38:33.327 | INFO     | test_compute_statistics:test_errors_are_caught:441 - an info
2024-07-15 14:38:33.327 | ERROR    | test_compute_statistics:test_errors_are_caught:442 - an error
2024-07-15 14:38:33.327 | CRITICAL | test_compute_statistics:test_errors_are_caught:443 - a very bad thing

tests\unit\test_compute_statistics.py:438 (test_errors_are_caught)
caplog = <_pytest.logging.LogCaptureFixture object at 0x000001A41CBB4550>

    def test_errors_are_caught(caplog):
        logger.debug("debug message")
        logger.info("an info")
        logger.error("an error")
        logger.critical("a very bad thing")
>       with pytest.raises(AssertionError):
E       Failed: DID NOT RAISE <class 'AssertionError'>

test_compute_statistics.py:444: Failed

Process finished with exit code 1
pytest loguru
1个回答
0
投票

logger.complete()
之前致电
assert_no_errors_logged()

Delgan(loguru 的创建者/维护者)说这里

enqueue=True
时,消息不会立即记录:它们被添加到队列中并由后台线程处理。我认为您的测试失败了,因为当调用
assert_no_errors_logged()
时,并非所有日志都到达
caplog
接收器。添加对
logger.complete()
的调用可确保没有剩余的待处理日志。

© www.soinside.com 2019 - 2024. All rights reserved.