Skip to content

[3.8] bpo-37052: Add examples for mocking async iterators and context managers (GH-14660) #15834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 10, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Doc/library/unittest.mock-examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

.. testsetup::

import asyncio
import unittest
from unittest.mock import Mock, MagicMock, patch, call, sentinel

Expand Down Expand Up @@ -276,6 +277,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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down