_pytest.monkeypatch module¶
monkeypatching and mocking functionality.
-
for ... in
monkeypatch()[source]¶ The returned
monkeypatchfixture 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
raisingparameter 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:
objectObject returned by the
monkeypatchfixture keeping a record of setattr/item/env/syspath changes.-
with
context() → Generator[MonkeyPatch, None, None][source]¶ Context manager that returns a new
MonkeyPatchobject which undoes any patching done inside thewithblock 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
stdlibfunctions 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
targetwhich will be interpreted as a dotted import path, with the last part being the attribute name. Example:monkeypatch.setattr("os.getcwd", lambda: "/")would set thegetcwdfunction of theosmodule.The
raisingvalue 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
namefromtarget, by default raise AttributeError it the attribute did not previously exist.If no
nameis specified andtargetis a string it will be interpreted as a dotted import path with the last part being the attribute name.If
raisingis set to False, no exception will be raised if the attribute is missing.
-
delitem(dic, name, raising=True)[source]¶ Delete
namefrom dict. Raise KeyError if it doesn’t exist.If
raisingis 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
nametovalue. Ifprependis a character, read the current environment variable value and prepend thevalueadjoined with theprependcharacter.A value of
Noneunsets it, which is useful as a shortcut with parametrization.
-
delenv(name: str, raising: bool = True) → None[source]¶ Delete
namefrom the environment. Raise KeyError if it does not exist.If
raisingis 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
monkeypatchfixture is used across a single test function invocation. Ifmonkeypatchis 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