python pytest occasionally fails with OSError: reading from stdin while output is captured

python pytest occasionally fails with OSError: reading from stdin while output is captured

虽然 运行 一个特定的 unittestpytest,它偶尔会因这个错误而失败(在标题中提到)并且从堆栈跟踪中它发生在行

choice = input().lower()

当控件到达这条语句时,整个函数为:

def prompt_to_activate(bear, printer):
    PROMPT_TO_ACTIVATE_STR = ('program has found {} to be useful '
                              'based of dependencies discovered from your '
                              'project files. \n Would you like to activate '
                              'it? (y/n)')
    printer.print(PROMPT_TO_ACTIVATE_STR)

    choice = input().lower()

    if choice.startswith('y'):
        return True
    elif choice.startswith('n'):
        return False
    else:
        return prompt_to_activate(bear, printer)
for i in range(0, 3):
    a = i
print(a)

我尝试在该语句之前添加一些 time.sleep(x),但这并不能解决问题。有人可以告诉我发生这种情况的确切原因以及如何解决吗?

由于 input() 是一个交互式函数,您需要在自动化测试中模拟出 return 值。像这样:

def test_prompt(capsys, monkeypatch):
    monkeypatch.setattr('path.to.yourmodule.input', lambda: 'no')
    val = prompt_to_activate(bear=..., printer=...)
    assert not val

万一其他人偶然发现这个问题,如果您在代码中忘记了 pdb 断点 (import ipdb; ipdb.set_trace()),也会引发此错误。

如果您设置了断点,但没有在 pytest 中使用 -s 标志,您也可能会收到此信息。