Title: Add examples for mocking async for and async context manager in unittest.mock docs
Type: enhancement Stage: patch review
Components: Documentation Versions: Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: asvetlov, cjw296, docs@python, lisroach, mariocj89, michael.foord, xtreak, yselivanov
Priority: normal Keywords: patch

Created on 2019-05-26 07:51 by xtreak, last changed 2019-07-09 09:31 by xtreak.

Pull Requests
URL Status Linked Edit
PR 14660 open xtreak, 2019-07-09 09:31
Messages (1)
msg343536 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python triager) Date: 2019-05-26 07:51
Since issue26467 implemented AsyncMock along with async dunder methods for MagicMock it enables users to mock async for and async with statements. Currently examples of how to use this is present only in tests and would be good to add it to docs. There is a docs page for mock that contains similar cookbook style examples [0] where I hope these can be added. I can raise a PR with these examples if it's okay. Do you think it's worthy enough to add these examples? Any additional examples you find around asyncio and mock that can be documented ?

An example of mocking async for statement by setting return value for __aiter__ method : 


import asyncio
from unittest.mock import MagicMock

mock = MagicMock()
mock.__aiter__.return_value = range(3)

async def main(): 
    print([i async for i in mock])

$ ./python.exe
[0, 1, 2]

An example of mocking async with statement by implementing __aenter__ and __aexit__ method. In this example __aenter__ and __aexit__ are not called. __aenter__ and __aexit__ implementations are tested to have been called in the test at [1]. These tests work since MagicMock is returned during attribute access (mock_instance.entered) which is always True in boolean context under assertTrue. I will raise a separate PR to discuss this since normally while mocking __enter__ and __exit__ the class's __enter__ and __exit__ are not used as a side_effect for the mock calls unless they are set explicitly.


import asyncio
from unittest.mock import MagicMock

class WithAsyncContextManager:

    async def __aenter__(self, *args, **kwargs):
        return self

    async def __aexit__(self, *args, **kwargs):

instance = WithAsyncContextManager()
mock_instance = MagicMock(instance)

async def main():
    async with mock_instance as result:


Date User Action Args
2019-07-09 09:31:47xtreaksetkeywords: + patch
stage: patch review
pull_requests: + pull_request14467
2019-05-26 07:51:03xtreakcreate