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

Ish*_*ava 7 python unit-testing pytest python-unittest

在运行特定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)
Run Code Online (Sandbox Code Playgroud)

我尝试time.sleep(x)在该语句之前添加一些内容,但这无法解决。有人可以告诉我发生这种情况的确切原因以及解决方法吗?

Jos*_*ook 13

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

  • 这是我的问题的解决方案 (3认同)

wim*_*wim 6

由于input()是一种交互式功能,您将需要在自动化测试中模拟返回值。像这样:

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


小智 5

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

  • 如果你想使用`import ipdb; ipdb.set_trace()` 在你的代码中,不要忘记在 pytest 中添加 `-s` 标志,否则你会得到错误。 (3认同)