| 1 |
"""Exception classes and constants handling test outcomes as well as |
| 2 |
functions creating them.""" |
| 3 |
|
| 4 |
import sys |
| 5 |
from typing import Any |
| 6 |
from typing import Callable |
| 7 |
from typing import cast |
| 8 |
from typing import NoReturn |
| 9 |
from typing import Optional |
| 10 |
from typing import Protocol |
| 11 |
from typing import Type |
| 12 |
from typing import TypeVar |
| 13 |
|
| 14 |
from .warning_types import PytestDeprecationWarning |
| 15 |
|
| 16 |
|
| 17 |
class OutcomeException(BaseException): |
| 18 |
"""OutcomeException and its subclass instances indicate and contain info |
| 19 |
about test and collection outcomes.""" |
| 20 |
|
| 21 |
def __init__(self, msg: Optional[str] = None, pytrace: bool = True) -> None: |
| 22 |
if msg is not None and not isinstance(msg, str): |
| 23 |
error_msg = ( # type: ignore[unreachable] |
| 24 |
"{} expected string as 'msg' parameter, got '{}' instead.\n" |
| 25 |
"Perhaps you meant to use a mark?" |
| 26 |
) |
| 27 |
raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__)) |
| 28 |
super().__init__(msg) |
| 29 |
self.msg = msg |
| 30 |
self.pytrace = pytrace |
| 31 |
|
| 32 |
def __repr__(self) -> str: |
| 33 |
if self.msg is not None: |
| 34 |
return self.msg |
| 35 |
return f"<{self.__class__.__name__} instance>" |
| 36 |
|
| 37 |
__str__ = __repr__ |
| 38 |
|
| 39 |
|
| 40 |
TEST_OUTCOME = (OutcomeException, Exception) |
| 41 |
|
| 42 |
|
| 43 |
class Skipped(OutcomeException): |
| 44 |
# XXX hackish: on 3k we fake to live in the builtins |
| 45 |
# in order to have Skipped exception printing shorter/nicer |
| 46 |
__module__ = "builtins" |
| 47 |
|
| 48 |
def __init__( |
| 49 |
self, |
| 50 |
msg: Optional[str] = None, |
| 51 |
pytrace: bool = True, |
| 52 |
allow_module_level: bool = False, |
| 53 |
*, |
| 54 |
_use_item_location: bool = False, |
| 55 |
) -> None: |
| 56 |
super().__init__(msg=msg, pytrace=pytrace) |
| 57 |
self.allow_module_level = allow_module_level |
| 58 |
# If true, the skip location is reported as the item's location, |
| 59 |
# instead of the place that raises the exception/calls skip(). |
| 60 |
self._use_item_location = _use_item_location |
| 61 |
|
| 62 |
|
| 63 |
class Failed(OutcomeException): |
| 64 |
"""Raised from an explicit call to pytest.fail().""" |
| 65 |
|
| 66 |
__module__ = "builtins" |
| 67 |
|
| 68 |
|
| 69 |
class Exit(Exception): |
| 70 |
"""Raised for immediate program exits (no tracebacks/summaries).""" |
| 71 |
|
| 72 |
def __init__( |
| 73 |
self, msg: str = "unknown reason", returncode: Optional[int] = None |
| 74 |
) -> None: |
| 75 |
self.msg = msg |
| 76 |
self.returncode = returncode |
| 77 |
super().__init__(msg) |
| 78 |
|
| 79 |
|
| 80 |
# Elaborate hack to work around https://github.com/python/mypy/issues/2087. |
| 81 |
# Ideally would just be `exit.Exception = Exit` etc. |
| 82 |
|
| 83 |
_F = TypeVar("_F", bound=Callable[..., object]) |
| 84 |
_ET = TypeVar("_ET", bound=Type[BaseException]) |
| 85 |
|
| 86 |
|
| 87 |
class _WithException(Protocol[_F, _ET]): |
| 88 |
Exception: _ET |
| 89 |
__call__: _F |
| 90 |
|
| 91 |
|
| 92 |
def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]: |
| 93 |
def decorate(func: _F) -> _WithException[_F, _ET]: |
| 94 |
func_with_exception = cast(_WithException[_F, _ET], func) |
| 95 |
func_with_exception.Exception = exception_type |
| 96 |
return func_with_exception |
| 97 |
|
| 98 |
return decorate |
| 99 |
|
| 100 |
|
| 101 |
# Exposed helper methods. |
| 102 |
|
| 103 |
|
| 104 |
@_with_exception(Exit) |
| 105 |
def exit( |
| 106 |
reason: str = "", |
| 107 |
returncode: Optional[int] = None, |
| 108 |
) -> NoReturn: |
| 109 |
"""Exit testing process. |
| 110 |
|
| 111 |
:param reason: |
| 112 |
The message to show as the reason for exiting pytest. reason has a default value |
| 113 |
only because `msg` is deprecated. |
| 114 |
|
| 115 |
:param returncode: |
| 116 |
Return code to be used when exiting pytest. None means the same as ``0`` (no error), same as :func:`sys.exit`. |
| 117 |
|
| 118 |
:raises pytest.exit.Exception: |
| 119 |
The exception that is raised. |
| 120 |
""" |
| 121 |
__tracebackhide__ = True |
| 122 |
raise Exit(reason, returncode) |
| 123 |
|
| 124 |
|
| 125 |
@_with_exception(Skipped) |
| 126 |
def skip( |
| 127 |
reason: str = "", |
| 128 |
*, |
| 129 |
allow_module_level: bool = False, |
| 130 |
) -> NoReturn: |
| 131 |
"""Skip an executing test with the given message. |
| 132 |
|
| 133 |
This function should be called only during testing (setup, call or teardown) or |
| 134 |
during collection by using the ``allow_module_level`` flag. This function can |
| 135 |
be called in doctests as well. |
| 136 |
|
| 137 |
:param reason: |
| 138 |
The message to show the user as reason for the skip. |
| 139 |
|
| 140 |
:param allow_module_level: |
| 141 |
Allows this function to be called at module level. |
| 142 |
Raising the skip exception at module level will stop |
| 143 |
the execution of the module and prevent the collection of all tests in the module, |
| 144 |
even those defined before the `skip` call. |
| 145 |
|
| 146 |
Defaults to False. |
| 147 |
|
| 148 |
:raises pytest.skip.Exception: |
| 149 |
The exception that is raised. |
| 150 |
|
| 151 |
.. note:: |
| 152 |
It is better to use the :ref:`pytest.mark.skipif ref` marker when |
| 153 |
possible to declare a test to be skipped under certain conditions |
| 154 |
like mismatching platforms or dependencies. |
| 155 |
Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`) |
| 156 |
to skip a doctest statically. |
| 157 |
""" |
| 158 |
__tracebackhide__ = True |
| 159 |
raise Skipped(msg=reason, allow_module_level=allow_module_level) |
| 160 |
|
| 161 |
|
| 162 |
@_with_exception(Failed) |
| 163 |
def fail(reason: str = "", pytrace: bool = True) -> NoReturn: |
| 164 |
"""Explicitly fail an executing test with the given message. |
| 165 |
|
| 166 |
:param reason: |
| 167 |
The message to show the user as reason for the failure. |
| 168 |
|
| 169 |
:param pytrace: |
| 170 |
If False, msg represents the full failure information and no |
| 171 |
python traceback will be reported. |
| 172 |
|
| 173 |
:raises pytest.fail.Exception: |
| 174 |
The exception that is raised. |
| 175 |
""" |
| 176 |
__tracebackhide__ = True |
| 177 |
raise Failed(msg=reason, pytrace=pytrace) |
| 178 |
|
| 179 |
|
| 180 |
class XFailed(Failed): |
| 181 |
"""Raised from an explicit call to pytest.xfail().""" |
| 182 |
|
| 183 |
|
| 184 |
@_with_exception(XFailed) |
| 185 |
def xfail(reason: str = "") -> NoReturn: |
| 186 |
"""Imperatively xfail an executing test or setup function with the given reason. |
| 187 |
|
| 188 |
This function should be called only during testing (setup, call or teardown). |
| 189 |
|
| 190 |
No other code is executed after using ``xfail()`` (it is implemented |
| 191 |
internally by raising an exception). |
| 192 |
|
| 193 |
:param reason: |
| 194 |
The message to show the user as reason for the xfail. |
| 195 |
|
| 196 |
.. note:: |
| 197 |
It is better to use the :ref:`pytest.mark.xfail ref` marker when |
| 198 |
possible to declare a test to be xfailed under certain conditions |
| 199 |
like known bugs or missing features. |
| 200 |
|
| 201 |
:raises pytest.xfail.Exception: |
| 202 |
The exception that is raised. |
| 203 |
""" |
| 204 |
__tracebackhide__ = True |
| 205 |
raise XFailed(reason) |
| 206 |
|
| 207 |
|
| 208 |
def importorskip( |
| 209 |
modname: str, |
| 210 |
minversion: Optional[str] = None, |
| 211 |
reason: Optional[str] = None, |
| 212 |
*, |
| 213 |
exc_type: Optional[Type[ImportError]] = None, |
| 214 |
) -> Any: |
| 215 |
"""Import and return the requested module ``modname``, or skip the |
| 216 |
current test if the module cannot be imported. |
| 217 |
|
| 218 |
:param modname: |
| 219 |
The name of the module to import. |
| 220 |
:param minversion: |
| 221 |
If given, the imported module's ``__version__`` attribute must be at |
| 222 |
least this minimal version, otherwise the test is still skipped. |
| 223 |
:param reason: |
| 224 |
If given, this reason is shown as the message when the module cannot |
| 225 |
be imported. |
| 226 |
:param exc_type: |
| 227 |
The exception that should be captured in order to skip modules. |
| 228 |
Must be :py:class:`ImportError` or a subclass. |
| 229 |
|
| 230 |
If the module can be imported but raises :class:`ImportError`, pytest will |
| 231 |
issue a warning to the user, as often users expect the module not to be |
| 232 |
found (which would raise :class:`ModuleNotFoundError` instead). |
| 233 |
|
| 234 |
This warning can be suppressed by passing ``exc_type=ImportError`` explicitly. |
| 235 |
|
| 236 |
See :ref:`import-or-skip-import-error` for details. |
| 237 |
|
| 238 |
|
| 239 |
:returns: |
| 240 |
The imported module. This should be assigned to its canonical name. |
| 241 |
|
| 242 |
:raises pytest.skip.Exception: |
| 243 |
If the module cannot be imported. |
| 244 |
|
| 245 |
Example:: |
| 246 |
|
| 247 |
docutils = pytest.importorskip("docutils") |
| 248 |
|
| 249 |
.. versionadded:: 8.2 |
| 250 |
|
| 251 |
The ``exc_type`` parameter. |
| 252 |
""" |
| 253 |
import warnings |
| 254 |
|
| 255 |
__tracebackhide__ = True |
| 256 |
compile(modname, "", "eval") # to catch syntaxerrors |
| 257 |
|
| 258 |
# Until pytest 9.1, we will warn the user if we catch ImportError (instead of ModuleNotFoundError), |
| 259 |
# as this might be hiding an installation/environment problem, which is not usually what is intended |
| 260 |
# when using importorskip() (#11523). |
| 261 |
# In 9.1, to keep the function signature compatible, we just change the code below to: |
| 262 |
# 1. Use `exc_type = ModuleNotFoundError` if `exc_type` is not given. |
| 263 |
# 2. Remove `warn_on_import` and the warning handling. |
| 264 |
if exc_type is None: |
| 265 |
exc_type = ImportError |
| 266 |
warn_on_import_error = True |
| 267 |
else: |
| 268 |
warn_on_import_error = False |
| 269 |
|
| 270 |
skipped: Optional[Skipped] = None |
| 271 |
warning: Optional[Warning] = None |
| 272 |
|
| 273 |
with warnings.catch_warnings(): |
| 274 |
# Make sure to ignore ImportWarnings that might happen because |
| 275 |
# of existing directories with the same name we're trying to |
| 276 |
# import but without a __init__.py file. |
| 277 |
warnings.simplefilter("ignore") |
| 278 |
|
| 279 |
try: |
| 280 |
__import__(modname) |
| 281 |
except exc_type as exc: |
| 282 |
# Do not raise or issue warnings inside the catch_warnings() block. |
| 283 |
if reason is None: |
| 284 |
reason = f"could not import {modname!r}: {exc}" |
| 285 |
skipped = Skipped(reason, allow_module_level=True) |
| 286 |
|
| 287 |
if warn_on_import_error and not isinstance(exc, ModuleNotFoundError): |
| 288 |
lines = [ |
| 289 |
"", |
| 290 |
f"Module '{modname}' was found, but when imported by pytest it raised:", |
| 291 |
f" {exc!r}", |
| 292 |
"In pytest 9.1 this warning will become an error by default.", |
| 293 |
"You can fix the underlying problem, or alternatively overwrite this behavior and silence this " |
| 294 |
"warning by passing exc_type=ImportError explicitly.", |
| 295 |
"See https://docs.pytest.org/en/stable/deprecations.html#pytest-importorskip-default-behavior-regarding-importerror", |
| 296 |
] |
| 297 |
warning = PytestDeprecationWarning("\n".join(lines)) |
| 298 |
|
| 299 |
if warning: |
| 300 |
warnings.warn(warning, stacklevel=2) |
| 301 |
if skipped: |
| 302 |
raise skipped |
| 303 |
|
| 304 |
mod = sys.modules[modname] |
| 305 |
if minversion is None: |
| 306 |
return mod |
| 307 |
verattr = getattr(mod, "__version__", None) |
| 308 |
if minversion is not None: |
| 309 |
# Imported lazily to improve start-up time. |
| 310 |
from packaging.version import Version |
| 311 |
|
| 312 |
if verattr is None or Version(verattr) < Version(minversion): |
| 313 |
raise Skipped( |
| 314 |
f"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}", |
| 315 |
allow_module_level=True, |
| 316 |
) |
| 317 |
return mod |