Skip to content

Commit 0453081

Browse files
mariocj89csabella
authored andcommitted
bpo-32299: Return patched dict when using patch.dict as a context manager (GH-11062)
1 parent eb65e24 commit 0453081

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

Doc/library/unittest.mock.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1556,15 +1556,24 @@ patch.dict
15561556
decorator. When used as a class decorator :func:`patch.dict` honours
15571557
``patch.TEST_PREFIX`` for choosing which methods to wrap.
15581558

1559+
.. versionchanged:: 3.8
1560+
1561+
:func:`patch.dict` now returns the patched dictionary when used as a context
1562+
manager.
1563+
15591564
:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
15601565
change a dictionary, and ensure the dictionary is restored when the test
15611566
ends.
15621567

15631568
>>> foo = {}
1564-
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
1569+
>>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
15651570
... assert foo == {'newkey': 'newvalue'}
1571+
... assert patched_foo == {'newkey': 'newvalue'}
1572+
... # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
1573+
... patched_foo['spam'] = 'eggs'
15661574
...
15671575
>>> assert foo == {}
1576+
>>> assert patched_foo == {}
15681577

15691578
>>> import os
15701579
>>> with patch.dict('os.environ', {'newkey': 'newvalue'}):

Lib/unittest/mock.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1730,6 +1730,7 @@ def decorate_class(self, klass):
17301730
def __enter__(self):
17311731
"""Patch the dict."""
17321732
self._patch_dict()
1733+
return self.in_dict
17331734

17341735

17351736
def _patch_dict(self):

Lib/unittest/test/testmock/testpatch.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,13 @@ def test():
619619
self.assertEqual(foo.values, original)
620620

621621

622+
def test_patch_dict_as_context_manager(self):
623+
foo = {'a': 'b'}
624+
with patch.dict(foo, a='c') as patched:
625+
self.assertEqual(patched, {'a': 'c'})
626+
self.assertEqual(foo, {'a': 'b'})
627+
628+
622629
def test_name_preserved(self):
623630
foo = {}
624631

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Changed :func:`unittest.mock.patch.dict` to return the patched
2+
dictionary when used as context manager. Patch by Vadim Tsander.

0 commit comments

Comments
 (0)