Mocking a Slow API
Opened this issue · 1 comments
Enprogames commented
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?
marcinsulikowski commented
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)