Python unittest.mock patch.object and patch.dict

Python unittest.mock patch.object and patch.dict

patch.object and patch.dict

  • patch.object


patch the named member (attribute) on an object (targetwith a mock object.

patch.object() can be used as a decorator, class decorator or a context manager. Arguments newspeccreatespec_setautospec and new_callable have the same meaning as for patch(). Like patch(), patch.object() takes arbitrary keyword arguments for configuring the mock object it creates.

When used as a class decorator patch.object() honours patch.TEST_PREFIX for choosing which methods to wrap.

You can either call patch.object() with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with. When calling with the two argument form you omit the replacement object and a mock is created for you and passed in as an extra argument to the decorated function:


unittest.mock import patch

class SomeClass:


    def class_method(cls, param):


@patch.object(SomeClass, 'class_method')

def test(mock_method):




speccreate and the other arguments to patch.object() have the same meaning as they do for patch().

  • patch.dict


Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after 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.

Changes in version 3.8: 

patch.dict() now returns the patched dictionary when used as a context manager.

patch.dict() can be used as a context manager, decorator or class decorator:


unittest.mock import patch

cppsecrets = {}

@patch.dict(cppsecrets, {'newkey': 'newvalue'})

def test():

    assert cppsecrets == {'newkey': 'newvalue'}


assert cppsecrets == {}

When used as a class decorator patch.dict() honours patch.TEST_PREFIX (default to 'test') for choosing which methods to wrap:

import os
import unittest
from unittest.mock import patch

@patch.dict('os.environ', {'newkey': 'newvalue'})
class TestSample(unittest.TestCase):
def test_sample(self):
self.assertEqual(os.environ['newkey'], 'newvalue')

If you want to use a different prefix for your test, you can inform the patchers of the different prefix by setting patch.TEST_PREFIX. For more details about how to change the value of see TEST_PREFIX.

patch.dict() can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.

from unittest.mock import patch
with patch.dict(cppsecrets, {'newkey': 'newvalue'}) as patched_cppsecrets:
assert cppsecrets == {'newkey': 'newvalue'}
assert patched_cppsecrets == {'newkey': 'newvalue'}
# You can add, update or delete keys of cppsecrets (or patched_cppsecrets, it's the same dict)
patched_cppsecrets['spam'] = 'eggs'
cppsecrets == {}
assert patched_cppsecrets == {}
import os
from unittest.mock import patch
with patch.dict('os.environ', {'newkey': 'newvalue'}):
assert 'newkey' not in os.environ

Keywords can be used in the patch.dict() call to set values in the dictionary:

from unittest.mock import patch, MagicMock

mymodule = MagicMock()
mymodule.function.return_value =
patch.dict('sys.modules', mymodule=mymodule):
import mymodule
'some', 'args')

patch.dict() can be used with dictionary like objects that aren't actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods __getitem__(), __setitem__(), __delitem__() and either __iter__() or __contains__().

from unittest.mock import patch

class Container:
def __init__(self):
self.values = {}
def __getitem__(self, name):
return self.values[name]
def __setitem__(self, name, value):
self.values[name] = value
def __delitem__(self, name):
del self.values[name]
def __iter__(self):
return iter(self.values)

thing = Container()
'one'] = 1
with patch.dict(thing, one=2, two=3):
assert thing['one'] == 2
assert thing['two'] == 3

assert thing['one'] == 1
assert list(thing) == ['one']

<<PREV                                                                                                                                          NEXT>> 

More Articles of Shubhanjay Pandey:

Name Views Likes
Python ssl Sockets 998 3
Python unittest.mock side_effect 503 2
Python ssl Example Server Side Operation 771 3
Python unittest.mock method_calls and mock_calls 841 2
Python ssl TLS 1.3 and LibreSSL Support 1450 2
Python unittest.mock The patchers 310 2
Python unittest.mock Attaching Mocks as Attributes 433 2
Python ssl Example Client Side Operations 463 3
Python unittest.mock patch.object and patch.dict 2748 2
Python unittest.mock.call_args and call_args_list 3283 2
Python ssl Certificates 321 3
Python unittest.mock Deleting, Mock Names and the name attribute 517 2
Python unittest.mock FILTER_DIR 254 2
Python ssl Introduction 286 3
Python unitest.mock Where to patch, patching descriptors and proxy objects 268 2
Python ssl Memory BIO Support 539 3
Python mimetypes - Introduction 333 3
Python unittest.mock Helpers call 282 2
Python unittest.mock function assert_*() 283 2
Python unittest.mock Introduction 340 2
Python sunau library 305 2
Python unittest.mock The Mock Class 275 2
Python ssl Constants Part 1 357 3
Python mimetypes.add_type 256 4
Python ssl Socket and Context Creation 1300 3
Python unittest.mock.mock_open 297 2
Python ssl non-blocking sockets 646 3
Python unittest.mock MagicMock and magic method support 847 1
Python unittest.mock Magic Mock 370 2
Python ssl Exceptions 307 3
Python unittest.mock TEST_PREFIX and Nesting Patch Decorators 395 2
Python unittest.mock patch.multiple and builtins 2017 2
Python mimetypes additional data 232 3
Python unittest.mock Other HELPERS 252 2
Python MimeTypes Object 267 3
Python mimetypes.guess_type 331 3
Python unittest.mock Autospeccing 304 2
Python unittest.mock.AsyncMock 2440 2
Python ssl Certificates Handling 375 3
Python ssl Random Generation 290 3
Python unittest.mock Function configure_mock 385 2
Python ssl SSLContexts Part 1 618 3
Python unittest.mock patch methods: start and stop 1693 2
Python unittest.mock Calling 271 2
Python unittest.mock other functions 268 2
Python ssl Constants Part 2 430 3
Python ssl SSLContexts Part 2 764 3
Python ssl Security Considerations and SSL Session 416 3
Python mimetypes.guess_extension 313 3
Python unittest.mock PropertyMock and NonCallableMock 787 2
Python mimetypes additional functions 253 3