pytest如何将fixture值作为参数化测试输入实现动态用例生成
问题原因与解决方案
第一个错误(NameError)原因
@pytest.mark.parametrize装饰器在模块导入阶段就会执行,而fixture是在测试用例执行前才会被pytest初始化加载,装饰器执行时fixture还不存在,自然无法调用mytests.items()。
第二个错误(duplicate 'myparam')原因
metafunc.parametrize是一次性为指定参数注入所有参数值的,你在循环中反复对同一个参数名myparam调用该方法,导致重复定义参数,触发报错。
正确实现代码
1. conftest.py 代码
import json import pytest def pytest_addoption(parser): parser.addoption( "--tests", default="tests.json", help="Path to test case json file" ) @pytest.hookimpl(tryfirst=True) def pytest_generate_tests(metafunc): # 只有测试函数参数包含test_case时才触发参数化 if "test_case" in metafunc.fixturenames: test_file = metafunc.config.getoption("--tests") with open(test_file, encoding="utf-8") as f: tests = json.load(f) # 一次性传入所有测试项,ids设置为json的键名,方便-k参数筛选 metafunc.parametrize( "test_case", tests.items(), ids=list(tests.keys()) )
2. 测试用例文件(test_pytest.py)代码
def test_all(test_case): test_name, test_value = test_case # 这里写你的测试逻辑,以下是示例 print(f"当前执行测试:{test_name},测试值:{test_value}") assert test_value is not None
使用效果
- 直接运行
pytest -v会自动生成3条测试用例,分别显示为test_all[test1]、test_all[test2]、test_all[test3] - 要单独执行某条用例,直接用
-k参数匹配即可,比如执行test2的命令为:pytest -k test2 -v
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

