[Python-checkins] bpo-37052: Add examples for mocking async iterators and context managers (GH-14660)

Miss Islington (bot) webhook-mailer at python.org
Tue Sep 10 07:08:59 EDT 2019


https://github.com/python/cpython/commit/ab74e52f768be5048faf2a11e78822533afebcb7
commit: ab74e52f768be5048faf2a11e78822533afebcb7
branch: 3.8
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2019-09-10T04:08:52-07:00
summary:

bpo-37052: Add examples for mocking async iterators and context managers (GH-14660)


Add examples for mocking asynchronous iterators and asynchronous context managers.

https://bugs.python.org/issue37052
(cherry picked from commit c8dfa7333d6317d7cd8c5c7366023f5a668e3f91)

Co-authored-by: Xtreak <tir.karthi at gmail.com>

files:
M Doc/library/unittest.mock-examples.rst

diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst
index 811f0fb1ce93..cf6b671b5bee 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
 
@@ -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
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 



More information about the Python-checkins mailing list