我怎样才能模拟出 aiohttp 做出的回应.客户端会话?



我正在使用aiohttp发出异步请求,我想测试我的代码。我想模拟aiohttp发送的请求。客户端会话。我正在寻找类似于响应处理requests库嘲笑的方式。

我怎样才能模拟aiohttp.ClientSession做出的回应?

# sample method
async def get_resource(self, session):
async with aiohttp.ClientSession() as session:
response = await self.session.get("some-external-api.com/resource")
if response.status == 200:
result = await response.json()
return result
return {...}
# I want to do something like ...
aiohttp_responses.add(
method='GET', 
url="some-external-api.com/resource", 
status=200, 
json={"message": "this worked"}
)
async def test_get_resource(self):
result = await get_resource()
assert result == {"message": "this worked"}
  • 我已经通读了 aiohttp 测试文档。似乎它们涵盖了模拟对您的 Web 服务器的传入请求,但我不确定这是否有助于我模拟对传出请求的响应

编辑

我已经在一些项目中使用了 https://github.com/pnuckowski/aioresponses,它很好地满足了我的需求。

  1. 创建模拟响应
class MockResponse:
def __init__(self, text, status):
self._text = text
self.status = status
async def text(self):
return self._text
async def __aexit__(self, exc_type, exc, tb):
pass
async def __aenter__(self):
return self
  1. 使用 pytest 模拟器模拟请求
@pytest.mark.asyncio
async def test_exchange_access_token(self, mocker):
data = {}
resp = MockResponse(json.dumps(data), 200)
mocker.patch('aiohttp.ClientSession.post', return_value=resp)
resp_dict = await account_api.exchange_access_token('111')

自从我发布了这个问题以来,我就使用这个库来模拟 aiohttp 请求:https://github.com/pnuckowski/aioresponses 它很好地满足了我的需求。

  1. 创建函数,它将返回您的模拟响应
async def create_resp(status_code=200, resp_data=None):
resp = mock.AsyncMock(status_code=status_code)
resp.json.return_value = resp_data
return resp
  1. 然后在测试中使用它
@pytest.mark.asyncio
@mock.patch('ms_printers.clients.menu.aiohttp.ClientSession.get')
async def test_ok(self, mock_get):
mock_get.return_value = create_resp(resp_data={'a': 1})

最新更新