diff --git a/requests/models.py b/requests/models.py index ccaf5968..7ab21f78 100644 --- a/requests/models.py +++ b/requests/models.py @@ -842,4 +842,7 @@ class Response(object): *Note: Should not normally need to be called explicitly.* """ + if not self._content_consumed: + return self.raw.close() + return self.raw.release_conn() diff --git a/test_requests.py b/test_requests.py index cad8c055..92cdb154 100755 --- a/test_requests.py +++ b/test_requests.py @@ -9,6 +9,8 @@ import os import pickle import unittest import collections +import contextlib +import random import io import requests @@ -1252,6 +1254,27 @@ class TestCaseInsensitiveDict(unittest.TestCase): assert frozenset(cid) == keyset +class TestSessionContextClosing(unittest.TestCase): + + def _perform_session_without_consuming(self): + session = requests.Session() + + urls = [ + 'http://reddit.com', + 'http://github.com', + 'http://bitbucket.org', + ] + + for _ in range(25): + with contextlib.closing(session.get(random.choice(urls), stream=True)) as r: + pass + + return "OK" + + def test_stream_session_content_not_consumed(self): + self.assertEqual(self._perform_session_without_consuming(), "OK") + + class UtilsTestCase(unittest.TestCase): def test_super_len_io_streams(self):