futurized¶
-
aiounittest.futurized(o)[source]¶ Makes the given object to be awaitable.
Parameters: o (any) – Object to wrap Returns: awaitable that resolves to provided object Return type: asyncio.Future Anything passed to
futurizedis wrapped inasyncio.Future. This makes it awaitable (can be run withawaitoryield from) as a result of await it returns the original object.If provided object is a Exception (or its sublcass) then the Future will raise it on await.
fut = aiounittest.futurized('SOME TEXT') ret = await fut print(ret) # prints SOME TEXT fut = aiounittest.futurized(Exception('Dummy error')) ret = await fut # will raise the exception "dummy error"
The main goal is to use it with
unittest.mock.Mock(orMagicMock) to be able to mock awaitable functions (coroutines).Consider the below code
from asyncio import sleep async def add(x, y): await sleep(666) return x + y
You rather don’t want to wait 666 seconds, you’ve gotta mock that.
from aiounittest import futurized, AsyncTestCase from unittest.mock import Mock, patch import dummy_math class MyAddTest(AsyncTestCase): async def test_add(self): mock_sleep = Mock(return_value=futurized('whatever')) patch('dummy_math.sleep', mock_sleep).start() ret = await dummy_math.add(5, 6) self.assertEqual(ret, 11) mock_sleep.assert_called_once_with(666) async def test_fail(self): mock_sleep = Mock(return_value=futurized(Exception('whatever'))) patch('dummy_math.sleep', mock_sleep).start() with self.assertRaises(Exception) as e: await dummy_math.add(5, 6) mock_sleep.assert_called_once_with(666)