def _handle_bad_response(self, response: Response): """Convert the error into an understandable client exception.""" exception_class = self._get_exception_class(response.get_status_code()) raise exception_class( message= (f"{response.get_status_code()} Error: {response.get_status_reason()} " f"for url: {response.get_requested_url()}"), status_code=response.get_status_code(), info=response.get_raw_data(), )
def get_request_data(response: Response) -> Optional[XmlType]: if response.get_raw_data() == "": return None try: xml_element = ElementTree.fromstring(response.get_raw_data()) except ElementTree.ParseError as error: raise ResponseParseError( f"Unable to parse response data to xml. data='{response.get_raw_data()}'" ) from error return xml_element
def get_request_data(response: Response) -> Optional[JsonType]: if response.get_raw_data() == "": return None try: response_json = response.get_json() except JSONDecodeError as error: raise ResponseParseError( f"Unable to decode response data to json. data='{response.get_raw_data()}'" ) from error return response_json
def get_exception(response: Response) -> exceptions.APIRequestError: status_code = response.get_status_code() exception_class = exceptions.UnexpectedError if 300 <= status_code < 400: exception_class = exceptions.RedirectionError elif 400 <= status_code < 500: exception_class = exceptions.ClientError elif 500 <= status_code < 600: exception_class = exceptions.ServerError return exception_class( message=(f"{status_code} Error: {response.get_status_reason()} " f"for url: {response.get_requested_url()}"), status_code=status_code, info=response.get_raw_data(), )
def get_exception(response: Response) -> APIRequestError: if response.get_raw_data() == "": return ErrorHandler.get_exception(response) key_fields = ("errorCode", "error_code") error_code = None try: data = response.get_json() except JSONDecodeError: return ErrorHandler.get_exception(response) for key_field in key_fields: try: error_code = int(data.get(key_field)) if error_code is not None: break except (ValueError, TypeError): pass exception_class = ERROR_CODES_WITH_EXCEPTIONS_MAP.get(error_code) if not exception_class: return ErrorHandler.get_exception(response) return exception_class()
class TestResponse: """Simple tests for 100% coverage - testing abstract class.""" response = Response() @pytest.mark.parametrize( "method", [ response.get_original, response.get_status_code, response.get_raw_data, response.get_json, response.get_status_reason, response.get_requested_url, ], ) def test_needs_implementation(self, method): with pytest.raises(NotImplementedError): method()
def get_request_data(response: Response) -> requests.Response: return response.get_original()
def _check_response(self, response: Response): """Raise a custom exception if the response is not OK.""" status_code = response.get_status_code() if status_code < 200 or status_code >= 300: self._handle_bad_response(response)