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.

Author xtreak
Recipients lisroach, xtreak
Date 2020-10-27.06:59:02
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1603781943.06.0.127932553655.issue42159@roundup.psfhosted.org>
In-reply-to
Content
This is not a problem with AsyncMock. The patching is not done when the patch object is created to store reference to the original unpatched function. Hence patcher1, patcher2 that patch the same function don't store a reference to the original sync_func. The lookup is done during start(). patcher1.start() makes a lookup and stores the function. When patcher2.start() makes a lookup the function is already patched with a mock and thus it resorts to the original as the mock. 

When stop is called on patcher1 it resets back to the original function. Meanwhile for patcher2 the original function set during start itself is a mock and it resets back to that. The lookup is done at https://github.com/python/cpython/blob/a6879d9445f98833c4e300e187956e2a218a2315/Lib/unittest/mock.py#L1360 . Here target will print the function for patcher1.start() but the mock for patcher2.start().

import asyncio
import unittest
from unittest import TestCase
from unittest.mock import *

def sync_func():
    raise Exception

class Test(TestCase):

    def test_simultaneous_mocks_sync(self):
        patcher1 = patch(f"{__name__}.sync_func")
        patcher2 = patch(f"{__name__}.sync_func")

        patcher1.start()
        print(sync_func())

        patcher2.start()
        print(sync_func())

        breakpoint()
        patcher1.stop()
        with self.assertRaises(Exception):
            sync_func()

        breakpoint()
        patcher2.stop()

        with self.assertRaises(Exception): # Fails, mock is restored!
            sync_func()

if __name__ == "__main__":
    unittest.main()
History
Date User Action Args
2020-10-27 06:59:03xtreaksetrecipients: + xtreak, lisroach
2020-10-27 06:59:03xtreaksetmessageid: <1603781943.06.0.127932553655.issue42159@roundup.psfhosted.org>
2020-10-27 06:59:03xtreaklinkissue42159 messages
2020-10-27 06:59:02xtreakcreate