python config_error ai_generated true

AssertionError: assert 'expected message' in [] # caplog.records is empty

ID: python/pytest-caplog-not-propagating

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

The logger's propagate flag is False, or the code uses a logger configured with a custom handler and propagate=False, so records never reach the root logger that caplog attaches to.

generic

中文

logger 的 propagate 标志为 False,或代码使用了 propagate=False 的自定义 handler 配置的 logger,记录无法到达 caplog 所附加的根 logger。

Workarounds

  1. 92% success
    def test_logs(caplog):
        logging.getLogger('mypkg').propagate = True
        with caplog.at_level(logging.INFO, logger='mypkg'):
            mypkg.do_work()
        assert 'expected message' in caplog.text
  2. 85% success
    def test_logs(caplog):
        logger = logging.getLogger('mypkg')
        logger.addHandler(caplog.handler)
        mypkg.do_work()
        assert 'expected message' in caplog.text

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Adjusts the level but does not change propagate; the record still never reaches caplog's handler.

  2. 80% fail

    Adds a root handler but does not affect the child logger's propagate=False setting.