[Python-checkins] cpython: Adding patch.stopall method to unittest.mock
michael.foord
python-checkins at python.org
Sun Jun 10 21:36:41 CEST 2012
http://hg.python.org/cpython/rev/4d28666c54f2
changeset: 77401:4d28666c54f2
user: Michael Foord <michael at voidspace.org.uk>
date: Sun Jun 10 20:36:32 2012 +0100
summary:
Adding patch.stopall method to unittest.mock
files:
Doc/library/unittest.mock.rst | 8 +++-
Lib/unittest/mock.py | 22 +++++++++++-
Lib/unittest/test/testmock/testpatch.py | 18 ++++++++++
3 files changed, 44 insertions(+), 4 deletions(-)
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -1354,8 +1354,12 @@
As an added bonus you no longer need to keep a reference to the `patcher`
object.
-In fact `start` and `stop` are just aliases for the context manager
-`__enter__` and `__exit__` methods.
+It is also possible to stop all patches which have been started by using
+`patch.stopall`.
+
+.. function:: patch.stopall
+
+ Stop all active patches.
TEST_PREFIX
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1002,6 +1002,7 @@
class _patch(object):
attribute_name = None
+ _active_patches = set()
def __init__(
self, getter, attribute, new, spec, create,
@@ -1270,8 +1271,18 @@
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 @@
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
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -1762,6 +1762,24 @@
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()
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list