python data_error ai_generated true

AssertionError: assert '' == 'hello\n' + 其中 '' = capsys.readouterr().out

AssertionError: assert '' == 'hello\n' + where '' = capsys.readouterr().out

ID: python/pytest-capsys-not-captured

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-11-27首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

输出写入了日志处理器、子进程或 C 层文件描述符,这些 capsys 都无法捕获。capsys 仅捕获 Python 层的 sys.stdout/stderr 写入。

English

Output was written to a logging handler, a subprocess, or a C-level fd, none of which capsys captures. capsys only captures Python-level sys.stdout/stderr writes.

generic

解决方案

  1. 92% 成功率
    def test_cli(capfd):
        import subprocess, sys
        subprocess.run([sys.executable, "-c", "print('hello')"])
        out, err = capfd.readouterr()
        assert out == "hello\n"
  2. 94% 成功率
    import logging
    
    def test_log(caplog):
        with caplog.at_level(logging.INFO):
            logging.getLogger("app").info("hello")
        assert "hello" in caplog.text

无效尝试

常见但无效的做法:

  1. 80% 失败

    Each call drains the buffer; repeated calls return empty strings after the first.

  2. 70% 失败

    That disables capture entirely; the assertion still sees nothing.