Skip to content

Commit d6872e3

Browse files
committed
Accept generic ExceptionGroups for raises
Closes #13115
1 parent b89c1ce commit d6872e3

File tree

4 files changed

+69
-5
lines changed

4 files changed

+69
-5
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,7 @@ Tim Hoffmann
435435
Tim Strazny
436436
TJ Bruno
437437
Tobias Diez
438+
Tobias Petersen
438439
Tom Dalton
439440
Tom Viner
440441
Tomáš Gavenčiak

changelog/13115.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allows supplying ``ExceptionGroup[Exception]`` and ``BaseExceptionGroup[BaseException]`` to ``pytest.raises`` to keep full typing on ExcInfo.

src/_pytest/python_api.py

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212
from numbers import Complex
1313
import pprint
1414
import re
15+
import sys
1516
from types import TracebackType
1617
from typing import Any
1718
from typing import cast
1819
from typing import final
20+
from typing import get_args
21+
from typing import get_origin
1922
from typing import overload
2023
from typing import TYPE_CHECKING
2124
from typing import TypeVar
@@ -24,6 +27,10 @@
2427
from _pytest.outcomes import fail
2528

2629

30+
if sys.version_info < (3, 11):
31+
from exceptiongroup import BaseExceptionGroup
32+
from exceptiongroup import ExceptionGroup
33+
2734
if TYPE_CHECKING:
2835
from numpy import ndarray
2936

@@ -954,15 +961,43 @@ def raises(
954961
f"Raising exceptions is already understood as failing the test, so you don't need "
955962
f"any special code to say 'this should never raise an exception'."
956963
)
964+
965+
expected_exceptions: tuple[type[E], ...]
966+
origin_exc: type[E] | None = get_origin(expected_exception)
957967
if isinstance(expected_exception, type):
958-
expected_exceptions: tuple[type[E], ...] = (expected_exception,)
968+
expected_exceptions = (expected_exception,)
969+
elif origin_exc and issubclass(origin_exc, BaseExceptionGroup):
970+
expected_exceptions = (cast(type[E], expected_exception),)
959971
else:
960972
expected_exceptions = expected_exception
961-
for exc in expected_exceptions:
962-
if not isinstance(exc, type) or not issubclass(exc, BaseException):
973+
974+
def validate_exc(exc: type[E]) -> type[E]:
975+
origin_exc: type[E] | None = get_origin(exc)
976+
if origin_exc and issubclass(origin_exc, BaseExceptionGroup):
977+
exc_type = get_args(exc)[0]
978+
if issubclass(origin_exc, ExceptionGroup) and exc_type is Exception:
979+
return cast(type[E], origin_exc)
980+
elif (
981+
issubclass(origin_exc, BaseExceptionGroup) and exc_type is BaseException
982+
):
983+
return cast(type[E], origin_exc)
984+
else:
985+
raise ValueError(
986+
f"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseExeption]` "
987+
f"are accepted as generic types but got `{exc}`. "
988+
f"As `raises` will catch all instances of the specified group regardless of the "
989+
f"generic argument specific nested exceptions has to be checked "
990+
f"with `ExceptionInfo.group_contains()`"
991+
)
992+
993+
elif not isinstance(exc, type) or not issubclass(exc, BaseException):
963994
msg = "expected exception must be a BaseException type, not {}" # type: ignore[unreachable]
964995
not_a = exc.__name__ if isinstance(exc, type) else type(exc).__name__
965996
raise TypeError(msg.format(not_a))
997+
else:
998+
return exc
999+
1000+
expected_exceptions = tuple(validate_exc(exc) for exc in expected_exceptions)
9661001

9671002
message = f"DID NOT RAISE {expected_exception}"
9681003

@@ -973,14 +1008,14 @@ def raises(
9731008
msg += ", ".join(sorted(kwargs))
9741009
msg += "\nUse context-manager form instead?"
9751010
raise TypeError(msg)
976-
return RaisesContext(expected_exception, message, match)
1011+
return RaisesContext(expected_exceptions, message, match)
9771012
else:
9781013
func = args[0]
9791014
if not callable(func):
9801015
raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
9811016
try:
9821017
func(*args[1:], **kwargs)
983-
except expected_exception as e:
1018+
except expected_exceptions as e:
9841019
return _pytest._code.ExceptionInfo.from_exception(e)
9851020
fail(message)
9861021

testing/code/test_excinfo.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from _pytest._code.code import TracebackStyle
3232

3333
if sys.version_info < (3, 11):
34+
from exceptiongroup import BaseExceptionGroup
3435
from exceptiongroup import ExceptionGroup
3536

3637

@@ -453,6 +454,32 @@ def test_division_zero():
453454
result.stdout.re_match_lines([r".*__tracebackhide__ = True.*", *match])
454455

455456

457+
def test_raises_accepts_generic_group() -> None:
458+
exc_group = ExceptionGroup("", [RuntimeError()])
459+
with pytest.raises(ExceptionGroup[Exception]) as exc_info:
460+
raise exc_group
461+
assert exc_info.group_contains(RuntimeError)
462+
463+
464+
def test_raises_accepts_generic_base_group() -> None:
465+
exc_group = ExceptionGroup("", [RuntimeError()])
466+
with pytest.raises(BaseExceptionGroup[BaseException]) as exc_info:
467+
raise exc_group
468+
assert exc_info.group_contains(RuntimeError)
469+
470+
471+
def test_raises_rejects_specific_generic_group() -> None:
472+
with pytest.raises(ValueError):
473+
pytest.raises(ExceptionGroup[RuntimeError])
474+
475+
476+
def test_raises_accepts_generic_group_in_tuple() -> None:
477+
exc_group = ExceptionGroup("", [RuntimeError()])
478+
with pytest.raises((ValueError, ExceptionGroup[Exception])) as exc_info:
479+
raise exc_group
480+
assert exc_info.group_contains(RuntimeError)
481+
482+
456483
class TestGroupContains:
457484
def test_contains_exception_type(self) -> None:
458485
exc_group = ExceptionGroup("", [RuntimeError()])

0 commit comments

Comments
 (0)