mcr*_*n18 14 python-asyncio aiohttp pytest-aiohttp
我正在使用 aiohttp 发出异步请求,我想测试我的代码。我想模拟 aiohttp.ClientSession 发送的请求。我正在寻找类似于响应处理requestslib模拟的方式。
我如何模拟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"}
Run Code Online (Sandbox Code Playgroud)
编辑
我在几个项目中使用了https://github.com/pnuckowski/aioresponses,它非常适合我的需求。
小智 16
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
Run Code Online (Sandbox Code Playgroud)
@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')
Run Code Online (Sandbox Code Playgroud)
自从我发布这个问题以来,我已经使用这个库来模拟 aiohttp 请求:https : //github.com/pnuckowski/aioresponses,它非常适合我的需求。
| 归档时间: |
|
| 查看次数: |
4794 次 |
| 最近记录: |