_pytest.monkeypatch module¶
monkeypatching and mocking functionality.
-
for ... in
monkeypatch
()[source]¶ The returned
monkeypatch
fixture provides these helper methods to modify objects, dictionaries or os.environ:monkeypatch.setattr(obj, name, value, raising=True) monkeypatch.delattr(obj, name, raising=True) monkeypatch.setitem(mapping, name, value) monkeypatch.delitem(obj, name, raising=True) monkeypatch.setenv(name, value, prepend=False) monkeypatch.delenv(name, raising=True) monkeypatch.syspath_prepend(path) monkeypatch.chdir(path)
All modifications will be undone after the requesting test function or fixture has finished. The
raising
parameter determines if a KeyError or AttributeError will be raised if the set/deletion operation has no target.
-
for ... in
monkeypatch_session
(request)[source]¶ Experimental (https://github.com/pytest-dev/pytest/issues/363).
-
class
MonkeyPatch
[source]¶ Bases:
object
Object returned by the
monkeypatch
fixture keeping a record of setattr/item/env/syspath changes.-
with
context
() → Generator[MonkeyPatch, None, None][source]¶ Context manager that returns a new
MonkeyPatch
object which undoes any patching done inside thewith
block upon exit:import functools def test_partial(monkeypatch): with monkeypatch.context() as m: m.setattr(functools, "partial", 3)
Useful in situations where it is desired to undo some patches before the test ends, such as mocking
stdlib
functions that might break pytest itself if mocked (for examples of this see #3290.
-
setattr
(target, name, value=<notset>, raising=True)[source]¶ Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist.
For convenience you can specify a string as
target
which will be interpreted as a dotted import path, with the last part being the attribute name. Example:monkeypatch.setattr("os.getcwd", lambda: "/")
would set thegetcwd
function of theos
module.The
raising
value determines if the setattr should fail if the attribute is not already present (defaults to True which means it will raise).
-
delattr
(target, name=<notset>, raising=True)[source]¶ Delete attribute
name
fromtarget
, by default raise AttributeError it the attribute did not previously exist.If no
name
is specified andtarget
is a string it will be interpreted as a dotted import path with the last part being the attribute name.If
raising
is set to False, no exception will be raised if the attribute is missing.
-
delitem
(dic, name, raising=True)[source]¶ Delete
name
from dict. Raise KeyError if it doesn’t exist.If
raising
is set to False, no exception will be raised if the key is missing.
-
setenv
(name: str, value: Optional[str], prepend: Optional[str] = None) → None[source]¶ Set environment variable
name
tovalue
. Ifprepend
is a character, read the current environment variable value and prepend thevalue
adjoined with theprepend
character.A value of
None
unsets it, which is useful as a shortcut with parametrization.
-
delenv
(name: str, raising: bool = True) → None[source]¶ Delete
name
from the environment. Raise KeyError if it does not exist.If
raising
is set to False, no exception will be raised if the environment variable is missing.
-
mockimport
(mocked_imports: Union[str, Sequence[str]], err: Union[function, Type[BaseException]] = <class 'ImportError'>) → None[source]¶ Mock import with given error to be raised, or callable.
The callable gets called instead of
__import__()
.This is considered to be experimental.
-
chdir
(path)[source]¶ Change the current working directory to the specified path. Path can be a string or a py.path.local object.
-
undo
()[source]¶ Undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call.
There is generally no need to call
undo()
, since it is called automatically during tear-down.Note that the same
monkeypatch
fixture is used across a single test function invocation. Ifmonkeypatch
is used both by the test function itself and one of the test fixtures, callingundo()
will undo all of the changes made in both functions.
-
with