diff options
author | Emmanuel Arias <emmanuelarias30@gmail.com> | 2019-09-12 11:29:54 (GMT) |
---|---|---|
committer | Julien Palard <julien@palard.fr> | 2019-09-12 11:29:54 (GMT) |
commit | 31a82e25b6044a5b5ee25246bad3eb7b873cf5ec (patch) | |
tree | df2abcd002dd76cd187d9fb3aed5a5a1afc3559c /Doc/library/unittest.mock.rst | |
parent | 2c910c1e732c9a3ec4c67a7c43d789d6c729304a (diff) | |
download | cpython-31a82e25b6044a5b5ee25246bad3eb7b873cf5ec.zip cpython-31a82e25b6044a5b5ee25246bad3eb7b873cf5ec.tar.gz cpython-31a82e25b6044a5b5ee25246bad3eb7b873cf5ec.tar.bz2 |
bpo-35685: Add examples of unittest.mock.patch.dict usage (GH-11456)
Diffstat (limited to 'Doc/library/unittest.mock.rst')
-rw-r--r-- | Doc/library/unittest.mock.rst | 31 |
1 files changed, 27 insertions, 4 deletions
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst index 04ff8a6..b446ddb 100644 --- a/Doc/library/unittest.mock.rst +++ b/Doc/library/unittest.mock.rst @@ -1572,15 +1572,36 @@ patch.dict :func:`patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary. - :func:`patch.dict` can be used as a context manager, decorator or class - decorator. When used as a class decorator :func:`patch.dict` honours - ``patch.TEST_PREFIX`` for choosing which methods to wrap. - .. versionchanged:: 3.8 :func:`patch.dict` now returns the patched dictionary when used as a context manager. +:func:`patch.dict` can be used as a context manager, decorator or class +decorator: + + >>> foo = {} + >>> @patch.dict(foo, {'newkey': 'newvalue'}) + ... def test(): + ... assert foo == {'newkey': 'newvalue'} + >>> test() + >>> assert foo == {} + +When used as a class decorator :func:`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 :ref:`test-prefix`. + :func:`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. @@ -1793,6 +1814,8 @@ builtin :func:`ord`:: 101 +.. _test-prefix: + TEST_PREFIX ~~~~~~~~~~~ |