在py.test
中,我需要根据我在文件中定义的测试动态定义测试
所以我想的是在conftest.py
中定义一个fixture,它读取文件并返回一个包含测试的字典
文件tests.json
:
{
"test1": "text",
"test2": "42",
"test3": 1
}
然后,我在conftest.py
中定义一个fixture以返回带有测试的字典:
def pytest_addoption(parser):
parser.addoption(
"--tests",
default="tests.json",
)
@pytest.fixture
def mytests(request):
testfile = request.config.getoption("--tests")
with open(testfile) as f:
tests = json.load(f)
return tests
然后我可以在test_pytest.py
中使用参数化测试,如下所示:
@pytest.mark.parametrize("test_name", [(key) for key, value in mytests.items()])
def test1(test_name):
print(test_name)
这不起作用,因为在这一点上,py.test
似乎不知道mytests
是一个固定装置。我犯了一个错误
E NameError: name 'mytests' is not defined
如何正确处理?我只希望能够运行json文件中定义的所有测试,或者能够使用-k
选项(如果py.test
)从中选择单个测试
怎么做
根据下面给出的一些评论,我尝试实现以下内容:
@pytest.hookimpl
def pytest_generate_tests(metafunc):
if "myparam" in metafunc.fixturenames:
with open(metafunc.config.option.tests) as f:
tests = json.load(f)
# add parametrization for each fixture name
for name, value in tests.items():
print(name, value)
metafunc.parametrize("mparam", (name, value))
def test1(myparam):
print(myparam)
但是我犯了一个错误
ERROR test_pytest.py - ValueError: duplicate 'myparam'
如注释中所述,您不能在
mark.parametrize
中使用装置。夹具只能用于测试功能和其他夹具要像本例中那样进行动态参数化,可以实现钩子函数
pytest_generate_tests
:这将使用“test_name”参数(例如fixture)和配置文件中的项目参数化所有测试
使用给定的json文件运行此命令将导致如下结果:
相关问题 更多 >
编程相关推荐