如何在pytest中添加标准输入交互

5
我正在为一个系统编写集成测试,其中大部分测试都可以通过 Web 服务调用自动化完成,但由于遗留问题我无法更改,因此需要一些步骤由人工测试人员完成。
我想使用 pytest 并创建一个 fixture,它会暂停测试执行并提示用户在控制台上输入(例如:“在系统中执行 XYZ;完成后键入'done'”),然后继续进行剩余的测试。
我承认我还没有对此进行过多的研究,但我从pytest文档中看到:
“... stdin设置为“null”对象,试图从该对象读取内容将导致失败,因为运行自动化测试时很少需要等待交互式输入。”
除了这个之外,在我的情况下,我真的需要等待,而且除此之外,我的东西看起来非常适合使用 pytest。
仍在通过网络搜索获取提示,但如果有人已经克服了这个障碍,我很想知道。

注意:在发布此内容之前,我没有尝试过sys.stdin,这让我感到很糟糕。当我重新连接时,这将是我要做的第一件事(只是为了确认我的担忧是否成立)。 - Daniel Hoag
我成功地解决了类似的问题,使用pytest -s来绕过IO捕获。这里有一些更好解决方案的提示:https://github.com/pytest-dev/pytest/issues/2189 - dmitry_romanov
1个回答

4
从版本3开始,您可以暂时禁用捕获功能:
def test_input(capsys):
    with capsys.disabled():
        input("hit enter to continue: ")
    print("this line is invisible as normal")

提供

(py36) dsm@notebook:~/coding$ py.test -v stdin.py 
========================================== test session starts ===========================================
platform linux -- Python 3.6.0, pytest-3.0.7, py-1.4.32, pluggy-0.4.0 -- /home/dsm/sys/miniconda3/envs/py36/bin/python
cachedir: .cache
rootdir: /home/dsm/coding, inifile:
plugins: cov-2.3.1
collected 1 items 

stdin.py::test_input hit enter to continue: [here I hit enter]
PASSED

======================================= 1 passed in 23.11 seconds ========================================

2
capsys.disabled()stdin 没有任何影响,它只影响 stdout/stderr - jmetz
我认为这个答案已经过时了,也许在之前的pytest版本中它可以工作,但是我可以确认在7.2.0中它不起作用 - Terseus

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