Add ability to pass `response` to `HTTPError()`
authorDmitry Medvinsky <me@dmedvinsky.name>
Fri, 1 Mar 2013 08:43:39 +0000 (12:43 +0400)
committerDmitry Medvinsky <me@dmedvinsky.name>
Sun, 3 Mar 2013 06:05:42 +0000 (10:05 +0400)
Just a little refactoring, but it seems nicer to me to be able to pass
the response when constructing the `HTTPError` instance instead of
constructing it and then changing the member variable.

AUTHORS.rst
requests/exceptions.py
requests/models.py
test_requests.py

index 9963923..4395b3b 100644 (file)
@@ -122,3 +122,4 @@ Patches and Suggestions
 - Johnny Goodnow <j.goodnow29@gmail.com>
 - Denis Ryzhkov <denisr@denisr.com>
 - Wilfred Hughes <me@wilfred.me.uk> @dontYetKnow
+- Dmitry Medvinsky <me@dmedvinsky.name>
index 6759af5..c0588f6 100644 (file)
@@ -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):
index faa0cbe..3d27d0c 100644 (file)
@@ -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()
index 0a2e643..e40d44f 100644 (file)
@@ -385,7 +385,17 @@ class RequestsTestCase(unittest.TestCase):
 
         # 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()