python config_error ai_generated true

AssertionError: assert 'processing item' in '' # caplog.text 为空

AssertionError: assert 'processing item' in '' # caplog.text is empty

ID: python/pytest-caplog-propagation-disabled

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

版本兼容性

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

根因分析

应用 logger 设置了 propagate=False(通常用于避免重复 handler),因此日志记录永远到不了 caplog 挂载 handler 的根 logger。caplog 捕获不到任何内容。

English

The application logger has propagate=False set (often to avoid duplicate handlers), so records never reach the root logger that caplog attaches its handler to. caplog captures nothing.

generic

解决方案

  1. 92% 成功率
    def test_logs(caplog):
        logger = logging.getLogger('myapp')
        logger.propagate = True
        with caplog.at_level(logging.INFO, logger='myapp'):
            run()
        assert 'processing item' in caplog.text
  2. 88% 成功率
    def test_logs(caplog):
        logger = logging.getLogger('myapp')
        logger.addHandler(caplog.handler)
        try:
            run()
        finally:
            logger.removeHandler(caplog.handler)
        assert any('processing item' in r.message for r in caplog.records)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Level is not the problem; propagation is disabled so no records reach caplog regardless of level.

  2. 70% 失败

    Logging handlers may not write to stderr, and the format is not the log message alone.