I have several test functions in Python (using PyTest) and I pass in a template as a fixture in which to evaluate. In order to interpret the results accurately, I need to know the template name (a value of the template) and not just a value assigned by PyTest.
Does anyone know how I can replace '[template[1,2,3]]' in the output below to use a value of the fixture instead? Note that the template is a dictionary from a parsed JSON file.
I would like to replace the value in the brackets with 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
What I would like instead is:
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
Below is my current test file:
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
CodePudding user response:
You can use the ids
argument to configure the parameter names, it works the same way as with parametrize. The only caveat is that you have to load the template again to get the name, e.g. something like:
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