【问题标题】:aiohttp Mock ClientSession Responseaiohttp 模拟客户端会话响应
【发布时间】:2020-02-11 20:42:59
【问题描述】:

为了测试目的,试图模拟 aiohttp.ClientSession 的响应

我的代码如下所示:

async def run_request(endpoint: str, **kwargs) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.post(endpoint, **kwargs) as response:
            response_json = await response.json()

            return {"response": response, "response_json": response_json}

我想用我想象的如下图来测试我的代码:

@patch("aiohttp.ClientSession.post", <something>)
def test_run_request(self):

我该怎么做?

【问题讨论】:

    标签: aiohttp pytest-aiohttp


    【解决方案1】:

    这个问题有很多不同的解决方案,我认为最简单的方法是使用 aioresponses lib。 (https://github.com/pnuckowski/aioresponses)

    但这只有在您只使用没有 aiohttp.web.Application 的 ClientSession 时才能正常工作。如果您使用 CS 作为 aiohttp.web.Application 的一部分,您将破坏应用程序 test_client (pytest-aiohttp)。

    另请参阅此问题How to mock aiohttp.client.ClientSession.get async context manager。那里有一些有用的例子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 2013-11-02
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2017-06-01
      相关资源
      最近更新 更多