From: Victor Stinner <victor.stinner@haypocalc.com>
Date: Fri, 17 Jun 2011 12:01:18 +0000 (+0200)
Subject: Issue #12133: fix a ResourceWarning in urllib.request
X-Git-Tag: v3.2.2rc1~234
X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=a4c45d73cf6eeb8ede6ee701c0372d7e45dc24f2;p=python

Issue #12133: fix a ResourceWarning in urllib.request

AbstractHTTPHandler.do_open() of urllib.request closes the HTTP connection if
its getresponse() method fails with a socket error. Patch written by Ezio
Melotti.
---

diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
index e9fb2fc271..58ef83611d 100644
--- a/Lib/test/test_urllib2.py
+++ b/Lib/test/test_urllib2.py
@@ -317,6 +317,9 @@ class MockHTTPClass:
     def getresponse(self):
         return MockHTTPResponse(MockFile(), {}, 200, "OK")
 
+    def close(self):
+        pass
+
 class MockHandler:
     # useful for testing handler machinery
     # see add_ordered_mock_handlers() docstring
diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py
index 5325d62c40..35fd1f136f 100644
--- a/Lib/urllib/request.py
+++ b/Lib/urllib/request.py
@@ -1137,6 +1137,8 @@ class AbstractHTTPHandler(BaseHandler):
             r = h.getresponse()  # an HTTPResponse instance
         except socket.error as err:
             raise URLError(err)
+        finally:
+            h.close()
 
         r.url = req.get_full_url()
         # This line replaces the .msg attribute of the HTTPResponse
diff --git a/Misc/NEWS b/Misc/NEWS
index 75d10827ca..6cc0f03637 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -25,6 +25,10 @@ Core and Builtins
 Library
 -------
 
+- Issue #12133: AbstractHTTPHandler.do_open() of urllib.request closes the HTTP
+  connection if its getresponse() method fails with a socket error. Patch
+  written by Ezio Melotti.
+
 - Issue #9284: Allow inspect.findsource() to find the source of doctest
   functions.