如何让 py.test 测试接受交互式输入? [英] How can I make py.test tests accept interactive input?

查看:98
本文介绍了如何让 py.test 测试接受交互式输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 py.test 用于一个有点非常规的应用程序.基本上,我希望通过 print() 和 input()(这是 Python 3.5)在测试中进行用户交互.最终目标是对硬件和多层软件进行半自动化测试,即使在原则上也无法进行自动测试.一些测试用例会要求测试技术人员做某事(通过控制台上的输入或按​​任意键或类似方式进行确认)或要求他们进行简单的测量或视觉确认某事(在控制台上输入).

I'm using py.test for a somewhat unconventional application. Basically, I want to have user interaction in a test via print() and input() (this is Python 3.5). The ultimate goal is to have semi-automated testing for hardware and multi-layered software which cannot be automatically tested even in principle. Some test cases will ask the testing technician to do something (to be confirmed by enter or press any key or similar on the console) or ask them to take a simple measurement or visually confirm something (to be entered on the console).

我(天真地)想做的例子:

Example of what I (naively) want to do:

def test_thingie():
    thingie_init('red')
    print('Testing the thingie.')
    # Ask the testing technician to enter info, or confirm that he has set things up physically
    x = int(input('Technician: How many *RED* widgets are on the thingie? Enter integer:')) 
    assert x == the_correct_number

这适用于使用 pytest -s 调用测试文件以防止 stdin 和 stdout 捕获,但 py.test 文档中记录的方法(with capsys.disabled())t 工作,因为它们只影响 stdout 和 stderr.

This works with when the test file is called with pytest -s to prevent stdin and stdout capturing, but the documented means (with capsys.disabled()) in the py.test documentation don't work since they only affect stdout and stderr.

使用 py.test 模块中的代码,没有命令行选项,理想情况下是每个测试,有什么好方法可以使这项工作正常进行?

What's a good way to make this work using code in the py.test module, no command line options, and ideally per-test?

就其价值而言,该平台是 Windows,我不希望有这种破坏或被 stdin/out/任何由嵌套外壳、不常见外壳等导致的包装破坏.

The platform, for what it's worth, is Windows and I'd prefer not to have this clobber or get clobbered by the wrapping of stdin/out/whatever that results from nested shells, uncommon shells, etc.

推荐答案

没有命令行选项

使用 pytest.ini option 或 env 变量 避免每次都使用命令行选项.

Use pytest.ini option or env variable to avoid using command line option every time.

理想情况下每次测试?

使用函数作用域夹具来获取用户输入.示例代码:

Use function scoped fixture to take user input. Example code:

# contents of conftest.py
import pytest
@pytest.fixture(scope='function')
def take_input(request):
    val = input(request.param)
    return val



#Content of test_input.py
import pytest

@pytest.mark.parametrize('prompt',('Enter value here:'), indirect=True)
def test_input(take_input):
    assert take_input == "expected string"

这篇关于如何让 py.test 测试接受交互式输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆