如何将多个命令行参数传递给pytest fixture作为参数
如何向单个pytest Fixture传递多个命令行参数
我希望执行如下命令时,把--arg1和--arg2两个参数传递给同一个fixture:
pytest test_sample.py --arg1 "Hello" --arg2 "World"
但我尝试的代码无法实现这个需求,以下是失败的代码:
test_string.py
import pytest @pytest.fixture() def stringinput(): # 如何将--arg1和--arg2都传递给它? 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")) # 此方法无效,如何添加多个选项?
我知道如何给fixture传递单个参数,但不知道怎么同时传递这两个命令行参数。
解决方法
要实现这个需求,需要修改conftest.py中的参数生成逻辑,将两个命令行参数组合成一组参数对后传递给fixture;同时调整fixture的定义来接收这组参数。
修改后的conftest.py
import pytest def pytest_addoption(parser): parser.addoption( "--arg1", default="Hello", # 若不需要多次追加参数,可去掉action="append",设置默认值即可 help="第一个输入参数", ) parser.addoption( "--arg2", default="World", help="第二个输入参数", ) def pytest_generate_tests(metafunc): if "stringinput" in metafunc.fixturenames: # 获取两个命令行参数的值 arg1 = metafunc.config.getoption("--arg1") arg2 = metafunc.config.getoption("--arg2") # 将参数组合成元组,作为fixture的输入参数 metafunc.parametrize("stringinput", [(arg1, arg2)])
修改后的test_string.py
import pytest @pytest.fixture() def stringinput(request): # 从request.param获取传递的参数元组 arg1, arg2 = request.param print(f"arg1 is: {arg1}") print(f"arg2 is: {arg2}") # 可将参数返回给测试用例使用 return (arg1, arg2) def test_valid_string(stringinput): arg1, arg2 = stringinput assert arg1 == "Hello" assert arg2 == "World"
扩展说明
如果需要支持多组参数传递(比如多次输入--arg1和--arg2),可以保留action="append",并将两个参数列表按索引配对:
def pytest_generate_tests(metafunc): if "stringinput" in metafunc.fixturenames: arg1_list = metafunc.config.getoption("--arg1") arg2_list = metafunc.config.getoption("--arg2") # 确保两组参数数量一致 assert len(arg1_list) == len(arg2_list), "arg1和arg2的输入数量必须匹配" # 配对成参数元组列表 params = list(zip(arg1_list, arg2_list)) metafunc.parametrize("stringinput", params)
此时可执行如下命令,测试用例会自动运行两次,分别使用两组参数:
pytest test_sample.py --arg1 "Hello" --arg1 "Hi" --arg2 "World" --arg2 "There"
内容的提问来源于stack exchange,提问作者HalfOfRain
相关产品推荐
相关产品推荐

