Skip to content

Instantly share code, notes, and snippets.

@constverum
Created January 19, 2016 18:41
Show Gist options
  • Select an option

  • Save constverum/c1e934f9a8d05764aea1 to your computer and use it in GitHub Desktop.

Select an option

Save constverum/c1e934f9a8d05764aea1 to your computer and use it in GitHub Desktop.
Example of async test
import asyncio
import aiohttp
import unittest
from unittest import mock
async def get_my_ip(timeout=3, loop=None):
try:
with aiohttp.Timeout(timeout, loop=loop):
with aiohttp.ClientSession(loop=loop) as session:
async with session.get('http://httpbin.org/get?show_env') as resp:
data = await resp.json()
except asyncio.TimeoutError as e:
raise RuntimeError('Could not get a external IP. Error: %s' % e)
ip = data['origin'].split(', ')[0]
return ip
class TestUtils(unittest.TestCase):
def test_get_my_ip(self):
loop = asyncio.get_event_loop()
def side_effect(*args, **kwargs):
def _side_effect(*args, **kwargs):
fut = asyncio.Future(loop=loop)
fut.set_result({'origin': '127.0.0.1'})
return fut
resp = mock.Mock()
resp.json.side_effect = resp.release.side_effect = _side_effect
fut = asyncio.Future(loop=loop)
fut.set_result(resp)
return fut
with mock.patch("aiohttp.client.ClientSession._request") as patched:
patched.side_effect = side_effect
ip = loop.run_until_complete(get_my_ip(loop=loop))
self.assertEqual(ip, '127.0.0.1')
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment