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

Method context

src/_pytest/monkeypatch.py:133–156  ·  view source on GitHub ↗

Context manager that returns a new :class:`MonkeyPatch` object which undoes any patching done inside the ``with`` block upon exit. Example: .. code-block:: python import functools def test_partial(monkeypatch): with monkeypatch.con

(cls)

Source from the content-addressed store, hash-verified

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(

Calls 2

clsFunction · 0.85
undoMethod · 0.80