Mocking async call in python 3.5

后端 未结 7 1626
花落未央
花落未央 2020-12-04 23:38

How do I mock async call from one native coroutine to other one using unittest.mock.patch?

I currently have quite an awkward solution:

c         


        
7条回答
  •  北海茫月
    2020-12-05 00:08

    The solution was actually quite simple: I just needed to convert __call__ method of mock into coroutine:

    class AsyncMock(MagicMock):
        async def __call__(self, *args, **kwargs):
            return super(AsyncMock, self).__call__(*args, **kwargs)
    

    This works perfectly, when mock is called, code receives native coroutine

    Example usage:

    @mock.patch('my.path.asyncio.sleep', new_callable=AsyncMock)
    def test_stuff(sleep):
        # code
    

提交回复
热议问题