python pytest有时会因OSError失败:捕获输出时从stdin读取

时间:2018-07-18 02:52:03

标签: python unit-testing pytest python-unittest

使用unittest运行特定的pytest时,有时会因该错误而失败(标题中提到),并且从堆栈跟踪中发现它发生在行上

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),但这无法解决。有人可以告诉我发生这种情况的确切原因以及解决方法吗?

3 个答案:

答案 0 :(得分:4)

由于input()是一个交互式函数,因此您将需要在自动测试中模拟返回值。像这样:

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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