Skip to content

use callable protocols for pytest.skip/exit/fail/xfail instead of _WithException wrapper with __call__ attribute #13445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Deysha Rivera
Dheeraj C K
Dhiren Serai
Diego Russo
Dima Gerasimov
Dmitry Dygalo
Dmitry Pribysh
Dominic Mortlock
Expand Down
1 change: 1 addition & 0 deletions changelog/13445.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Made the type annotations of :func:`pytest.skip` and friends more spec-complaint to have them work across more type checkers.
95 changes: 43 additions & 52 deletions src/_pytest/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@

from __future__ import annotations

from collections.abc import Callable
import sys
from typing import Any
from typing import cast
from typing import ClassVar
from typing import NoReturn
from typing import Protocol
from typing import TypeVar

from .warning_types import PytestDeprecationWarning

Expand Down Expand Up @@ -77,57 +74,36 @@ def __init__(
super().__init__(msg)


# We need a callable protocol to add attributes, for discussion see
# https://github.com/python/mypy/issues/2087.

_F = TypeVar("_F", bound=Callable[..., object])
_ET = TypeVar("_ET", bound=type[BaseException])


class _WithException(Protocol[_F, _ET]):
Exception: _ET
__call__: _F


def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]:
def decorate(func: _F) -> _WithException[_F, _ET]:
func_with_exception = cast(_WithException[_F, _ET], func)
func_with_exception.Exception = exception_type
return func_with_exception

return decorate


# Exposed helper methods.
class XFailed(Failed):
"""Raised from an explicit call to pytest.xfail()."""


@_with_exception(Exit)
def exit(
reason: str = "",
returncode: int | None = None,
) -> NoReturn:
class _Exit:
"""Exit testing process.

:param reason:
The message to show as the reason for exiting pytest. reason has a default value
only because `msg` is deprecated.

:param returncode:
Return code to be used when exiting pytest. None means the same as ``0`` (no error), same as :func:`sys.exit`.
Return code to be used when exiting pytest. None means the same as ``0`` (no error),
same as :func:`sys.exit`.

:raises pytest.exit.Exception:
The exception that is raised.
"""
__tracebackhide__ = True
raise Exit(reason, returncode)

Exception: ClassVar[type[Exit]] = Exit

@_with_exception(Skipped)
def skip(
reason: str = "",
*,
allow_module_level: bool = False,
) -> NoReturn:
def __call__(self, reason: str = "", returncode: int | None = None) -> NoReturn:
__tracebackhide__ = True
raise Exit(msg=reason, returncode=returncode)


exit: _Exit = _Exit()


class _Skip:
"""Skip an executing test with the given message.

This function should be called only during testing (setup, call or teardown) or
Expand Down Expand Up @@ -155,12 +131,18 @@ def skip(
Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)
to skip a doctest statically.
"""
__tracebackhide__ = True
raise Skipped(msg=reason, allow_module_level=allow_module_level)

Exception: ClassVar[type[Skipped]] = Skipped

def __call__(self, reason: str = "", allow_module_level: bool = False) -> NoReturn:
__tracebackhide__ = True
raise Skipped(msg=reason, allow_module_level=allow_module_level)


skip: _Skip = _Skip()

@_with_exception(Failed)
def fail(reason: str = "", pytrace: bool = True) -> NoReturn:

class _Fail:
"""Explicitly fail an executing test with the given message.

:param reason:
Expand All @@ -173,16 +155,18 @@ def fail(reason: str = "", pytrace: bool = True) -> NoReturn:
:raises pytest.fail.Exception:
The exception that is raised.
"""
__tracebackhide__ = True
raise Failed(msg=reason, pytrace=pytrace)

Exception: ClassVar[type[Failed]] = Failed

class XFailed(Failed):
"""Raised from an explicit call to pytest.xfail()."""
def __call__(self, reason: str = "", pytrace: bool = True) -> NoReturn:
__tracebackhide__ = True
raise Failed(msg=reason, pytrace=pytrace)


@_with_exception(XFailed)
def xfail(reason: str = "") -> NoReturn:
fail: _Fail = _Fail()


class _XFail:
"""Imperatively xfail an executing test or setup function with the given reason.

This function should be called only during testing (setup, call or teardown).
Expand All @@ -201,8 +185,15 @@ def xfail(reason: str = "") -> NoReturn:
:raises pytest.xfail.Exception:
The exception that is raised.
"""
__tracebackhide__ = True
raise XFailed(reason)

Exception: ClassVar[type[XFailed]] = XFailed

def __call__(self, reason: str = "") -> NoReturn:
__tracebackhide__ = True
raise XFailed(msg=reason)


xfail: _XFail = _XFail()


def importorskip(
Expand Down
3 changes: 2 additions & 1 deletion testing/python/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1075,7 +1075,8 @@ class TestTracebackCutting:
def test_skip_simple(self):
with pytest.raises(pytest.skip.Exception) as excinfo:
pytest.skip("xxx")
assert excinfo.traceback[-1].frame.code.name == "skip"
if sys.version_info >= (3, 11):
assert excinfo.traceback[-1].frame.code.raw.co_qualname == "_Skip.__call__"
assert excinfo.traceback[-1].ishidden(excinfo)
assert excinfo.traceback[-2].frame.code.name == "test_skip_simple"
assert not excinfo.traceback[-2].ishidden(excinfo)
Expand Down