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