Skip to content

Commit 4782ea6

Browse files
committed
feat: add cli, ini option skips pytest internal logic of id generation and raise error
1 parent 1d0c8a7 commit 4782ea6

File tree

5 files changed

+164
-0
lines changed

5 files changed

+164
-0
lines changed

changelog/13737.feature.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Added the ``--require-unique-parameterization-ids`` command-line flag and :confval:`require_unique_parameterization_ids` configuration option to pytest.
2+
3+
When passed, this flag causes pytest to raise an exception upon detection of non-unique parameter set IDs,
4+
rather than automatically modifying the IDs to ensure uniqueness.

doc/en/reference/reference.rst

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2082,6 +2082,30 @@ passed multiple times. The expected format is ``name=value``. For example::
20822082
[pytest]
20832083
xfail_strict = True
20842084
2085+
.. confval:: require_unique_parameterization_ids
2086+
2087+
When passed, this flag causes pytest to raise an exception upon detection of non-unique parameter set IDs,
2088+
rather than attempting to generate them automatically.
2089+
2090+
Can be overridden by `--require-unique-parameterization-ids`.
2091+
2092+
.. code-block:: ini
2093+
2094+
[pytest]
2095+
require_unique_parameterization_ids = True
2096+
2097+
.. code-block:: python
2098+
2099+
import pytest
2100+
2101+
2102+
@pytest.mark.parametrize("x", [1, 2], ids=["a", "a"])
2103+
def test_example(x):
2104+
assert x in (1, 2)
2105+
2106+
will raise an exception due to the duplicate IDs "a".
2107+
when normal pytest behavior would be to handle this by generating unique IDs like "a-0", "a-1".
2108+
20852109

20862110
.. _`command-line-flags`:
20872111

@@ -2239,6 +2263,11 @@ All the command-line flags can be obtained by running ``pytest --help``::
22392263
--doctest-continue-on-failure
22402264
For a given doctest, continue to run after the first
22412265
failure
2266+
--require-unique-parameterization-ids
2267+
If pytest collects test ids with non-unique names, raise an
2268+
error rather than handling it.
2269+
Useful if you collect in one process,
2270+
and then execute tests in independent workers.
22422271

22432272
test session debugging and configuration:
22442273
-c, --config-file FILE

src/_pytest/main.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,21 @@ def pytest_addoption(parser: Parser) -> None:
9090
action="store_true",
9191
help="(Deprecated) alias to --strict-markers",
9292
)
93+
group.addoption(
94+
"--require-unique-parameterization-ids",
95+
action="store_true",
96+
default=False,
97+
help="When passed, this flag causes pytest to raise an exception upon detection of non-unique parameter set IDs"
98+
" rather than attempting to generate them automatically.",
99+
)
100+
101+
parser.addini(
102+
"require_unique_parameterization_ids",
103+
type="bool",
104+
default=False,
105+
help="When passed, this flag causes pytest to raise an exception upon detection of non-unique parameter set IDs"
106+
" rather than attempting to generate them automatically.",
107+
)
93108

94109
group = parser.getgroup("pytest-warnings")
95110
group.addoption(

src/_pytest/python.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import os
2222
from pathlib import Path
2323
import re
24+
import textwrap
2425
import types
2526
from typing import Any
2627
from typing import final
@@ -902,6 +903,29 @@ def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]:
902903
resolved_ids = list(self._resolve_ids())
903904
# All IDs must be unique!
904905
if len(resolved_ids) != len(set(resolved_ids)):
906+
if self._require_unique_ids_enabled():
907+
duplicate_indexs = defaultdict(list)
908+
for i, val in enumerate(resolved_ids):
909+
duplicate_indexs[val].append(i)
910+
911+
# Keep only duplicates
912+
duplicates = {k: v for k, v in duplicate_indexs.items() if len(v) > 1}
913+
arugment_values = [
914+
saferepr(param.values) for param in self.parametersets
915+
]
916+
error_msg = f"""
917+
When --require-unique-parameterization-ids set, pytest won't generate unique IDs for parameters.
918+
test name: {self.nodeid}
919+
argument names: {self.argnames}
920+
argument values: {arugment_values}
921+
resolved (with non-unique) IDs: {resolved_ids}
922+
duplicates: {duplicates}
923+
you must make sure all parameterization IDs are unique, either by:
924+
- providing unique IDs per parameterization via the ids=[...] argument to @pytest.mark.parametrize
925+
- providing a custom id function that generates unique IDs for each parameterization
926+
- not setting --require-unique-parameterization-ids
927+
"""
928+
raise nodes.Collector.CollectError(textwrap.dedent(error_msg))
905929
# Record the number of occurrences of each ID.
906930
id_counts = Counter(resolved_ids)
907931
# Map the ID to its next suffix.
@@ -925,6 +949,14 @@ def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]:
925949
)
926950
return resolved_ids
927951

952+
def _require_unique_ids_enabled(self) -> bool:
953+
if self.config:
954+
cli_value = self.config.getoption("require_unique_parameterization_ids")
955+
if cli_value:
956+
return bool(cli_value)
957+
return bool(self.config.getini("require_unique_parameterization_ids"))
958+
return False
959+
928960
def _resolve_ids(self) -> Iterable[str | _HiddenParam]:
929961
"""Resolve IDs for all ParameterSets (may contain duplicates)."""
930962
for idx, parameterset in enumerate(self.parametersets):

testing/test_collection.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from pathlib import Path
66
from pathlib import PurePath
77
import pprint
8+
import re
89
import shutil
910
import sys
1011
import tempfile
@@ -2702,3 +2703,86 @@ def test_1(): pass
27022703
],
27032704
consecutive=True,
27042705
)
2706+
2707+
2708+
class TestRequireUniqueParamsetIds:
2709+
CASES = [
2710+
("[(1, 1), (1, 1)]", {"1-1": [0, 1]}),
2711+
("[(1, 1), (1, 2), (1, 1)]", {"1-1": [0, 2]}),
2712+
("[(1, 1), (2, 2), (1, 1)]", {"1-1": [0, 2]}),
2713+
("[(1, 1), (2, 2), (1, 2), (2, 1), (1, 1)]", {"1-1": [0, 4]}),
2714+
]
2715+
2716+
@staticmethod
2717+
def _fnmatch_escape_repr(obj) -> str:
2718+
return re.sub(r"[*?[\]]", (lambda m: f"[{m.group()}]"), repr(obj))
2719+
2720+
def _assert_duplicate_msg(self, result, expected_indices):
2721+
stream = result.stdout
2722+
stream.fnmatch_lines(
2723+
[
2724+
"When --require-unique-parameterization-ids set, pytest won't generate unique IDs for parameters.",
2725+
"test name: *::test1",
2726+
"argument names: [[]'y', 'x'[]]",
2727+
f"duplicates: {self._fnmatch_escape_repr(expected_indices)}",
2728+
"you must make sure all parameterization IDs are unique, either by:",
2729+
"- providing unique IDs per parameterization via the ids=[...] argument to @pytest.mark.parametrize",
2730+
"- providing a custom id function that generates unique IDs for each parameterization",
2731+
"- not setting --require-unique-parameterization-ids",
2732+
]
2733+
)
2734+
assert result.ret != 0
2735+
2736+
@pytest.mark.parametrize("parametrize_args, expected_indices", CASES)
2737+
def test_cli_enables(self, pytester: Pytester, parametrize_args, expected_indices):
2738+
pytester.makepyfile(
2739+
f"""
2740+
import pytest
2741+
2742+
@pytest.mark.parametrize('y, x', {parametrize_args})
2743+
def test1(y, x):
2744+
pass
2745+
"""
2746+
)
2747+
result = pytester.runpytest("--require-unique-parameterization-ids")
2748+
self._assert_duplicate_msg(result, expected_indices)
2749+
2750+
@pytest.mark.parametrize("parametrize_args, expected_indices", CASES)
2751+
def test_ini_enables(self, pytester: Pytester, parametrize_args, expected_indices):
2752+
pytester.makeini(
2753+
"""
2754+
[pytest]
2755+
require_unique_parameterization_ids = true
2756+
"""
2757+
)
2758+
pytester.makepyfile(
2759+
f"""
2760+
import pytest
2761+
2762+
@pytest.mark.parametrize('y, x', {parametrize_args})
2763+
def test1(y, x):
2764+
pass
2765+
"""
2766+
)
2767+
result = pytester.runpytest()
2768+
self._assert_duplicate_msg(result, expected_indices)
2769+
2770+
def test_cli_overrides_ini_false(self, pytester: Pytester):
2771+
"""CLI True should override ini False."""
2772+
pytester.makeini(
2773+
"""
2774+
[pytest]
2775+
require_unique_parameterization_ids = false
2776+
"""
2777+
)
2778+
pytester.makepyfile(
2779+
"""
2780+
import pytest
2781+
2782+
@pytest.mark.parametrize('y, x', [(1,1), (1,1)])
2783+
def test1(y, x):
2784+
pass
2785+
"""
2786+
)
2787+
result = pytester.runpytest("--require-unique-parameterization-ids")
2788+
self._assert_duplicate_msg(result, {"1-1": [0, 1]})

0 commit comments

Comments
 (0)