我想从 aiohttp.ClientSession.get 方法模拟 json() 协程。它看起来返回一个异步生成器对象,这是我对如何在我的示例中模拟感到困惑的地方。这是我的代码:
async def get_access_token():
async with aiohttp.ClientSession(auth=auth_credentials) as client:
async with client.get(auth_path, params={'grant_type': 'client_credentials'}) as auth_response:
assert auth_response.status == 200
auth_json = await auth_response.json()
return auth_json['access_token']
这是我模拟 get 方法的测试用例:
json_data = [{
'access_token': 'HSG9hsf328bJSWO82sl',
'expires_in': 86399,
'token_type': 'bearer'
}]
class AsyncMock:
async def __aenter__(self):
return self
async def __aexit__(self, *error_info):
return self
@pytest.mark.asyncio
async def test_wow_api_invalid_credentials(monkeypatch, mocker):
def mock_client_get(self, auth_path, params):
mock_response = AsyncMock()
mock_response.status = 200
mock_response.json = mocker.MagicMock(return_value=json_data)
return mock_response
monkeypatch.setattr('wow.aiohttp.ClientSession.get', mock_client_get)
result = await wow.get_access_token()
assert result == 'HSG9hsf328bJSWO82sl'
我认为问题可能是 mock_response.json() 不可等待。在我的示例中,我无法从非异步函数调用 await,所以我对如何做到这一点感到困惑。我想将测试库保持在最低限度,即 pytest 和 pytest-asyncio 用于学习体验,并减少对 3rd 方库的依赖。