来自pytest.org的示例代码,是否可以从json文件加载params?
# content of conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module",
params=["smtp.gmail.com", "mail.python.org"])
def smtp(request):
smtp = smtplib.SMTP(request.param)
def fin():
print ("finalizing %s" % smtp)
smtp.close()
request.addfinalizer(fin)
return smtp
我想做点什么
# conftest.py
@pytest.fixture(scope="module", params=a_list_var)
def fixture_a(request):
# some.py or anywhere?
a_list_var = load_json(parameter_file_path)
# test_foo.py
...
def test_foo(fixture_a)
...
答案 0 :(得分:4)
给出json文件:
["smtp.gmail.com", "mail.python.org"]
您可以简单地将其加载到Python对象并将该对象传递给装饰器。
import json
import pytest
import smtplib
def load_params_from_json(json_path):
with open(json_path) as f:
return json.load(f)
@pytest.fixture(scope="module", params=load_params_from_json('path/to/file.json'))
def smtp(request):
smtp = smtplib.SMTP(request.param)
def fin():
print ("finalizing %s" % smtp)
smtp.close()
request.addfinalizer(fin)
return smtp
答案 1 :(得分:2)
谢谢,我最终使用pytest-generate-tests,我的json路径将根据测试用例进行更改。
# test_foo.py
def test_foo(param)
# conftest.py
def pytest_generate_tests(metafunc):
... my <same_name_as_test>.json
... get info from metafunc.module
with open(param_full_path,'r') as f:
obj = json.load(f)
metafunc.parametrize("param", obj)