HTTPretty now supports asyncio!
and Python 3, consequently…
Try it yourself!
class AioHttpEntryTestCase(TestCase):
@httprettified
def test_https_session(self):
url = 'https://httpbin.org/ip'
HTTPretty.register_uri(
HTTPretty.GET,
url,
body=json.dumps(dict(origin='127.0.0.1')),
) async def main(l):
async with aiohttp.ClientSession(loop=l) as session:
with async_timeout.timeout(3):
async with session.get(url) as get_response:
assert get_response.status == 200
assert await get_response.text() == '{"origin": "127.0.0.1"}' loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(main(loop))
Well, I forgot the import block.
import jsonimport aiohttp
import asyncio
import async_timeout
from unittest import TestCasefrom mocket.plugins.httpretty import HTTPretty, httprettified
Wait! Mocket?! What the Hell is that? We were supposed to talk about HTTPretty!
Yeah, you’re right, and more or less we are talking about it, or better, we are talking about a project born in 2013 and initially inspired by HTTPretty.
Then, in 4 years much water has flowed under the bridge, and after a long period where we almost forgot it, Mocket kept growing even if for long I have been the only developer to maintain it.
So, back to the example, this would be the Mocket way to do the same:
import jsonimport aiohttp
import asyncio
import async_timeout
from unittest import TestCasefrom mocket.mocket import mocketize
from mocket.mockhttp import Entryclass AioHttpEntryTestCase(TestCase):
@mocketize
def test_https_session(self):
url = 'https://httpbin.org/ip'
Entry.single_register(
Entry.GET,
url,
body=json.dumps(dict(origin='127.0.0.1')),
) async def main(l):
async with aiohttp.ClientSession(loop=l) as session:
with async_timeout.timeout(3):
async with session.get(url) as get_response:
assert get_response.status == 200
assert await get_response.text() == '{"origin": "127.0.0.1"}' loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(main(loop))
So, if you like it, I encourage you to do one or more of the following things:
- Use Mocket ;
- Contribute to Mocket ;
- ★ Mocket at https://github.com/mindflayer/python-mocket/ ;
- 👍 my PR at https://github.com/vinta/awesome-python/pull/956 ;
Mocket: a socket mock framework
for all kinds of socket animals, web-clients included