Python 3.7 mock: How to mock async function wrapped in async_to_sync

Viewed 117

I am trying to mock an async coroutine wrapped in asgiref async_to_sync wrapper inside a synchronous function

#a.py
class A:
 # the async function I am trying to mock
 async def foo(*args):
    result = await async_http_call()
    return result


#b.py
from asgiref.sync import async_to_sync

# since normal MagicMock can't be used with await expression
class AsyncMock(mock.MagicMock):
async def __call__(self, *args, **kwargs):
    return super(AsyncMock, self).__call__(*args, **kwargs)

class B:
# the sync function invoked by test
def sync_foo(*args):
 ans = async_to_sync(A.foo)(*args) # A.foo() returns a dict
 if ans and ans["bool"] == "true":
  return "success"


#test.py
class Test(..):
 @mock.patch(a.A.foo, new_callable=AsyncMock)
 def test sync_foo(mock_foo):
  mock_foo.return_value = {
     "bool" : "true"
  }
  B.sync_foo()

When following this approach I get:

TypeError:object dict can't be used in 'await' expression
0 Answers
Related