Skip to content

Commit 08017d9

Browse files
Merge pull request #15296 from pytest-dev/claude/project-thread-cukdhn
Accept numeric strings for verbosity options in TOML again, with a deprecation
2 parents 8b005ed + a9b505d commit 08017d9

8 files changed

Lines changed: 119 additions & 5 deletions

File tree

‎changelog/15290.bugfix.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Native TOML configuration again accepts numeric strings such as ``"2"`` for :confval:`verbosity_assertions`, :confval:`verbosity_test_cases` and :confval:`verbosity_subtests`, now with a deprecation warning -- regressed by :pr:`15153`.

‎changelog/15290.deprecation.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Numeric strings such as ``"2"`` for :confval:`verbosity_assertions`, :confval:`verbosity_test_cases`, :confval:`verbosity_subtests` and :confval:`tmp_path_retention_count` in native TOML configuration are deprecated, use integers instead -- see :ref:`toml-numeric-strings`.

‎doc/en/deprecations.rst‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,30 @@ Deprecated Features
1414
Below is a complete list of all pytest features which are considered deprecated. Using those features will issue
1515
:class:`~pytest.PytestWarning` or subclasses, which can be filtered using :ref:`standard warning filters <warnings>`.
1616

17+
.. _toml-numeric-strings:
18+
19+
Numeric strings for integer options in TOML
20+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
21+
22+
.. deprecated:: 9.2.1
23+
24+
In native TOML configuration, :confval:`verbosity_assertions`,
25+
:confval:`verbosity_test_cases` and :confval:`verbosity_subtests` take an
26+
integer or ``"auto"``, and :confval:`tmp_path_retention_count` takes an
27+
integer. Numeric strings are still accepted for backward
28+
compatibility, but issue a deprecation warning and will be rejected in pytest 10.
29+
30+
.. code-block:: toml
31+
32+
# Deprecated
33+
verbosity_assertions = "2"
34+
35+
# Use this instead
36+
verbosity_assertions = 2
37+
38+
INI files are not affected, since all their values are strings.
39+
40+
1741
.. _terminalreporter-write-line-bytes:
1842

1943
Passing ``bytes`` to ``TerminalReporter.write_line()``

‎src/_pytest/config/__init__.py‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1261,6 +1261,7 @@ def __init__(
12611261
self.trace = self.pluginmanager.trace.root.get("config")
12621262
self.hook = self.pluginmanager.hook
12631263
self._inicache: dict[str, Any] = {}
1264+
self._warned_verbosity_strings: set[str] = set()
12641265
self._inicfg: ConfigDict = {}
12651266
self._cleanup_stack = contextlib.ExitStack()
12661267
self.pluginmanager.register(self, "pytestconfig")
@@ -2268,8 +2269,26 @@ def get_verbosity(self, verbosity_type: str | None = None) -> int:
22682269
level = self.getini(ini_name)
22692270
if level == Config._VERBOSITY_INI_DEFAULT:
22702271
return global_level
2271-
2272-
return int(level)
2272+
if isinstance(level, int):
2273+
return level
2274+
try:
2275+
int_level = int(level)
2276+
except ValueError:
2277+
raise UsageError(
2278+
f"{self.inipath}: config option '{ini_name}' expects an int "
2279+
f"or 'auto', got {level!r}"
2280+
) from None
2281+
# A numeric str only gets here from TOML: in ini mode the int member
2282+
# of the option type already converted it.
2283+
if ini_name not in self._warned_verbosity_strings:
2284+
self._warned_verbosity_strings.add(ini_name)
2285+
self.issue_config_time_warning(
2286+
_pytest.deprecated.TOML_NUMERIC_STRING.format(
2287+
name=ini_name, value=level
2288+
),
2289+
stacklevel=2,
2290+
)
2291+
return int_level
22732292

22742293
@staticmethod
22752294
def _verbosity_ini_name(verbosity_type: str) -> str:
@@ -2289,7 +2308,9 @@ def _add_verbosity_ini(parser: Parser, verbosity_type: str, help: str) -> None:
22892308
parser.addini(
22902309
Config._verbosity_ini_name(verbosity_type),
22912310
help=help,
2292-
type=int | Literal["auto"],
2311+
# str rather than Literal["auto"]: numeric strings in TOML are
2312+
# deprecated but still accepted, see get_verbosity.
2313+
type=int | str,
22932314
default=Config._VERBOSITY_INI_DEFAULT,
22942315
)
22952316

‎src/_pytest/deprecated.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@
114114
'(e.g. type="args") instead of relying on the implicit string default.'
115115
)
116116

117+
TOML_NUMERIC_STRING = UnformattedWarning(
118+
PytestRemovedIn10Warning,
119+
"{name} = {value!r} in TOML configuration is deprecated, "
120+
"use an integer instead: {name} = {value}\n"
121+
"See https://docs.pytest.org/en/stable/deprecations.html#toml-numeric-strings",
122+
)
123+
117124
# You want to make some `__init__` or function "private".
118125
#
119126
# def my_private_function(some, args):

‎src/_pytest/tmpdir.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from _pytest.config import hookimpl
3131
from _pytest.config.argparsing import Parser
3232
from _pytest.deprecated import check_ispytest
33+
from _pytest.deprecated import TOML_NUMERIC_STRING
3334
from _pytest.fixtures import fixture
3435
from _pytest.fixtures import FixtureRequest
3536
from _pytest.monkeypatch import MonkeyPatch
@@ -97,7 +98,18 @@ def from_config(
9798
:meta private:
9899
"""
99100
check_ispytest(_ispytest)
100-
count = int(config.getini("tmp_path_retention_count"))
101+
count = config.getini("tmp_path_retention_count")
102+
if isinstance(count, str):
103+
# A str only gets here from TOML: in ini mode the int member of
104+
# the option type already converted it.
105+
value = count
106+
count = int(value)
107+
config.issue_config_time_warning(
108+
TOML_NUMERIC_STRING.format(
109+
name="tmp_path_retention_count", value=value
110+
),
111+
stacklevel=2,
112+
)
101113
if count < 0:
102114
raise ValueError(
103115
f"tmp_path_retention_count must be >= 0. Current input: {count}."
@@ -299,6 +311,7 @@ def pytest_addoption(parser: Parser) -> None:
299311
"tmp_path_retention_count",
300312
help="How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.",
301313
default=3,
314+
# str: numeric strings in TOML are deprecated but still accepted.
302315
type=int | str,
303316
)
304317

‎testing/test_config.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from typing import Any
1414
from typing import cast
1515
from typing import Literal
16+
import warnings
1617

1718
import _pytest._code
1819
from _pytest.assertion.rewrite import AssertionRewritingHook
@@ -3630,7 +3631,6 @@ def test_getini(
36303631
@pytest.mark.parametrize(
36313632
("name", "value"),
36323633
[
3633-
("verbosity_assertions", '"loud"'),
36343634
("log_file_mode", '"x"'),
36353635
("parametrize_long_str_id_strategy", '"bogus"'),
36363636
],
@@ -3645,3 +3645,36 @@ def test_get_verbosity(self, pytester: Pytester) -> None:
36453645
pytester.maketoml("[pytest]\nverbosity_assertions = 2\n")
36463646
config = pytester.parseconfig()
36473647
assert config.get_verbosity(Config.VERBOSITY_ASSERTIONS) == 2
3648+
3649+
def test_get_verbosity_numeric_string_deprecated(self, pytester: Pytester) -> None:
3650+
pytester.maketoml('[pytest]\nverbosity_assertions = "2"\n')
3651+
pytester.makepyfile(
3652+
"""
3653+
from pytest import Config
3654+
3655+
def test_a(pytestconfig):
3656+
assert pytestconfig.get_verbosity(Config.VERBOSITY_ASSERTIONS) == 2
3657+
3658+
def test_b(pytestconfig):
3659+
assert pytestconfig.get_verbosity(Config.VERBOSITY_ASSERTIONS) == 2
3660+
"""
3661+
)
3662+
result = pytester.runpytest()
3663+
result.assert_outcomes(passed=2, warnings=1)
3664+
result.stdout.fnmatch_lines(
3665+
["*PytestRemovedIn10Warning: verbosity_assertions = '2' in TOML*"]
3666+
)
3667+
3668+
def test_get_verbosity_ini_numeric_string(self, pytester: Pytester) -> None:
3669+
pytester.makeini("[pytest]\nverbosity_assertions = 2\n")
3670+
config = pytester.parseconfig()
3671+
with warnings.catch_warnings():
3672+
warnings.simplefilter("error")
3673+
assert config.get_verbosity(Config.VERBOSITY_ASSERTIONS) == 2
3674+
3675+
@pytest.mark.parametrize("toml_value", ['"loud"', "true", "2.5"])
3676+
def test_get_verbosity_invalid(self, pytester: Pytester, toml_value: str) -> None:
3677+
pytester.maketoml(f"[pytest]\nverbosity_assertions = {toml_value}\n")
3678+
config = pytester.parseconfig()
3679+
with pytest.raises(UsageError, match="verbosity_assertions"):
3680+
config.get_verbosity(Config.VERBOSITY_ASSERTIONS)

‎testing/test_tmpdir.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,20 @@ def test_1(tmp_path):
232232
# Check the base dir itself is gone without depending on test results
233233
assert base_dir == []
234234

235+
def test_retention_count_toml_string_deprecated(self, pytester: Pytester) -> None:
236+
pytester.maketoml('[pytest]\ntmp_path_retention_count = "2"\n')
237+
pytester.makepyfile(
238+
"""
239+
def test_1(tmp_path_factory):
240+
assert tmp_path_factory._retention_count == 2
241+
"""
242+
)
243+
result = pytester.runpytest()
244+
result.assert_outcomes(passed=1, warnings=1)
245+
result.stdout.fnmatch_lines(
246+
["*PytestRemovedIn10Warning: tmp_path_retention_count = '2' in TOML*"]
247+
)
248+
235249
@pytest.mark.parametrize("policy", ['"failed"', '"all"'])
236250
@pytest.mark.parametrize("count", [0, 1, 3])
237251
def test_retention_count(self, pytester: Pytester, policy, count) -> None:

0 commit comments

Comments
 (0)