python config_error ai_generated true

AssertionError: assert 'user created' in [] where [] = caplog.messages

ID: python/pytest-caplog-no-logs-captured

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

Version Compatibility

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

Root Cause

caplog only captures records at WARNING or above by default when the root logger has no handler configured, or the application uses a custom logger with propagate=False. Propagation must be enabled for caplog to intercept records.

generic

中文

当根 logger 未配置 handler 时,caplog 默认只捕获 WARNING 及以上级别的记录;或者应用程序使用了 propagate=False 的自定义 logger。必须启用传播才能让 caplog 拦截记录。

Workarounds

  1. 95% success
    def test_create_user(caplog):
        caplog.set_level(logging.INFO, logger='myapp')
        create_user('[email protected]')
        assert 'user created' in caplog.text
    
    # in myapp/__init__.py
    logger = logging.getLogger('myapp')
    logger.propagate = True
  2. 93% success
    def test_create_user(caplog):
        with caplog.at_level(logging.INFO, logger='myapp'):
            create_user('[email protected]')
        assert any('user created' in r.message for r in caplog.records)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Clearing removes whatever was captured; if nothing was captured to begin with, the list stays empty.

  2. 85% fail

    Logging does not necessarily write to stdout; the logger may use a file or syslog handler, so capsys captures nothing.