Skip to content

Commit 57b5f00

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

File tree

5 files changed

+168
-0
lines changed

5 files changed

+168
-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-paramset-ids`` command-line flag and :confval:`require_unique_paramset_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_paramset_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-paramset-ids`.
2091+
2092+
.. code-block:: ini
2093+
2094+
[pytest]
2095+
require_unique_paramset_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-paramset-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-paramset-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_paramset_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: 28 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,25 @@ 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-paramset-ids set, pytest won't attempt to 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+
"""
924+
raise nodes.Collector.CollectError(textwrap.dedent(error_msg))
905925
# Record the number of occurrences of each ID.
906926
id_counts = Counter(resolved_ids)
907927
# Map the ID to its next suffix.
@@ -925,6 +945,14 @@ def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]:
925945
)
926946
return resolved_ids
927947

948+
def _require_unique_ids_enabled(self) -> bool:
949+
if self.config:
950+
cli_value = self.config.getoption("require_unique_paramset_ids")
951+
if cli_value:
952+
return bool(cli_value)
953+
return bool(self.config.getini("require_unique_paramset_ids"))
954+
return False
955+
928956
def _resolve_ids(self) -> Iterable[str | _HiddenParam]:
929957
"""Resolve IDs for all ParameterSets (may contain duplicates)."""
930958
for idx, parameterset in enumerate(self.parametersets):

testing/test_collection.py

Lines changed: 92 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,94 @@ 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 _make_testfile(pytester: Pytester, parametrize_args: str) -> None:
2718+
pytester.makepyfile(
2719+
f"""
2720+
import pytest
2721+
2722+
@pytest.mark.parametrize('y, x', {parametrize_args})
2723+
def test1(y, x):
2724+
pass
2725+
"""
2726+
)
2727+
2728+
@staticmethod
2729+
def _fnmatch_escape_repr(obj) -> str:
2730+
return re.sub(r"[*?[\]]", (lambda m: f"[{m.group()}]"), repr(obj))
2731+
2732+
def _assert_duplicate_msg(self, result, expected_indices):
2733+
stream = result.stdout
2734+
stream.fnmatch_lines(
2735+
[
2736+
"When --require-unique-paramset-ids set, pytest won't attempt to generate unique IDs for parameters.",
2737+
"test name: *::test1",
2738+
"argument names: [[]'y', 'x'[]]",
2739+
f"duplicates: {self._fnmatch_escape_repr(expected_indices)}",
2740+
]
2741+
)
2742+
assert result.ret != 0
2743+
2744+
@pytest.mark.parametrize("parametrize_args, expected_indices", CASES)
2745+
def test_cli_enables(self, pytester: Pytester, parametrize_args, expected_indices):
2746+
pytester.makepyfile(
2747+
f"""
2748+
import pytest
2749+
2750+
@pytest.mark.parametrize('y, x', {parametrize_args})
2751+
def test1(y, x):
2752+
pass
2753+
"""
2754+
)
2755+
result = pytester.runpytest("--require-unique-paramset-ids")
2756+
self._assert_duplicate_msg(result, expected_indices)
2757+
2758+
@pytest.mark.parametrize("parametrize_args, expected_indices", CASES)
2759+
def test_ini_enables(self, pytester: Pytester, parametrize_args, expected_indices):
2760+
pytester.makeini(
2761+
"""
2762+
[pytest]
2763+
require_unique_paramset_ids = true
2764+
"""
2765+
)
2766+
pytester.makepyfile(
2767+
f"""
2768+
import pytest
2769+
2770+
@pytest.mark.parametrize('y, x', {parametrize_args})
2771+
def test1(y, x):
2772+
pass
2773+
"""
2774+
)
2775+
result = pytester.runpytest()
2776+
self._assert_duplicate_msg(result, expected_indices)
2777+
2778+
def test_cli_overrides_ini_false(self, pytester: Pytester):
2779+
"""CLI True should override ini False."""
2780+
pytester.makeini(
2781+
"""
2782+
[pytest]
2783+
require_unique_paramset_ids = false
2784+
"""
2785+
)
2786+
pytester.makepyfile(
2787+
"""
2788+
import pytest
2789+
2790+
@pytest.mark.parametrize('y, x', [(1,1), (1,1)])
2791+
def test1(y, x):
2792+
pass
2793+
"""
2794+
)
2795+
result = pytester.runpytest("--require-unique-paramset-ids")
2796+
self._assert_duplicate_msg(result, {"1-1": [0, 1]})

0 commit comments

Comments
 (0)