python runtime_error ai_generated true

AssertionError: assert '' == 'hello\n' - + hello

ID: python/pytest-capsys-flush-buffering

其他格式: JSON · Markdown 中文 · English
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`.

generic

解决方案

  1. 95% 成功率
    Force flush in the code under test or use print(..., flush=True):
    
    print('hello', flush=True)
  2. 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'

无效尝试

常见但无效的做法:

  1. 80% 失败

    Flushing is not time-based; the buffer may still be unflushed and the test is now flaky.

  2. 60% 失败

    capfd captures file descriptors; if the code uses sys.__stdout__ directly it still bypasses both.