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):
    @patch('__main__.Service')
    def test_handle(self, mock):
        loop = asyncio.get_event_loop()
        app = App()
        res = loop.run_until_complete(app.handle('foo'))
        app.service.compute.assert_called_with("foo")
if __name__ == '__main__':
    unittest.main()
How should I fix it with built-in python3 libraries?
 
     
     
     
     
     
    