class _patch(object):
attribute_name = None
- _active_patches = set()
+ _active_patches = []
def __init__(
self, getter, attribute, new, spec, create,
def start(self):
"""Activate a patch, returning any created mock."""
result = self.__enter__()
- self._active_patches.add(self)
+ self._active_patches.append(self)
return result
def stop(self):
"""Stop an active patch."""
- self._active_patches.discard(self)
+ try:
+ self._active_patches.remove(self)
+ except ValueError:
+ # If the patch hasn't been started this will fail
+ pass
+
return self.__exit__()
def _patch_stopall():
- """Stop all active patches."""
- for patch in list(_patch._active_patches):
+ """Stop all active patches. LIFO to unroll nested patches."""
+ for patch in reversed(_patch._active_patches):
patch.stop()
from unittest.mock import (
NonCallableMock, CallableMixin, patch, sentinel,
MagicMock, Mock, NonCallableMagicMock, patch, _patch,
- DEFAULT, call, _get_target
+ DEFAULT, call, _get_target, _patch
)
patched()
self.assertIs(os.path, path)
+ def test_stopall_lifo(self):
+ stopped = []
+ class thing(object):
+ one = two = three = None
+
+ def get_patch(attribute):
+ class mypatch(_patch):
+ def stop(self):
+ stopped.append(attribute)
+ return super(mypatch, self).stop()
+ return mypatch(lambda: thing, attribute, None, None,
+ False, None, None, None, {})
+ [get_patch(val).start() for val in ("one", "two", "three")]
+ patch.stopall()
+
+ self.assertEqual(stopped, ["three", "two", "one"])
+
if __name__ == '__main__':
unittest.main()