python config_error ai_generated true

assert 0 == 1 E AssertionError: expected 1 log record, got 0 E assert 0 == 1 E + where 0 = len(caplog.records)

ID: python/pytest-caplog-empty-no-propagate

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-04-22First Seen

Version Compatibility

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

Root Cause

The application logger has propagate=False, or caplog's level is not set to the level of the emitted records, so records never reach the root handler that caplog attaches to.

generic

中文

应用 logger 设置了 propagate=False,或 caplog 的级别未设置为所发出记录的级别,导致记录无法到达 caplog 挂载的 root handler。

Workarounds

  1. 90% success
    def test_logs(caplog):
        caplog.set_level(logging.INFO, logger='myapp')
        import logging
        logging.getLogger('myapp').propagate = True
        my_function()
        assert 'started' in caplog.text
  2. 92% success
    def test_logs(caplog):
        with caplog.at_level(logging.INFO, logger='myapp'):
            my_function()
        assert any('started' in r.message for r in caplog.records)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Clearing does not help when records never propagate to caplog in the first place.

  2. 85% fail

    Same propagation issue; caplog.text is also empty.