我有以下异步功能:
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
试图测试它,但仍然没有找到方法。
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
但没有按我的意愿工作。任何有关如何测试上下文管理器的帮助将不胜感激。