pytest中fixture返回值与参数化测试结合使用的写法校验
结论
你给出的写法不正确,存在多处语法错误、API调用错误和pytest用法错误,直接执行会报错,无法达到预期效果。
具体错误点
- 自定义命令行参数的钩子函数名拼写错误:pytest注册自定义参数的钩子是
pytest_addoption,不是你写的pytest_adoption,拼写错误会导致你定义的--arg1、--arg2参数根本不会被pytest识别。 conftest.py中参数注册逻辑错误:注册参数需要调用parser对象的addoption方法,不能直接把parser当函数调用;同时"--arg2缺少闭合的双引号,存在基础语法错误。- fixture使用逻辑错误:你给
getArg加了autouse=True只会让fixture在测试用例执行前自动运行,但不会把fixture的返回值自动注入到测试函数的作用域,必须把fixture名称作为参数传入测试函数,才能拿到它返回的元组,你当前写法里getArg就是个函数对象,那个类型断言会直接失败。 - Python语法错误:Python中的逻辑与运算符是
and,不支持其他语言常用的&&,写&&会直接触发语法报错。
修正后可运行代码
conftest.py
import pytest def pytest_addoption(parser): parser.addoption("--arg1", action="store", help="first argument") parser.addoption("--arg2", action="store", help="second argument")
example_test.py
import pytest test_data = [("name1","surname1",40),("name2","surname2",30)] @pytest.fixture(autouse=True) def getArg(pytestconfig): arg1 = pytestconfig.getoption("arg1") arg2 = pytestconfig.getoption("arg2") return arg1, arg2 @pytest.mark.parametrize("name,surname,age", test_data) # 传入fixture名称才能拿到返回值 def test_example(name, surname, age, getArg): assert type(getArg) == tuple arg1, arg2 = getArg # 替换&&为Python原生的and运算符 if arg1 == "first" and arg2 == "second": print('My name is {} {} and I am {} years old'.format(name, surname, age)) # 建议补充有效断言,避免测试无校验逻辑 assert True
执行命令
保持你原来的写法即可:
pytest example_test.py --arg1 "first" --arg2 "second"
补充:如果不想额外写fixture,也可以直接在测试函数中传入
pytestconfig参数,直接调用pytestconfig.getoption()拿命令行参数,效果完全一致。
内容的提问来源于stack exchange,提问作者ibra
相关产品推荐
相关产品推荐

