[英]How can I change the value of the returned fixture in a test in PyTest
我在 Python 中有几个测试函数(使用 PyTest),我传入一个模板作为要评估的夹具。 为了准确解释结果,我需要知道模板名称(模板的值),而不仅仅是 PyTest 分配的值。
有谁知道如何在下面的 output 中替换 '[template[1,2,3]]' 以使用夹具的值来代替? 请注意,模板是来自已解析 JSON 文件的字典。
我想用template['name']
替换括号中的值。
FAILED tests/test_device_group.py::test_device_group_staging_type[template78] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template109] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template110] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template116] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template117] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template125] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template126] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[template131] - assert False
我想要的是:
FAILED tests/test_device_group.py::test_device_group_staging_type[my_template] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[testing_template] - assert False
FAILED tests/test_device_group.py::test_device_group_staging_type[another_template] - assert False
以下是我当前的测试文件:
import json
import pytest
import pathlib
templates = './templates/device_groups'
list_of_templates = []
d = pathlib.Path(templates)
for entry in d.iterdir():
if entry.is_file():
list_of_templates.append(entry)
@pytest.fixture(params=list_of_templates)
def template(request):
with open(request.param) as file:
template = json.loads(file.read())
return template
def test_device_group_description(template: dict):
'''
Description must be present
'''
if 'description' in template:
if template['description'] != '':
assert True
else:
assert False
else:
assert False, 'Description is empty.'
def test_device_group_staging_type(template: dict):
'''
Staging must be configured
'''
if template['enable-staging-url']:
if template['staging-type'] == 'staging':
assert True
else:
assert False
您可以使用ids
参数来配置参数名称,它的工作方式与参数化相同。 唯一需要注意的是,您必须再次加载模板才能获得名称,例如:
def ids(template_name):
with open(template_name) as file:
template = json.loads(file.read())
return template['name'] if 'name' in template else template_name
@pytest.fixture(params=list_of_templates, ids=ids)
def template(request):
with open(request.param) as file:
template = json.loads(file.read())
return template
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.