Python的pytest偶尔会出现OSError错误:在输出被捕获时从stdin读取。

19

在使用pytest运行特定的unittest时,偶尔会出现这个错误(在标题中提到),从堆栈跟踪来看,它发生在以下代码行:

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),但这并没有解决问题。有人可以告诉我发生这种情况的确切原因以及如何解决吗?

4个回答

12
你可能会收到这个消息,如果你设置了断点,但没有使用pytest的-s标志。

2
这是我的问题的解决方案。 - Nisanio

12

由于 input() 是交互式函数,在自动化测试中,您需要模拟返回值。可以像这样实现:

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

5
如果其他人遇到这个问题,也可能是因为你在代码中忘记了设置 pdb 断点(import ipdb; ipdb.set_trace())。

3
如果您想在代码中使用 import ipdb; ipdb.set_trace(),请不要忘记在 pytest 中添加 -s 标志,否则会出现错误。 - Sina

0

我也遇到了同样的问题,在学习更多单元测试和模拟后解决了它!除了@wim的答案之外...另一种模拟输入的方法是:

@mock.patch("my_module.input")
def test_my_actual_func(self, mock_input):
    my_actual_func()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接