From dc8a86893df37e137cfe992e95e7d66cd68e9eaf Mon Sep 17 00:00:00 2001 From: Dong-hee Na Date: Thu, 8 Dec 2022 11:20:34 +0900 Subject: gh-98778: Update HTTPError to initialize properly even if fp is None (gh-99966) --- Lib/test/test_urllib2.py | 4 ++++ Lib/urllib/error.py | 11 ++++------- 2 files changed, 8 insertions(+), 7 deletions(-) (limited to 'Lib') diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 28f88412fd..498c0382d2 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -1824,6 +1824,10 @@ class MiscTests(unittest.TestCase): expected_errmsg = '' % (err.code, err.msg) self.assertEqual(repr(err), expected_errmsg) + def test_gh_98778(self): + x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + self.assertEqual(getattr(x, "__notes__", ()), ()) + def test_parse_proxy(self): parse_proxy_test_cases = [ ('proxy.example.com', diff --git a/Lib/urllib/error.py b/Lib/urllib/error.py index 8cd901f13f..feec0e7f84 100644 --- a/Lib/urllib/error.py +++ b/Lib/urllib/error.py @@ -10,7 +10,7 @@ responses, with a status code, headers, and a body. In some contexts, an application may want to handle an exception like a regular response. """ - +import io import urllib.response __all__ = ['URLError', 'HTTPError', 'ContentTooShortError'] @@ -42,12 +42,9 @@ class HTTPError(URLError, urllib.response.addinfourl): self.hdrs = hdrs self.fp = fp self.filename = url - # The addinfourl classes depend on fp being a valid file - # object. In some cases, the HTTPError may not have a valid - # file object. If this happens, the simplest workaround is to - # not initialize the base classes. - if fp is not None: - self.__super_init(fp, hdrs, url, code) + if fp is None: + fp = io.StringIO() + self.__super_init(fp, hdrs, url, code) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) -- cgit v1.2.1