python config_error ai_generated true

AssertionError: assert 'expected message' in [] where [] = caplog.messages

ID: python/pytest-caplog-not-captured

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-10-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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.

generic

中文

被测代码使用的 logger 设置了 propagate=False,或日志配置使用了绕过根 logger 的 handler,导致 caplog 的根 handler 从未收到日志记录。

Workarounds

  1. 90% success
    def test_x(caplog):
        logging.getLogger('myapp').propagate = True
        with caplog.at_level(logging.INFO, logger='myapp'):
            run()
        assert 'expected message' in caplog.text
  2. 92% success
    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)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Level is not the issue if propagate=False; the record never reaches the root logger's handlers regardless of level.

  2. 90% fail

    Both attributes are populated from the same captured records; an empty capture yields empty results in either.