This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: unittest.mock.patch.stopall intermittently doesn't work when the same thing is patched multiple times
Type: behavior Stage: resolved
Components: Versions: Python 3.4, Python 3.5
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: michael.foord Nosy List: michael.foord, python-dev
Priority: normal Keywords:

Created on 2014-04-15 15:54 by michael.foord, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg216322 - (view) Author: Michael Foord (michael.foord) * (Python committer) Date: 2014-04-15 15:54
stopall does not always stop all patches to single target

What steps will reproduce the problem?

python code to reproduce error

import mock

def myfunc():
   return 'hello'

m = mock.patch('__main__.myfunc').start()
m.return_value = 'firstmock'

m2 = mock.patch('__main__.myfunc').start()
m2.return_value = 'secondmock'


What is the expected output? What do you see instead?
I would expect the output from above to be:

Instead, sometimes it comes out as:

This result is non-deterministic though so it may also come out as expected. Re-run several times to get the error.

This is a result of using a set to store the active patches. Conversion from a set to a list is non-deterministic because the set has no notion of order.

Please provide any additional information below.

This use case may seem strange, but it shows up in large unit tests where a base class sets up a default patch to catch external calls or something similar and then an individual unit test requiring specific mock behavior patches it differently.

I have a patch here that fixes the problem using a list to store the patches to maintain order and call them in reverse order to stop them in the correct order.
msg216388 - (view) Author: Roundup Robot (python-dev) (Python triager) Date: 2014-04-15 21:22
New changeset 727b7e9c40e3 by Michael Foord in branch '3.4':
Closes issue 21239. unittest.mock.patch.stopall() did not work deterministically when the same name was patched multiple times.
Date User Action Args
2022-04-11 14:58:01adminsetgithub: 65438
2014-04-15 21:22:29python-devsetstatus: open -> closed

nosy: + python-dev
messages: + msg216388

resolution: fixed
stage: patch review -> resolved
2014-04-15 15:54:31michael.foordcreate