One function

_patch_dict in testing-cabal/mock

The author described this change as Fix `mock.patch.dict` to be stopped with `mock.patch.stopall` (#17606). It counts as a record because the check below fails on the code as it stood at aa5f6e9e2 and passes on 11df59664, with nothing else changed between the two runs.

Fix saved2020-01-29
Sharing licenceBSD-2-Clause · LICENSE.txt
Change size+17 2

What the code was meant to do, written into the code itself as a docstring

Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap.

The change

113113 self._unpatch_dict()
114114 return False
115115
116- start = __enter__
117- stop = __exit__
116+
117+ def start(self):
118+ """Activate a patch, returning any created mock."""
119+ result = self.__enter__()
120+ _patch._active_patches.append(self)
121+ return result
122+
123+
124+ def stop(self):
125+ """Stop an active patch."""
126+ try:
127+ _patch._active_patches.remove(self)
128+ except ValueError:
129+ # If the patch hasn't been started this will fail
130+ pass
131+
132+ return self.__exit__()

The check that tells the two apart

failpass·mock/tests/testpatch.py::PatchTest::test_patch_and_patch_dict_stopall

Check file mock/tests/testpatch.py, taken without changes from the fix and copied onto the older code, so the exact same check runs against both versions.

Origin and history

The code before itaa5f6e9e2df8a77b2f81714018043efc392ae676
Broken version dated2020-01-29
Modulemock.mock
Units changed_patch_dict
Fingerprintace9c5643d93e761
Checked2026-08-18 by goldset/0.1

Every field above is generated by our program. None of it is written by hand.

Other bugs found in testing-cabal/mock