我有以下异步函数:
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
但没有按我想要的方式工作。任何有关如何测试上下文管理器的帮助将不胜感激。
最佳答案
愚蠢的我,找到了解决方案。我使用的是 side_effect
而不是 return_value
。效果非常好。非常感谢
关于python - 使用 asynctest 模拟 aiohttp ClientSession contextmanager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429480/