[New-bugs-announce] [issue36996] unittest.mock.patch decorator doesn't work with async functions

Karthikeyan Singaravelan report at bugs.python.org
Tue May 21 11:22:08 EDT 2019


New submission from Karthikeyan Singaravelan <tir.karthi at gmail.com>:

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'>

----------
components: Library (Lib), asyncio
messages: 343067
nosy: asvetlov, cjw296, lisroach, michael.foord, xtreak, yselivanov
priority: normal
severity: normal
status: open
title: unittest.mock.patch decorator doesn't work with async functions
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36996>
_______________________________________


More information about the New-bugs-announce mailing list