Skip to content

Commit 353934c

Browse files
Accept type expressions in Parser.addini(type=...)
Address review feedback in #14692: - Replace the tuple-of-tags API with type expressions, as proposed by bluetech in #14675: plain Python types (str, bool, int, float) and unions of them (e.g. `int | str`) are now accepted in addition to the existing string tags. The truncation options are registered with `type=int | str`. - Raise ValueError instead of asserting on an invalid `type` argument, since it is user (plugin) provided. - Raise ValueError when a union type is registered without an explicit default, instead of silently defaulting to None. - Document the _IniTypeTag/_INI_TYPE_TAGS keep-in-sync requirement.
1 parent c755d27 commit 353934c

5 files changed

Lines changed: 112 additions & 23 deletions

File tree

‎changelog/14675.improvement.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:func:`parser.addini <pytest.Parser.addini>` now also accepts plain Python types (``str``, ``bool``, ``int``, ``float``) and unions of them (for example ``int | str``) for its ``type`` argument, in addition to the existing string tags. A union accepts a value of any of its member types.

‎src/_pytest/assertion/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ def pytest_addoption(parser: Parser) -> None:
4949

5050
parser.addini(
5151
"truncation_limit_lines",
52-
type=("int", "string"),
52+
type=int | str,
5353
default=None,
5454
help="Set threshold of LINES after which truncation will take effect",
5555
)
5656
parser.addini(
5757
"truncation_limit_chars",
58-
type=("int", "string"),
58+
type=int | str,
5959
default=None,
6060
help=("Set threshold of CHARS after which truncation will take effect"),
6161
)

‎src/_pytest/assertion/_typing.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class TruncationBudget:
3434
def from_config(cls, config: Config) -> TruncationBudget:
3535
"""Build a budget from the ``truncation_limit_*`` ini options.
3636
37-
Both options are registered with ``type=("int", "string")`` for
37+
Both options are registered with ``type=int | str`` for
3838
backward compatibility, so :meth:`~_pytest.config.Config.getini` may
3939
return an ``int`` (native TOML value) or a ``str`` (INI files, ``-o``
4040
overrides); it returns ``None`` when the option is unset, which falls

‎src/_pytest/config/argparsing.py‎

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@
77
import os
88
import sys
99
import textwrap
10+
import types
1011
from typing import Any
12+
from typing import cast
1113
from typing import final
14+
from typing import get_args
15+
from typing import get_origin
1216
from typing import Literal
1317
from typing import NoReturn
18+
from typing import Union
1419

1520
from .exceptions import UsageError
1621
import _pytest._io
@@ -21,14 +26,18 @@
2126
FILE_OR_DIR = "file_or_dir"
2227

2328
#: The string tags accepted by :meth:`Parser.addini` for its ``type`` argument.
29+
#: Keep in sync with _INI_TYPE_TAGS.
2430
_IniTypeTag = Literal[
2531
"string", "paths", "pathlist", "args", "linelist", "bool", "int", "float"
2632
]
2733

28-
#: An ini option type: either a single tag, or a tuple of tags meaning "accept
29-
#: a value of any of these types" (e.g. ``("int", "string")``).
34+
#: An ini option type, as stored internally after normalization: either a
35+
#: single tag, or a tuple of tags meaning "accept a value of any of these
36+
#: types" (e.g. ``("int", "string")``, normalized from ``int | str``).
3037
IniType = _IniTypeTag | tuple[_IniTypeTag, ...]
3138

39+
#: Runtime list tags accepted by :meth:`Parser.addini` for its ``type`` argument.
40+
#: Keep in sync with _IniTypeTag.
3241
_INI_TYPE_TAGS: tuple[str, ...] = (
3342
"string",
3443
"paths",
@@ -40,6 +49,33 @@
4049
"float",
4150
)
4251

52+
#: Maps the plain Python types accepted by :meth:`Parser.addini` for its
53+
#: ``type`` argument to the equivalent string tag.
54+
_INI_TYPE_TO_TAG: dict[type, _IniTypeTag] = {
55+
str: "string",
56+
bool: "bool",
57+
int: "int",
58+
float: "float",
59+
}
60+
61+
62+
def _ini_type_to_tag(name: str, type_: object) -> _IniTypeTag:
63+
"""Normalize one member of an `addini(type=...)` argument to a string tag.
64+
65+
Raise ValueError for anything that is neither a known tag nor a supported
66+
plain Python type.
67+
"""
68+
if isinstance(type_, str):
69+
if type_ in _INI_TYPE_TAGS:
70+
return cast("_IniTypeTag", type_)
71+
elif isinstance(type_, type) and type_ in _INI_TYPE_TO_TAG:
72+
return _INI_TYPE_TO_TAG[type_]
73+
raise ValueError(
74+
f"invalid type for ini option {name!r}: {type_!r} (expected one of "
75+
f"{', '.join(repr(tag) for tag in _INI_TYPE_TAGS)}, one of the types "
76+
"str, bool, int, float, or a union of these types such as `int | str`)"
77+
)
78+
4379

4480
@final
4581
class Parser:
@@ -202,7 +238,10 @@ def addini(
202238
self,
203239
name: str,
204240
help: str,
205-
type: _IniTypeTag | tuple[_IniTypeTag, ...] | None = None,
241+
type: _IniTypeTag
242+
| type[bool | int | float | str]
243+
| types.UnionType
244+
| None = None,
206245
default: Any = NOTSET,
207246
*,
208247
aliases: Sequence[str] = (),
@@ -227,15 +266,17 @@ def addini(
227266
228267
The ``float`` and ``int`` types.
229268
230-
A tuple of the above tags may also be passed to accept a value of
231-
any of those types, for example ``("int", "string")``. In TOML
269+
For the scalar types, the plain Python type may be passed instead
270+
of the string tag: ``str``, ``bool``, ``int`` and ``float`` (for
271+
example ``type=int``). A union of these types accepts a value of
272+
any of its members, for example ``int | str``. In TOML
232273
configuration files the value may then be any of the member types;
233274
string-based formats (INI files, ``-o`` overrides) coerce it to the
234275
first member that accepts it.
235276
236277
.. versionadded:: 9.1
237278
238-
Passing a tuple of types.
279+
Passing a type expression such as ``int`` or ``int | str``.
239280
240281
For ``paths`` and ``pathlist`` types, they are considered relative to the config-file.
241282
In case the execution is happening without a config-file defined,
@@ -260,14 +301,19 @@ def addini(
260301
The value of configuration keys can be retrieved via a call to
261302
:py:func:`config.getini(name) <pytest.Config.getini>`.
262303
"""
304+
ini_type: IniType
263305
if type is None:
264-
type = "string"
265-
tags = type if isinstance(type, tuple) else (type,)
266-
assert tags and all(tag in _INI_TYPE_TAGS for tag in tags), type
306+
ini_type = "string"
307+
elif get_origin(type) in (Union, types.UnionType):
308+
ini_type = tuple(
309+
_ini_type_to_tag(name, member) for member in get_args(type)
310+
)
311+
else:
312+
ini_type = _ini_type_to_tag(name, type)
267313
if default is NOTSET:
268-
default = get_ini_default_for_type(type)
314+
default = get_ini_default_for_type(name, ini_type)
269315

270-
self._inidict[name] = (help, type, default)
316+
self._inidict[name] = (help, ini_type, default)
271317

272318
for alias in aliases:
273319
if alias in self._inidict:
@@ -279,14 +325,17 @@ def addini(
279325
self._ini_aliases[alias] = name
280326

281327

282-
def get_ini_default_for_type(type: IniType) -> Any:
328+
def get_ini_default_for_type(name: str, type: IniType) -> Any:
283329
"""
284330
Used by addini to get the default value for a given config option type, when
285331
default is not supplied.
286332
"""
287333
if isinstance(type, tuple):
288334
# A union has no unambiguous implicit default; require an explicit one.
289-
return None
335+
raise ValueError(
336+
f"ini option {name!r} has a union type, which has no implicit "
337+
"default; pass an explicit `default` to `addini`"
338+
)
290339
elif type in ("paths", "pathlist", "args", "linelist"):
291340
return []
292341
elif type == "bool":

‎testing/test_config.py‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,8 +1092,8 @@ def pytest_addoption(parser):
10921092
@pytest.mark.parametrize(
10931093
"section, value, expected",
10941094
[
1095-
# Native TOML: int and str are both accepted; the first tuple
1096-
# member that matches wins (int before string).
1095+
# Native TOML: int and str are both accepted; the first union
1096+
# member that matches wins (int before str).
10971097
("[tool.pytest]", '"7"', "7"),
10981098
("[tool.pytest]", "7", 7),
10991099
# ini_options mode stringifies, then coerces to the first member.
@@ -1102,13 +1102,13 @@ def pytest_addoption(parser):
11021102
],
11031103
ids=["native-str", "native-int", "ini-options-str", "ini-options-int"],
11041104
)
1105-
def test_addini_tuple_type(
1105+
def test_addini_union_type(
11061106
self, pytester: Pytester, section: str, value: str, expected: object
11071107
) -> None:
11081108
pytester.makeconftest(
11091109
"""
11101110
def pytest_addoption(parser):
1111-
parser.addini("ini_param", "", type=("int", "string"), default=None)
1111+
parser.addini("ini_param", "", type=int | str, default=None)
11121112
"""
11131113
)
11141114
pytester.makepyprojecttoml(
@@ -1122,11 +1122,11 @@ def pytest_addoption(parser):
11221122
assert result == expected
11231123
assert type(result) is type(expected)
11241124

1125-
def test_addini_tuple_type_invalid(self, pytester: Pytester) -> None:
1125+
def test_addini_union_type_invalid_value(self, pytester: Pytester) -> None:
11261126
pytester.makeconftest(
11271127
"""
11281128
def pytest_addoption(parser):
1129-
parser.addini("ini_param", "", type=("int", "string"), default=None)
1129+
parser.addini("ini_param", "", type=int | str, default=None)
11301130
"""
11311131
)
11321132
pytester.makepyprojecttoml(
@@ -1141,6 +1141,39 @@ def pytest_addoption(parser):
11411141
):
11421142
_ = config.getini("ini_param")
11431143

1144+
def test_addini_plain_type(self, pytester: Pytester) -> None:
1145+
"""A plain Python type is accepted as an alias of its string tag."""
1146+
pytester.makeconftest(
1147+
"""
1148+
def pytest_addoption(parser):
1149+
parser.addini("ini_param", "", type=int)
1150+
"""
1151+
)
1152+
pytester.makepyprojecttoml(
1153+
"""
1154+
[tool.pytest]
1155+
ini_param = 7
1156+
"""
1157+
)
1158+
config = pytester.parseconfig()
1159+
assert config.getini("ini_param") == 7
1160+
1161+
def test_addini_invalid_type(self, pytester: Pytester) -> None:
1162+
parser = Parser(_ispytest=True)
1163+
with pytest.raises(ValueError, match="invalid type for ini option 'ini_param'"):
1164+
parser.addini("ini_param", "", type="integer") # type: ignore[arg-type]
1165+
with pytest.raises(ValueError, match="invalid type for ini option 'ini_param'"):
1166+
parser.addini("ini_param", "", type=dict) # type: ignore[arg-type]
1167+
with pytest.raises(ValueError, match="invalid type for ini option 'ini_param'"):
1168+
parser.addini("ini_param", "", type=int | dict)
1169+
1170+
def test_addini_union_type_requires_default(self) -> None:
1171+
parser = Parser(_ispytest=True)
1172+
with pytest.raises(
1173+
ValueError, match="union type, which has no implicit default"
1174+
):
1175+
parser.addini("ini_param", "", type=int | str)
1176+
11441177
def test_addinivalue_line_existing(self, pytester: Pytester) -> None:
11451178
pytester.makeconftest(
11461179
"""
@@ -1400,7 +1433,13 @@ def pytest_addoption(parser):
14001433
],
14011434
)
14021435
def test_get_ini_default_for_type(self, type: Any, expected: Any) -> None:
1403-
assert get_ini_default_for_type(type) == expected
1436+
assert get_ini_default_for_type("ini_param", type) == expected
1437+
1438+
def test_get_ini_default_for_type_union(self) -> None:
1439+
with pytest.raises(
1440+
ValueError, match="union type, which has no implicit default"
1441+
):
1442+
get_ini_default_for_type("ini_param", ("int", "string"))
14041443

14051444
def test_confcutdir_check_isdir(self, pytester: Pytester) -> None:
14061445
"""Give an error if --confcutdir is not a valid directory (#2078)"""

0 commit comments

Comments
 (0)