Python - object MagicMock can't be used in 'await' expression

When I was trying to mock an async function in unittest with MagicMock, I got this exception:

TypeError: object MagicMock can't be used in 'await' expression

With sample code like:

# source code
class Service:
    async def compute(self, x):
        return x

class App:
    def __init__(self):
        self.service = Service()

    async def handle(self, x):
        return await self.service.compute(x)

# test code
import asyncio
import unittest
from unittest.mock import patch

class TestApp(unittest.TestCase):
    def test_handle(self, mock):
        loop = asyncio.get_event_loop()
        app = App()
        res = loop.run_until_complete(app.handle('foo'))

if __name__ == '__main__':

How should I fix it with built-in python3 libraries?

1 answer

  • answered 2018-07-18 10:32 shaun shia

    I ended up with this hack.

    # monkey patch MagicMock
    async def async_magic():
    MagicMock.__await__ = lambda x: async_magic().__await__()

    It only works for MagicMock, not other pre-defined return_value