summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorMichael Foord <michael@voidspace.org.uk>2012-06-10 19:36:32 (GMT)
committerMichael Foord <michael@voidspace.org.uk>2012-06-10 19:36:32 (GMT)
commitf7c41580578fdae4f8ab6c8eb6135902de5214d1 (patch)
tree8528e1d98410b12e7f8f0dd7aaad3f9c6f4404c4 /Lib
parentbfcb42936bc53ff094d93db01a4fc9b78735f955 (diff)
downloadcpython-f7c41580578fdae4f8ab6c8eb6135902de5214d1.zip
cpython-f7c41580578fdae4f8ab6c8eb6135902de5214d1.tar.gz
cpython-f7c41580578fdae4f8ab6c8eb6135902de5214d1.tar.bz2
Adding patch.stopall method to unittest.mock
Diffstat (limited to 'Lib')
-rw-r--r--Lib/unittest/mock.py22
-rw-r--r--Lib/unittest/test/testmock/testpatch.py18
2 files changed, 38 insertions, 2 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 4ae3d16..95570aa 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1002,6 +1002,7 @@ def _is_started(patcher):
class _patch(object):
attribute_name = None
+ _active_patches = set()
def __init__(
self, getter, attribute, new, spec, create,
@@ -1270,8 +1271,18 @@ class _patch(object):
if _is_started(patcher):
patcher.__exit__(*exc_info)
- start = __enter__
- stop = __exit__
+
+ def start(self):
+ """Activate a patch, returning any created mock."""
+ result = self.__enter__()
+ self._active_patches.add(self)
+ return result
+
+
+ def stop(self):
+ """Stop an active patch."""
+ self._active_patches.discard(self)
+ return self.__exit__()
@@ -1562,9 +1573,16 @@ def _clear_dict(in_dict):
del in_dict[key]
+def _patch_stopall():
+ """Stop all active patches."""
+ for patch in list(_patch._active_patches):
+ patch.stop()
+
+
patch.object = _patch_object
patch.dict = _patch_dict
patch.multiple = _patch_multiple
+patch.stopall = _patch_stopall
patch.TEST_PREFIX = 'test'
magic_methods = (
diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py
index 6256855..c1091b4 100644
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -1762,6 +1762,24 @@ class PatchTest(unittest.TestCase):
p.stop()
+ def test_patch_stopall(self):
+ unlink = os.unlink
+ chdir = os.chdir
+ path = os.path
+ patch('os.unlink', something).start()
+ patch('os.chdir', something_else).start()
+
+ @patch('os.path')
+ def patched(mock_path):
+ patch.stopall()
+ self.assertIs(os.path, mock_path)
+ self.assertIs(os.unlink, unlink)
+ self.assertIs(os.chdir, chdir)
+
+ patched()
+ self.assertIs(os.path, path)
+
+
if __name__ == '__main__':
unittest.main()