Debian Codegraph @

src/_pytest/monkeypatch.py

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