changeset: 956:9d8749ed35a6 branch: issue21600 tag: tip user: fumihiko kakuma date: Fri Jun 06 23:29:25 2014 +0900 summary: support patch.dict by stopall. diff -r d356250e275d -r 9d8749ed35a6 mock.py --- a/mock.py Tue Apr 09 14:53:33 2013 +0100 +++ b/mock.py Fri Jun 06 23:29:25 2014 +0900 @@ -1616,6 +1616,8 @@ `patch.TEST_PREFIX` for choosing which methods to wrap. """ + _active_patches = set() + def __init__(self, in_dict, values=(), clear=False, **kwargs): if isinstance(in_dict, basestring): in_dict = _importer(in_dict) @@ -1655,6 +1657,7 @@ def __enter__(self): """Patch the dict.""" self._patch_dict() + self._active_patches.add(self) def _patch_dict(self): @@ -1698,6 +1701,7 @@ def __exit__(self, *args): """Unpatch the dict.""" + self._active_patches.discard(self) self._unpatch_dict() return False @@ -1718,6 +1722,8 @@ """Stop all active patches.""" for patch in list(_patch._active_patches): patch.stop() + for patch in list(_patch_dict._active_patches): + patch.stop() patch.object = _patch_object diff -r d356250e275d -r 9d8749ed35a6 tests/testpatch.py --- a/tests/testpatch.py Tue Apr 09 14:53:33 2013 +0100 +++ b/tests/testpatch.py Fri Jun 06 23:29:25 2014 +0900 @@ -1785,6 +1785,47 @@ self.assertIs(os.path, path) + def test_patch_dict_stopall(self): + dic1 = {} + dic2 = {1: 'a'} + dic3 = {1: 'A', 2: 'B'} + origdic1 = {} + origdic2 = dic2.copy() + origdic3 = dic3.copy() + patch.dict(dic1, {1: 'I', 2: 'II'}).start() + patch.dict(dic2, {2: 'b'}).start() + + @patch.dict(dic3) + def patched(): + del dic3[1] + patch.stopall() + self.assertEqual(dic1, origdic1) + self.assertEqual(dic2, origdic2) + self.assertEqual(dic3, {2: 'B'}) + + patched() + self.assertEqual(dic3, origdic3) + + + def test_patch_and_patch_dict_stopall(self): + unlink = os.unlink + chdir = os.chdir + dic1 = {} + dic2 = {1: 'A', 2: 'B'} + origdic1 = {} + origdic2 = dic2.copy() + patch('os.unlink', something).start() + patch('os.chdir', something_else).start() + patch.dict(dic1, {1: 'I', 2: 'II'}).start() + patch.dict(dic2).start() + del dic2[1] + patch.stopall() + self.assertIs(os.unlink, unlink) + self.assertIs(os.chdir, chdir) + self.assertEqual(dic1, origdic1) + self.assertEqual(dic2, origdic2) + + def test_wrapped_patch(self): decorated = patch('sys.modules')(function) self.assertIs(decorated.__wrapped__, function)