I have a code which uses files in a directory as parameters:
def get_testcases(directory):
files = list(os.listdir(directory))
testcases = filter(lambda x: x.endswith('.yaml'), files)
for testcase in testcases:
postconf = testcase.replace('.yaml', '.conf')
yield (
os.path.join(directory, testcase),
os.path.join(directory, postconf)
)
def get_pre_configs(directory):
for file in os.listdir(directory):
if file.endswith('.conf'):
yield os.path.join(directory, file)
@pytest.mark.parametrize("pre_config", get_pre_configs('pre_configs'))
@pytest.mark.parametrize("testcase_declaration, testcase_result", get_testcases('testcases'))
def test_foo(pre_config, testcase_declaration, testcase_result):
assert testcase_declaration
assert testcase_result
assert pre_config
It works as I need, but I don't like pytest output:
test_interface.py::test_foo[testcases/up.yaml-testcases/up.conf-pre_configs/bad.conf] PASSED [ 16%]
test_interface.py::test_foo[testcases/up.yaml-testcases/up.conf-pre_configs/simple.conf] PASSED [ 33%]
test_interface.py::test_foo[testcases/up.yaml-testcases/up.conf-pre_configs/complicated.conf] PASSED [ 50%]
test_interface.py::test_foo[testcases/down.yaml-testcases/down.conf-pre_configs/bad.conf] PASSED [ 66%]
test_interface.py::test_foo[testcases/down.yaml-testcases/down.conf-pre_configs/simple.conf] PASSED [ 83%]
test_interface.py::test_foo[testcases/down.yaml-testcases/down.conf-pre_configs/complicated.conf] PASSED [100%]
Is there any way to show a different name for the test than the value passed to the test? I want to trim away a directory name and an extension from filenames (for test names only, I'd like to pass them 'as is' to the test).
It turns out that
@pytest.mark.parametrize
(as well as@pytest.fixtures
) are quite powerful. They allow you to change the name of each test by specifying anids
list. The trick is to generate the arguments forparametrize
dynamically.I refactored your code (see further below). Given a local dir containing:
Then the pytest output is:
Here is the refactored code. Note how both
get_testcases()
andget_pre_configs()
both return adict
that can be used askwargs
for@pytest.mark.parametrize
. In particular,ids
allows you to override the name used bypytest
.