MCPcopy Create free account
hub / github.com/pytest-dev/pytest / MonkeyPatch

Class MonkeyPatch

src/_pytest/monkeypatch.py:112–383  ·  view source on GitHub ↗

Helper to conveniently monkeypatch attributes/items/environment variables/syspath. Returned by the :fixture:`monkeypatch` fixture. :versionchanged:: 6.2 Can now also be used directly as `pytest.MonkeyPatch()`, for when the fixture is not available. In this case, use

Source from the content-addressed store, hash-verified

110
111@final
112class MonkeyPatch:
113 """Helper to conveniently monkeypatch attributes/items/environment
114 variables/syspath.
115
116 Returned by the :fixture:`monkeypatch` fixture.
117
118 :versionchanged:: 6.2
119 Can now also be used directly as `pytest.MonkeyPatch()`, for when
120 the fixture is not available. In this case, use
121 :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
122 :meth:`undo` explicitly.
123 """
124
125 def __init__(self) -> None:
126 self._setattr: List[Tuple[object, str, object]] = []
127 self._setitem: List[Tuple[MutableMapping[Any, Any], object, object]] = []
128 self._cwd: Optional[str] = None
129 self._savesyspath: Optional[List[str]] = None
130
131 @classmethod
132 @contextmanager
133 def context(cls) -> Generator["MonkeyPatch", None, None]:
134 """Context manager that returns a new :class:`MonkeyPatch` object
135 which undoes any patching done inside the ``with`` block upon exit.
136
137 Example:
138
139 .. code-block:: python
140
141 import functools
142
143
144 def test_partial(monkeypatch):
145 with monkeypatch.context() as m:
146 m.setattr(functools, "partial", 3)
147
148 Useful in situations where it is desired to undo some patches before the test ends,
149 such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
150 of this see :issue:`3290`).
151 """
152 m = cls()
153 try:
154 yield m
155 finally:
156 m.undo()
157
158 @overload
159 def setattr(
160 self,
161 target: str,
162 name: object,
163 value: Notset = ...,
164 raising: bool = ...,
165 ) -> None:
166 ...
167
168 @overload
169 def setattr(

Callers 15

__init__Method · 0.90
pytest_configureFunction · 0.90
pytest_configureFunction · 0.90
mpFunction · 0.90
test_setattrFunction · 0.90
test_delattrFunction · 0.90
test_setitemFunction · 0.90
test_delitemFunction · 0.90
test_setenvFunction · 0.90

Calls

no outgoing calls

Tested by 15

__init__Method · 0.72
mpFunction · 0.72
test_setattrFunction · 0.72
test_delattrFunction · 0.72
test_setitemFunction · 0.72
test_delitemFunction · 0.72
test_setenvFunction · 0.72
test_delenvFunction · 0.72
test_setenv_prependFunction · 0.72