我正在使用aiohttp发出异步请求,并且我想测试我的代码。我想模拟aiohttp.ClientSession发送的请求。我正在寻找类似于responses处理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"}
答案 0 :(得分:1)
自从我发布了这个问题以来,我就使用该库来模拟aiohttp请求:https://github.com/pnuckowski/aioresponse,它可以很好地满足我的需求。
答案 1 :(得分:0)
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
@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')