From a33c3859ea45531ce68e3dc0e11d2a0f38a476a7 Mon Sep 17 00:00:00 2001 From: Xtreak Date: Tue, 9 Jul 2019 14:54:53 +0530 Subject: [PATCH 1/2] Add examples for mocking async iterators and context managers --- Doc/library/unittest.mock-examples.rst | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst index 811f0fb1ce9397..5aa809732ea063 100644 --- a/Doc/library/unittest.mock-examples.rst +++ b/Doc/library/unittest.mock-examples.rst @@ -276,6 +276,44 @@ function returns is what the call returns: 2 +Mocking asynchronous iterators +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since Python 3.8, ``MagicMock`` has support to mock :ref:`async-iterators` +through ``__aiter__``. The :attr:`~Mock.return_value` attribute of ``__aiter__`` +can be used to set the return values to be used for iteration. + + >>> mock = MagicMock() + >>> mock.__aiter__.return_value = [1, 2, 3] + >>> async def main(): + ... return [i async for i in mock] + >>> asyncio.run(main()) + [1, 2, 3] + + +Mocking asynchronous context manager +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since Python 3.8, ``MagicMock`` has support to mock +:ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. The +return value of ``__aenter__`` is an :class:`AsyncMock`. + + >>> class AsyncContextManager: + ... + ... async def __aenter__(self): + ... return self + ... + ... async def __aexit__(self): + ... pass + >>> mock_instance = MagicMock(AsyncContextManager()) + >>> async def main(): + ... async with mock_instance as result: + ... pass + >>> asyncio.run(main()) + >>> mock_instance.__aenter__.assert_called_once() + >>> mock_instance.__aexit__.assert_called_once() + + Creating a Mock from an Existing Object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From d564162d90f62d30f609265dfae5bf196cc39a05 Mon Sep 17 00:00:00 2001 From: Xtreak Date: Tue, 9 Jul 2019 15:11:57 +0530 Subject: [PATCH 2/2] Add missing asyncio import for doctest --- Doc/library/unittest.mock-examples.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst index 5aa809732ea063..cf6b671b5beeb4 100644 --- a/Doc/library/unittest.mock-examples.rst +++ b/Doc/library/unittest.mock-examples.rst @@ -12,6 +12,7 @@ .. testsetup:: + import asyncio import unittest from unittest.mock import Mock, MagicMock, patch, call, sentinel