python runtime_error ai_generated true

AssertionError: assert '' == 'expected output' - expected output +

ID: python/pytest-capture-stdout-not-shown

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

generic

解决方案

  1. 92% 成功率
    def test_logs(caplog):
        with caplog.at_level('INFO'):
            run_task()
        assert 'expected output' in caplog.text
  2. 90% 成功率
    def test_prints(capsys):
        print('expected output')
        captured = capsys.readouterr()
        assert captured.out.strip() == 'expected output'

无效尝试

常见但无效的做法:

  1. 70% 失败

    capsysbinary only changes the encoding of captured bytes; it still won't capture logger output or writes to sys.__stdout__.

  2. 65% 失败

    Flushing does not redirect output into the capture buffer if the code wrote to a different stream.