python
runtime_error
ai_generated
true
AssertionError: assert '' == 'hello\n' - + hello
ID: python/pytest-capsys-flush-buffering
80%修复率
85%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
`capsys.readouterr()` 返回空,因为被测代码使用了 `print(..., flush=False)` 且缓冲区尚未刷新,或者它写入的是 `sys.__stdout__` 而不是 `sys.stdout`。
English
`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`.
解决方案
-
95% 成功率
Force flush in the code under test or use print(..., flush=True): print('hello', flush=True) -
90% 成功率
Use capfd and ensure the code writes to sys.stdout: def test_out(capfd): my_func() out, err = capfd.readouterr() assert out == 'hello\n'
无效尝试
常见但无效的做法:
-
80% 失败
Flushing is not time-based; the buffer may still be unflushed and the test is now flaky.
-
60% 失败
capfd captures file descriptors; if the code uses sys.__stdout__ directly it still bypasses both.