Skip to content

Commit 9410c59

Browse files
committed
Export MonkeyPatch as pytest.MonkeyPatch
We want to export `pytest.MonkeyPatch` for the purpose of type-annotating the `monkeypatch` fixture. For other fixtures we export in this way, we also make direct construction of them (e.g. `MonkeyPatch()`) private. But unlike the others, `MonkeyPatch` is also widely used directly already, mostly because the `monkeypatch` fixture only works in `function` scope (issue pytest-dev#363), but also in other cases. So making it private will be annoying and we don't offer a decent replacement yet. So, let's just make direct construction public & documented.
1 parent 3bcd316 commit 9410c59

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

changelog/TBD.feature.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
It is now possible to construct a :class:`MonkeyPatch` object directly as ``pytest.MonkeyPatch()``,
2+
in cases when the :fixture:`monkeypatch` fixture cannot be used. Previously some users imported it
3+
from the private `_pytest.monkeypatch.MonkeyPatch` namespace.

src/_pytest/monkeypatch.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,16 @@ def __repr__(self) -> str:
111111

112112
@final
113113
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 :meth:`context` or
122+
remember to call :meth:`undo` explicitly.
123+
"""
116124

117125
def __init__(self) -> None:
118126
self._setattr: List[Tuple[object, str, object]] = []

src/pytest/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from _pytest.main import Session
2020
from _pytest.mark import MARK_GEN as mark
2121
from _pytest.mark import param
22+
from _pytest.monkeypatch import MonkeyPatch
2223
from _pytest.nodes import Collector
2324
from _pytest.nodes import File
2425
from _pytest.nodes import Item

0 commit comments

Comments
 (0)