pnuckowski / aioresponses

Aioresponses is a helper for mock/fake web requests in python aiohttp package.
MIT License
508 stars 86 forks source link

How to mock multiple requests with `asyncio.gather`? #205

Open MuriloScarpaSitonio opened 2 years ago

MuriloScarpaSitonio commented 2 years ago

I have a piece of code which uses asyncio.gather to make simultaneous requests:

estimated_income, judicial_records = await asyncio.gather(
        *(client.get_estimated_income(), client.get_judicial_records()), return_exceptions=True
    )

# `client.get_estimated_income()` calls `CREDIT_BUREAU_URL`
# `client.get_judicial_records()` calls `NATIONAL_ARCHIVES_URL`

In my tests I'm trying to simulate some scenarios by mocking the requests status:

mock_aioresponse.get(NATIONAL_ARCHIVES_URL, status=200)
mock_aioresponse.get(CREDIT_BUREAU_URL, status=400)

If I run a single test, it works as expected but if I run more than one (and the others don't even have to use mock_aioresponse) I start to get some Connection refused errors.

How can I use aioresponses to accomplish my test cases?

Dexter2389 commented 2 years ago

Any updates on this issue? I am also trying to make simultaneous requests and getting the same error.

an0o0nym commented 2 years ago

Hey, I would also like to know if there is any nice solution to this issue?

an0o0nym commented 2 years ago

I just found an answer in another issue https://github.com/pnuckowski/aioresponses/issues/164

simply pass repeat=True to aioresponses method (in this case get method) i.e. .get(SOME_URL, status=400, repeat=True)

jemshit commented 1 year ago

I just found an answer in another issue #164

simply pass repeat=True to aioresponses method (in this case get method) i.e. .get(SOME_URL, status=400, repeat=True)

Interesting, why this works though o.O I do this and seems working:

mocked.get(re.compile('.+index_price.+'),
                     payload=expected_index_price_dict,
                     repeat=True)
mocked.get(re.compile('.+fair_price.+'),
                     payload=expected_fair_price_dict,
                     repeat=True)
# ...                     
await asyncio.gather(index_price(symbol),
                     fair_price(symbol),
                     return_exceptions=True)