Change to be specific to urllib

This commit is contained in:
Clément Robert 2024-01-29 09:26:15 +01:00 committed by Ran Benita
parent ccac3261ea
commit 1fc7425134
3 changed files with 25 additions and 9 deletions

View File

@ -700,10 +700,21 @@ class ExceptionInfo(Generic[E]):
return fmt.repr_excinfo(self)
def _stringify_exception(self, exc: BaseException) -> str:
try:
notes = getattr(exc, "__notes__", [])
except KeyError:
# Workaround for https://github.com/python/cpython/issues/98778 on
# Python <= 3.9, and some 3.10 and 3.11 patch versions.
HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
if sys.version_info[:2] <= (3, 11) and isinstance(exc, HTTPError):
notes = []
else:
raise
return "\n".join(
[
str(exc),
*safe_getattr(exc, "__notes__", []),
*notes,
]
)

View File

@ -1450,11 +1450,3 @@ def test_issue_9765(pytester: Pytester) -> None:
raise AssertionError(
f"pytest command failed:\n{exc.stdout=!s}\n{exc.stderr=!s}"
) from exc
def test_issue_11872() -> None:
# see https://github.com/pytest-dev/pytest/issues/11872
from urllib.error import HTTPError
with pytest.raises(HTTPError, match="Not Found"):
raise HTTPError(code=404, msg="Not Found", fp=None, hdrs=None, url="") # type: ignore [arg-type]

View File

@ -302,3 +302,16 @@ class TestRaises:
with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]
pass # pragma: no cover
assert "must be a BaseException type, not str" in str(excinfo.value)
def test_issue_11872(self) -> None:
"""Regression test for #11872.
urllib.error.HTTPError on Python<=3.9 raises KeyError instead of
AttributeError on invalid attribute access.
https://github.com/python/cpython/issues/98778
"""
from urllib.error import HTTPError
with pytest.raises(HTTPError, match="Not Found"):
raise HTTPError(code=404, msg="Not Found", fp=None, hdrs=None, url="") # type: ignore [arg-type]