async def async_request_tsa_response(self, req: tsp.TimeStampReq) \ -> tsp.TimeStampResp: session = await self.get_session() cl_timeout = aiohttp.ClientTimeout(total=self.timeout) headers = await self.async_request_headers() try: async with session.post(url=self.url, headers=headers, data=req.dump(), auth=self.auth, raise_for_status=True, timeout=cl_timeout) as response: response_data = await response.read() ct = response.headers.get('Content-Type') if ct != 'application/timestamp-reply': msg = ( f'Bad content type. Expected ' f'application/timestamp-reply,but got {ct}.' ) raise aiohttp.ContentTypeError( response.request_info, response.history, message=msg, headers=response.headers, ) except aiohttp.ClientError as e: raise TimestampRequestError( "Error while contacting timestamp service", ) from e return tsp.TimeStampResp.load(response_data)
async def test_request_content_error(self): self.auth.token_type = "type" self.auth.access_token = "token" base_url = "base_url" response = mock.MagicMock() error = aiohttp.ContentTypeError(None, None) response.json = mock.CoroutineMock(side_effect=error) session = mock.MagicMock() session.request = mock.CoroutineMock(return_value=response) self.client._get_http_session = mock.CoroutineMock( return_value=session ) self.client._get_base_url = mock.CoroutineMock(return_value=base_url) self.client._verify_response = mock.CoroutineMock() method = "method" path = "path" json = object() params = object() auth_header = self.auth.token_type + " " + self.auth.access_token expected_headers = {"Authorization": auth_header} result = await self.client._request(method, path, json=json, params=params) self.assertIsNone(result) session.request.assert_called_with(method, base_url + path, json=json, params=params, headers=expected_headers) self.client._verify_response.assert_called_with(response)
class StubResponse: real_url = "https://some.url" status = http.HTTPStatus.BAD_REQUEST headers = {} json = mock.AsyncMock(side_effect=aiohttp.ContentTypeError(None, None)) async def read(self): return "some raw body"
async def json(self) -> Any: """Return the JSON data contained in the response. Depending on what values were specified when this dummy response was created, this may raise errors. """ if not (self.is_json and self.reports_json): raise aiohttp.ContentTypeError(self.request_info, (), message='Dummy') return self._data
async def test_raise_error_from_error_map_on_json_error(self): self.assertIn(HTTPStatus.NOT_FOUND, self.client._ERROR_MAP) response = mock.MagicMock() content = "content" response.json = mock.CoroutineMock( side_effect=aiohttp.ContentTypeError(None, None) ) response.status = HTTPStatus.NOT_FOUND response.text = mock.CoroutineMock(return_value=content) with self.assertRaisesRegex( self.client._ERROR_MAP[HTTPStatus.NOT_FOUND], content): await self.client._raise_error(response)
async def test_raise_error_general_error_on_json_error(self): self.assertNotIn(HTTPStatus.TOO_MANY_REQUESTS, self.client._ERROR_MAP) response = mock.MagicMock() content = "content" response.json = mock.CoroutineMock( side_effect=aiohttp.ContentTypeError(None, None) ) response.status = HTTPStatus.TOO_MANY_REQUESTS response.text = mock.CoroutineMock(return_value=content) with self.assertRaisesRegex(SalesforceRestError, content): await self.client._raise_error(response)
async def test_generate_error_when_error_with_json(status_, expected_error): json_response = aiohttp.ContentTypeError(None, None) class StubResponse: real_url = "https://some.url" status = status_ headers = {} json = mock.AsyncMock(side_effect=json_response) async def read(self): return "some raw body" with mock.patch.object(errors, expected_error) as error: returned = await net.generate_error_response(StubResponse()) error.assert_called_once_with("https://some.url", {}, "some raw body") assert returned is error()
async def test_handle_response(nw): class MockResponse: def __init__(self, data, raise_exc=None): self.data = data self.raise_exc = raise_exc @property def status(self): return 200 async def text(self): return 'some text' async def json(self): if self.raise_exc: raise self.raise_exc return json.loads(self.data) with pytest.raises(EtherscanClientContentTypeError) as e: await nw._handle_response( MockResponse('qweasd', aiohttp.ContentTypeError('info', 'hist'))) assert e.value.status == 200 assert e.value.content == 'some text' with pytest.raises(EtherscanClientError, match='some exc'): await nw._handle_response(MockResponse('qweasd', Exception('some exc'))) with pytest.raises(EtherscanClientApiError) as e: await nw._handle_response( MockResponse( '{"status": "0", "message": "NOTOK", "result": "res"}')) assert e.value.message == 'NOTOK' assert e.value.result == 'res' with pytest.raises(EtherscanClientProxyError) as e: await nw._handle_response( MockResponse('{"error": {"code": "100", "message": "msg"}}')) assert e.value.code == '100' assert e.value.message == 'msg' assert await nw._handle_response(MockResponse('{"result": "someresult"}') ) == 'someresult'
async def mock_invalid_HTTP_response(*args, **kwargs): return (None, None, None, aiohttp.ContentTypeError(None, None))
from galaxy.api.errors import (AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, TooManyRequests, UnknownBackendResponse, UnknownError) from galaxy.http import handle_exception request_info = aiohttp.RequestInfo(URL("http://o.pl"), "GET", CIMultiDictProxy(CIMultiDict())) @pytest.mark.parametrize( "aiohttp_exception,expected_exception_type", [(asyncio.TimeoutError(), BackendTimeout), (aiohttp.ServerDisconnectedError(), BackendNotAvailable), (aiohttp.ClientConnectionError(), NetworkError), (aiohttp.ContentTypeError(request_info, ()), UnknownBackendResponse), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.UNAUTHORIZED), AuthenticationRequired), (aiohttp.ClientResponseError(request_info, (), status=HTTPStatus.FORBIDDEN), AccessDenied), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.SERVICE_UNAVAILABLE), BackendNotAvailable), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.TOO_MANY_REQUESTS), TooManyRequests), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.INTERNAL_SERVER_ERROR), BackendError), (aiohttp.ClientResponseError(
async def json(self): content_type = self.headers.get('Content-Type', '') if 'application/json' not in content_type: raise aiohttp.ContentTypeError() return json.loads(self.data)