python
runtime_error
ai_generated
true
AssertionError: assert '' == 'hello\n' - + hello
ID: python/pytest-capsys-flush-buffering
80%Fix Rate
85%Confidence
0Evidence
2024-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
`capsys.readouterr()` returns empty because the code under test uses `print(..., flush=False)` and the buffer has not been flushed, or it writes to `sys.__stdout__` instead of `sys.stdout`.
generic中文
`capsys.readouterr()` 返回空,因为被测代码使用了 `print(..., flush=False)` 且缓冲区尚未刷新,或者它写入的是 `sys.__stdout__` 而不是 `sys.stdout`。
Workarounds
-
95% success
Force flush in the code under test or use print(..., flush=True): print('hello', flush=True) -
90% success
Use capfd and ensure the code writes to sys.stdout: def test_out(capfd): my_func() out, err = capfd.readouterr() assert out == 'hello\n'
Dead Ends
Common approaches that don't work:
-
80% fail
Flushing is not time-based; the buffer may still be unflushed and the test is now flaky.
-
60% fail
capfd captures file descriptors; if the code uses sys.__stdout__ directly it still bypasses both.