From 1da62a65d9b28306c3be7ad603b2721374ce7d13 Mon Sep 17 00:00:00 2001 From: colin Date: Sun, 24 May 2015 09:59:35 -0400 Subject: [PATCH] fix contextlib.closing bug for sessions where content is not consumed (issue #2593) --- AUTHORS.rst | 1 + requests/models.py | 3 +++ test_requests.py | 10 ++++++++++ 3 files changed, 14 insertions(+) diff --git a/AUTHORS.rst b/AUTHORS.rst index b81910862b..5ac39e4bed 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -158,3 +158,4 @@ Patches and Suggestions - Ulrich Petri (`@ulope `_) - Muhammad Yasoob Ullah Khalid (`@yasoob `_) - Paul van der Linden (`@pvanderlinden `_) +- Colin Dickson (`@colindickson `_) diff --git a/requests/models.py b/requests/models.py index ccaf5968fa..7ab21f78cb 100644 --- a/requests/models.py +++ b/requests/models.py @@ -842,4 +842,7 @@ def close(self): *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 cad8c055c8..cf93c48a66 100755 --- a/test_requests.py +++ b/test_requests.py @@ -9,6 +9,7 @@ import pickle import unittest import collections +import contextlib import io import requests @@ -1060,6 +1061,15 @@ def test_response_iter_lines(self): next(it) assert len(list(it)) == 3 + def test_unconsumed_session_response_closes_connection(self): + s = requests.session() + + with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response: + pass + + self.assertEqual(response._content_consumed, False) + self.assertTrue(response.raw.closed, True) + @pytest.mark.xfail def test_response_iter_lines_reentrant(self): """Response.iter_lines() is not reentrant safe"""