我试图模拟对外部URL的单个请求,但在文档中只存在内部请求的示例(以'/‘开头),不可能在当前版本的aiohttp上添加不以’/‘开头的路由器。我使用的是pytest和pytest-aiohttp,以下是请求代码的示例:
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
return resp.status, (await resp.text())
async def main():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())我想要做的断言非常简单,比如检查状态代码、头文件和内容。
发布于 2019-02-12 17:02:41
您可以(使用asynctest.patch)修补您的ClientSession。但在这种情况下,您需要使用.status, async .text() (async .json()), etc.方法和属性实现简单的ResponseContextManager。
发布于 2020-12-23 10:08:51
在你的评论中(在你的问题下面),你说你实际上是想模拟aiohttp响应。为此,我一直在使用第三方库aioresponses:https://github.com/pnuckowski/aioresponses
我将其用于集成测试,在那里它似乎比直接模拟或修补aiohttp方法更好。
我把它做成了一个最小的灯具,如下所示:
@pytest.fixture
def aiohttp_mock():
with aioresponses() as aioresponse_mock:
yield aioresponse_mock然后我可以像调用aiohttp客户端/会话一样调用它:aiohttp_mock.get(...)
来自未来的编辑:我们实际上回到了模拟aiohttp方法,因为aioresponses目前缺乏验证调用中使用的参数的能力。我们决定验证args是我们的一项要求。
https://stackoverflow.com/questions/54632639
复制相似问题