Backtestspytestrun-20261106-234554#14912
Shared PytestWarning instances in deprecated.py accumulate tracebacks under -W error
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Patch A converts all 11 shared PytestWarning instances to UnformattedWarning and updates every call site, including INI_STRING_TYPE_NON_STR_VALUE in config/__init__.py. Patch B leaves INI_STRING_TYPE_NON_STR_VALUE as a module-level PytestRemovedIn10Warning instance and its call site unchanged, so that deprecation still accumulates tracebacks under -W error; the independent test test_ini_string_non_str_warning_traceback_does_not_accumulate confirms this (FAIL-ASSERT on B, PASS on A). B's new docstring also claims all constants are UnformattedWarning while its own module violates that. On tests, A adds a guard test that no uppercase constant is a Warning instance (which would have caught B's omission), a parametrized fresh-instance test across four deprecations with an exact traceback-depth equality check, and an end-to-end pytester test for the corrupted-report scenario from the issue. B adds a single test with a weak `second <= first` assertion. B's changelog entry is a nice convention touch but does not offset an incomplete root-cause fix. A is the better patch.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
8m 8s
Wall-clock time in the container
Full test suite
No new failures
2,681 passed · 36 skipped · 2,717 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
183vs 122 merged
Changed lines, ours vs merged
The issue
View on GitHubsrc/_pytest/deprecated.py stores 11 deprecations as module-level instances (PRIVATE, CALLSPEC2_RENAMED, YIELD_FIXTURE, …) that call sites pass straight to warnings.warn(). When warnings are errors, warn raises that exact object, and CPython appends to an exception's existing __traceback__ instead of resetting it — so each raise grows the traceback of a process-lifetime global (measured 2 → 4 → 6 → 8 frames over four raises). Failure reports get corrupted: with two tests tripping the same deprecation, the second one's traceback carries 20+ stale frames from the first run and ends pointing at the other test's source line. The frames also pin their locals forever, and concurrent raises mutate shared __traceback__/__context__. The four UnformattedWarning constants are fine, since .format() returns a fresh instance. Fix: build a fresh instance per warn() — fold the 11 into UnformattedWarning (its format() works with no kwargs) or store text and pass warnings.warn(TEXT, Category) — and update the module docstring, which currently mandates the instance form.
The two patches
src/_pytest/config/__init__.pyindex c7bd3e1af..97fb22dd3 100644@@ -303,7 +303,7 @@ def console_main() -> int: from _pytest.deprecated import CONSOLE_MAIN - warnings.warn(CONSOLE_MAIN, stacklevel=2)+ warnings.warn(CONSOLE_MAIN.format(), stacklevel=2) return _console_main() @@ -1241,7 +1241,7 @@ class Config: @property def inicfg(self) -> _DeprecatedInicfgProxy: warnings.warn(- _pytest.deprecated.CONFIG_INICFG,+ _pytest.deprecated.CONFIG_INICFG.format(), stacklevel=2, ) return _DeprecatedInicfgProxy(self)@@ -2000,7 +2000,7 @@ class Config: elif type == "string": if not isinstance(value, str): warnings.warn(- _pytest.deprecated.INI_STRING_TYPE_NON_STR_VALUE,+ _pytest.deprecated.INI_STRING_TYPE_NON_STR_VALUE.format(), stacklevel=2, ) return valuesrc/_pytest/deprecated.pyindex 0370240ee..d61b8b95e 100644@@ -4,9 +4,14 @@ is planned to be removed in the next pytest release. Keeping it in a central location makes it easy to track what is deprecated and should be removed when the time comes. -All constants defined in this module should be either instances of-:class:`PytestWarning`, or :class:`UnformattedWarning`-in case of warnings which need to format their messages.+All warning constants defined in this module should be instances of+:class:`UnformattedWarning`, and call sites should issue them via+``CONSTANT.format(...)`` (with no arguments if the message has no placeholders),+so that each ``warnings.warn()`` call gets a fresh warning instance.++Do not store :class:`PytestWarning` instances here: when warnings are turned+into errors, ``warnings.warn()`` raises the given instance itself, and a shared+exception object would accumulate tracebacks (and pin their frames) across raises. """ from __future__ import annotations@@ -29,9 +34,10 @@ DEPRECATED_EXTERNAL_PLUGINS = { # This could have been removed pytest 8, but it's harmless and common, so no rush to remove.-YIELD_FIXTURE = PytestRemovedIn10Warning(+YIELD_FIXTURE = UnformattedWarning(+ PytestRemovedIn10Warning, "@pytest.yield_fixture is deprecated.\n"- "Use @pytest.fixture instead; they are the same."+ "Use @pytest.fixture instead; they are the same.", ) CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning(@@ -44,7 +50,10 @@ CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning( ) # This deprecation is never really meant to be removed.-PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.")+PRIVATE = UnformattedWarning(+ PytestDeprecationWarning,+ "A private pytest class or function was used.",+) HOOK_LEGACY_MARKING = UnformattedWarning(@@ -56,11 +65,12 @@ HOOK_LEGACY_MARKING = UnformattedWarning( "#configuring-hook-specs-impls-using-markers", ) -MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = PytestRemovedIn10Warning(+MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = UnformattedWarning(+ PytestRemovedIn10Warning, "monkeypatch.syspath_prepend() called with pkg_resources legacy namespace packages detected.\n" "Legacy namespace packages (using pkg_resources.declare_namespace) are deprecated.\n" "Please use native namespace packages (PEP 420) instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages"+ "See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages", ) PARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning(@@ -71,15 +81,17 @@ PARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning( "See https://docs.pytest.org/en/stable/deprecations.html#parametrize-iterators", ) -CONSOLE_MAIN = PytestRemovedIn10Warning(+CONSOLE_MAIN = UnformattedWarning(+ PytestRemovedIn10Warning, "pytest.console_main() is deprecated and will be removed in pytest 10.\n" "It was never intended for programmatic use; use pytest.main() instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#console-main"+ "See https://docs.pytest.org/en/stable/deprecations.html#console-main", ) -CONFIG_INICFG = PytestRemovedIn10Warning(+CONFIG_INICFG = UnformattedWarning(+ PytestRemovedIn10Warning, "config.inicfg is deprecated, use config.getini() to access configuration values instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg"+ "See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg", ) FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning(@@ -90,18 +102,20 @@ FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning( "See https://docs.pytest.org/en/stable/deprecations.html#dynamic-fixture-request-during-teardown", ) -PASTEBIN = PytestRemovedIn10Warning(+PASTEBIN = UnformattedWarning(+ PytestRemovedIn10Warning, "The --pastebin option is deprecated. " "The functionality is now available in an external plugin package, pytest-pastebin.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#the-pastebin-option"+ "See https://docs.pytest.org/en/stable/deprecations.html#the-pastebin-option", ) -INI_STRING_TYPE_NON_STR_VALUE = PytestRemovedIn10Warning(+INI_STRING_TYPE_NON_STR_VALUE = UnformattedWarning(+ PytestRemovedIn10Warning, "Passing a value that is not a string to a 'string'-typed ini option is deprecated.\n" "In a future version this will raise a TypeError, matching the behavior of the " "corresponding TOML config path.\n" "If your plugin intentionally accepts non-string values, declare an explicit type "- '(e.g. type="args") instead of relying on the implicit string default.'+ '(e.g. type="args") instead of relying on the implicit string default.', ) # You want to make some `__init__` or function "private".@@ -123,33 +137,38 @@ INI_STRING_TYPE_NON_STR_VALUE = PytestRemovedIn10Warning( # the warning (possibly error in the future). -FIXTURE_BASEID_DEPRECATED = PytestRemovedIn10Warning(- "Passing baseid to FixtureDef is deprecated. Pass node instead for fixture scoping."+FIXTURE_BASEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning,+ "Passing baseid to FixtureDef is deprecated. Pass node instead for fixture scoping.", ) -FIXTURE_NODEID_DEPRECATED = PytestRemovedIn10Warning(+FIXTURE_NODEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "Passing nodeid to _register_fixture is deprecated. "- "Pass node instead for fixture scoping."+ "Pass node instead for fixture scoping.", ) -FIXTUREDEF_HAS_LOCATION_DEPRECATED = PytestRemovedIn10Warning(+FIXTUREDEF_HAS_LOCATION_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "FixtureDef.has_location is deprecated and will be removed in pytest 10. "- "See https://docs.pytest.org/en/stable/deprecations.html#fixturedef-has-location-deprecated"+ "See https://docs.pytest.org/en/stable/deprecations.html#fixturedef-has-location-deprecated", ) -PARSEFACTORIES_NODEID_DEPRECATED = PytestRemovedIn10Warning(+PARSEFACTORIES_NODEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "Passing nodeid string to parsefactories is deprecated. "- "Use parsefactories(holder=obj, node=node) instead."+ "Use parsefactories(holder=obj, node=node) instead.", ) -CALLSPEC2_RENAMED = PytestRemovedIn10Warning(+CALLSPEC2_RENAMED = UnformattedWarning(+ PytestRemovedIn10Warning, "_pytest.python.CallSpec2 has been renamed to CallSpec.\n" "The CallSpec2 alias will be removed in pytest 10.\n" "Update imports to use CallSpec instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#callspec2-renamed"+ "See https://docs.pytest.org/en/stable/deprecations.html#callspec2-renamed", ) def check_ispytest(ispytest: bool) -> None: if not ispytest:- warn(PRIVATE, stacklevel=3)+ warn(PRIVATE.format(), stacklevel=3)src/_pytest/fixtures.pyindex 30f44d44d..20e43f891 100644@@ -1132,7 +1132,7 @@ class FixtureDef(Generic[FixtureValue]): check_ispytest(_ispytest) # Emit deprecation warning if deprecated baseid string is used. if node is NOTSET:- warnings.warn(FIXTURE_BASEID_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTURE_BASEID_DEPRECATED.format(), stacklevel=2) if baseid is NOTSET: baseid = None # The node where this fixture was defined, if available.@@ -1197,7 +1197,7 @@ class FixtureDef(Generic[FixtureValue]): @property def has_location(self) -> bool:- warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED.format(), stacklevel=2) return self._has_location def addfinalizer(self, finalizer: Callable[[], object]) -> None:@@ -1620,7 +1620,7 @@ def yield_fixture( .. deprecated:: 3.0 Use :py:func:`pytest.fixture` directly instead. """- warnings.warn(YIELD_FIXTURE, stacklevel=2)+ warnings.warn(YIELD_FIXTURE.format(), stacklevel=2) return fixture( fixture_function, *args,@@ -2091,7 +2091,7 @@ class FixtureManager: """ # Emit deprecation warning if nodeid string. if nodeid is not NOTSET or node is NOTSET:- warnings.warn(FIXTURE_NODEID_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTURE_NODEID_DEPRECATED.format(), stacklevel=2) fixture_def = FixtureDef( config=self.config, baseid=nodeid,@@ -2280,7 +2280,7 @@ class FixtureManager: raise TypeError("parsefactories() requires holder or node_or_obj") elif nodeid is not NOTSET: # Legacy: parsefactories(obj, nodeid) - string-based scoping only.- warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED, stacklevel=2)+ warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED.format(), stacklevel=2) holderobj = node_or_obj effective_nodeid = nodeid else:src/_pytest/monkeypatch.pyindex 453c6728e..da9f25f56 100644@@ -385,7 +385,8 @@ class MonkeyPatch: ns_pkg_path = path_obj / ns_pkg.replace(".", os.sep) if ns_pkg_path.is_dir(): warnings.warn(- MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES, stacklevel=2+ MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES.format(),+ stacklevel=2, ) break src/_pytest/pastebin.pyindex e6a143022..5e1c06ca9 100644@@ -35,7 +35,7 @@ def pytest_addoption(parser: Parser) -> None: @pytest.hookimpl(trylast=True) def pytest_configure(config: Config) -> None: if config.option.pastebin:- config.issue_config_time_warning(PASTEBIN, 2)+ config.issue_config_time_warning(PASTEBIN.format(), 2) if config.option.pastebin == "all": tr = config.pluginmanager.getplugin("terminalreporter")src/_pytest/python.pyindex 792d0d5b4..d392afc7e 100644@@ -1852,6 +1852,6 @@ class FunctionDefinition(Function): def __getattr__(name: str) -> object: if name == "CallSpec2":- warnings.warn(CALLSPEC2_RENAMED, stacklevel=2)+ warnings.warn(CALLSPEC2_RENAMED.format(), stacklevel=2) return CallSpec raise AttributeError(f"module {__name__!r} has no attribute {name!r}")testing/deprecated_test.pyindex ee91880d2..577b8c299 100644@@ -1,6 +1,9 @@ # mypy: allow-untyped-defs from __future__ import annotations +import traceback+import warnings+ from _pytest import deprecated from _pytest.pytester import Pytester from _pytest.scope import Scope@@ -365,3 +368,87 @@ def test_callspec2_renamed() -> None: with pytest.warns(pytest.PytestRemovedIn10Warning, match="CallSpec2"): assert python_mod.CallSpec2 is CallSpec+++def test_no_shared_warning_instances() -> None:+ """Deprecation constants must not be warning instances: under ``-W error``+ ``warnings.warn()`` raises the given object itself, so a shared instance would+ accumulate tracebacks across raises."""+ shared = [+ name+ for name, value in vars(deprecated).items()+ if name.isupper() and isinstance(value, Warning)+ ]+ assert shared == []+++def _trigger_yield_fixture(pytester: Pytester) -> None:+ pytest.yield_fixture(lambda: None) # type: ignore[deprecated]+++def _trigger_private(pytester: Pytester) -> None:+ deprecated.check_ispytest(False)+++def _trigger_callspec2(pytester: Pytester) -> None:+ import _pytest.python++ _pytest.python.CallSpec2 # type: ignore[attr-defined] # noqa: B018+++def _trigger_config_inicfg(pytester: Pytester) -> None:+ config = pytester.parseconfig()+ config.inicfg # type: ignore[deprecated] # noqa: B018+++@pytest.mark.parametrize(+ "trigger",+ [+ _trigger_yield_fixture,+ _trigger_private,+ _trigger_callspec2,+ _trigger_config_inicfg,+ ],+)+def test_deprecation_raised_as_error_gets_fresh_instance(+ pytester: Pytester, trigger+) -> None:+ def raise_once() -> BaseException:+ with warnings.catch_warnings():+ warnings.simplefilter("error", pytest.PytestDeprecationWarning)+ with pytest.raises(pytest.PytestDeprecationWarning) as excinfo:+ trigger(pytester)+ return excinfo.value++ def tb_depth(exc: BaseException) -> int:+ return len(traceback.extract_tb(exc.__traceback__))++ first = raise_once()+ first_depth = tb_depth(first)+ second = raise_once()+ assert second is not first+ # Each raise starts with its own traceback instead of extending a shared one.+ assert tb_depth(second) == first_depth+ assert tb_depth(first) == first_depth+++def test_deprecation_error_traceback_not_polluted_across_tests(+ pytester: Pytester,+) -> None:+ pytester.makepyfile(+ """+ import pytest++ def test_one():+ pytest.yield_fixture(lambda: None) # marker-one++ def test_two():+ pytest.yield_fixture(lambda: None) # marker-two+ """+ )+ result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")+ result.assert_outcomes(failed=2)+ output = result.stdout.str()+ two_section = output[output.index("_ test_two _") :]+ assert "marker-two" in two_section+ assert "marker-one" not in two_section
changelog/14912.bugfix.rstnew file mode 100644index 000000000..5ca820df3@@ -0,0 +1 @@+:class:`~pytest.PytestWarning` instances defined in ``_pytest.deprecated`` are no longer reused across ``warnings.warn`` calls, so warnings raised as errors (e.g. with ``-W error``) no longer accumulate stale traceback frames from previous raises.src/_pytest/config/__init__.pyindex c7bd3e1af..f04269f79 100644@@ -303,7 +303,7 @@ def console_main() -> int: from _pytest.deprecated import CONSOLE_MAIN - warnings.warn(CONSOLE_MAIN, stacklevel=2)+ warnings.warn(CONSOLE_MAIN.format(), stacklevel=2) return _console_main() @@ -1241,7 +1241,7 @@ class Config: @property def inicfg(self) -> _DeprecatedInicfgProxy: warnings.warn(- _pytest.deprecated.CONFIG_INICFG,+ _pytest.deprecated.CONFIG_INICFG.format(), stacklevel=2, ) return _DeprecatedInicfgProxy(self)src/_pytest/deprecated.pyindex 0370240ee..a94aeb735 100644@@ -4,9 +4,11 @@ is planned to be removed in the next pytest release. Keeping it in a central location makes it easy to track what is deprecated and should be removed when the time comes. -All constants defined in this module should be either instances of-:class:`PytestWarning`, or :class:`UnformattedWarning`-in case of warnings which need to format their messages.+All constants defined in this module should be instances of+:class:`UnformattedWarning`, whose ``format`` method returns a fresh warning+instance each time. Do not warn with shared warning instances: if a warning is+raised as an error, CPython appends to the exception's existing ``__traceback__``,+so a process-lifetime instance would accumulate stale frames from previous raises. """ from __future__ import annotations@@ -29,9 +31,10 @@ DEPRECATED_EXTERNAL_PLUGINS = { # This could have been removed pytest 8, but it's harmless and common, so no rush to remove.-YIELD_FIXTURE = PytestRemovedIn10Warning(+YIELD_FIXTURE = UnformattedWarning(+ PytestRemovedIn10Warning, "@pytest.yield_fixture is deprecated.\n"- "Use @pytest.fixture instead; they are the same."+ "Use @pytest.fixture instead; they are the same.", ) CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning(@@ -44,7 +47,10 @@ CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning( ) # This deprecation is never really meant to be removed.-PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.")+PRIVATE = UnformattedWarning(+ PytestDeprecationWarning,+ "A private pytest class or function was used.",+) HOOK_LEGACY_MARKING = UnformattedWarning(@@ -56,11 +62,12 @@ HOOK_LEGACY_MARKING = UnformattedWarning( "#configuring-hook-specs-impls-using-markers", ) -MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = PytestRemovedIn10Warning(+MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = UnformattedWarning(+ PytestRemovedIn10Warning, "monkeypatch.syspath_prepend() called with pkg_resources legacy namespace packages detected.\n" "Legacy namespace packages (using pkg_resources.declare_namespace) are deprecated.\n" "Please use native namespace packages (PEP 420) instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages"+ "See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages", ) PARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning(@@ -71,15 +78,17 @@ PARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning( "See https://docs.pytest.org/en/stable/deprecations.html#parametrize-iterators", ) -CONSOLE_MAIN = PytestRemovedIn10Warning(+CONSOLE_MAIN = UnformattedWarning(+ PytestRemovedIn10Warning, "pytest.console_main() is deprecated and will be removed in pytest 10.\n" "It was never intended for programmatic use; use pytest.main() instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#console-main"+ "See https://docs.pytest.org/en/stable/deprecations.html#console-main", ) -CONFIG_INICFG = PytestRemovedIn10Warning(+CONFIG_INICFG = UnformattedWarning(+ PytestRemovedIn10Warning, "config.inicfg is deprecated, use config.getini() to access configuration values instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg"+ "See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg", ) FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning(@@ -90,10 +99,11 @@ FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning( "See https://docs.pytest.org/en/stable/deprecations.html#dynamic-fixture-request-during-teardown", ) -PASTEBIN = PytestRemovedIn10Warning(+PASTEBIN = UnformattedWarning(+ PytestRemovedIn10Warning, "The --pastebin option is deprecated. " "The functionality is now available in an external plugin package, pytest-pastebin.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#the-pastebin-option"+ "See https://docs.pytest.org/en/stable/deprecations.html#the-pastebin-option", ) INI_STRING_TYPE_NON_STR_VALUE = PytestRemovedIn10Warning(@@ -123,33 +133,38 @@ INI_STRING_TYPE_NON_STR_VALUE = PytestRemovedIn10Warning( # the warning (possibly error in the future). -FIXTURE_BASEID_DEPRECATED = PytestRemovedIn10Warning(- "Passing baseid to FixtureDef is deprecated. Pass node instead for fixture scoping."+FIXTURE_BASEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning,+ "Passing baseid to FixtureDef is deprecated. Pass node instead for fixture scoping.", ) -FIXTURE_NODEID_DEPRECATED = PytestRemovedIn10Warning(+FIXTURE_NODEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "Passing nodeid to _register_fixture is deprecated. "- "Pass node instead for fixture scoping."+ "Pass node instead for fixture scoping.", ) -FIXTUREDEF_HAS_LOCATION_DEPRECATED = PytestRemovedIn10Warning(+FIXTUREDEF_HAS_LOCATION_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "FixtureDef.has_location is deprecated and will be removed in pytest 10. "- "See https://docs.pytest.org/en/stable/deprecations.html#fixturedef-has-location-deprecated"+ "See https://docs.pytest.org/en/stable/deprecations.html#fixturedef-has-location-deprecated", ) -PARSEFACTORIES_NODEID_DEPRECATED = PytestRemovedIn10Warning(+PARSEFACTORIES_NODEID_DEPRECATED = UnformattedWarning(+ PytestRemovedIn10Warning, "Passing nodeid string to parsefactories is deprecated. "- "Use parsefactories(holder=obj, node=node) instead."+ "Use parsefactories(holder=obj, node=node) instead.", ) -CALLSPEC2_RENAMED = PytestRemovedIn10Warning(+CALLSPEC2_RENAMED = UnformattedWarning(+ PytestRemovedIn10Warning, "_pytest.python.CallSpec2 has been renamed to CallSpec.\n" "The CallSpec2 alias will be removed in pytest 10.\n" "Update imports to use CallSpec instead.\n"- "See https://docs.pytest.org/en/stable/deprecations.html#callspec2-renamed"+ "See https://docs.pytest.org/en/stable/deprecations.html#callspec2-renamed", ) def check_ispytest(ispytest: bool) -> None: if not ispytest:- warn(PRIVATE, stacklevel=3)+ warn(PRIVATE.format(), stacklevel=3)src/_pytest/fixtures.pyindex 30f44d44d..20e43f891 100644@@ -1132,7 +1132,7 @@ class FixtureDef(Generic[FixtureValue]): check_ispytest(_ispytest) # Emit deprecation warning if deprecated baseid string is used. if node is NOTSET:- warnings.warn(FIXTURE_BASEID_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTURE_BASEID_DEPRECATED.format(), stacklevel=2) if baseid is NOTSET: baseid = None # The node where this fixture was defined, if available.@@ -1197,7 +1197,7 @@ class FixtureDef(Generic[FixtureValue]): @property def has_location(self) -> bool:- warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED.format(), stacklevel=2) return self._has_location def addfinalizer(self, finalizer: Callable[[], object]) -> None:@@ -1620,7 +1620,7 @@ def yield_fixture( .. deprecated:: 3.0 Use :py:func:`pytest.fixture` directly instead. """- warnings.warn(YIELD_FIXTURE, stacklevel=2)+ warnings.warn(YIELD_FIXTURE.format(), stacklevel=2) return fixture( fixture_function, *args,@@ -2091,7 +2091,7 @@ class FixtureManager: """ # Emit deprecation warning if nodeid string. if nodeid is not NOTSET or node is NOTSET:- warnings.warn(FIXTURE_NODEID_DEPRECATED, stacklevel=2)+ warnings.warn(FIXTURE_NODEID_DEPRECATED.format(), stacklevel=2) fixture_def = FixtureDef( config=self.config, baseid=nodeid,@@ -2280,7 +2280,7 @@ class FixtureManager: raise TypeError("parsefactories() requires holder or node_or_obj") elif nodeid is not NOTSET: # Legacy: parsefactories(obj, nodeid) - string-based scoping only.- warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED, stacklevel=2)+ warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED.format(), stacklevel=2) holderobj = node_or_obj effective_nodeid = nodeid else:src/_pytest/monkeypatch.pyindex 453c6728e..6002fa27a 100644@@ -385,7 +385,7 @@ class MonkeyPatch: ns_pkg_path = path_obj / ns_pkg.replace(".", os.sep) if ns_pkg_path.is_dir(): warnings.warn(- MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES, stacklevel=2+ MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES.format(), stacklevel=2 ) break src/_pytest/pastebin.pyindex e6a143022..5e1c06ca9 100644@@ -35,7 +35,7 @@ def pytest_addoption(parser: Parser) -> None: @pytest.hookimpl(trylast=True) def pytest_configure(config: Config) -> None: if config.option.pastebin:- config.issue_config_time_warning(PASTEBIN, 2)+ config.issue_config_time_warning(PASTEBIN.format(), 2) if config.option.pastebin == "all": tr = config.pluginmanager.getplugin("terminalreporter")src/_pytest/python.pyindex 792d0d5b4..d392afc7e 100644@@ -1852,6 +1852,6 @@ class FunctionDefinition(Function): def __getattr__(name: str) -> object: if name == "CallSpec2":- warnings.warn(CALLSPEC2_RENAMED, stacklevel=2)+ warnings.warn(CALLSPEC2_RENAMED.format(), stacklevel=2) return CallSpec raise AttributeError(f"module {__name__!r} has no attribute {name!r}")testing/deprecated_test.pyindex ee91880d2..5de659a48 100644@@ -1,6 +1,8 @@ # mypy: allow-untyped-defs from __future__ import annotations +from types import TracebackType+ from _pytest import deprecated from _pytest.pytester import Pytester from _pytest.scope import Scope@@ -365,3 +367,37 @@ def test_callspec2_renamed() -> None: with pytest.warns(pytest.PytestRemovedIn10Warning, match="CallSpec2"): assert python_mod.CallSpec2 is CallSpec+++def test_deprecation_warning_instance_not_shared_across_raises() -> None:+ """Each raise must use a fresh warning instance (#14912).++ When a warning is raised as an error, CPython appends to the exception's+ existing ``__traceback__`` instead of replacing it, so reusing a single+ module-level instance accumulates stale frames from previous raises.+ """+ import warnings++ class PrivateClass:+ def __init__(self) -> None:+ deprecated.check_ispytest(False)++ def count_frames(tb: TracebackType | None) -> int:+ n = 0+ while tb is not None:+ n += 1+ tb = tb.tb_next+ return n++ def raise_and_count() -> int:+ with warnings.catch_warnings():+ warnings.simplefilter("error", PytestDeprecationWarning)+ with pytest.raises(PytestDeprecationWarning) as excinfo:+ PrivateClass()+ return count_frames(excinfo.value.__traceback__)++ first = raise_and_count()+ second = raise_and_count()++ # The traceback of a shared instance would grow with every raise.+ assert second <= first