MCPcopy
hub / github.com/pytest-dev/pytest / MonkeyPatch

Class MonkeyPatch

src/_pytest/monkeypatch.py:114–430  ·  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

112
113@final
114class 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,

Callers 15

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
test_delenvFunction · 0.90

Calls

no outgoing calls

Tested by 14

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