Skip to content

Commit c53e07c

Browse files
deprecate hook configuration via marks/attributes
fixes #4562
1 parent f65dfc3 commit c53e07c

File tree

7 files changed

+153
-22
lines changed

7 files changed

+153
-22
lines changed

changelog/4562.deprecation.rst

+4
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

+32
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

+3
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

+39-22
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

@@ -329,6 +331,32 @@ def _prepareconfig(
329331
raise
330332

331333

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

395-
method = getattr(plugin, name)
396423
opts = super().parse_hookimpl_opts(plugin, name)
424+
if opts is not None:
425+
return opts
397426

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

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

431448
def register(

src/_pytest/deprecated.py

+10
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

+19
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

+46
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,52 @@ def test_fillfixtures_is_deprecated() -> None:
5151
_pytest.fixtures.fillfixtures(mock.Mock())
5252

5353

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

0 commit comments

Comments
 (0)