Skip to content

Commit 1fc7425

Browse files
neutrinocerosbluetech
authored andcommitted
Change to be specific to urllib
1 parent ccac326 commit 1fc7425

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

src/_pytest/_code/code.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,10 +700,21 @@ def getrepr(
700700
return fmt.repr_excinfo(self)
701701

702702
def _stringify_exception(self, exc: BaseException) -> str:
703+
try:
704+
notes = getattr(exc, "__notes__", [])
705+
except KeyError:
706+
# Workaround for https://github.com/python/cpython/issues/98778 on
707+
# Python <= 3.9, and some 3.10 and 3.11 patch versions.
708+
HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
709+
if sys.version_info[:2] <= (3, 11) and isinstance(exc, HTTPError):
710+
notes = []
711+
else:
712+
raise
713+
703714
return "\n".join(
704715
[
705716
str(exc),
706-
*safe_getattr(exc, "__notes__", []),
717+
*notes,
707718
]
708719
)
709720

testing/acceptance_test.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,11 +1450,3 @@ def my_fixture(self, request):
14501450
raise AssertionError(
14511451
f"pytest command failed:\n{exc.stdout=!s}\n{exc.stderr=!s}"
14521452
) from exc
1453-
1454-
1455-
def test_issue_11872() -> None:
1456-
# see https://github.com/pytest-dev/pytest/issues/11872
1457-
from urllib.error import HTTPError
1458-
1459-
with pytest.raises(HTTPError, match="Not Found"):
1460-
raise HTTPError(code=404, msg="Not Found", fp=None, hdrs=None, url="") # type: ignore [arg-type]

testing/python/raises.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,16 @@ class NotAnException:
302302
with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]
303303
pass # pragma: no cover
304304
assert "must be a BaseException type, not str" in str(excinfo.value)
305+
306+
def test_issue_11872(self) -> None:
307+
"""Regression test for #11872.
308+
309+
urllib.error.HTTPError on Python<=3.9 raises KeyError instead of
310+
AttributeError on invalid attribute access.
311+
312+
https://github.com/python/cpython/issues/98778
313+
"""
314+
from urllib.error import HTTPError
315+
316+
with pytest.raises(HTTPError, match="Not Found"):
317+
raise HTTPError(code=404, msg="Not Found", fp=None, hdrs=None, url="") # type: ignore [arg-type]

0 commit comments

Comments
 (0)