Skip to content

Commit 9d37ae0

Browse files
bpo-36918: Fix "Exception ignored in" in test_urllib (GH-13996)
Mock the HTTPConnection.close() method in a few unit tests to avoid logging "Exception ignored in: ..." messages. (cherry picked from commit eb976e4) Co-authored-by: Victor Stinner <[email protected]>
1 parent 3ba2107 commit 9d37ae0

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

‎Lib/test/test_urllib.py‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def FancyURLopener():
5656
return urllib.request.FancyURLopener()
5757

5858

59-
def fakehttp(fakedata):
59+
def fakehttp(fakedata, mock_close=False):
6060
class FakeSocket(io.BytesIO):
6161
io_refs = 1
6262

@@ -90,15 +90,24 @@ class FakeHTTPConnection(http.client.HTTPConnection):
9090
def connect(self):
9191
self.sock = FakeSocket(self.fakedata)
9292
type(self).fakesock = self.sock
93+
94+
if mock_close:
95+
# bpo-36918: HTTPConnection destructor calls close() which calls
96+
# flush(). Problem: flush() calls self.fp.flush() which raises
97+
# "ValueError: I/O operation on closed file" which is logged as an
98+
# "Exception ignored in". Override close() to silence this error.
99+
def close(self):
100+
pass
93101
FakeHTTPConnection.fakedata = fakedata
94102

95103
return FakeHTTPConnection
96104

97105

98106
class FakeHTTPMixin(object):
99-
def fakehttp(self, fakedata):
107+
def fakehttp(self, fakedata, mock_close=False):
108+
fake_http_class = fakehttp(fakedata, mock_close=mock_close)
100109
self._connection_class = http.client.HTTPConnection
101-
http.client.HTTPConnection = fakehttp(fakedata)
110+
http.client.HTTPConnection = fake_http_class
102111

103112
def unfakehttp(self):
104113
http.client.HTTPConnection = self._connection_class
@@ -400,7 +409,7 @@ def test_read_bogus(self):
400409
Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
401410
Connection: close
402411
Content-Type: text/html; charset=iso-8859-1
403-
''')
412+
''', mock_close=True)
404413
try:
405414
self.assertRaises(OSError, urlopen, "http://python.org/")
406415
finally:
@@ -414,7 +423,7 @@ def test_invalid_redirect(self):
414423
Location: file://guidocomputer.athome.com:/python/license
415424
Connection: close
416425
Content-Type: text/html; charset=iso-8859-1
417-
''')
426+
''', mock_close=True)
418427
try:
419428
msg = "Redirection to url 'file:"
420429
with self.assertRaisesRegex(urllib.error.HTTPError, msg):
@@ -429,7 +438,7 @@ def test_redirect_limit_independent(self):
429438
self.fakehttp(b'''HTTP/1.1 302 Found
430439
Location: file://guidocomputer.athome.com:/python/license
431440
Connection: close
432-
''')
441+
''', mock_close=True)
433442
try:
434443
self.assertRaises(urllib.error.HTTPError, urlopen,
435444
"http://something")

0 commit comments

Comments
 (0)