pytest 参数化夹具 - 来自 json 的参数?

pytest parametrized fixture - parameters from json?

来自 pytest.org 的示例代码,是否可以从 json 文件加载参数?

# 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)
    ...

给定 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

谢谢,为此我最终使用了 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)