Skip to content

Instantly share code, notes, and snippets.

@holgi
Created January 30, 2019 13:31
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save holgi/00d8fa4affacdc80f896dd97c064b6a4 to your computer and use it in GitHub Desktop.
Save holgi/00d8fa4affacdc80f896dd97c064b6a4 to your computer and use it in GitHub Desktop.
Example for mocking async context managers
import pytest
import aiohttp
import asyncio
from asynctest import CoroutineMock, MagicMock, patch
# Example Code
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://google.com")
print(html[:50])
# Example Test
@patch('aiohttp.ClientSession.get')
@pytest.mark.asyncio
async def test_fetch(mock_get):
from example import fetch
# in this case the result must be a coroutine mock
# see: https://stackoverflow.com/a/48762969
mock_get.return_value.__aenter__.return_value.text = CoroutineMock(side_effect=["custom text"])
async with aiohttp.ClientSession() as session:
result = await fetch(session, "http://example.com")
assert result == "custom text"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
@kiri11-mi1
Copy link

Thanks very match!!!

mock_get.return_value.__aenter__.return_value.text = CoroutineMock(side_effect=["custom text"])

it is help to test async context manager in function

@Joshuaalbert
Copy link

Awesome thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment