@@ -111,17 +111,27 @@ def __repr__(self) -> str:
111
111
112
112
@final
113
113
class MonkeyPatch :
114
- """Object returned by the ``monkeypatch`` fixture keeping a record of
115
- setattr/item/env/syspath changes."""
114
+ """Helper to conveniently monkeypatch attributes/items/environment
115
+ variables/syspath.
116
+
117
+ Returned by the :fixture:`monkeypatch` fixture.
118
+
119
+ :versionchanged:: 6.2
120
+ Can now also be used directly as `pytest.MonkeyPatch()`, for when
121
+ the fixture is not available. In this case, use
122
+ :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
123
+ :meth:`undo` explicitly.
124
+ """
116
125
117
126
def __init__ (self ) -> None :
118
127
self ._setattr : List [Tuple [object , str , object ]] = []
119
128
self ._setitem : List [Tuple [MutableMapping [Any , Any ], object , object ]] = ([])
120
129
self ._cwd : Optional [str ] = None
121
130
self ._savesyspath : Optional [List [str ]] = None
122
131
132
+ @classmethod
123
133
@contextmanager
124
- def context (self ) -> Generator ["MonkeyPatch" , None , None ]:
134
+ def context (cls ) -> Generator ["MonkeyPatch" , None , None ]:
125
135
"""Context manager that returns a new :class:`MonkeyPatch` object
126
136
which undoes any patching done inside the ``with`` block upon exit.
127
137
@@ -140,7 +150,7 @@ def test_partial(monkeypatch):
140
150
such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
141
151
of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_.
142
152
"""
143
- m = MonkeyPatch ()
153
+ m = cls ()
144
154
try :
145
155
yield m
146
156
finally :
0 commit comments