paint-brush
HTTPretty now supports asyncio!by@mindflayer
1,200 reads
1,200 reads

HTTPretty now supports asyncio!

by Giorgio SalluzzoOctober 17th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Try it yourself!

Company Mentioned

Mention Thumbnail
featured image - HTTPretty now supports asyncio!
Giorgio Salluzzo HackerNoon profile picture

and Python 3, consequently…

Try it yourself!









class AioHttpEntryTestCase(TestCase):@httprettifieddef 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 json




import aiohttpimport asyncioimport async_timeoutfrom 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 json




import aiohttpimport asyncioimport async_timeoutfrom unittest import TestCase


from mocket.mocket import mocketizefrom mocket.mockhttp import Entry









class AioHttpEntryTestCase(TestCase):@mocketizedef 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:

Mocket: a socket mock framework

for all kinds of socket animals, web-clients included