fix iteration on null responses in safe_mode
authorOri Livneh <ori.livneh@gmail.com>
Fri, 23 Dec 2011 02:10:43 +0000 (21:10 -0500)
committerOri Livneh <ori.livneh@gmail.com>
Fri, 23 Dec 2011 02:10:43 +0000 (21:10 -0500)
requests/models.py
test_requests.py

index 09ea87d975c691d4d986d1b37ae8659e063f5cbf..a51ee7001065ac367990ed98ad3a8acaa20e26a2 100644 (file)
@@ -559,11 +559,13 @@ class Response(object):
             )
 
         def generate():
-            while 1:
-                chunk = self.raw.read(chunk_size)
-                if not chunk:
-                    break
-                yield chunk
+            # self.raw can be None if we're in safe_mode and the request failed
+            if self.raw is not None:
+                while 1:
+                    chunk = self.raw.read(chunk_size)
+                    if not chunk:
+                        break
+                    yield chunk
             self._content_consumed = True
 
         gen = generate()
@@ -597,23 +599,24 @@ class Response(object):
             )
 
         def generate():
-            chunk = []
+            if self.raw is not None:
+                chunk = []
 
-            while 1:
-                c = self.raw.read(1)
-                if not c:
-                    break
+                while 1:
+                    c = self.raw.read(1)
+                    if not c:
+                        break
 
-                if c in newlines:
-                    yield ''.join(chunk)
-                    chunk = []
-                else:
-                    chunk.append(c)
+                    if c in newlines:
+                        yield ''.join(chunk)
+                        chunk = []
+                    else:
+                        chunk.append(c)
 
-            # Yield the remainder, in case the response
-            # did not terminate with a newline
-            if chunk:
-                yield ''.join(chunk)
+                # Yield the remainder, in case the response
+                # did not terminate with a newline
+                if chunk:
+                    yield ''.join(chunk)
 
             self._content_consumed = True
 
index e547aa64df5f8a6dc3ca433964610839fb72d839..2543103f2879f3cf81cffccfb4613c67510e0e58 100755 (executable)
@@ -619,6 +619,17 @@ class RequestsTestSuite(unittest.TestCase):
         lines = '\n'.join(r.iter_lines())
         self.assertEqual(lines, quote)
 
+    def test_null_response(self):
+
+        # Safe mode creates empty responses for failed requests.
+
+        # Iterating on these responses should produce empty sequences
+        r = requests.get('http://_/', config=dict(safe_mode=True))
+        self.assertEquals(list(r.iter_lines()), [])
+
+        r = requests.get('http://_/', config=dict(safe_mode=True))
+        self.assertEquals(list(r.iter_content()), [])
+
     def test_timeout(self):
 
         # When not in safe mode, should raise Timeout exception