PyDocs

Nav

Development Tools

patch.dict

unittest.mock

function of patch (source)
  • patch.dict(in_dict, values=(), clear=False, **kwargs)
Patch a dictionary, or dictionary like object, and restore the dictionary
to its original state after the test, where the restored dictionary is
a copy of the dictionary as it was before the test.

`in_dict` can be a dictionary or a mapping like container. If it is a
mapping then it must at least support getting, setting and deleting items
plus iterating over keys.

`in_dict` can also be a string specifying the name of the dictionary, which
will then be fetched by importing it.

`values` can be a dictionary of values to set in the dictionary. `values`
can also be an iterable of `(key, value)` pairs.

If `clear` is True then the dictionary will be cleared before the new
values are set.

`patch.dict` can also be called with arbitrary keyword arguments to set
values in the dictionary::

    with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
        ...

`patch.dict` can be used as a context manager, decorator or class
decorator. When used as a class decorator `patch.dict` honours
`patch.TEST_PREFIX` for choosing which methods to wrap.
Changed in 3.8
  • 3.8: patch.dict() now returns the patched dictionary when used as a context manager.
1 Example
>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
...     assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original
from the Python docs
See Also
No see-alsos for unittest.mock/patch.dict
0 Notes
No notes for patch.dict