使用pytest+ddt传递测试数据时出现fixture 'sort_by'未找到错误
解决ddt的file_data装饰器结合pytest时fixture找不到的问题
问题场景
在PyCharm中使用ddt的file_data装饰器读取JSON测试数据,运行pytest测试时触发fixture 'sort_by' not found错误。
执行代码
from ddt import file_data, ddt import pytest @ddt class TestCase: @file_data('../testdata/testdatajson.json') def test_ddtfile(self, sort_by, sort_id): print(sort_by, sort_id)
测试数据文件(testdatajson.json)
{ "test1" : { "sort_by": 2, "sort_id" : "wc-block-components-sort-select__select-0" } }
报错信息
________________________________________________________ ERROR at setup of TestCase.test_ddtfile_1_test1 _________________________________________________________ file D:\WORK_WK\learn_github\testcases\test_ddtfile.py, line 6 @file_data('../testdata/testdatajson.json') def test_ddtfile(self, sort_by, sort_id): E fixture 'sort_by' not found > available fixtures: GSSetup, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record _testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory > use 'pytest --fixtures [testpath]' for help on them.
报错原因
pytest会默认将测试方法的参数识别为需要注入的fixture,而原生ddt是为unittest设计的,其file_data装饰器传递命名参数的方式和pytest的fixture机制冲突,导致pytest误将测试方法的sort_by、sort_id参数当成fixture去查找,最终抛出找不到fixture的错误。
解决方案
方法一:修改测试方法为接收单个字典参数
将测试方法的参数改为接收单个字典,再从字典中提取所需字段,避免pytest将参数识别为fixture:
from ddt import file_data, ddt import pytest @ddt class TestCase: @file_data('../testdata/testdatajson.json') def test_ddtfile(self, data): sort_by = data['sort_by'] sort_id = data['sort_id'] print(sort_by, sort_id)
方法二:使用pytest原生参数化替代ddt(推荐)
直接使用pytest自带的@pytest.mark.parametrize装饰器,更适配pytest生态,无需依赖ddt:
import json import pytest def load_test_data(file_path): with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) # 将JSON中的每个测试用例转为元组,适配parametrize的参数格式 return [tuple(item.values()) for item in data.values()] class TestCase: @pytest.mark.parametrize('sort_by, sort_id', load_test_data('../testdata/testdatajson.json')) def test_ddtfile(self, sort_by, sort_id): print(sort_by, sort_id)
方法三:安装适配pytest的ddt版本
卸载原生ddt,安装专门适配pytest的pytest-ddt包,保持原有代码结构即可正常运行:
- 卸载原生ddt:
pip uninstall -y ddt
- 安装pytest-ddt:
pip install pytest-ddt
- 修改导入语句并运行原有代码:
from pytest_ddt import file_data, ddt import pytest @ddt class TestCase: @file_data('../testdata/testdatajson.json') def test_ddtfile(self, sort_by, sort_id): print(sort_by, sort_id)
内容的提问来源于stack exchange,提问作者K A S
相关产品推荐
相关产品推荐

