Skip to content

Commit cfb2a2e

Browse files
deprecate hook configuration via marks/attributes
fixes #4562
1 parent b4ab2f0 commit cfb2a2e

File tree

7 files changed

+163
-22
lines changed

7 files changed

+163
-22
lines changed

changelog/4562.deprecation.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Deprecate configuring hook specs/impls using attributes/marks.
2+
3+
Instead use :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec`.
4+
For more details, see the :ref:`docs <configuring-hook-specs-impls-using-markers>`.

doc/en/deprecations.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,50 @@ no matter what argument was used in the constructor. We expect to deprecate the
7878

7979
.. _legacy-path-hooks-deprecated:
8080

81+
configuring hook specs/impls using markers
82+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83+
84+
Before pluggy, pytest's plugin library, was its own package and had a clear API,
85+
pytest just used ``pytest.mark`` to configure hooks.
86+
87+
The :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec` decorators
88+
have been available since years and should be used instead.
89+
90+
.. code-block:: python
91+
92+
@pytest.mark.tryfirst
93+
def pytest_runtest_call():
94+
...
95+
96+
97+
# or
98+
def pytest_runtest_call():
99+
...
100+
101+
102+
pytest_runtest_call.tryfirst = True
103+
104+
should be changed to:
105+
106+
.. code-block:: python
107+
108+
@pytest.hookimpl(tryfirst=True)
109+
def pytest_runtest_call():
110+
...
111+
112+
Changed ``hookimpl`` attributes:
113+
114+
* ``tryfirst``
115+
* ``trylast``
116+
* ``optionalhook``
117+
* ``hookwrapper``
118+
119+
Changed ``hookwrapper`` attributes:
120+
121+
* ``firstresult``
122+
* ``historic``
123+
124+
81125
``py.path.local`` arguments for hooks replaced with ``pathlib.Path``
82126
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83127

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ filterwarnings = [
3838
# Those are caught/handled by pyupgrade, and not easy to filter with the
3939
# module being the filename (with .py removed).
4040
"default:invalid escape sequence:DeprecationWarning",
41+
# ignore not yet fixed warnings for hook markers
42+
"default:.*not marked using pytest.hook.*",
43+
"ignore:.*not marked using pytest.hook.*::xdist.*",
4144
# ignore use of unregistered marks, because we use many to test the implementation
4245
"ignore::_pytest.warning_types.PytestUnknownMarkWarning",
4346
# https://github.com/benjaminp/six/issues/341

src/_pytest/config/__init__.py

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from functools import lru_cache
1515
from pathlib import Path
1616
from textwrap import dedent
17+
from types import FunctionType
1718
from types import TracebackType
1819
from typing import Any
1920
from typing import Callable
@@ -58,6 +59,7 @@
5859
from _pytest.pathlib import resolve_package_path
5960
from _pytest.stash import Stash
6061
from _pytest.warning_types import PytestConfigWarning
62+
from _pytest.warning_types import warn_explicit_for
6163

6264
if TYPE_CHECKING:
6365

@@ -341,6 +343,32 @@ def _get_directory(path: Path) -> Path:
341343
return path
342344

343345

346+
def _get_legacy_hook_marks(
347+
method: object, # using object to avoid function type excess
348+
hook_type: str,
349+
opt_names: Tuple[str, ...],
350+
) -> Dict[str, bool]:
351+
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
352+
must_warn = False
353+
opts = {}
354+
for opt_name in opt_names:
355+
if hasattr(method, opt_name) or opt_name in known_marks:
356+
opts[opt_name] = True
357+
must_warn = True
358+
else:
359+
opts[opt_name] = False
360+
if must_warn:
361+
362+
hook_opts = ", ".join(f"{name}=True" for name, val in opts.items() if val)
363+
message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(
364+
type=hook_type,
365+
fullname=method.__qualname__, # type: ignore
366+
hook_opts=hook_opts,
367+
)
368+
warn_explicit_for(cast(FunctionType, method), message)
369+
return opts
370+
371+
344372
@final
345373
class PytestPluginManager(PluginManager):
346374
"""A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
@@ -414,40 +442,29 @@ def parse_hookimpl_opts(self, plugin: _PluggyPlugin, name: str):
414442
if name == "pytest_plugins":
415443
return
416444

417-
method = getattr(plugin, name)
418445
opts = super().parse_hookimpl_opts(plugin, name)
446+
if opts is not None:
447+
return opts
419448

449+
method = getattr(plugin, name)
420450
# Consider only actual functions for hooks (#3775).
421451
if not inspect.isroutine(method):
422452
return
423-
424453
# Collect unmarked hooks as long as they have the `pytest_' prefix.
425-
if opts is None and name.startswith("pytest_"):
426-
opts = {}
427-
if opts is not None:
428-
# TODO: DeprecationWarning, people should use hookimpl
429-
# https://github.com/pytest-dev/pytest/issues/4562
430-
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
431-
432-
for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
433-
opts.setdefault(name, hasattr(method, name) or name in known_marks)
434-
return opts
454+
return _get_legacy_hook_marks(
455+
method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
456+
)
435457

436458
def parse_hookspec_opts(self, module_or_class, name: str):
437459
opts = super().parse_hookspec_opts(module_or_class, name)
438460
if opts is None:
439461
method = getattr(module_or_class, name)
440-
441462
if name.startswith("pytest_"):
442-
# todo: deprecate hookspec hacks
443-
# https://github.com/pytest-dev/pytest/issues/4562
444-
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
445-
opts = {
446-
"firstresult": hasattr(method, "firstresult")
447-
or "firstresult" in known_marks,
448-
"historic": hasattr(method, "historic")
449-
or "historic" in known_marks,
450-
}
463+
opts = _get_legacy_hook_marks(
464+
method,
465+
"spec",
466+
("firstresult", "historic"),
467+
)
451468
return opts
452469

453470
def register(

src/_pytest/deprecated.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,14 @@
9898
"The pytest.Instance collector type is deprecated and is no longer used. "
9999
"See https://docs.pytest.org/en/latest/deprecations.html#the-pytest-instance-collector",
100100
)
101+
HOOK_LEGACY_MARKING = UnformattedWarning(
102+
PytestDeprecationWarning,
103+
"The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n"
104+
"Please use the pytest.hook{type}({hook_opts}) decorator instead\n"
105+
" to configure the hooks.\n"
106+
" See https://docs.pytest.org/en/latest/deprecations.html"
107+
"#configuring-hook-specs-impls-using-markers",
108+
)
101109

102110
# You want to make some `__init__` or function "private".
103111
#

src/_pytest/warning_types.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import inspect
2+
import warnings
3+
from types import FunctionType
14
from typing import Any
25
from typing import Generic
36
from typing import Type
@@ -143,3 +146,19 @@ class UnformattedWarning(Generic[_W]):
143146
def format(self, **kwargs: Any) -> _W:
144147
"""Return an instance of the warning category, formatted with given kwargs."""
145148
return self.category(self.template.format(**kwargs))
149+
150+
151+
def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
152+
lineno = method.__code__.co_firstlineno
153+
filename = inspect.getfile(method)
154+
module = method.__module__
155+
mod_globals = method.__globals__
156+
157+
warnings.warn_explicit(
158+
message,
159+
type(message),
160+
filename=filename,
161+
module=module,
162+
registry=mod_globals.setdefault("__warningregistry__", {}),
163+
lineno=lineno,
164+
)

testing/deprecated_test.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,52 @@ def test_external_plugins_integrated(pytester: Pytester, plugin) -> None:
2020
pytester.parseconfig("-p", plugin)
2121

2222

23+
def test_hookspec_via_function_attributes_are_deprecated():
24+
from _pytest.config import PytestPluginManager
25+
26+
pm = PytestPluginManager()
27+
28+
class DeprecatedHookMarkerSpec:
29+
def pytest_bad_hook(self):
30+
pass
31+
32+
pytest_bad_hook.historic = True # type: ignore[attr-defined]
33+
34+
with pytest.warns(
35+
PytestDeprecationWarning, match="instead of pytest.mark"
36+
) as recorder:
37+
pm.add_hookspecs(DeprecatedHookMarkerSpec)
38+
(record,) = recorder
39+
assert (
40+
record.lineno
41+
== DeprecatedHookMarkerSpec.pytest_bad_hook.__code__.co_firstlineno
42+
)
43+
assert record.filename == __file__
44+
45+
46+
def test_hookimpl_via_function_attributes_are_deprecated():
47+
from _pytest.config import PytestPluginManager
48+
49+
pm = PytestPluginManager()
50+
51+
class DeprecatedMarkImplPlugin:
52+
def pytest_runtest_call(self):
53+
pass
54+
55+
pytest_runtest_call.tryfirst = True # type: ignore[attr-defined]
56+
57+
with pytest.warns(
58+
PytestDeprecationWarning, match="Please use the pytest.hookspec(historic=True)"
59+
) as recorder:
60+
pm.register(DeprecatedMarkImplPlugin())
61+
(record,) = recorder
62+
assert (
63+
record.lineno
64+
== DeprecatedMarkImplPlugin.pytest_runtest_call.__code__.co_firstlineno
65+
)
66+
assert record.filename == __file__
67+
68+
2369
def test_fscollector_gethookproxy_isinitpath(pytester: Pytester) -> None:
2470
module = pytester.getmodulecol(
2571
"""

0 commit comments

Comments
 (0)