bpo-38093: Correctly returns AsyncMock for async subclasses. (GH-15947)
diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst
index cf6b671..e650bb1 100644
--- a/Doc/library/unittest.mock-examples.rst
+++ b/Doc/library/unittest.mock-examples.rst
@@ -14,7 +14,7 @@
import asyncio
import unittest
- from unittest.mock import Mock, MagicMock, patch, call, sentinel
+ from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel
class SomeClass:
attribute = 'this is a doctest'
@@ -280,14 +280,16 @@
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.
+Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have 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 = MagicMock() # AsyncMock also works here
>>> mock.__aiter__.return_value = [1, 2, 3]
>>> async def main():
... return [i async for i in mock]
+ ...
>>> asyncio.run(main())
[1, 2, 3]
@@ -295,24 +297,25 @@
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`.
+Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock
+:ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``.
+By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that
+return an async function.
>>> class AsyncContextManager:
- ...
... async def __aenter__(self):
... return self
- ...
- ... async def __aexit__(self):
+ ... async def __aexit__(self, exc_type, exc, tb):
... pass
- >>> mock_instance = MagicMock(AsyncContextManager())
+ ...
+ >>> mock_instance = MagicMock(AsyncContextManager()) # AsyncMock also works here
>>> 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()
+ >>> mock_instance.__aenter__.assert_awaited_once()
+ >>> mock_instance.__aexit__.assert_awaited_once()
Creating a Mock from an Existing Object