python
config_error
ai_generated
true
AssertionError: assert 'expected log' in []
ID: python/pytest-caplog-no-capture
80%Fix Rate
88%Confidence
0Evidence
2024-09-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
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.
generic中文
caplog 默认通过 logging 的根 logger 捕获;若被测代码使用 propagate=False 的自定义 logger 或其他 handler,caplog 看不到任何内容。
Workarounds
-
90% success
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% success
def test_logs(caplog): logger = logging.getLogger('myapp.worker') logger.addHandler(caplog.handler) run_worker() assert 'expected log' in caplog.text
Dead Ends
Common approaches that don't work:
-
85% fail
Sets the level but does not fix propagation; if propagate=False, records still never reach caplog's handler.
-
80% fail
Adds a root handler but caplog replaces handlers per test; custom loggers with propagate=False still bypass.
-
90% fail
capsys captures stdout/stderr; logging output may not be written there depending on handler configuration.