[issue21600] mock.patch.stopall doesn't work with patch.dict

Karthikeyan Singaravelan report at bugs.python.org
Fri Dec 13 04:05:59 EST 2019


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

This sounds like a good idea given the docs and the general agreement in the thread. I would like to target this for 3.9 . Differentiation between the normal patches and the ones from patch.dict is nice but given that docstring indicates LIFO for all active patches storing patch.dict items also in _patch.active_patches ensures we can do LIFO if there is a mixture of normal and dictionary patches started with start method. Adding other maintainers for thoughts.

diff --git Lib/unittest/mock.py Lib/unittest/mock.py
index cd5a2aeb60..96115e06ba 100644
--- Lib/unittest/mock.py
+++ Lib/unittest/mock.py
@@ -1853,8 +1853,21 @@ class _patch_dict(object):
         self._unpatch_dict()
         return False

-    start = __enter__
-    stop = __exit__
+    def start(self):
+        """Activate a patch, returning any created mock."""
+        result = self.__enter__()
+        _patch._active_patches.append(self)
+        return result
+
+    def stop(self):
+        """Stop an active patch."""
+        try:
+            _patch._active_patches.remove(self)
+        except ValueError:
+            # If the patch hasn't been started this will fail
+            pass
+
+        return self.__exit__()

----------
components: +Library (Lib) -Tests
nosy: +cjw296, lisroach, mariocj89, xtreak
versions: +Python 3.9 -Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue21600>
_______________________________________


More information about the Python-bugs-list mailing list