Skip to content

Instantly share code, notes, and snippets.

@pfertyk
Created June 21, 2017 21:46
Show Gist options
  • Save pfertyk/8b9a1feab8799379d1a0090779e7044a to your computer and use it in GitHub Desktop.
Save pfertyk/8b9a1feab8799379d1a0090779e7044a to your computer and use it in GitHub Desktop.
Testing response status for aiohttp ClientSession
import random
from aiohttp import ClientSession
from asynctest import CoroutineMock, MagicMock, patch
async def get_random_photo_url():
while True:
async with ClientSession() as session:
async with session.get('random.photos') as resp:
json = await resp.json()
photos = json['photos']
if not photos or resp.status != 200:
continue
return random.choice(photos)['img_src']
# TESTS
class AsyncContextManagerMock(MagicMock):
async def __aenter__(self):
return self.aenter()
async def __aexit__(self, *args):
pass
class MockedResponse(MagicMock):
def __init__(self, status, json=None, *args):
super().__init__(*args)
self.status = status
self.json = CoroutineMock(return_value=json)
@patch('aiohttp.ClientSession.get', new_callable=AsyncContextManagerMock)
async def test_status(mock_get):
mock_get.return_value.aenter.side_effect = [
MockedResponse(500, {'photos': [{'img_src': 'a.jpg'}]}),
MockedResponse(200, {'photos': [{'img_src': 'b.jpg'}]}),
]
image_url = await get_random_photo_url()
assert mock_get.return_value.aenter.call_count == 2
assert image_url == 'b.jpg'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment