python runtime_error ai_generated true

AssertionError:assert 'starting' in capsys.readouterr().out E AssertionError:assert 'starting' in ''

AssertionError: assert 'starting' in capsys.readouterr().out E AssertionError: assert 'starting' in ''

ID: python/pytest-capture-log-with-caplog-and-capsys

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-12-14首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

该消息通过 logging 发出,而不是 print,因此 capsys 没有捕获到任何内容。日志记录通过日志处理器写入 stderr,而不是 stdout。

English

The message was emitted via logging, not print, so capsys captured nothing. Logging writes to stderr through the logging handler, not stdout.

generic

解决方案

  1. 95% 成功率
    def test_start(caplog):
        with caplog.at_level("INFO"):
            start()
        assert "starting" in caplog.text
  2. 85% 成功率
    def test_start(capsys):
        start()
        captured = capsys.readouterr()
        assert "starting" in captured.err

无效尝试

常见但无效的做法:

  1. 90% 失败

    Nothing was written to stdout in the first place.

  2. 90% 失败

    Same stream issue; binary vs text doesn't help.

  3. 80% 失败

    Pollutes production code to satisfy a test.