aioresponses icon indicating copy to clipboard operation
aioresponses copied to clipboard

Mocking a Slow API

Open Enprogames opened this issue 2 years ago • 1 comments

I'm wondering if there's a way of mocking an API which takes a long time to respond. I currently have issues with slow APIs and want to be able to test that my requests wait long enough for them. I also want to make sure they retry if the slow API fails.

Is there any way of doing this with the aioresponses library?

Enprogames avatar Aug 12 '22 21:08 Enprogames

You can do this using the existing features of the library. One way would be to just pretend that a request was slow and raised asyncio.TimeoutError as a result (this is the exception aiohttp raises when things fail due to timeouts):

aioresponses.get("https://some-url/", exception=asyncio.TimeoutError())

Alternatively, you can make the request actually slow:

async def callback(url: Any, **kwargs: Any) -> CallbackResult:
    await asyncio.sleep(10)
    return CallbackResult(body="something", status=200)

aioresponses.get("https://some-url/", callback=callback)

or do both – slow and eventually failing due to a timeout:

async def callback(url: Any, **kwargs: Any) -> CallbackResult:
    await asyncio.sleep(10)
    raise asyncio.TimeoutError()

aioresponses.get("https://some-url/", callback=callback)

marcinsulikowski avatar Oct 19 '22 19:10 marcinsulikowski