python data_error ai_generated true

AssertionError: assert '' == 'hello\n' + where '' = capsys.readouterr().out

ID: python/pytest-capsys-not-captured

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Output was written to a logging handler, a subprocess, or a C-level fd, none of which capsys captures. capsys only captures Python-level sys.stdout/stderr writes.

generic

中文

输出写入了日志处理器、子进程或 C 层文件描述符,这些 capsys 都无法捕获。capsys 仅捕获 Python 层的 sys.stdout/stderr 写入。

Workarounds

  1. 92% success
    def test_cli(capfd):
        import subprocess, sys
        subprocess.run([sys.executable, "-c", "print('hello')"])
        out, err = capfd.readouterr()
        assert out == "hello\n"
  2. 94% success
    import logging
    
    def test_log(caplog):
        with caplog.at_level(logging.INFO):
            logging.getLogger("app").info("hello")
        assert "hello" in caplog.text

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Each call drains the buffer; repeated calls return empty strings after the first.

  2. 70% fail

    That disables capture entirely; the assertion still sees nothing.