python-pytest-cases
python-pytest-cases copied to clipboard
Adding Support for Tuple of Prefixes
Problem
In a project I am working on, I recently came across a need for referring to cases with differing prefixes. That is,
prefix1_id():
pass
prefix2_id():
pass
Present Solution
One could rename the case functions with a common prefix—e.g., case_prefix1... and case_prefix2.... However, this removes the customization of having support for custom prefixes in pytest_cases. Additionally, it would involve refactoring any pre-existing test code.
My Solution
After digging through the source code of pytest_cases, I modified a few lines to support tuples of prefixes:
First, I altered the validation code in get_all_cases() to support tuple[str].
pytest_cases/case_parametrizer_new.py::251
# validate prefix
if not isinstance(prefix, str):
if not (isinstance(prefix, tuple) and all(isinstance(val, str) for val in prefix)):
raise TypeError("`prefix` should be a string, found: %r" % prefix)
if isinstance(prefix, tuple):
# Reverse sort prefix to guarantee greedy prefix completion
prefix = sorted(tuple, reverse=True)
Then, I modified get_case_id() to return the appropriate id when a tuple of prefixes is given.
pytest_cases/case_funcs.py::162
if _id is None:
# default case id from function name based on prefix
if isinstance(prefix_for_default_ids, str):
_id = case_func.__name__.removeprefix(prefix_for_default_ids)
else:
original = case_func.__name__
for prefix in prefix_for_default_ids:
modified_id = original.removeprefix(prefix)
if not original == modified_id:
_id = modified_id
break
From my brief testing, the changes seem to cover all the use cases of prefix and performed as expected.
Usage:
@pytest_cases.parametrize_with_cases('case', prefix=('prefix1_', 'prefix2_')...)
def test_foo(case):
pass
Proposal
Would support for tuples of prefixes be desirable behaviour for pytest_cases? If so, I would be more than happy to draft up a pull request and formalize these code changes with the appropriate refactors.
Thanks @ImplyingICheck for your proposal and first tests ! The changes seem limited in scope so I would be happy to consider this feature for inclusion. Still, that would require a few tests combining a tuple of prefixes AND a filters/tags/both (I let you check whichever is relevant as interacting with the prefix, if any)