python
config_error
ai_generated
true
AssertionError: assert 'expected message' in [] 其中 [] = caplog.messages
AssertionError: assert 'expected message' in [] where [] = caplog.messages
ID: python/pytest-caplog-not-captured
80%修复率
85%置信度
0证据数
2024-10-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
被测代码使用的 logger 设置了 propagate=False,或日志配置使用了绕过根 logger 的 handler,导致 caplog 的根 handler 从未收到日志记录。
English
The logger used by the code under test has propagate=False, or logging was configured with a handler that bypasses the root logger, so caplog's root handler never receives the record.
解决方案
-
90% 成功率
def test_x(caplog): logging.getLogger('myapp').propagate = True with caplog.at_level(logging.INFO, logger='myapp'): run() assert 'expected message' in caplog.text -
92% 成功率
import logging def test_x(): records = [] h = logging.Handler() h.emit = records.append log = logging.getLogger('myapp') log.addHandler(h) try: run() finally: log.removeHandler(h) assert any('expected' in r.getMessage() for r in records)
无效尝试
常见但无效的做法:
-
85% 失败
Level is not the issue if propagate=False; the record never reaches the root logger's handlers regardless of level.
-
90% 失败
Both attributes are populated from the same captured records; an empty capture yields empty results in either.