用法:
class unittest.mock.AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
MagicMock
的異步版本。AsyncMock
對象的行為將使得該對象被識別為異步函數,並且調用的結果是可等待的。>>> mock = AsyncMock() >>> asyncio.iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) True
mock()
的結果是一個異步函數,它在等待後將具有side_effect
或return_value
的結果:- 如果
side_effect
是一個函數,異步函數將返回該函數的結果, - 如果
side_effect
是異常,異步函數將引發異常, - 如果
side_effect
是一個可迭代對象,則異步函數將返回可迭代對象的下一個值,但是,如果結果序列用完,則立即引發StopAsyncIteration
, - 如果
side_effect
未定義,異步函數將返回由return_value
定義的值,因此,默認情況下,異步函數返回一個新的AsyncMock
對象。
將
Mock
或MagicMock
的spec
設置為異步函數將導致調用後返回協程對象。>>> async def async_func(): pass ... >>> mock = MagicMock(async_func) >>> mock <MagicMock spec='function' id='...'> >>> mock() <coroutine object AsyncMockMixin._mock_call at ...>
將
Mock
、MagicMock
或AsyncMock
的spec
設置為具有異步和同步函數的類將自動檢測同步函數並將它們設置為MagicMock
(如果父模擬是AsyncMock
或MagicMock
)或Mock
(如果父模擬是Mock
)。所有異步函數都是AsyncMock
。>>> class ExampleClass: ... def sync_foo(): ... pass ... async def async_foo(): ... pass ... >>> a_mock = AsyncMock(ExampleClass) >>> a_mock.sync_foo <MagicMock name='mock.sync_foo' id='...'> >>> a_mock.async_foo <AsyncMock name='mock.async_foo' id='...'> >>> mock = Mock(ExampleClass) >>> mock.sync_foo <Mock name='mock.sync_foo' id='...'> >>> mock.async_foo <AsyncMock name='mock.async_foo' id='...'>
3.8 版中的新函數。
- 如果
相關用法
- Python unittest.mock.AsyncMock.assert_awaited_once_with用法及代碼示例
- Python unittest.mock.AsyncMock.assert_any_await用法及代碼示例
- Python unittest.mock.AsyncMock.await_args_list用法及代碼示例
- Python unittest.mock.AsyncMock.assert_awaited_with用法及代碼示例
- Python unittest.mock.AsyncMock.assert_has_awaits用法及代碼示例
- Python unittest.mock.AsyncMock.assert_awaited_once用法及代碼示例
- Python unittest.mock.AsyncMock.await_count用法及代碼示例
- Python unittest.mock.AsyncMock.await_args用法及代碼示例
- Python unittest.mock.AsyncMock.assert_awaited用法及代碼示例
- Python unittest.mock.Mock.reset_mock用法及代碼示例
- Python unittest.mock.Mock.__class__用法及代碼示例
- Python unittest.mock.Mock.call_args用法及代碼示例
- Python unittest.mock.call用法及代碼示例
- Python unittest.mock.Mock.method_calls用法及代碼示例
- Python unittest.mock.Mock.call_args_list用法及代碼示例
- Python unittest.mock.Mock.assert_called用法及代碼示例
- Python unittest.mock.Mock.assert_not_called用法及代碼示例
- Python unittest.mock.Mock.mock_calls用法及代碼示例
- Python unittest.mock.Mock.assert_has_calls用法及代碼示例
- Python unittest.mock.Mock.configure_mock用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 unittest.mock.AsyncMock。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。