Message 343067 - Python tracker

Message343067

Author xtreak
Recipients asvetlov, cjw296, lisroach, michael.foord, xtreak, yselivanov
Date 2019-05-21.15:22:08
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1558452128.6.0.303675531512.issue36996@roundup.psfhosted.org>
In-reply-to
Content
I came across this while using AsyncMock but it seems to apply to Mock/MagicMock too. When patch decorator is used to wrap an async function to mock sync or async functions it doesn't seem to work. Manually adding patcher or using patch as context manager works. Meanwhile sync_main which is not an async function works fine. Is this an expected behavior with @patch and async def? Does evaluating an async function with asyncio.run has any effect on this? Debugging it tells me the correct object is being replaced with AsyncMock inside patch.

import asyncio
from unittest.mock import patch, AsyncMock

mock = AsyncMock()

async def foo():
    pass

def bar():
    pass

@patch(f"{__name__}.foo", mock)
@patch(f"{__name__}.bar", mock)
async def main():
    print(f"Inside main {foo=}")
    patcher1 = patch(f"{__name__}.foo", mock)
    patcher2 = patch(f"{__name__}.bar", mock)
    print(f"Inside main before patch start {foo} {bar}")
    patcher1.start()
    patcher2.start()
    print(f"Inside main after patch start {foo} {bar}")
    await foo()
    with patch(f"{__name__}.foo", mock):
        with patch(f"{__name__}.bar", mock):
            print(f"Inside main with {foo} {bar}")
            await foo()

@patch(f"{__name__}.foo", mock)
@patch(f"{__name__}.bar", mock)
def sync_main():
    print(f"Inside sync_main patch {foo} {bar}")
    with patch(f"{__name__}.foo", mock):
        with patch(f"{__name__}.bar", mock):
            print(f"Inside sync_main with {foo} {bar}")


if __name__ == "__main__":
    asyncio.run(main())
    sync_main()


./python.exe foo.py
Inside main foo=<function foo at 0x10f115af0>
Inside main before patch start <function foo at 0x10f115af0> <function bar at 0x10f13f730>
Inside main after patch start <AsyncMock id='4541648720'> <AsyncMock id='4541648720'>
Inside main with <AsyncMock id='4541648720'> <AsyncMock id='4541648720'>
Inside sync_main patch <AsyncMock id='4541648720'> <AsyncMock id='4541648720'>
Inside sync_main with <AsyncMock id='4541648720'> <AsyncMock id='4541648720'>
History
Date User Action Args
2019-05-21 15:22:08xtreaksetrecipients: + xtreak, cjw296, michael.foord, asvetlov, yselivanov, lisroach
2019-05-21 15:22:08xtreaksetmessageid: <1558452128.6.0.303675531512.issue36996@roundup.psfhosted.org>
2019-05-21 15:22:08xtreaklinkissue36996 messages
2019-05-21 15:22:08xtreakcreate