Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: fix an edge case where ExceptionInfo._stringify_exception could crash pytest.raises #11879

Merged
merged 7 commits into from Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -93,6 +93,7 @@ Christopher Dignam
Christopher Gilling
Claire Cecil
Claudio Madotto
Clément M.T. Robert
CrazyMerlyn
Cristian Vera
Cyrus Maden
Expand Down
1 change: 1 addition & 0 deletions changelog/11879.bugfix.rst
@@ -0,0 +1 @@
Fix an edge case where ``ExceptionInfo._stringify_exception`` could crash :func:`pytest.raises`.
13 changes: 12 additions & 1 deletion src/_pytest/_code/code.py
Expand Up @@ -699,10 +699,21 @@
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

Check warning on line 711 in src/_pytest/_code/code.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_code/code.py#L711

Added line #L711 was not covered by tests

return "\n".join(
[
str(exc),
*getattr(exc, "__notes__", []),
*notes,
]
)

Expand Down
13 changes: 13 additions & 0 deletions testing/python/raises.py
Expand Up @@ -302,3 +302,16 @@ class NotAnException:
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]