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 asvetlov, cjw296, docs@python, ezio.melotti, lisroach, mariocj89, michael.foord, miss-islington, xtreak, yselivanov
Date 2019-09-10.12:32:51
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1568118772.06.0.0176318246248.issue37052@roundup.psfhosted.org>
In-reply-to
Content
I will open a separate PR as discussed around mocking a class with an async method which is patched with AsyncMock. Meanwhile a method that returns a coroutine is patched with a MagicMock and needs to be explicitly mocked with an AsyncMock as new in the patch call. The original example in Zulip is as below showing the difference.


from unittest.mock import AsyncMock, patch
import asyncio

async def foo():
    pass

async def post(url):
    pass


class Response:

    async def json(self):
        pass

    def sync_json(self):
        return foo() # Returns a coroutine which should be awaited to get the result


async def main():
    # post function is an async function and hence AsyncMock is returned.
    with patch(f"{__name__}.post", return_value={'a': 1}) as m:
        print(await post("http://example.com"))

    # The json method call is a coroutine whose return_value is set with the dictionary
    # json is an async function and hence during patching here m is an AsyncMock
    response = Response()
    with patch.object(response, 'json', return_value={'a': 1}):
        print(await response.json())

    # sync_json returns a coroutine and not an async def itself. So it's mocked as MagicMock
    # by patch.object and we need to pass an explicit callable as AsyncMock to make sure it's
    # awaitable
    response = Response()
    with patch.object(response, 'sync_json', AsyncMock(return_value={'a': 1})):
        print(await response.sync_json())


asyncio.run(main())
History
Date User Action Args
2019-09-10 12:32:52xtreaksetrecipients: + xtreak, cjw296, ezio.melotti, michael.foord, asvetlov, docs@python, yselivanov, lisroach, mariocj89, miss-islington
2019-09-10 12:32:52xtreaksetmessageid: <1568118772.06.0.0176318246248.issue37052@roundup.psfhosted.org>
2019-09-10 12:32:52xtreaklinkissue37052 messages
2019-09-10 12:32:51xtreakcreate