Skip to content

Commit 4eaf20e

Browse files
committed
feat: add cli, ini option skips pytest internal logic of id generation and raise error
1 parent c97a401 commit 4eaf20e

File tree

5 files changed

+202
-0
lines changed

5 files changed

+202
-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-parametrization-ids`` command-line flag and :confval:`require_unique_parametrization_ids` configuration option.
2+
3+
When passed, pytest will emit an error if it detects non-unique parameter set IDs,
4+
rather than automatically making the IDs unique by adding `0`, `1`, ... to them.

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_parametrization_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-parametrization-ids`.
2091+
2092+
.. code-block:: ini
2093+
2094+
[pytest]
2095+
require_unique_parametrization_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+
Otherwise, pytest would handle this by generating unique IDs like "a0", "a1".
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-parametrization-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-parametrization-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_parametrization_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 = textwrap.dedent(f"""
917+
Duplicate parametrization IDs detected, but --require-unique-parametrization-ids is set.
918+
919+
Test name: {self.nodeid}
920+
Argument names: {self.argnames}
921+
Argument values: {arugment_values}
922+
Resolved IDs: {resolved_ids}
923+
Duplicates: {duplicates}
924+
925+
You can fix this problem using:
926+
the `ids` argument of `@pytest.mark.parametrize()` or the `id` argument of `pytest.param()`.
927+
""")
928+
raise nodes.Collector.CollectError(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_parametrization_ids")
955+
if cli_value:
956+
return bool(cli_value)
957+
return bool(self.config.getini("require_unique_parametrization_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: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# mypy: allow-untyped-defs
22
from __future__ import annotations
33

4+
from collections.abc import Sequence
45
import os
56
from pathlib import Path
67
from pathlib import PurePath
@@ -20,6 +21,7 @@
2021
from _pytest.pathlib import symlink_or_skip
2122
from _pytest.pytester import HookRecorder
2223
from _pytest.pytester import Pytester
24+
from _pytest.pytester import RunResult
2325
import pytest
2426

2527

@@ -2702,3 +2704,123 @@ def test_1(): pass
27022704
],
27032705
consecutive=True,
27042706
)
2707+
2708+
2709+
class TestRequireUniqueParametrizationtIds:
2710+
CASES = [
2711+
([(1, 1), (1, 1)], {"1-1": [0, 1]}),
2712+
([(1, 1), (1, 2), (1, 1)], {"1-1": [0, 2]}),
2713+
([(1, 1), (2, 2), (1, 1)], {"1-1": [0, 2]}),
2714+
([(1, 1), (2, 2), (1, 2), (2, 1), (1, 1)], {"1-1": [0, 4]}),
2715+
]
2716+
2717+
@pytest.mark.parametrize(("parametrize_args", "expected_indices"), CASES)
2718+
def test_cli_enables(
2719+
self,
2720+
pytester: Pytester,
2721+
parametrize_args: Sequence[tuple[int, int]],
2722+
expected_indices: dict[str, Sequence[int]],
2723+
) -> None:
2724+
pytester.makepyfile(
2725+
f"""
2726+
import pytest
2727+
2728+
@pytest.mark.parametrize('x, y', {parametrize_args})
2729+
def test1(y, x):
2730+
pass
2731+
"""
2732+
)
2733+
result = pytester.runpytest("--require-unique-parametrization-ids")
2734+
resolved_ids = self._convert_to_resolved_ids(parametrize_args)
2735+
argument_values = self._convert_to_argument_values(parametrize_args)
2736+
self._assert_duplicate_msg(
2737+
result, expected_indices, argument_values, resolved_ids
2738+
)
2739+
2740+
@pytest.mark.parametrize("parametrize_args, expected_indices", CASES)
2741+
def test_ini_enables(
2742+
self,
2743+
pytester: Pytester,
2744+
parametrize_args: Sequence[tuple[int, int]],
2745+
expected_indices: dict[str, Sequence[int]],
2746+
) -> None:
2747+
pytester.makeini(
2748+
"""
2749+
[pytest]
2750+
require_unique_parametrization_ids = true
2751+
"""
2752+
)
2753+
pytester.makepyfile(
2754+
f"""
2755+
import pytest
2756+
2757+
@pytest.mark.parametrize('x, y', {parametrize_args})
2758+
def test1(y, x):
2759+
pass
2760+
"""
2761+
)
2762+
result = pytester.runpytest()
2763+
resolved_ids = self._convert_to_resolved_ids(parametrize_args)
2764+
argument_values = self._convert_to_argument_values(parametrize_args)
2765+
self._assert_duplicate_msg(
2766+
result, expected_indices, argument_values, resolved_ids
2767+
)
2768+
2769+
def test_cli_overrides_ini_false(self, pytester: Pytester) -> None:
2770+
"""CLI True should override ini False."""
2771+
pytester.makeini(
2772+
"""
2773+
[pytest]
2774+
require_unique_parametrization_ids = false
2775+
"""
2776+
)
2777+
parametrization_args = [(1, 1), (1, 1)]
2778+
pytester.makepyfile(
2779+
f"""
2780+
import pytest
2781+
2782+
@pytest.mark.parametrize('x, y', {parametrization_args})
2783+
def test1(y, x):
2784+
pass
2785+
"""
2786+
)
2787+
result = pytester.runpytest("--require-unique-parametrization-ids")
2788+
resolved_ids = self._convert_to_resolved_ids(parametrization_args)
2789+
argument_values = self._convert_to_argument_values(parametrization_args)
2790+
self._assert_duplicate_msg(
2791+
result, {"1-1": [0, 1]}, argument_values, resolved_ids
2792+
)
2793+
2794+
def _assert_duplicate_msg(
2795+
self,
2796+
result: RunResult,
2797+
expected_indices: dict[str, Sequence[int]],
2798+
argument_values: Sequence[str],
2799+
resolved_ids: Sequence[str],
2800+
) -> None:
2801+
stream = result.stdout
2802+
stream.fnmatch_lines(
2803+
[
2804+
"Duplicate parametrization IDs detected, but --require-unique-parametrization-ids is set.",
2805+
"Test name: *::test1",
2806+
"Argument names: [[]'x', 'y'[]]",
2807+
f"Argument values: {argument_values}",
2808+
f"Resolved IDs: {resolved_ids}",
2809+
f"Duplicates: {expected_indices}",
2810+
"You can fix this problem using:",
2811+
"the `ids` argument of `@pytest.mark.parametrize()` or the `id` argument of `pytest.param()`.",
2812+
]
2813+
)
2814+
assert result.ret != 0
2815+
2816+
def _convert_to_resolved_ids(
2817+
self, parametrize_args: Sequence[tuple[int, int]]
2818+
) -> Sequence[str]:
2819+
return [
2820+
f"{argument1}-{argument2}" for (argument1, argument2) in parametrize_args
2821+
]
2822+
2823+
def _convert_to_argument_values(
2824+
self, parametrize_args: Sequence[tuple[int, int]]
2825+
) -> Sequence[str]:
2826+
return [str(argument) for argument in parametrize_args]

0 commit comments

Comments
 (0)