HTTPretty now supports asyncio!

2 min read Original article โ†—

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 TestCase
from 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 TestCase
from mocket.mocket import mocketize
from mocket.mockhttp import Entry
class 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:

Much water has flowed under the bridge