Issue 36222: ValueError: a coroutine was expected with asyncio.run (original) (raw)

Refs: https://github.com/Martiusweb/asynctest/issues/114

I was trying to mock a asyncio.run(asyncio.gather()) call and I discovered that while it was working with loop.run_until_complete it wasn't with asyncio.run

Is there a reason for this difference of behaviour?

import asyncio
from unittest.mock import Mock


class AsyncMock(Mock):

    def __call__(self, *args, **kwargs):
        sup = super(AsyncMock, self)
        async def coro():
            return sup.__call__(*args, **kwargs)
        return coro()

    def __await__(self):
        return self().__await__()

mocked_function = AsyncMock()

asyncio.run(asyncio.gather(mocked_function()))
import asyncio
from unittest.mock import Mock


class AsyncMock(Mock):

    def __call__(self, *args, **kwargs):
        sup = super(AsyncMock, self)
        async def coro():
            return sup.__call__(*args, **kwargs)
        return coro()

    def __await__(self):
        return self().__await__()

mocked_function = AsyncMock()

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(mocked_function()))