【问题标题】:How can I make py.test tests accept interactive input?如何让 py.test 测试接受交互式输入?
【发布时间】:2020-03-20 13:57:29
【问题描述】:

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

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

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 调用测试文件以防止标准输入和标准输出捕获,但 py.test 文档中记录的方法 (with capsys.disabled()) 不起作用,因为它们只影响标准输出和标准错误。

使用 py.test 模块中的代码 来完成这项工作的好方法是什么,没有命令行选项,最好是按测试?

这个平台,不管它的价值,是 Windows,我不希望有这个 clobber 或被 stdin/out/任何嵌套 shell、不常见 shell 等结果的包装所破坏。

【问题讨论】:

  • 你想做什么样的测试?单元测试、集成测试、行为测试、可用性测试……?看起来您正在尝试混合所有这些。顺便说一句,原则上每个软件都可以测试。
  • 我想要做的具体是让 input() 内置在 Pytest 单元案例中的工作方式与在交互式 python 或脚本中的工作方式相同。
  • 你找到解决这个问题的好方法了吗!?我基本上是在尝试做完全相同的测试,多个软件层与硬件接口,需要技术人员在测试之间操作硬件的一部分。

标签: python pytest


【解决方案1】:

没有命令行选项

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

理想情况下每次测试?

使用功能范围的夹具来获取用户输入。示例代码:

# 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"

【讨论】:

    猜你喜欢
    • 2022-10-08
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多