如何通过Python脚本(而非命令行)在pytest调用时传递变量?
解决pytest自定义fixture未找到的问题
问题描述
在Python脚本中通过pytest.main运行测试时,尝试将script.py中定义的config参数传递给test_functions.py的测试用例,却遇到以下错误:
E fixture 'config' not found available fixtures: anyio_backend, anyio_backend_name, anyio_backend_options, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, info, 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.
原代码
script.py
import pytest if __name__ == '__main__': config = { 'key1': 'value1', 'key2': 'value2', # Add more key-value pairs as needed } class MyPlugin(object): def __init__(self, data): self.data = data @pytest.fixture def info(self, request): return self.data myplugin = MyPlugin(config) pytest.main(['test_functions.py'],plugins=[myplugin])
test_functions.py
def test_function(config): # Access the config dictionary print(config['monthly_or_weekly']) assert config['value1']=='value2'
问题分析
- Fixture名称不匹配:插件中定义的fixture名称是
info,但测试用例里请求的是config,这是导致"fixture 'config' not found"的直接原因。 - 测试用例逻辑错误:
- 测试用例中尝试打印
config['monthly_or_weekly'],但原config字典中不存在该键; - 断言
config['value1']=='value2'逻辑错误,原config中只有key1对应value1,不存在value1这个键。
- 测试用例中尝试打印
解决方案
方案1:修改fixture名称为config
调整script.py中的fixture名称,使其与测试用例中请求的名称一致,同时补充config中缺失的键:
修正后的script.py
import pytest if __name__ == '__main__': config = { 'key1': 'value1', 'key2': 'value2', 'monthly_or_weekly': 'monthly' # 添加测试用例需要的键 } class MyPlugin(object): def __init__(self, data): self.data = data @pytest.fixture def config(self, request): # 将fixture名称改为config return self.data myplugin = MyPlugin(config) pytest.main(['test_functions.py'], plugins=[myplugin])
修正后的test_functions.py
def test_function(config): print(config['monthly_or_weekly']) assert config['key1'] == 'value1' # 修正断言逻辑
方案2:测试用例中使用已定义的info fixture
如果不想修改fixture名称,直接在测试用例中使用插件里定义的info作为参数:
修正后的test_functions.py
def test_function(info): print(info['monthly_or_weekly']) assert info['key1'] == 'value1'
同时记得在script.py的config字典中添加monthly_or_weekly键。
内容的提问来源于stack exchange,提问作者Tilak Mallikarjun
相关产品推荐
相关产品推荐

