Skip to main content
 首页 » 编程设计

python之如何添加标准输入与pytest的交互

2024年10月01日15jiqing9006

我正在为一个系统编写集成测试,在该系统中我可以通过 Web 服务调用自动执行大部分测试,但由于我无法更改的遗留问题,我需要手动测试人员完成一些步骤。

我想使用 pytest 并创建一个 fixture,该 fixture 基本上暂停测试执行并提示控制台输入(例如“在系统中执行 XYZ;完成时键入‘done’”)并继续测试的其余部分。

诚然,我还没有对此做大量的黑客攻击,但我从 pytest 文档中看到:

... stdin is set to a “null” object which will fail on attempts to read from it because it is rarely desired to wait for interactive input when running automated tests.

除了,就我而言,我真的很想等待,除此之外,我的东西看起来是 pytest 的一个很好的用例。

仍在互联网上搜索提示,但如果有人已经越过了这个障碍,我很想知道。

请您参考如下方法:

从版本 3 开始,您可以 temporarily disable捕获:

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 ========================================