将多个命令行参数作为参数传递给 pytest 夹具

问题描述 投票:0回答:1

我想将多个参数传递给单个 pytest 固定装置,例如:

pytest test_sample.py --arg1 "Hello" --arg2 "World" 

我有一个需要 2 个参数的装置。下面是一次失败的尝试。

# test_string.py
import pytest

@pytest.fixture()
def stringinput():  # How to pass both --arg1 and --arg2 to it?
    print("arg1 is: ", arg1)
    print("arg2 is: ", arg2)


def test_valid_string(stringinput):
    pass
# conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--arg1",
        action="append",
        default=[],
        help="list of stringinputs to pass to test functions",
    )
    parser.addoption(
        "--arg2",
        action="append",
        default=[],
        help="list of stringinputs to pass to test functions",
    )


def pytest_generate_tests(metafunc):
    if "stringinput" in metafunc.fixturenames:
        metafunc.parametrize("stringinput", metafunc.config.getoption("arg1"))
        metafunc.parametrize("stringinput", metafunc.config.getoption("arg2"))  # This doesn't work. How to add multiple options?

这篇文章解决了将单个参数传递给固定装置的问题,但是如何将

--arg1
--arg2
都传递给固定装置?

python pytest
1个回答
0
投票

如果我正确理解你的问题,你根本不需要参数化测试。如果您只想处理固定装置中的命令行参数,则可以通过标准

request
固定装置访问固定装置内的参数:

import pytest


@pytest.fixture
def stringinput(request):
    arg1 = request.config.option.arg1 if "arg1" in request.config.option else ""
    arg2 = request.config.option.arg2 if "arg2" in request.config.option else ""
    yield f"{arg1}-{arg2}"


def test_valid_string(stringinput):
    print(f"{stringinput=}")

因此,如果使用

--arg1=foo --arg2=bar
运行测试,输出将为
stringinput=foo-bar

您仍然想像现在一样使用

pytest_addoption
注册您的选项,但不需要实现
pytest_generate_tests

© www.soinside.com 2019 - 2024. All rights reserved.