python runtime_error ai_generated true

AssertionError: assert 'hello' in '' where '' = capsys.readouterr().out

ID: python/pytest-capsys-no-output

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

Version Compatibility

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

Root Cause

capsys only captures sys.stdout/sys.stderr writes. Code that uses logging, os.write(1, ...), or a C extension writing to fd 1 bypasses Python's sys.stdout and is not captured.

generic

中文

capsys 仅捕获通过 sys.stdout/sys.stderr 的写入。使用 logging、os.write(1, ...) 或 C 扩展直接写文件描述符 1 的代码会绕过 sys.stdout,无法被捕获。

Workarounds

  1. 95% success
    Use caplog for logging output:
    
    def test_log(caplog):
        logging.getLogger(__name__).warning('hello')
        assert 'hello' in caplog.text
  2. 92% success
    Use capfd for file-descriptor-level output:
    
    def test_fd(capfd):
        os.write(1, b'hello')
        out, err = capfd.readouterr()
        assert 'hello' in out

Dead Ends

Common approaches that don't work:

  1. 90% fail

    readouterr() drains the buffer; the second call returns empty strings.

  2. 85% fail

    Mixing fixtures means output goes to the fd-level buffer while the test reads the sys-level buffer.