我尝试将测试数据文件路径列表作为命令行参数传递。但是,我最终得到了以下代码块:
来自
conftest.py
文件:
import json
from pytest import fixture
def pytest_addoption(parser):
parser.addoption(
"--test-data-path",
action="store",
default="test_data/test_data.json", # not suggested
help="Path of test data file"
)
@fixture(scope='session')
def get_test_data_path(request):
return request.config.getoption("--test-data-path")
def load_test_data(path=get_test_data_path):
with open(path) as test_data_file:
return json.load(test_data_file)
@fixture(scope="session", params=load_test_data()["body_types"])
def get_body_list(request):
body_type = request.param
yield body_type
test_data/test_data.json
的内容:
{
"body_types": ["coupes", "cabriolets"]
}
似乎造成了问题,因为我无法访问非夹具功能内的夹具。
如有遗漏请指正
我尝试过以不同的方式编写
load_test_data
函数,例如:
import json
from pytest import fixture
def load_test_data(path):
with open(path) as test_data_file:
return json.load(test_data_file)
@fixture(scope='session')
def get_test_data_path(request):
return request.config.getoption("--test-data-path")
@fixture(scope="session", params=load_test_data(get_test_data_path)["body_types"])
def get_body_list(request):
body_type = request.param
yield body_type
然而,一切都没有改变。
问题是当模块被加载时,包装器也会被加载。 所以这意味着
load_test_data
接收到的只是函数调用,就像您也想到的那样。
我仍然没有找到如何以一种简单易懂的方式做到这一点的运气,但请看一下这里。人们已经做了一些伎俩。 https://github.com/pytest-dev/pytest/issues/6374
我发现了一个旧的例子,我做了类似你想要的事情。 这里我从 pytest_configure 钩子预加载数据,然后将其传递到全局变量中,然后在加载测试用例时,从全局变量传递测试数据
# conftest.py
test_data = []
def pytest_configure(config):
global test_data
path = "./test_data.json" # config.getoption("--test-data-path")
with open(path) as test_data_file:
test_data = json.load(test_data_file)
这是我的测试用例:
# testcase
import pytest
from tests.conftest import test_data
@pytest.mark.parametrize("body", test_data["body_types"])
def test_pass(body):
pass