首页 > 解决方案 > 如何模拟 aiohttp 客户端会话超时

问题描述

我有以下获取请求的实现

def function():
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(
                    url="http://test-api/v1/radiation",
                    allow_redirects=False,
                    params={
                        "alpha": "a",
                        "beta": "b",
                    },
                    timeout=5
            ) as response:
                return await self.json_response(
                    results=await response.json(),
                    status=response.status
                )
        except ClientError as e:
            return await self.json_response(
                results={"100": "error"},
                status=408
            )

我嘲笑aiohttp.ClientSession.get如下

 def r_val():
     sleep(10)
     return CoroutineMock(side_effect=[{}])

 with asynctest.patch("aiohttp.ClientSession.get") as mocked_session:
        mock = mocked_session.return_value.__aenter__.return_value
        mock.json = r_val()
        mock.status = 200

如何在这里模拟超时场景?

标签: pythonmockingpytestpatch

解决方案


推荐阅读