I have the following async function:
async def my_func(request):
# preparation code here
with aiohttp.ClientSession() as s:
with s.post(url, headers) as response:
status_code = response.status
if status_code == 200:
json_resp = await response.json()
elif:
# more checks
Trying to test it but still haven't found a way.
from asynctest.mock import CoroutineMock, MagicMock as AsyncMagicMock
@mock.patch("path_to_function.aiohttp.ClientSession", new_callable=AsyncMagicMock) # this is unittest.mock
def test_async_function(self, mocked_session):
s = AsyncMagicMock()
mocked_client_session().__aenter__ = CoroutineMock(side_effect=s)
session_post = s.post()
response_mock = AsyncMagicMock()
session_post.__aenter__ = CoroutineMock(side_effect=response_mock)
response_mock.status = 200
but not working as I want. Any help on how to test context managers would be highly appreciated.
Silly me, Found the solution. I was using
side_effect
instead ofreturn_value
.Works like a charm. Thank you very much