python
config_error
ai_generated
true
AssertionError: assert 'expected log' in []
ID: python/pytest-caplog-no-capture
80%修复率
88%置信度
0证据数
2024-09-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
caplog 默认通过 logging 的根 logger 捕获;若被测代码使用 propagate=False 的自定义 logger 或其他 handler,caplog 看不到任何内容。
English
caplog captures via logging's root logger by default; if the code under test uses a custom logger with propagate=False or a different handler, caplog sees nothing.
解决方案
-
90% 成功率
def test_logs(caplog): logger = logging.getLogger('myapp.worker') logger.propagate = True with caplog.at_level(logging.INFO): run_worker() assert 'expected log' in caplog.text -
85% 成功率
def test_logs(caplog): logger = logging.getLogger('myapp.worker') logger.addHandler(caplog.handler) run_worker() assert 'expected log' in caplog.text
无效尝试
常见但无效的做法:
-
85% 失败
Sets the level but does not fix propagation; if propagate=False, records still never reach caplog's handler.
-
80% 失败
Adds a root handler but caplog replaces handlers per test; custom loggers with propagate=False still bypass.
-
90% 失败
capsys captures stdout/stderr; logging output may not be written there depending on handler configuration.