]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-98778: Update HTTPError to initialize properly even if fp is None (gh-99966)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 8 Dec 2022 04:17:23 +0000 (20:17 -0800)
committerGitHub <noreply@github.com>
Thu, 8 Dec 2022 04:17:23 +0000 (20:17 -0800)
(cherry picked from commit dc8a86893df37e137cfe992e95e7d66cd68e9eaf)

Co-authored-by: Dong-hee Na <donghee.na@python.org>
Lib/test/test_urllib2.py
Lib/urllib/error.py
Misc/NEWS.d/next/Library/2022-12-03-20-06-16.gh-issue-98778.t5U9uc.rst [new file with mode: 0644]

index 46a0ab1d83e60eaaa049f16f665b8c0a1e2857d4..db92ba56c34f80c56392c0f165a2a7b936725127 100644 (file)
@@ -1825,6 +1825,10 @@ class MiscTests(unittest.TestCase):
         expected_errmsg = '<HTTPError %s: %r>' % (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',
index 8cd901f13f8e49b4f964b183e89e2009b9beb182..feec0e7f848e463ed22f03785373ed90f3aff561 100644 (file)
@@ -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)
diff --git a/Misc/NEWS.d/next/Library/2022-12-03-20-06-16.gh-issue-98778.t5U9uc.rst b/Misc/NEWS.d/next/Library/2022-12-03-20-06-16.gh-issue-98778.t5U9uc.rst
new file mode 100644 (file)
index 0000000..b1c170d
--- /dev/null
@@ -0,0 +1,2 @@
+Update :exc:`~urllib.error.HTTPError` to be initialized properly, even if
+the ``fp`` is ``None``. Patch by Dong-hee Na.