Created
January 30, 2019 13:31
-
-
Save holgi/00d8fa4affacdc80f896dd97c064b6a4 to your computer and use it in GitHub Desktop.
Example for mocking async context managers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks very match!!!
it is help to test async context manager in function