python - 如何使用命令行在pytest中传递多个参数?

标签 python python-3.x pytest

我想将输入作为命令行选项传递到我的 pytest 文件。这个问题 https://stackoverflow.com/a/42145604/8031479 很有帮助,但我不知道要添加多个解析器采用。

我曾尝试将其添加到我的 conftest.py 文件中,但没有帮助:

def pytest_addoption(parser):
    """
        This function is used to extract input1 and input2 values from the command line
    """
    parser.addoption(
        "--input1", action="store", default="input1"
    )
    parser.addoption(
        "--input2", action="store", default="input2"
    )

我的 test.py 文件的内容:

import pytest

@pytest.fixture()
def get_input1(input1):
    print 'input1:', input1
    return input1

# @pytest.mark.unit
@pytest.fixture()
def get_input2(input2):
    print 'input2:', input2
    return input2

def test_hello(get_input1, get_input2):
    print 'testing pytest fixtures with command line options'
    print get_input1, get_input2

这是我运行 test.py 文件的命令:

py.test test.py --input1="hello" --input2="world"

我收到此错误消息:

@pytest.fixture()
def get_input1(input1):
E       fixture 'input1' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, get_input1, get_input2, metadata, monkeypatch, pytestconfig, record_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

最佳答案

你可以让它这样工作:

conftest.py:

import pytest


def pytest_addoption(parser):
    parser.addoption("--input1", action="store", default="default input1")
    parser.addoption("--input2", action="store", default="default input2")



@pytest.fixture
def input1(request):
    return request.config.getoption("--input1")


@pytest.fixture
def input2(request):
    return request.config.getoption("--input2")

测试.py:

import pytest

@pytest.mark.unit
def test_print_name(input1, input2):
    print ("Displaying input1: %s" % input1)
    print("Displaying input2: %s" % input2)

命令行界面:

>py.test -s test.py --input1 tt --input2 12
================================================= test session starts =================================================
platform win32 -- Python 3.7.0, pytest-4.1.1, py-1.7.0, pluggy-0.8.1
rootdir: pytest, inifile:
collected 1 item

test.py Displaying input1: tt
Displaying input2: 12
.

============================================== 1 passed in 0.04 seconds ===============================================

关于python - 如何使用命令行在pytest中传递多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54416550/

相关文章:

python - 如何安装py.test?

python - 运行时错误 : CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling `cublasSgemm( handle)` with GPU only

python - 当我尝试使用默认构造函数实例化对象时,为什么会因调用参数化构造函数而收到错误?

python - 有没有办法断言两个字符串除了 python 中的一部分之外是相同的?

python - 变量赋值错误

python-3.x - 无法预测表情符号的情绪

python - pytest ScopeMismatch 错误 : how to use fixtures properly

python - 通过 lambda 将变量传递到函数 Tkinter

python - Django login_required 装饰器未将 "next"值传递给模板

python - 从文本文件中的行中剥离字符串并将列读入以列表为值的字典中