diff options
author | Ran Benita <ran@unusedvar.com> | 2020-11-09 11:45:38 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-09 11:45:38 +0200 |
commit | e986d84466dfa98dbbc55cc1bf5fcb99075f4ac3 (patch) | |
tree | f2e1e2e8afebad698ca7d6e19d16eb782dad987a /src | |
parent | 7aa5e49fc412b0675bd4d019d99613556469a2a5 (diff) | |
parent | 6f13d1b03b1e1af7def99505234075878407767d (diff) | |
download | pytest-e986d84466dfa98dbbc55cc1bf5fcb99075f4ac3.tar.gz |
Merge pull request #8006 from bluetech/export-MonkeyPatch
Export MonkeyPatch as pytest.MonkeyPatch
Diffstat (limited to 'src')
-rw-r--r-- | src/_pytest/monkeypatch.py | 18 | ||||
-rw-r--r-- | src/pytest/__init__.py | 2 |
2 files changed, 16 insertions, 4 deletions
diff --git a/src/_pytest/monkeypatch.py b/src/_pytest/monkeypatch.py index a50c7c8d5..a052f693a 100644 --- a/src/_pytest/monkeypatch.py +++ b/src/_pytest/monkeypatch.py @@ -111,8 +111,17 @@ notset = Notset() @final class MonkeyPatch: - """Object returned by the ``monkeypatch`` fixture keeping a record of - setattr/item/env/syspath changes.""" + """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 + :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call + :meth:`undo` explicitly. + """ def __init__(self) -> None: self._setattr: List[Tuple[object, str, object]] = [] @@ -120,8 +129,9 @@ class MonkeyPatch: self._cwd: Optional[str] = None self._savesyspath: Optional[List[str]] = None + @classmethod @contextmanager - def context(self) -> Generator["MonkeyPatch", None, None]: + def context(cls) -> Generator["MonkeyPatch", None, None]: """Context manager that returns a new :class:`MonkeyPatch` object which undoes any patching done inside the ``with`` block upon exit. @@ -140,7 +150,7 @@ class MonkeyPatch: such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_. """ - m = MonkeyPatch() + m = cls() try: yield m finally: diff --git a/src/pytest/__init__.py b/src/pytest/__init__.py index a9c1ee028..d7a5b2299 100644 --- a/src/pytest/__init__.py +++ b/src/pytest/__init__.py @@ -19,6 +19,7 @@ from _pytest.freeze_support import freeze_includes from _pytest.main import Session from _pytest.mark import MARK_GEN as mark from _pytest.mark import param +from _pytest.monkeypatch import MonkeyPatch from _pytest.nodes import Collector from _pytest.nodes import File from _pytest.nodes import Item @@ -74,6 +75,7 @@ __all__ = [ "main", "mark", "Module", + "MonkeyPatch", "Package", "param", "PytestAssertRewriteWarning", |