diff --git a/AUTHORS.rst b/AUTHORS.rst index 6bbddfde..4395b3b2 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -121,3 +121,5 @@ Patches and Suggestions - Vinod Chandru - Johnny Goodnow - Denis Ryzhkov +- Wilfred Hughes @dontYetKnow +- Dmitry Medvinsky diff --git a/requests/exceptions.py b/requests/exceptions.py index 6759af56..c0588f6a 100644 --- a/requests/exceptions.py +++ b/requests/exceptions.py @@ -16,7 +16,11 @@ class RequestException(RuntimeError): class HTTPError(RequestException): """An HTTP error occurred.""" - response = None + + def __init__(self, *args, **kwargs): + """ Initializes HTTPError with optional `response` object. """ + self.response = kwargs.pop('response', None) + super(HTTPError, self).__init__(*args, **kwargs) class ConnectionError(RequestException): diff --git a/requests/models.py b/requests/models.py index faa0cbe4..3d27d0c5 100644 --- a/requests/models.py +++ b/requests/models.py @@ -657,9 +657,7 @@ class Response(object): http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: - http_error = HTTPError(http_error_msg) - http_error.response = self - raise http_error + raise HTTPError(http_error_msg, response=self) def close(self): return self.raw.release_conn() diff --git a/test_requests.py b/test_requests.py index c497f599..e40d44f0 100644 --- a/test_requests.py +++ b/test_requests.py @@ -366,5 +366,36 @@ class RequestsTestCase(unittest.TestCase): r = requests.Request(url=HTTPBIN) self.assertRaises(ValueError, requests.Session().send, r) + def test_can_specify_retries(self): + # monkey patch urlopen + from requests.packages.urllib3.poolmanager import HTTPConnectionPool + old_urlopen = HTTPConnectionPool.urlopen + + max_retries_used = [] + def urlopen(*args, **kwargs): + """Save what value we used for retries each time we call urlopen.""" + max_retries_used.append(kwargs.get('retries')) + return old_urlopen(*args, **kwargs) + + HTTPConnectionPool.urlopen = urlopen + + # do the request and check that max_retries was passed through + requests.get(httpbin('get'), max_retries=5) + self.assertEqual(max_retries_used, [5]) + + # undo monkey patch + HTTPConnectionPool.urlopen = old_urlopen + + def test_http_error(self): + error = requests.exceptions.HTTPError() + self.assertEqual(error.response, None) + response = requests.Response() + error = requests.exceptions.HTTPError(response=response) + self.assertEqual(error.response, response) + error = requests.exceptions.HTTPError('message', response=response) + self.assertEqual(str(error), 'message') + self.assertEqual(error.response, response) + + if __name__ == '__main__': unittest.main()