当使用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)
,但这无法解决。有人可以告诉我发生这种情况的确切原因以及如何解决吗? 最佳答案
由于 input()
是一个交互式函数,因此您将需要在自动化测试中模拟返回值。像这样的东西:
def test_prompt(capsys, monkeypatch):
monkeypatch.setattr('path.to.yourmodule.input', lambda: 'no')
val = prompt_to_activate(bear=..., printer=...)
assert not val
关于python pytest有时会因OSError : reading from stdin while output is captured而失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51392889/