Skip to content

Commit 73371a0

Browse files
authored
Merge pull request #11894 from pytest-dev/backport-11879-to-8.0.x
[8.0.x] BUG: fix an edge case where ExceptionInfo._stringify_exception could crash pytest.raises
2 parents 3e48ef6 + eb698a6 commit 73371a0

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-1
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ Christopher Dignam
9393
Christopher Gilling
9494
Claire Cecil
9595
Claudio Madotto
96+
Clément M.T. Robert
9697
CrazyMerlyn
9798
Cristian Vera
9899
Cyrus Maden

changelog/11879.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix an edge case where ``ExceptionInfo._stringify_exception`` could crash :func:`pytest.raises`.

src/_pytest/_code/code.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -698,10 +698,21 @@ def getrepr(
698698
return fmt.repr_excinfo(self)
699699

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

testing/python/raises.py

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

0 commit comments

Comments
 (0)