python runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-04-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

测试通过 capsys 捕获 stdout,但被测代码写入的是 logger 或 sys.__stdout__ 而非 sys.stdout,或者 capsys 在输出已被刷新后才被请求。capsys 只捕获调用时通过 sys.stdout 的写入。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 65% fail

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