| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Monkeypatching and mocking functionality.""" |
| 3 |
|
| 4 |
from contextlib import contextmanager |
| 5 |
import os |
| 6 |
import re |
| 7 |
import sys |
| 8 |
from typing import Any |
| 9 |
from typing import final |
| 10 |
from typing import Generator |
| 11 |
from typing import List |
| 12 |
from typing import Mapping |
| 13 |
from typing import MutableMapping |
| 14 |
from typing import Optional |
| 15 |
from typing import overload |
| 16 |
from typing import Tuple |
| 17 |
from typing import TypeVar |
| 18 |
from typing import Union |
| 19 |
import warnings |
| 20 |
|
| 21 |
from _pytest.fixtures import fixture |
| 22 |
from _pytest.warning_types import PytestWarning |
| 23 |
|
| 24 |
|
| 25 |
RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$") |
| 26 |
|
| 27 |
|
| 28 |
K = TypeVar("K") |
| 29 |
V = TypeVar("V") |
| 30 |
|
| 31 |
|
| 32 |
@fixture |
| 33 |
def monkeypatch() -> Generator["MonkeyPatch", None, None]: |
| 34 |
"""A convenient fixture for monkey-patching. |
| 35 |
|
| 36 |
The fixture provides these methods to modify objects, dictionaries, or |
| 37 |
:data:`os.environ`: |
| 38 |
|
| 39 |
* :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>` |
| 40 |
* :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>` |
| 41 |
* :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>` |
| 42 |
* :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>` |
| 43 |
* :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>` |
| 44 |
* :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>` |
| 45 |
* :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>` |
| 46 |
* :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>` |
| 47 |
* :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>` |
| 48 |
|
| 49 |
All modifications will be undone after the requesting test function or |
| 50 |
fixture has finished. The ``raising`` parameter determines if a :class:`KeyError` |
| 51 |
or :class:`AttributeError` will be raised if the set/deletion operation does not have the |
| 52 |
specified target. |
| 53 |
|
| 54 |
To undo modifications done by the fixture in a contained scope, |
| 55 |
use :meth:`context() <pytest.MonkeyPatch.context>`. |
| 56 |
""" |
| 57 |
mpatch = MonkeyPatch() |
| 58 |
yield mpatch |
| 59 |
mpatch.undo() |
| 60 |
|
| 61 |
|
| 62 |
def resolve(name: str) -> object: |
| 63 |
# Simplified from zope.dottedname. |
| 64 |
parts = name.split(".") |
| 65 |
|
| 66 |
used = parts.pop(0) |
| 67 |
found: object = __import__(used) |
| 68 |
for part in parts: |
| 69 |
used += "." + part |
| 70 |
try: |
| 71 |
found = getattr(found, part) |
| 72 |
except AttributeError: |
| 73 |
pass |
| 74 |
else: |
| 75 |
continue |
| 76 |
# We use explicit un-nesting of the handling block in order |
| 77 |
# to avoid nested exceptions. |
| 78 |
try: |
| 79 |
__import__(used) |
| 80 |
except ImportError as ex: |
| 81 |
expected = str(ex).split()[-1] |
| 82 |
if expected == used: |
| 83 |
raise |
| 84 |
else: |
| 85 |
raise ImportError(f"import error in {used}: {ex}") from ex |
| 86 |
found = annotated_getattr(found, part, used) |
| 87 |
return found |
| 88 |
|
| 89 |
|
| 90 |
def annotated_getattr(obj: object, name: str, ann: str) -> object: |
| 91 |
try: |
| 92 |
obj = getattr(obj, name) |
| 93 |
except AttributeError as e: |
| 94 |
raise AttributeError( |
| 95 |
f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}" |
| 96 |
) from e |
| 97 |
return obj |
| 98 |
|
| 99 |
|
| 100 |
def derive_importpath(import_path: str, raising: bool) -> Tuple[str, object]: |
| 101 |
if not isinstance(import_path, str) or "." not in import_path: |
| 102 |
raise TypeError(f"must be absolute import path string, not {import_path!r}") |
| 103 |
module, attr = import_path.rsplit(".", 1) |
| 104 |
target = resolve(module) |
| 105 |
if raising: |
| 106 |
annotated_getattr(target, attr, ann=module) |
| 107 |
return attr, target |
| 108 |
|
| 109 |
|
| 110 |
class Notset: |
| 111 |
def __repr__(self) -> str: |
| 112 |
return "<notset>" |
| 113 |
|
| 114 |
|
| 115 |
notset = Notset() |
| 116 |
|
| 117 |
|
| 118 |
@final |
| 119 |
class MonkeyPatch: |
| 120 |
"""Helper to conveniently monkeypatch attributes/items/environment |
| 121 |
variables/syspath. |
| 122 |
|
| 123 |
Returned by the :fixture:`monkeypatch` fixture. |
| 124 |
|
| 125 |
.. versionchanged:: 6.2 |
| 126 |
Can now also be used directly as `pytest.MonkeyPatch()`, for when |
| 127 |
the fixture is not available. In this case, use |
| 128 |
:meth:`with MonkeyPatch.context() as mp: <context>` or remember to call |
| 129 |
:meth:`undo` explicitly. |
| 130 |
""" |
| 131 |
|
| 132 |
def __init__(self) -> None: |
| 133 |
self._setattr: List[Tuple[object, str, object]] = [] |
| 134 |
self._setitem: List[Tuple[Mapping[Any, Any], object, object]] = [] |
| 135 |
self._cwd: Optional[str] = None |
| 136 |
self._savesyspath: Optional[List[str]] = None |
| 137 |
|
| 138 |
@classmethod |
| 139 |
@contextmanager |
| 140 |
def context(cls) -> Generator["MonkeyPatch", None, None]: |
| 141 |
"""Context manager that returns a new :class:`MonkeyPatch` object |
| 142 |
which undoes any patching done inside the ``with`` block upon exit. |
| 143 |
|
| 144 |
Example: |
| 145 |
.. code-block:: python |
| 146 |
|
| 147 |
import functools |
| 148 |
|
| 149 |
|
| 150 |
def test_partial(monkeypatch): |
| 151 |
with monkeypatch.context() as m: |
| 152 |
m.setattr(functools, "partial", 3) |
| 153 |
|
| 154 |
Useful in situations where it is desired to undo some patches before the test ends, |
| 155 |
such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples |
| 156 |
of this see :issue:`3290`). |
| 157 |
""" |
| 158 |
m = cls() |
| 159 |
try: |
| 160 |
yield m |
| 161 |
finally: |
| 162 |
m.undo() |
| 163 |
|
| 164 |
@overload |
| 165 |
def setattr( |
| 166 |
self, |
| 167 |
target: str, |
| 168 |
name: object, |
| 169 |
value: Notset = ..., |
| 170 |
raising: bool = ..., |
| 171 |
) -> None: ... |
| 172 |
|
| 173 |
@overload |
| 174 |
def setattr( |
| 175 |
self, |
| 176 |
target: object, |
| 177 |
name: str, |
| 178 |
value: object, |
| 179 |
raising: bool = ..., |
| 180 |
) -> None: ... |
| 181 |
|
| 182 |
def setattr( |
| 183 |
self, |
| 184 |
target: Union[str, object], |
| 185 |
name: Union[object, str], |
| 186 |
value: object = notset, |
| 187 |
raising: bool = True, |
| 188 |
) -> None: |
| 189 |
""" |
| 190 |
Set attribute value on target, memorizing the old value. |
| 191 |
|
| 192 |
For example: |
| 193 |
|
| 194 |
.. code-block:: python |
| 195 |
|
| 196 |
import os |
| 197 |
|
| 198 |
monkeypatch.setattr(os, "getcwd", lambda: "/") |
| 199 |
|
| 200 |
The code above replaces the :func:`os.getcwd` function by a ``lambda`` which |
| 201 |
always returns ``"/"``. |
| 202 |
|
| 203 |
For convenience, you can specify a string as ``target`` which |
| 204 |
will be interpreted as a dotted import path, with the last part |
| 205 |
being the attribute name: |
| 206 |
|
| 207 |
.. code-block:: python |
| 208 |
|
| 209 |
monkeypatch.setattr("os.getcwd", lambda: "/") |
| 210 |
|
| 211 |
Raises :class:`AttributeError` if the attribute does not exist, unless |
| 212 |
``raising`` is set to False. |
| 213 |
|
| 214 |
**Where to patch** |
| 215 |
|
| 216 |
``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one. |
| 217 |
There can be many names pointing to any individual object, so for patching to work you must ensure |
| 218 |
that you patch the name used by the system under test. |
| 219 |
|
| 220 |
See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock` |
| 221 |
docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but |
| 222 |
applies to ``monkeypatch.setattr`` as well. |
| 223 |
""" |
| 224 |
__tracebackhide__ = True |
| 225 |
import inspect |
| 226 |
|
| 227 |
if isinstance(value, Notset): |
| 228 |
if not isinstance(target, str): |
| 229 |
raise TypeError( |
| 230 |
"use setattr(target, name, value) or " |
| 231 |
"setattr(target, value) with target being a dotted " |
| 232 |
"import string" |
| 233 |
) |
| 234 |
value = name |
| 235 |
name, target = derive_importpath(target, raising) |
| 236 |
else: |
| 237 |
if not isinstance(name, str): |
| 238 |
raise TypeError( |
| 239 |
"use setattr(target, name, value) with name being a string or " |
| 240 |
"setattr(target, value) with target being a dotted " |
| 241 |
"import string" |
| 242 |
) |
| 243 |
|
| 244 |
oldval = getattr(target, name, notset) |
| 245 |
if raising and oldval is notset: |
| 246 |
raise AttributeError(f"{target!r} has no attribute {name!r}") |
| 247 |
|
| 248 |
# avoid class descriptors like staticmethod/classmethod |
| 249 |
if inspect.isclass(target): |
| 250 |
oldval = target.__dict__.get(name, notset) |
| 251 |
self._setattr.append((target, name, oldval)) |
| 252 |
setattr(target, name, value) |
| 253 |
|
| 254 |
def delattr( |
| 255 |
self, |
| 256 |
target: Union[object, str], |
| 257 |
name: Union[str, Notset] = notset, |
| 258 |
raising: bool = True, |
| 259 |
) -> None: |
| 260 |
"""Delete attribute ``name`` from ``target``. |
| 261 |
|
| 262 |
If no ``name`` is specified and ``target`` is a string |
| 263 |
it will be interpreted as a dotted import path with the |
| 264 |
last part being the attribute name. |
| 265 |
|
| 266 |
Raises AttributeError it the attribute does not exist, unless |
| 267 |
``raising`` is set to False. |
| 268 |
""" |
| 269 |
__tracebackhide__ = True |
| 270 |
import inspect |
| 271 |
|
| 272 |
if isinstance(name, Notset): |
| 273 |
if not isinstance(target, str): |
| 274 |
raise TypeError( |
| 275 |
"use delattr(target, name) or " |
| 276 |
"delattr(target) with target being a dotted " |
| 277 |
"import string" |
| 278 |
) |
| 279 |
name, target = derive_importpath(target, raising) |
| 280 |
|
| 281 |
if not hasattr(target, name): |
| 282 |
if raising: |
| 283 |
raise AttributeError(name) |
| 284 |
else: |
| 285 |
oldval = getattr(target, name, notset) |
| 286 |
# Avoid class descriptors like staticmethod/classmethod. |
| 287 |
if inspect.isclass(target): |
| 288 |
oldval = target.__dict__.get(name, notset) |
| 289 |
self._setattr.append((target, name, oldval)) |
| 290 |
delattr(target, name) |
| 291 |
|
| 292 |
def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None: |
| 293 |
"""Set dictionary entry ``name`` to value.""" |
| 294 |
self._setitem.append((dic, name, dic.get(name, notset))) |
| 295 |
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict |
| 296 |
dic[name] = value # type: ignore[index] |
| 297 |
|
| 298 |
def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None: |
| 299 |
"""Delete ``name`` from dict. |
| 300 |
|
| 301 |
Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to |
| 302 |
False. |
| 303 |
""" |
| 304 |
if name not in dic: |
| 305 |
if raising: |
| 306 |
raise KeyError(name) |
| 307 |
else: |
| 308 |
self._setitem.append((dic, name, dic.get(name, notset))) |
| 309 |
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict |
| 310 |
del dic[name] # type: ignore[attr-defined] |
| 311 |
|
| 312 |
def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None: |
| 313 |
"""Set environment variable ``name`` to ``value``. |
| 314 |
|
| 315 |
If ``prepend`` is a character, read the current environment variable |
| 316 |
value and prepend the ``value`` adjoined with the ``prepend`` |
| 317 |
character. |
| 318 |
""" |
| 319 |
if not isinstance(value, str): |
| 320 |
warnings.warn( # type: ignore[unreachable] |
| 321 |
PytestWarning( |
| 322 |
f"Value of environment variable {name} type should be str, but got " |
| 323 |
f"{value!r} (type: {type(value).__name__}); converted to str implicitly" |
| 324 |
), |
| 325 |
stacklevel=2, |
| 326 |
) |
| 327 |
value = str(value) |
| 328 |
if prepend and name in os.environ: |
| 329 |
value = value + prepend + os.environ[name] |
| 330 |
self.setitem(os.environ, name, value) |
| 331 |
|
| 332 |
def delenv(self, name: str, raising: bool = True) -> None: |
| 333 |
"""Delete ``name`` from the environment. |
| 334 |
|
| 335 |
Raises ``KeyError`` if it does not exist, unless ``raising`` is set to |
| 336 |
False. |
| 337 |
""" |
| 338 |
environ: MutableMapping[str, str] = os.environ |
| 339 |
self.delitem(environ, name, raising=raising) |
| 340 |
|
| 341 |
def syspath_prepend(self, path) -> None: |
| 342 |
"""Prepend ``path`` to ``sys.path`` list of import locations.""" |
| 343 |
if self._savesyspath is None: |
| 344 |
self._savesyspath = sys.path[:] |
| 345 |
sys.path.insert(0, str(path)) |
| 346 |
|
| 347 |
# https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171 |
| 348 |
# this is only needed when pkg_resources was already loaded by the namespace package |
| 349 |
if "pkg_resources" in sys.modules: |
| 350 |
from pkg_resources import fixup_namespace_packages |
| 351 |
|
| 352 |
fixup_namespace_packages(str(path)) |
| 353 |
|
| 354 |
# A call to syspathinsert() usually means that the caller wants to |
| 355 |
# import some dynamically created files, thus with python3 we |
| 356 |
# invalidate its import caches. |
| 357 |
# This is especially important when any namespace package is in use, |
| 358 |
# since then the mtime based FileFinder cache (that gets created in |
| 359 |
# this case already) gets not invalidated when writing the new files |
| 360 |
# quickly afterwards. |
| 361 |
from importlib import invalidate_caches |
| 362 |
|
| 363 |
invalidate_caches() |
| 364 |
|
| 365 |
def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None: |
| 366 |
"""Change the current working directory to the specified path. |
| 367 |
|
| 368 |
:param path: |
| 369 |
The path to change into. |
| 370 |
""" |
| 371 |
if self._cwd is None: |
| 372 |
self._cwd = os.getcwd() |
| 373 |
os.chdir(path) |
| 374 |
|
| 375 |
def undo(self) -> None: |
| 376 |
"""Undo previous changes. |
| 377 |
|
| 378 |
This call consumes the undo stack. Calling it a second time has no |
| 379 |
effect unless you do more monkeypatching after the undo call. |
| 380 |
|
| 381 |
There is generally no need to call `undo()`, since it is |
| 382 |
called automatically during tear-down. |
| 383 |
|
| 384 |
.. note:: |
| 385 |
The same `monkeypatch` fixture is used across a |
| 386 |
single test function invocation. If `monkeypatch` is used both by |
| 387 |
the test function itself and one of the test fixtures, |
| 388 |
calling `undo()` will undo all of the changes made in |
| 389 |
both functions. |
| 390 |
|
| 391 |
Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead. |
| 392 |
""" |
| 393 |
for obj, name, value in reversed(self._setattr): |
| 394 |
if value is not notset: |
| 395 |
setattr(obj, name, value) |
| 396 |
else: |
| 397 |
delattr(obj, name) |
| 398 |
self._setattr[:] = [] |
| 399 |
for dictionary, key, value in reversed(self._setitem): |
| 400 |
if value is notset: |
| 401 |
try: |
| 402 |
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict |
| 403 |
del dictionary[key] # type: ignore[attr-defined] |
| 404 |
except KeyError: |
| 405 |
pass # Was already deleted, so we have the desired state. |
| 406 |
else: |
| 407 |
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict |
| 408 |
dictionary[key] = value # type: ignore[index] |
| 409 |
self._setitem[:] = [] |
| 410 |
if self._savesyspath is not None: |
| 411 |
sys.path[:] = self._savesyspath |
| 412 |
self._savesyspath = None |
| 413 |
|
| 414 |
if self._cwd is not None: |
| 415 |
os.chdir(self._cwd) |
| 416 |
self._cwd = None |