Skip to content

Commit 648494b

Browse files
bpo-35685: Add examples of unittest.mock.patch.dict usage (GH-11456)
(cherry picked from commit 31a82e2) Co-authored-by: Emmanuel Arias <emmanuelarias30@gmail.com>
1 parent 94a6847 commit 648494b

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

Doc/library/unittest.mock.rst

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,15 +1572,36 @@ patch.dict
15721572
:func:`patch.dict` can also be called with arbitrary keyword arguments to set
15731573
values in the dictionary.
15741574

1575-
:func:`patch.dict` can be used as a context manager, decorator or class
1576-
decorator. When used as a class decorator :func:`patch.dict` honours
1577-
``patch.TEST_PREFIX`` for choosing which methods to wrap.
1578-
15791575
.. versionchanged:: 3.8
15801576

15811577
:func:`patch.dict` now returns the patched dictionary when used as a context
15821578
manager.
15831579

1580+
:func:`patch.dict` can be used as a context manager, decorator or class
1581+
decorator:
1582+
1583+
>>> foo = {}
1584+
>>> @patch.dict(foo, {'newkey': 'newvalue'})
1585+
... def test():
1586+
... assert foo == {'newkey': 'newvalue'}
1587+
>>> test()
1588+
>>> assert foo == {}
1589+
1590+
When used as a class decorator :func:`patch.dict` honours
1591+
``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap:
1592+
1593+
>>> import os
1594+
>>> import unittest
1595+
>>> from unittest.mock import patch
1596+
>>> @patch.dict('os.environ', {'newkey': 'newvalue'})
1597+
... class TestSample(unittest.TestCase):
1598+
... def test_sample(self):
1599+
... self.assertEqual(os.environ['newkey'], 'newvalue')
1600+
1601+
If you want to use a different prefix for your test, you can inform the
1602+
patchers of the different prefix by setting ``patch.TEST_PREFIX``. For
1603+
more details about how to change the value of see :ref:`test-prefix`.
1604+
15841605
:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
15851606
change a dictionary, and ensure the dictionary is restored when the test
15861607
ends.
@@ -1793,6 +1814,8 @@ builtin :func:`ord`::
17931814
101
17941815

17951816

1817+
.. _test-prefix:
1818+
17961819
TEST_PREFIX
17971820
~~~~~~~~~~~
17981821

0 commit comments

Comments
 (0)