python config_error ai_generated true

assert 0 == 1 E AssertionError: 期望 1 条日志,实际 0 条 E assert 0 == 1 E + 其中 0 = len(caplog.records)

assert 0 == 1 E AssertionError: expected 1 log record, got 0 E assert 0 == 1 E + where 0 = len(caplog.records)

ID: python/pytest-caplog-empty-no-propagate

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-04-22首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

应用 logger 设置了 propagate=False,或 caplog 的级别未设置为所发出记录的级别,导致记录无法到达 caplog 挂载的 root handler。

English

The application logger has propagate=False, or caplog's level is not set to the level of the emitted records, so records never reach the root handler that caplog attaches to.

generic

解决方案

  1. 90% 成功率
    def test_logs(caplog):
        caplog.set_level(logging.INFO, logger='myapp')
        import logging
        logging.getLogger('myapp').propagate = True
        my_function()
        assert 'started' in caplog.text
  2. 92% 成功率
    def test_logs(caplog):
        with caplog.at_level(logging.INFO, logger='myapp'):
            my_function()
        assert any('started' in r.message for r in caplog.records)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Clearing does not help when records never propagate to caplog in the first place.

  2. 85% 失败

    Same propagation issue; caplog.text is also empty.