1

我有以下异步功能:

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

但没有按我的意愿工作。任何有关如何测试上下文管理器的帮助将不胜感激。

4

1 回答 1

0

愚蠢的我,找到了解决方案。我正在使用side_effect而不是return_value.Works 就像一个魅力。非常感谢

于 2019-10-17T11:08:28.680 回答