Skip to content

Commit dde165b

Browse files
deprecate hook configuration via marks/attributes
fixes #4562
1 parent 62107fb commit dde165b

File tree

7 files changed

+153
-22
lines changed

7 files changed

+153
-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: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,38 @@ Below is a complete list of all pytest features which are considered deprecated.
1919
:class:`PytestWarning` or subclasses, which can be filtered using :ref:`standard warning filters <warnings>`.
2020

2121

22+
configuring hook specs/impls using markers
23+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24+
25+
Before pluggy, pytest's plugin library, was its own package and had a clear API,
26+
pytest just used ``pytest.mark`` to configure hooks.
27+
28+
The :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec` decorators
29+
have been available since years and should be used instead.
30+
31+
.. code-block:: python
32+
33+
@pytest.mark.tryfirst
34+
def pytest_runtest_call():
35+
...
36+
37+
38+
# or
39+
def pytest_runtest_call():
40+
...
41+
42+
43+
pytest_runtest_call.tryfirst = True
44+
45+
should be changed to:
46+
47+
.. code-block:: python
48+
49+
@pytest.hookimpl(tryfirst=True)
50+
def pytest_runtest_call():
51+
...
52+
53+
2254
``py.path.local`` arguments for hooks replaced with ``pathlib.Path``
2355
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2456

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ filterwarnings = [
4040
# Those are caught/handled by pyupgrade, and not easy to filter with the
4141
# module being the filename (with .py removed).
4242
"default:invalid escape sequence:DeprecationWarning",
43+
# ignore not yet fixed warnings for hook markers
44+
"default:.*not marked using pytest.hook.*",
45+
"ignore:.*not marked using pytest.hook.*::xdist.*",
4346
# ignore use of unregistered marks, because we use many to test the implementation
4447
"ignore::_pytest.warning_types.PytestUnknownMarkWarning",
4548
# 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
@@ -13,6 +13,7 @@
1313
import warnings
1414
from functools import lru_cache
1515
from pathlib import Path
16+
from types import FunctionType
1617
from types import TracebackType
1718
from typing import Any
1819
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

@@ -330,6 +332,32 @@ def _prepareconfig(
330332
raise
331333

332334

335+
def _get_legacy_hook_marks(
336+
method: FunctionType,
337+
hook_type: str,
338+
opt_names: Tuple[str, ...],
339+
) -> Dict[str, bool]:
340+
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
341+
must_warn = False
342+
opts = {}
343+
for opt_name in opt_names:
344+
if hasattr(method, opt_name) or opt_name in known_marks:
345+
opts[opt_name] = True
346+
must_warn = True
347+
else:
348+
opts[opt_name] = False
349+
if must_warn:
350+
351+
hook_opts = ", ".join(f"{name}=True" for name, val in opts.items() if val)
352+
message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(
353+
type=hook_type,
354+
fullname=method.__qualname__,
355+
hook_opts=hook_opts,
356+
)
357+
warn_explicit_for(method, message)
358+
return opts
359+
360+
333361
@final
334362
class PytestPluginManager(PluginManager):
335363
"""A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
@@ -393,40 +421,29 @@ def parse_hookimpl_opts(self, plugin: _PluggyPlugin, name: str):
393421
if name == "pytest_plugins":
394422
return
395423

396-
method = getattr(plugin, name)
397424
opts = super().parse_hookimpl_opts(plugin, name)
425+
if opts is not None:
426+
return opts
398427

428+
method = getattr(plugin, name)
399429
# Consider only actual functions for hooks (#3775).
400430
if not inspect.isroutine(method):
401431
return
402-
403432
# Collect unmarked hooks as long as they have the `pytest_' prefix.
404-
if opts is None and name.startswith("pytest_"):
405-
opts = {}
406-
if opts is not None:
407-
# TODO: DeprecationWarning, people should use hookimpl
408-
# https://github.com/pytest-dev/pytest/issues/4562
409-
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
410-
411-
for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
412-
opts.setdefault(name, hasattr(method, name) or name in known_marks)
413-
return opts
433+
return _get_legacy_hook_marks(
434+
method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
435+
)
414436

415437
def parse_hookspec_opts(self, module_or_class, name: str):
416438
opts = super().parse_hookspec_opts(module_or_class, name)
417439
if opts is None:
418440
method = getattr(module_or_class, name)
419-
420441
if name.startswith("pytest_"):
421-
# todo: deprecate hookspec hacks
422-
# https://github.com/pytest-dev/pytest/issues/4562
423-
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
424-
opts = {
425-
"firstresult": hasattr(method, "firstresult")
426-
or "firstresult" in known_marks,
427-
"historic": hasattr(method, "historic")
428-
or "historic" in known_marks,
429-
}
442+
opts = _get_legacy_hook_marks(
443+
method,
444+
"spec",
445+
("firstresult", "historic"),
446+
)
430447
return opts
431448

432449
def register(

src/_pytest/deprecated.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,16 @@
106106
" Replace pytest.warns(None) by simply pytest.warns()."
107107
)
108108

109+
110+
HOOK_LEGACY_MARKING = UnformattedWarning(
111+
PytestDeprecationWarning,
112+
"The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n"
113+
"Please use the pytest.hook{type}({hook_opts}) decorator instead\n"
114+
" to configure the hooks.\n"
115+
" See https://docs.pytest.org/en/latest/deprecations.html"
116+
"#configuring-hook-specs-impls-using-markers",
117+
)
118+
109119
# You want to make some `__init__` or function "private".
110120
#
111121
# def my_private_function(some, args):

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
@@ -130,3 +133,19 @@ class UnformattedWarning(Generic[_W]):
130133
def format(self, **kwargs: Any) -> _W:
131134
"""Return an instance of the warning category, formatted with given kwargs."""
132135
return self.category(self.template.format(**kwargs))
136+
137+
138+
def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
139+
lineno = method.__code__.co_firstlineno
140+
filename = inspect.getfile(method)
141+
module = method.__module__
142+
mod_globals = method.__globals__
143+
144+
warnings.warn_explicit(
145+
message,
146+
type(message),
147+
filename=filename,
148+
module=module,
149+
registry=mod_globals.setdefault("__warningregistry__", {}),
150+
lineno=lineno,
151+
)

testing/deprecated_test.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,52 @@ def test_fillfixtures_is_deprecated() -> None:
5252
_pytest.fixtures.fillfixtures(mock.Mock())
5353

5454

55+
def test_hookspec_via_function_attributes_are_deprecated():
56+
from _pytest.config import PytestPluginManager
57+
58+
pm = PytestPluginManager()
59+
60+
class DeprecatedHookMarkerSpec:
61+
def pytest_bad_hook(self):
62+
pass
63+
64+
pytest_bad_hook.historic = True # type: ignore[attr-defined]
65+
66+
with pytest.warns(
67+
PytestDeprecationWarning, match="instead of pytest.mark"
68+
) as recorder:
69+
pm.add_hookspecs(DeprecatedHookMarkerSpec)
70+
(record,) = recorder
71+
assert (
72+
record.lineno
73+
== DeprecatedHookMarkerSpec.pytest_bad_hook.__code__.co_firstlineno
74+
)
75+
assert record.filename == __file__
76+
77+
78+
def test_hookimpl_via_function_attributes_are_deprecated():
79+
from _pytest.config import PytestPluginManager
80+
81+
pm = PytestPluginManager()
82+
83+
class DeprecatedMarkImplPlugin:
84+
def pytest_runtest_call(self):
85+
pass
86+
87+
pytest_runtest_call.tryfirst = True # type: ignore[attr-defined]
88+
89+
with pytest.warns(
90+
PytestDeprecationWarning, match="instead of pytest.mark"
91+
) as recorder:
92+
pm.register(DeprecatedMarkImplPlugin())
93+
(record,) = recorder
94+
assert (
95+
record.lineno
96+
== DeprecatedMarkImplPlugin.pytest_runtest_call.__code__.co_firstlineno
97+
)
98+
assert record.filename == __file__
99+
100+
55101
def test_minus_k_dash_is_deprecated(pytester: Pytester) -> None:
56102
threepass = pytester.makepyfile(
57103
test_threepass="""

0 commit comments

Comments
 (0)