python
runtime_error
ai_generated
true
AssertionError: assert '' == 'expected output' - expected output +
ID: python/pytest-capture-stdout-not-shown
80%修复率
85%置信度
0证据数
2024-04-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
测试通过 capsys 捕获 stdout,但被测代码写入的是 logger 或 sys.__stdout__ 而非 sys.stdout,或者 capsys 在输出已被刷新后才被请求。capsys 只捕获调用时通过 sys.stdout 的写入。
English
The test captures stdout via capsys but the code under test writes to a logger or to sys.__stdout__ instead of sys.stdout, or capsys was requested after the output was already flushed. capsys only captures writes through sys.stdout at call time.
解决方案
-
92% 成功率
def test_logs(caplog): with caplog.at_level('INFO'): run_task() assert 'expected output' in caplog.text -
90% 成功率
def test_prints(capsys): print('expected output') captured = capsys.readouterr() assert captured.out.strip() == 'expected output'
无效尝试
常见但无效的做法:
-
70% 失败
capsysbinary only changes the encoding of captured bytes; it still won't capture logger output or writes to sys.__stdout__.
-
65% 失败
Flushing does not redirect output into the capture buffer if the code wrote to a different stream.