代码之家  ›  专栏  ›  技术社区  ›  Ishan Srivastava

python pytest偶尔会失败,并出现OSError:在捕获输出时读取stdin

  •  4
  • Ishan Srivastava  · 技术社区  · 8 年前

    当运行一个特定的 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) 在那份声明之前,但那不能解决问题有人能告诉我发生这种事的确切原因以及如何解决吗?

    1 回复  |  直到 8 年前
        1
  •  6
  •   wim    8 年前

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

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