python - 使用 asynctest 模拟 aiohttp ClientSession contextmanager

标签 python python-asyncio asynctest

我有以下异步函数:

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/

相关文章:

Python:在生成器的开头插入元素

python - 如何模拟 aiohttp.client.ClientSession.get 异步上下文管理器

python - 如何为标准输入/标准输出创建异步流读取器/写入器?

javascript - 为什么 jest.useFakeTimers 不适用于 RxJs Observable 延迟

python - 如何配置 pybuilder?

python - 无法使用 cur.execute 更新数据库?

python - python 写入二进制文件

比异步更快的 Python 同步代码示例

python - Python 的 asyncio.coroutine 可以看作是一个生成器吗?