Debian Codegraph @

src/_pytest/raises.py

raw
1 from __future__ import annotations
2
3 from abc import ABC
4 from abc import abstractmethod
5 import re
6 from re import Pattern
7 import sys
8 from textwrap import indent
9 from typing import Any
10 from typing import cast
11 from typing import final
12 from typing import Generic
13 from typing import get_args
14 from typing import get_origin
15 from typing import Literal
16 from typing import overload
17 from typing import TYPE_CHECKING
18 import warnings
19
20 from _pytest._code import ExceptionInfo
21 from _pytest._code.code import stringify_exception
22 from _pytest.outcomes import fail
23 from _pytest.warning_types import PytestWarning
24
25
26 if TYPE_CHECKING:
27 from collections.abc import Callable
28 from collections.abc import Sequence
29
30 # for some reason Sphinx does not play well with 'from types import TracebackType'
31 import types
32 from typing import TypeGuard
33
34 from typing_extensions import ParamSpec
35 from typing_extensions import TypeVar
36
37 P = ParamSpec("P")
38
39 # this conditional definition is because we want to allow a TypeVar default
40 BaseExcT_co_default = TypeVar(
41 "BaseExcT_co_default",
42 bound=BaseException,
43 default=BaseException,
44 covariant=True,
45 )
46
47 # Use short name because it shows up in docs.
48 E = TypeVar("E", bound=BaseException, default=BaseException)
49 else:
50 from typing import TypeVar
51
52 BaseExcT_co_default = TypeVar(
53 "BaseExcT_co_default", bound=BaseException, covariant=True
54 )
55
56 # RaisesGroup doesn't work with a default.
57 BaseExcT_co = TypeVar("BaseExcT_co", bound=BaseException, covariant=True)
58 BaseExcT_1 = TypeVar("BaseExcT_1", bound=BaseException)
59 BaseExcT_2 = TypeVar("BaseExcT_2", bound=BaseException)
60 ExcT_1 = TypeVar("ExcT_1", bound=Exception)
61 ExcT_2 = TypeVar("ExcT_2", bound=Exception)
62
63 if sys.version_info < (3, 11):
64 from exceptiongroup import BaseExceptionGroup
65 from exceptiongroup import ExceptionGroup
66
67
68 # String patterns default to including the unicode flag.
69 _REGEX_NO_FLAGS = re.compile(r"").flags
70
71
72 # pytest.raises helper
73 @overload
74 def raises(
75 expected_exception: type[E] | tuple[type[E], ...],
76 *,
77 match: str | re.Pattern[str] | None = ...,
78 check: Callable[[E], bool] = ...,
79 ) -> RaisesExc[E]: ...
80
81
82 @overload
83 def raises(
84 *,
85 match: str | re.Pattern[str],
86 # If exception_type is not provided, check() must do any typechecks itself.
87 check: Callable[[BaseException], bool] = ...,
88 ) -> RaisesExc[BaseException]: ...
89
90
91 @overload
92 def raises(*, check: Callable[[BaseException], bool]) -> RaisesExc[BaseException]: ...
93
94
95 @overload
96 def raises(
97 expected_exception: type[E] | tuple[type[E], ...],
98 func: Callable[P, object],
99 *args: P.args,
100 **kwargs: P.kwargs,
101 ) -> ExceptionInfo[E]: ...
102
103
104 def raises(
105 expected_exception: type[E] | tuple[type[E], ...] | None = None,
106 func: Callable[P, object] | None = None,
107 *args: Any,
108 **kwargs: Any,
109 ) -> RaisesExc[BaseException] | ExceptionInfo[E]:
110 r"""Assert that a code block/function call raises an exception type, or one of its subclasses.
111
112 :param expected_exception:
113 The expected exception type, or a tuple if one of multiple possible
114 exception types are expected. Note that subclasses of the passed exceptions
115 will also match.
116
117 This is not a required parameter, you may opt to only use ``match`` and/or
118 ``check`` for verifying the raised exception.
119
120 :kwparam str | re.Pattern[str] | None match:
121 If specified, a string containing a regular expression,
122 or a regular expression object, that is tested against the string
123 representation of the exception and its :pep:`678` `__notes__`
124 using :func:`re.search`.
125
126 To match a literal string that may contain :ref:`special characters
127 <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
128
129 (This is only used when ``pytest.raises`` is used as a context manager,
130 and passed through to the function otherwise.
131 When using ``pytest.raises`` as a function, you can use:
132 ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)
133
134 :kwparam Callable[[BaseException], bool] check:
135
136 .. versionadded:: 8.4
137
138 If specified, a callable that will be called with the exception as a parameter
139 after checking the type and the match regex if specified.
140 If it returns ``True`` it will be considered a match, if not it will
141 be considered a failed match.
142
143
144 Use ``pytest.raises`` as a context manager, which will capture the exception of the given
145 type, or any of its subclasses::
146
147 >>> import pytest
148 >>> with pytest.raises(ZeroDivisionError):
149 ... 1/0
150
151 If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example
152 above), or no exception at all, the check will fail instead.
153
154 You can also use the keyword argument ``match`` to assert that the
155 exception matches a text or regex::
156
157 >>> with pytest.raises(ValueError, match='must be 0 or None'):
158 ... raise ValueError("value must be 0 or None")
159
160 >>> with pytest.raises(ValueError, match=r'must be \d+$'):
161 ... raise ValueError("value must be 42")
162
163 The ``match`` argument searches the formatted exception string, which includes any
164 `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``:
165
166 >>> with pytest.raises(ValueError, match=r"had a note added"): # doctest: +SKIP
167 ... e = ValueError("value must be 42")
168 ... e.add_note("had a note added")
169 ... raise e
170
171 The ``check`` argument, if provided, must return True when passed the raised exception
172 for the match to be successful, otherwise an :exc:`AssertionError` is raised.
173
174 >>> import errno
175 >>> with pytest.raises(OSError, check=lambda e: e.errno == errno.EACCES):
176 ... raise OSError(errno.EACCES, "no permission to view")
177
178 The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
179 details of the captured exception::
180
181 >>> with pytest.raises(ValueError) as exc_info:
182 ... raise ValueError("value must be 42")
183 >>> assert exc_info.type is ValueError
184 >>> assert exc_info.value.args[0] == "value must be 42"
185
186 .. warning::
187
188 Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this::
189
190 # Careful, this will catch ANY exception raised.
191 with pytest.raises(Exception):
192 some_function()
193
194 Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide
195 real bugs, where the user wrote this expecting a specific exception, but some other exception is being
196 raised due to a bug introduced during a refactoring.
197
198 Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch
199 **any** exception raised.
200
201 .. note::
202
203 When using ``pytest.raises`` as a context manager, it's worthwhile to
204 note that normal context manager rules apply and that the exception
205 raised *must* be the final line in the scope of the context manager.
206 Lines of code after that, within the scope of the context manager will
207 not be executed. For example::
208
209 >>> value = 15
210 >>> with pytest.raises(ValueError) as exc_info:
211 ... if value > 10:
212 ... raise ValueError("value must be <= 10")
213 ... assert exc_info.type is ValueError # This will not execute.
214
215 Instead, the following approach must be taken (note the difference in
216 scope)::
217
218 >>> with pytest.raises(ValueError) as exc_info:
219 ... if value > 10:
220 ... raise ValueError("value must be <= 10")
221 ...
222 >>> assert exc_info.type is ValueError
223
224 **Expecting exception groups**
225
226 When expecting exceptions wrapped in :exc:`BaseExceptionGroup` or
227 :exc:`ExceptionGroup`, you should instead use :class:`pytest.RaisesGroup`.
228
229 **Using with** ``pytest.mark.parametrize``
230
231 When using :ref:`pytest.mark.parametrize ref`
232 it is possible to parametrize tests such that
233 some runs raise an exception and others do not.
234
235 See :ref:`parametrizing_conditional_raising` for an example.
236
237 .. seealso::
238
239 :ref:`assertraises` for more examples and detailed discussion.
240
241 .. note::
242 Similar to caught exception objects in Python, explicitly clearing
243 local references to returned ``ExceptionInfo`` objects can
244 help the Python interpreter speed up its garbage collection.
245
246 Clearing those references breaks a reference cycle
247 (``ExceptionInfo`` --> caught exception --> frame stack raising
248 the exception --> current frame stack --> local variables -->
249 ``ExceptionInfo``) which makes Python keep all objects referenced
250 from that cycle (including all local variables in the current
251 frame) alive until the next cyclic garbage collection run.
252 More detailed information can be found in the official Python
253 documentation for :ref:`the try statement <python:try>`.
254 """
255 __tracebackhide__ = True
256
257 if func is None and not args:
258 if set(kwargs) - {"match", "check", "expected_exception"}:
259 msg = "Unexpected keyword arguments passed to pytest.raises: "
260 msg += ", ".join(sorted(kwargs))
261 msg += "\nUse context-manager form instead?"
262 raise TypeError(msg)
263
264 if expected_exception is None:
265 return RaisesExc(**kwargs)
266 return RaisesExc(expected_exception, **kwargs)
267
268 if not expected_exception:
269 raise ValueError(
270 f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
271 f"Raising exceptions is already understood as failing the test, so you don't need "
272 f"any special code to say 'this should never raise an exception'."
273 )
274 if not callable(func):
275 raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
276 with RaisesExc(expected_exception) as excinfo:
277 func(*args, **kwargs)
278 try:
279 return excinfo
280 finally:
281 del excinfo
282
283
284 # note: RaisesExc/RaisesGroup uses fail() internally, so this alias
285 # indicates (to [internal] plugins?) that `pytest.raises` will
286 # raise `_pytest.outcomes.Failed`, where
287 # `outcomes.Failed is outcomes.fail.Exception is raises.Exception`
288 # note: this is *not* the same as `_pytest.main.Failed`
289 # note: mypy does not recognize this attribute, and it's not possible
290 # to use a protocol/decorator like the others in outcomes due to
291 # https://github.com/python/mypy/issues/18715
292 raises.Exception = fail.Exception # type: ignore[attr-defined]
293
294
295 def _match_pattern(match: Pattern[str]) -> str | Pattern[str]:
296 """Helper function to remove redundant `re.compile` calls when printing regex"""
297 return match.pattern if match.flags == _REGEX_NO_FLAGS else match
298
299
300 def repr_callable(fun: Callable[[BaseExcT_1], bool]) -> str:
301 """Get the repr of a ``check`` parameter.
302
303 Split out so it can be monkeypatched (e.g. by hypothesis)
304 """
305 return repr(fun)
306
307
308 def backquote(s: str) -> str:
309 return "`" + s + "`"
310
311
312 def _exception_type_name(
313 e: type[BaseException] | tuple[type[BaseException], ...],
314 ) -> str:
315 if isinstance(e, type):
316 return e.__name__
317 if len(e) == 1:
318 return e[0].__name__
319 return "(" + ", ".join(ee.__name__ for ee in e) + ")"
320
321
322 def _check_raw_type(
323 expected_type: type[BaseException] | tuple[type[BaseException], ...] | None,
324 exception: BaseException,
325 ) -> str | None:
326 if expected_type is None or expected_type == ():
327 return None
328
329 if not isinstance(
330 exception,
331 expected_type,
332 ):
333 actual_type_str = backquote(_exception_type_name(type(exception)) + "()")
334 expected_type_str = backquote(_exception_type_name(expected_type))
335 if (
336 isinstance(exception, BaseExceptionGroup)
337 and isinstance(expected_type, type)
338 and not issubclass(expected_type, BaseExceptionGroup)
339 ):
340 return f"Unexpected nested {actual_type_str}, expected {expected_type_str}"
341 return f"{actual_type_str} is not an instance of {expected_type_str}"
342 return None
343
344
345 def is_fully_escaped(s: str) -> bool:
346 # we know we won't compile with re.VERBOSE, so whitespace doesn't need to be escaped
347 metacharacters = "{}()+.*?^$[]|"
348 # Strip all escape sequences (backslash + any char), then check if any
349 # metacharacter remains unescaped in the resulting string.
350 stripped = re.sub(r"\\.", "", s)
351 return not any(c in metacharacters for c in stripped)
352
353
354 def unescape(s: str) -> str:
355 return re.sub(r"\\([{}()+-.*?^$\[\]\s\\|])", r"\1", s)
356
357
358 # These classes conceptually differ from ExceptionInfo in that ExceptionInfo is tied, and
359 # constructed from, a particular exception - whereas these are constructed with expected
360 # exceptions, and later allow matching towards particular exceptions.
361 # But there's overlap in `ExceptionInfo.match` and `AbstractRaises._check_match`, as with
362 # `AbstractRaises.matches` and `ExceptionInfo.errisinstance`+`ExceptionInfo.group_contains`.
363 # The interaction between these classes should perhaps be improved.
364 class AbstractRaises(ABC, Generic[BaseExcT_co]):
365 """ABC with common functionality shared between RaisesExc and RaisesGroup"""
366
367 def __init__(
368 self,
369 *,
370 match: str | Pattern[str] | None,
371 check: Callable[[BaseExcT_co], bool] | None,
372 ) -> None:
373 if isinstance(match, str):
374 # juggle error in order to avoid context to fail (necessary?)
375 re_error = None
376 try:
377 self.match: Pattern[str] | None = re.compile(match)
378 except re.error as e:
379 re_error = e
380 if re_error is not None:
381 fail(f"Invalid regex pattern provided to 'match': {re_error}")
382 if match == "":
383 warnings.warn(
384 PytestWarning(
385 "matching against an empty string will *always* pass. If you want "
386 "to check for an empty message you need to pass '^$'. If you don't "
387 "want to match you should pass `None` or leave out the parameter."
388 ),
389 stacklevel=2,
390 )
391 else:
392 self.match = match
393
394 # check if this is a fully escaped regex and has ^$ to match fully
395 # in which case we can do a proper diff on error
396 self.rawmatch: str | None = None
397 if isinstance(match, str) or (
398 isinstance(match, Pattern) and match.flags == _REGEX_NO_FLAGS
399 ):
400 if isinstance(match, Pattern):
401 match = match.pattern
402 if (
403 match
404 and match[0] == "^"
405 and match[-1] == "$"
406 and is_fully_escaped(match[1:-1])
407 ):
408 self.rawmatch = unescape(match[1:-1])
409
410 self.check = check
411 self._fail_reason: str | None = None
412
413 # used to suppress repeated printing of `repr(self.check)`
414 self._nested: bool = False
415
416 # set in self._parse_exc
417 self.is_baseexception = False
418
419 def _parse_exc(
420 self, exc: type[BaseExcT_1] | types.GenericAlias, expected: str
421 ) -> type[BaseExcT_1]:
422 if isinstance(exc, type) and issubclass(exc, BaseException):
423 if not issubclass(exc, Exception):
424 self.is_baseexception = True
425 return exc
426 # because RaisesGroup does not support variable number of exceptions there's
427 # still a use for RaisesExc(ExceptionGroup[Exception]).
428 origin_exc: type[BaseException] | None = get_origin(exc)
429 if origin_exc and issubclass(origin_exc, BaseExceptionGroup):
430 exc_type = get_args(exc)[0]
431 if (
432 issubclass(origin_exc, ExceptionGroup) and exc_type in (Exception, Any)
433 ) or (
434 issubclass(origin_exc, BaseExceptionGroup)
435 and exc_type in (BaseException, Any)
436 ):
437 if not issubclass(origin_exc, ExceptionGroup):
438 self.is_baseexception = True
439 return cast(type[BaseExcT_1], origin_exc)
440 else:
441 raise ValueError(
442 f"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` "
443 f"are accepted as generic types but got `{exc}`. "
444 f"As `raises` will catch all instances of the specified group regardless of the "
445 f"generic argument specific nested exceptions has to be checked "
446 f"with `RaisesGroup`."
447 )
448 # unclear if the Type/ValueError distinction is even helpful here
449 msg = f"Expected {expected}, but got "
450 if isinstance(exc, type): # type: ignore[unreachable]
451 raise ValueError(msg + f"{exc.__name__!r}")
452 if isinstance(exc, BaseException): # type: ignore[unreachable]
453 raise TypeError(msg + f"an exception instance: {type(exc).__name__}")
454 raise TypeError(msg + repr(type(exc).__name__))
455
456 @property
457 def fail_reason(self) -> str | None:
458 """Set after a call to :meth:`matches` to give a human-readable reason for why the match failed.
459 When used as a context manager the string will be printed as the reason for the
460 test failing."""
461 return self._fail_reason
462
463 def _check_check(
464 self: AbstractRaises[BaseExcT_1],
465 exception: BaseExcT_1,
466 ) -> bool:
467 if self.check is None:
468 return True
469
470 if self.check(exception):
471 return True
472
473 check_repr = "" if self._nested else " " + repr_callable(self.check)
474 self._fail_reason = f"check{check_repr} did not return True"
475 return False
476
477 # TODO: harmonize with ExceptionInfo.match
478 def _check_match(self, e: BaseException) -> bool:
479 if self.match is None or re.search(
480 self.match,
481 stringified_exception := stringify_exception(
482 e, include_subexception_msg=False
483 ),
484 ):
485 return True
486
487 # if we're matching a group, make sure we're explicit to reduce confusion
488 # if they're trying to match an exception contained within the group
489 maybe_specify_type = (
490 f" the `{_exception_type_name(type(e))}()`"
491 if isinstance(e, BaseExceptionGroup)
492 else ""
493 )
494 if isinstance(self.rawmatch, str):
495 from _pytest.assertion.compare_text import _diff_text
496 from _pytest.assertion.highlight import dummy_highlighter
497 from _pytest.assertion.util import _config
498 from _pytest.config import Config
499
500 verbose = (
501 _config.get_verbosity(Config.VERBOSITY_ASSERTIONS)
502 if _config is not None
503 else 0
504 )
505 diff = list(
506 _diff_text(
507 self.rawmatch, stringified_exception, dummy_highlighter, verbose
508 )
509 )
510 self._fail_reason = ("\n" if diff[0][0] == "-" else "") + "\n".join(diff)
511 return False
512
513 self._fail_reason = (
514 f"Regex pattern did not match{maybe_specify_type}.\n"
515 f" Expected regex: {_match_pattern(self.match)!r}\n"
516 f" Actual message: {stringified_exception!r}"
517 )
518 if _match_pattern(self.match) == stringified_exception:
519 self._fail_reason += "\n Did you mean to `re.escape()` the regex?"
520 return False
521
522 @abstractmethod
523 def matches(
524 self: AbstractRaises[BaseExcT_1], exception: BaseException
525 ) -> TypeGuard[BaseExcT_1]:
526 """Check if an exception matches the requirements of this AbstractRaises.
527 If it fails, :meth:`AbstractRaises.fail_reason` should be set.
528 """
529
530
531 @final
532 class RaisesExc(AbstractRaises[BaseExcT_co_default]):
533 """
534 .. versionadded:: 8.4
535
536
537 This is the class constructed when calling :func:`pytest.raises`, but may be used
538 directly as a helper class with :class:`RaisesGroup` when you want to specify
539 requirements on sub-exceptions.
540
541 You don't need this if you only want to specify the type, since :class:`RaisesGroup`
542 accepts ``type[BaseException]``.
543
544 :param type[BaseException] | tuple[type[BaseException]] | None expected_exception:
545 The expected type, or one of several possible types.
546 May be ``None`` in order to only make use of ``match`` and/or ``check``
547
548 The type is checked with :func:`isinstance`, and does not need to be an exact match.
549 If that is wanted you can use the ``check`` parameter.
550
551 :kwparam str | Pattern[str] match:
552 A regex to match.
553
554 :kwparam Callable[[BaseException], bool] check:
555 If specified, a callable that will be called with the exception as a parameter
556 after checking the type and the match regex if specified.
557 If it returns ``True`` it will be considered a match, if not it will
558 be considered a failed match.
559
560 :meth:`RaisesExc.matches` can also be used standalone to check individual exceptions.
561
562 Examples::
563
564 with RaisesGroup(RaisesExc(ValueError, match="string"))
565 ...
566 with RaisesGroup(RaisesExc(check=lambda x: x.args == (3, "hello"))):
567 ...
568 with RaisesGroup(RaisesExc(check=lambda x: type(x) is ValueError)):
569 ...
570 """
571
572 # Trio bundled hypothesis monkeypatching, we will probably instead assume that
573 # hypothesis will handle that in their pytest plugin by the time this is released.
574 # Alternatively we could add a version of get_pretty_function_description ourselves
575 # https://github.com/HypothesisWorks/hypothesis/blob/8ced2f59f5c7bea3344e35d2d53e1f8f8eb9fcd8/hypothesis-python/src/hypothesis/internal/reflection.py#L439
576
577 # At least one of the three parameters must be passed.
578 @overload
579 def __init__(
580 self,
581 expected_exception: (
582 type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...]
583 ),
584 /,
585 *,
586 match: str | Pattern[str] | None = ...,
587 check: Callable[[BaseExcT_co_default], bool] | None = ...,
588 ) -> None: ...
589
590 @overload
591 def __init__(
592 self: RaisesExc[BaseException], # Give E a value.
593 /,
594 *,
595 match: str | Pattern[str] | None,
596 # If exception_type is not provided, check() must do any typechecks itself.
597 check: Callable[[BaseException], bool] | None = ...,
598 ) -> None: ...
599
600 @overload
601 def __init__(self, /, *, check: Callable[[BaseException], bool]) -> None: ...
602
603 def __init__(
604 self,
605 expected_exception: (
606 type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...] | None
607 ) = None,
608 /,
609 *,
610 match: str | Pattern[str] | None = None,
611 check: Callable[[BaseExcT_co_default], bool] | None = None,
612 ):
613 super().__init__(match=match, check=check)
614 if isinstance(expected_exception, tuple):
615 expected_exceptions = expected_exception
616 elif expected_exception is None:
617 expected_exceptions = ()
618 else:
619 expected_exceptions = (expected_exception,)
620
621 if (expected_exceptions == ()) and match is None and check is None:
622 raise ValueError("You must specify at least one parameter to match on.")
623
624 self.expected_exceptions = tuple(
625 self._parse_exc(e, expected="a BaseException type")
626 for e in expected_exceptions
627 )
628
629 self._just_propagate = False
630
631 def matches(
632 self,
633 exception: BaseException | None,
634 ) -> TypeGuard[BaseExcT_co_default]:
635 """Check if an exception matches the requirements of this :class:`RaisesExc`.
636 If it fails, :attr:`RaisesExc.fail_reason` will be set.
637
638 Examples::
639
640 assert RaisesExc(ValueError).matches(my_exception):
641 # is equivalent to
642 assert isinstance(my_exception, ValueError)
643
644 # this can be useful when checking e.g. the ``__cause__`` of an exception.
645 with pytest.raises(ValueError) as excinfo:
646 ...
647 assert RaisesExc(SyntaxError, match="foo").matches(excinfo.value.__cause__)
648 # above line is equivalent to
649 assert isinstance(excinfo.value.__cause__, SyntaxError)
650 assert re.search("foo", str(excinfo.value.__cause__)
651
652 """
653 self._just_propagate = False
654 if exception is None:
655 self._fail_reason = "exception is None"
656 return False
657 if not self._check_type(exception):
658 self._just_propagate = True
659 return False
660
661 if not self._check_match(exception):
662 return False
663
664 return self._check_check(exception)
665
666 def __repr__(self) -> str:
667 parameters = []
668 if self.expected_exceptions:
669 parameters.append(_exception_type_name(self.expected_exceptions))
670 if self.match is not None:
671 # If no flags were specified, discard the redundant re.compile() here.
672 parameters.append(
673 f"match={_match_pattern(self.match)!r}",
674 )
675 if self.check is not None:
676 parameters.append(f"check={repr_callable(self.check)}")
677 return f"RaisesExc({', '.join(parameters)})"
678
679 def _check_type(self, exception: BaseException) -> TypeGuard[BaseExcT_co_default]:
680 self._fail_reason = _check_raw_type(self.expected_exceptions, exception)
681 return self._fail_reason is None
682
683 def __enter__(self) -> ExceptionInfo[BaseExcT_co_default]:
684 self.excinfo: ExceptionInfo[BaseExcT_co_default] = ExceptionInfo.for_later()
685 return self.excinfo
686
687 # TODO: move common code into superclass
688 def __exit__(
689 self,
690 exc_type: type[BaseException] | None,
691 exc_val: BaseException | None,
692 exc_tb: types.TracebackType | None,
693 ) -> bool:
694 __tracebackhide__ = True
695 if exc_type is None:
696 if not self.expected_exceptions:
697 fail("DID NOT RAISE any exception")
698 if len(self.expected_exceptions) == 1:
699 fail(f"DID NOT RAISE {self.expected_exceptions[0].__name__}")
700 else:
701 names = ", ".join(x.__name__ for x in self.expected_exceptions)
702 fail(f"DID NOT RAISE any of ({names})")
703
704 assert self.excinfo is not None, (
705 "Internal error - should have been constructed in __enter__"
706 )
707
708 if not self.matches(exc_val):
709 if self._just_propagate:
710 return False
711 raise AssertionError(self._fail_reason) from None
712
713 # Cast to narrow the exception type now that it's verified....
714 # even though the TypeGuard in self.matches should be narrowing
715 exc_info = cast(
716 "tuple[type[BaseExcT_co_default], BaseExcT_co_default, types.TracebackType]",
717 (exc_type, exc_val, exc_tb),
718 )
719 self.excinfo.fill_unfilled(exc_info)
720 return True
721
722
723 @final
724 class RaisesGroup(AbstractRaises[BaseExceptionGroup[BaseExcT_co]]):
725 """
726 .. versionadded:: 8.4
727
728 Contextmanager for checking for an expected :exc:`ExceptionGroup`.
729 This works similar to :func:`pytest.raises`, but allows for specifying the structure of an :exc:`ExceptionGroup`.
730 :meth:`ExceptionInfo.group_contains` also tries to handle exception groups,
731 but it is very bad at checking that you *didn't* get unexpected exceptions.
732
733 The catching behaviour differs from :ref:`except* <except_star>`, being much
734 stricter about the structure by default.
735 By using ``allow_unwrapped=True`` and ``flatten_subgroups=True`` you can match
736 :ref:`except* <except_star>` fully when expecting a single exception.
737
738 :param args:
739 Any number of exception types, :class:`RaisesGroup` or :class:`RaisesExc`
740 to specify the exceptions contained in this exception.
741 All specified exceptions must be present in the raised group, *and no others*.
742
743 If you expect a variable number of exceptions you need to use
744 :func:`pytest.raises(ExceptionGroup) <pytest.raises>` and manually check
745 the contained exceptions. Consider making use of :meth:`RaisesExc.matches`.
746
747 It does not care about the order of the exceptions, so
748 ``RaisesGroup(ValueError, TypeError)``
749 is equivalent to
750 ``RaisesGroup(TypeError, ValueError)``.
751 :kwparam str | re.Pattern[str] | None match:
752 If specified, a string containing a regular expression,
753 or a regular expression object, that is tested against the string
754 representation of the exception group and its :pep:`678` `__notes__`
755 using :func:`re.search`.
756
757 To match a literal string that may contain :ref:`special characters
758 <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
759
760 Note that " (5 subgroups)" will be stripped from the ``repr`` before matching.
761 :kwparam Callable[[E], bool] check:
762 If specified, a callable that will be called with the group as a parameter
763 after successfully matching the expected exceptions. If it returns ``True``
764 it will be considered a match, if not it will be considered a failed match.
765 :kwparam bool allow_unwrapped:
766 If expecting a single exception or :class:`RaisesExc` it will match even
767 if the exception is not inside an exceptiongroup.
768
769 Using this together with ``match``, ``check`` or expecting multiple exceptions
770 will raise an error.
771 :kwparam bool flatten_subgroups:
772 "flatten" any groups inside the raised exception group, extracting all exceptions
773 inside any nested groups, before matching. Without this it expects you to
774 fully specify the nesting structure by passing :class:`RaisesGroup` as expected
775 parameter.
776
777 Examples::
778
779 with RaisesGroup(ValueError):
780 raise ExceptionGroup("", (ValueError(),))
781 # match
782 with RaisesGroup(
783 ValueError,
784 ValueError,
785 RaisesExc(TypeError, match="^expected int$"),
786 match="^my group$",
787 ):
788 raise ExceptionGroup(
789 "my group",
790 [
791 ValueError(),
792 TypeError("expected int"),
793 ValueError(),
794 ],
795 )
796 # check
797 with RaisesGroup(
798 KeyboardInterrupt,
799 match="^hello$",
800 check=lambda x: isinstance(x.__cause__, ValueError),
801 ):
802 raise BaseExceptionGroup("hello", [KeyboardInterrupt()]) from ValueError
803 # nested groups
804 with RaisesGroup(RaisesGroup(ValueError)):
805 raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
806
807 # flatten_subgroups
808 with RaisesGroup(ValueError, flatten_subgroups=True):
809 raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
810
811 # allow_unwrapped
812 with RaisesGroup(ValueError, allow_unwrapped=True):
813 raise ValueError
814
815
816 :meth:`RaisesGroup.matches` can also be used directly to check a standalone exception group.
817
818
819 The matching algorithm is greedy, which means cases such as this may fail::
820
821 with RaisesGroup(ValueError, RaisesExc(ValueError, match="hello")):
822 raise ExceptionGroup("", (ValueError("hello"), ValueError("goodbye")))
823
824 even though it generally does not care about the order of the exceptions in the group.
825 To avoid the above you should specify the first :exc:`ValueError` with a :class:`RaisesExc` as well.
826
827 .. note::
828 When raised exceptions don't match the expected ones, you'll get a detailed error
829 message explaining why. This includes ``repr(check)`` if set, which in Python can be
830 overly verbose, showing memory locations etc etc.
831
832 If installed and imported (in e.g. ``conftest.py``), the ``hypothesis`` library will
833 monkeypatch this output to provide shorter & more readable repr's.
834 """
835
836 # allow_unwrapped=True requires: singular exception, exception not being
837 # RaisesGroup instance, match is None, check is None
838 @overload
839 def __init__(
840 self,
841 expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co],
842 /,
843 *,
844 allow_unwrapped: Literal[True],
845 flatten_subgroups: bool = False,
846 ) -> None: ...
847
848 # flatten_subgroups = True also requires no nested RaisesGroup
849 @overload
850 def __init__(
851 self,
852 expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co],
853 /,
854 *other_exceptions: type[BaseExcT_co] | RaisesExc[BaseExcT_co],
855 flatten_subgroups: Literal[True],
856 match: str | Pattern[str] | None = None,
857 check: Callable[[BaseExceptionGroup[BaseExcT_co]], bool] | None = None,
858 ) -> None: ...
859
860 # simplify the typevars if possible (the following 3 are equivalent but go simpler->complicated)
861 # ... the first handles RaisesGroup[ValueError], the second RaisesGroup[ExceptionGroup[ValueError]],
862 # the third RaisesGroup[ValueError | ExceptionGroup[ValueError]].
863 # ... otherwise, we will get results like RaisesGroup[ValueError | ExceptionGroup[Never]] (I think)
864 # (technically correct but misleading)
865 @overload
866 def __init__(
867 self: RaisesGroup[ExcT_1],
868 expected_exception: type[ExcT_1] | RaisesExc[ExcT_1],
869 /,
870 *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1],
871 match: str | Pattern[str] | None = None,
872 check: Callable[[ExceptionGroup[ExcT_1]], bool] | None = None,
873 ) -> None: ...
874
875 @overload
876 def __init__(
877 self: RaisesGroup[ExceptionGroup[ExcT_2]],
878 expected_exception: RaisesGroup[ExcT_2],
879 /,
880 *other_exceptions: RaisesGroup[ExcT_2],
881 match: str | Pattern[str] | None = None,
882 check: Callable[[ExceptionGroup[ExceptionGroup[ExcT_2]]], bool] | None = None,
883 ) -> None: ...
884
885 @overload
886 def __init__(
887 self: RaisesGroup[ExcT_1 | ExceptionGroup[ExcT_2]],
888 expected_exception: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2],
889 /,
890 *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2],
891 match: str | Pattern[str] | None = None,
892 check: (
893 Callable[[ExceptionGroup[ExcT_1 | ExceptionGroup[ExcT_2]]], bool] | None
894 ) = None,
895 ) -> None: ...
896
897 # same as the above 3 but handling BaseException
898 @overload
899 def __init__(
900 self: RaisesGroup[BaseExcT_1],
901 expected_exception: type[BaseExcT_1] | RaisesExc[BaseExcT_1],
902 /,
903 *other_exceptions: type[BaseExcT_1] | RaisesExc[BaseExcT_1],
904 match: str | Pattern[str] | None = None,
905 check: Callable[[BaseExceptionGroup[BaseExcT_1]], bool] | None = None,
906 ) -> None: ...
907
908 @overload
909 def __init__(
910 self: RaisesGroup[BaseExceptionGroup[BaseExcT_2]],
911 expected_exception: RaisesGroup[BaseExcT_2],
912 /,
913 *other_exceptions: RaisesGroup[BaseExcT_2],
914 match: str | Pattern[str] | None = None,
915 check: (
916 Callable[[BaseExceptionGroup[BaseExceptionGroup[BaseExcT_2]]], bool] | None
917 ) = None,
918 ) -> None: ...
919
920 @overload
921 def __init__(
922 self: RaisesGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]],
923 expected_exception: type[BaseExcT_1]
924 | RaisesExc[BaseExcT_1]
925 | RaisesGroup[BaseExcT_2],
926 /,
927 *other_exceptions: type[BaseExcT_1]
928 | RaisesExc[BaseExcT_1]
929 | RaisesGroup[BaseExcT_2],
930 match: str | Pattern[str] | None = None,
931 check: (
932 Callable[
933 [BaseExceptionGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]]],
934 bool,
935 ]
936 | None
937 ) = None,
938 ) -> None: ...
939
940 def __init__(
941 self: RaisesGroup[ExcT_1 | BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]],
942 expected_exception: type[BaseExcT_1]
943 | RaisesExc[BaseExcT_1]
944 | RaisesGroup[BaseExcT_2],
945 /,
946 *other_exceptions: type[BaseExcT_1]
947 | RaisesExc[BaseExcT_1]
948 | RaisesGroup[BaseExcT_2],
949 allow_unwrapped: bool = False,
950 flatten_subgroups: bool = False,
951 match: str | Pattern[str] | None = None,
952 check: (
953 Callable[[BaseExceptionGroup[BaseExcT_1]], bool]
954 | Callable[[ExceptionGroup[ExcT_1]], bool]
955 | None
956 ) = None,
957 ):
958 # The type hint on the `self` and `check` parameters uses different formats
959 # that are *very* hard to reconcile while adhering to the overloads, so we cast
960 # it to avoid an error when passing it to super().__init__
961 check = cast(
962 "Callable[[BaseExceptionGroup[ExcT_1|BaseExcT_1|BaseExceptionGroup[BaseExcT_2]]], bool]",
963 check,
964 )
965 super().__init__(match=match, check=check)
966 self.allow_unwrapped = allow_unwrapped
967 self.flatten_subgroups: bool = flatten_subgroups
968 self.is_baseexception = False
969
970 if allow_unwrapped and other_exceptions:
971 raise ValueError(
972 "You cannot specify multiple exceptions with `allow_unwrapped=True.`"
973 " If you want to match one of multiple possible exceptions you should"
974 " use a `RaisesExc`."
975 " E.g. `RaisesExc(check=lambda e: isinstance(e, (...)))`",
976 )
977 if allow_unwrapped and isinstance(expected_exception, RaisesGroup):
978 raise ValueError(
979 "`allow_unwrapped=True` has no effect when expecting a `RaisesGroup`."
980 " You might want it in the expected `RaisesGroup`, or"
981 " `flatten_subgroups=True` if you don't care about the structure.",
982 )
983 if allow_unwrapped and (match is not None or check is not None):
984 raise ValueError(
985 "`allow_unwrapped=True` bypasses the `match` and `check` parameters"
986 " if the exception is unwrapped. If you intended to match/check the"
987 " exception you should use a `RaisesExc` object. If you want to match/check"
988 " the exceptiongroup when the exception *is* wrapped you need to"
989 " do e.g. `if isinstance(exc.value, ExceptionGroup):"
990 " assert RaisesGroup(...).matches(exc.value)` afterwards.",
991 )
992
993 self.expected_exceptions: tuple[
994 type[BaseExcT_co] | RaisesExc[BaseExcT_co] | RaisesGroup[BaseException], ...
995 ] = tuple(
996 self._parse_excgroup(e, "a BaseException type, RaisesExc, or RaisesGroup")
997 for e in (
998 expected_exception,
999 *other_exceptions,
1000 )
1001 )
1002
1003 def _parse_excgroup(
1004 self,
1005 exc: (
1006 type[BaseExcT_co]
1007 | types.GenericAlias
1008 | RaisesExc[BaseExcT_1]
1009 | RaisesGroup[BaseExcT_2]
1010 ),
1011 expected: str,
1012 ) -> type[BaseExcT_co] | RaisesExc[BaseExcT_1] | RaisesGroup[BaseExcT_2]:
1013 # verify exception type and set `self.is_baseexception`
1014 match exc:
1015 case RaisesGroup() if self.flatten_subgroups:
1016 raise ValueError(
1017 "You cannot specify a nested structure inside a RaisesGroup with"
1018 " `flatten_subgroups=True`. The parameter will flatten subgroups"
1019 " in the raised exceptiongroup before matching, which would never"
1020 " match a nested structure.",
1021 )
1022 case RaisesGroup() | RaisesExc():
1023 self.is_baseexception |= exc.is_baseexception
1024 exc._nested = True
1025 return exc
1026 case tuple():
1027 raise TypeError(
1028 f"Expected {expected}, but got {type(exc).__name__!r}.\n"
1029 "RaisesGroup does not support tuples of exception types when expecting one of "
1030 "several possible exception types like RaisesExc.\n"
1031 "If you meant to expect a group with multiple exceptions, list them as separate arguments."
1032 )
1033 case _:
1034 return super()._parse_exc(exc, expected)
1035
1036 @overload
1037 def __enter__(
1038 self: RaisesGroup[ExcT_1],
1039 ) -> ExceptionInfo[ExceptionGroup[ExcT_1]]: ...
1040 @overload
1041 def __enter__(
1042 self: RaisesGroup[BaseExcT_1],
1043 ) -> ExceptionInfo[BaseExceptionGroup[BaseExcT_1]]: ...
1044
1045 def __enter__(self) -> ExceptionInfo[BaseExceptionGroup[BaseException]]:
1046 self.excinfo: ExceptionInfo[BaseExceptionGroup[BaseExcT_co]] = (
1047 ExceptionInfo.for_later()
1048 )
1049 return self.excinfo
1050
1051 def __repr__(self) -> str:
1052 reqs = [
1053 e.__name__ if isinstance(e, type) else repr(e)
1054 for e in self.expected_exceptions
1055 ]
1056 if self.allow_unwrapped:
1057 reqs.append(f"allow_unwrapped={self.allow_unwrapped}")
1058 if self.flatten_subgroups:
1059 reqs.append(f"flatten_subgroups={self.flatten_subgroups}")
1060 if self.match is not None:
1061 # If no flags were specified, discard the redundant re.compile() here.
1062 reqs.append(f"match={_match_pattern(self.match)!r}")
1063 if self.check is not None:
1064 reqs.append(f"check={repr_callable(self.check)}")
1065 return f"RaisesGroup({', '.join(reqs)})"
1066
1067 def _unroll_exceptions(
1068 self,
1069 exceptions: Sequence[BaseException],
1070 ) -> Sequence[BaseException]:
1071 """Used if `flatten_subgroups=True`."""
1072 res: list[BaseException] = []
1073 for exc in exceptions:
1074 if isinstance(exc, BaseExceptionGroup):
1075 res.extend(self._unroll_exceptions(exc.exceptions))
1076
1077 else:
1078 res.append(exc)
1079 return res
1080
1081 @overload
1082 def matches(
1083 self: RaisesGroup[ExcT_1],
1084 exception: BaseException | None,
1085 ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ...
1086 @overload
1087 def matches(
1088 self: RaisesGroup[BaseExcT_1],
1089 exception: BaseException | None,
1090 ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ...
1091
1092 def matches(
1093 self,
1094 exception: BaseException | None,
1095 ) -> bool:
1096 """Check if an exception matches the requirements of this RaisesGroup.
1097 If it fails, `RaisesGroup.fail_reason` will be set.
1098
1099 Example::
1100
1101 with pytest.raises(TypeError) as excinfo:
1102 ...
1103 assert RaisesGroup(ValueError).matches(excinfo.value.__cause__)
1104 # the above line is equivalent to
1105 myexc = excinfo.value.__cause
1106 assert isinstance(myexc, BaseExceptionGroup)
1107 assert len(myexc.exceptions) == 1
1108 assert isinstance(myexc.exceptions[0], ValueError)
1109 """
1110 self._fail_reason = None
1111 if exception is None:
1112 self._fail_reason = "exception is None"
1113 return False
1114 if not isinstance(exception, BaseExceptionGroup):
1115 # we opt to only print type of the exception here, as the repr would
1116 # likely be quite long
1117 not_group_msg = f"`{type(exception).__name__}()` is not an exception group"
1118 if len(self.expected_exceptions) > 1:
1119 self._fail_reason = not_group_msg
1120 return False
1121 # if we have 1 expected exception, check if it would work even if
1122 # allow_unwrapped is not set
1123 res = self._check_expected(self.expected_exceptions[0], exception)
1124 if res is None and self.allow_unwrapped:
1125 return True
1126
1127 if res is None:
1128 self._fail_reason = (
1129 f"{not_group_msg}, but would match with `allow_unwrapped=True`"
1130 )
1131 elif self.allow_unwrapped:
1132 self._fail_reason = res
1133 else:
1134 self._fail_reason = not_group_msg
1135 return False
1136
1137 actual_exceptions: Sequence[BaseException] = exception.exceptions
1138 if self.flatten_subgroups:
1139 actual_exceptions = self._unroll_exceptions(actual_exceptions)
1140
1141 if not self._check_match(exception):
1142 self._fail_reason = cast(str, self._fail_reason)
1143 old_reason = self._fail_reason
1144 if (
1145 len(actual_exceptions) == len(self.expected_exceptions) == 1
1146 and isinstance(expected := self.expected_exceptions[0], type)
1147 and isinstance(actual := actual_exceptions[0], expected)
1148 and self._check_match(actual)
1149 ):
1150 assert self.match is not None, "can't be None if _check_match failed"
1151 assert self._fail_reason is old_reason is not None
1152 self._fail_reason += (
1153 f"\n"
1154 f" but matched the expected `{self._repr_expected(expected)}`.\n"
1155 f" You might want "
1156 f"`RaisesGroup(RaisesExc({expected.__name__}, match={_match_pattern(self.match)!r}))`"
1157 )
1158 else:
1159 self._fail_reason = old_reason
1160 return False
1161
1162 # do the full check on expected exceptions
1163 if not self._check_exceptions(
1164 exception,
1165 actual_exceptions,
1166 ):
1167 self._fail_reason = cast(str, self._fail_reason)
1168 assert self._fail_reason is not None
1169 old_reason = self._fail_reason
1170 # if we're not expecting a nested structure, and there is one, do a second
1171 # pass where we try flattening it
1172 if (
1173 not self.flatten_subgroups
1174 and not any(
1175 isinstance(e, RaisesGroup) for e in self.expected_exceptions
1176 )
1177 and any(isinstance(e, BaseExceptionGroup) for e in actual_exceptions)
1178 and self._check_exceptions(
1179 exception,
1180 self._unroll_exceptions(exception.exceptions),
1181 )
1182 ):
1183 # only indent if it's a single-line reason. In a multi-line there's already
1184 # indented lines that this does not belong to.
1185 indent = " " if "\n" not in self._fail_reason else ""
1186 self._fail_reason = (
1187 old_reason
1188 + f"\n{indent}Did you mean to use `flatten_subgroups=True`?"
1189 )
1190 else:
1191 self._fail_reason = old_reason
1192 return False
1193
1194 # Only run `self.check` once we know `exception` is of the correct type.
1195 if not self._check_check(exception):
1196 reason = (
1197 cast(str, self._fail_reason) + f" on the {type(exception).__name__}"
1198 )
1199 if (
1200 len(actual_exceptions) == len(self.expected_exceptions) == 1
1201 and isinstance(expected := self.expected_exceptions[0], type)
1202 # we explicitly break typing here :)
1203 and self._check_check(actual_exceptions[0]) # type: ignore[arg-type]
1204 ):
1205 self._fail_reason = reason + (
1206 f", but did return True for the expected {self._repr_expected(expected)}."
1207 f" You might want RaisesGroup(RaisesExc({expected.__name__}, check=<...>))"
1208 )
1209 else:
1210 self._fail_reason = reason
1211 return False
1212
1213 return True
1214
1215 @staticmethod
1216 def _check_expected(
1217 expected_type: (
1218 type[BaseException] | RaisesExc[BaseException] | RaisesGroup[BaseException]
1219 ),
1220 exception: BaseException,
1221 ) -> str | None:
1222 """Helper method for `RaisesGroup.matches` and `RaisesGroup._check_exceptions`
1223 to check one of potentially several expected exceptions."""
1224 if isinstance(expected_type, type):
1225 return _check_raw_type(expected_type, exception)
1226 res = expected_type.matches(exception)
1227 if res:
1228 return None
1229 assert expected_type.fail_reason is not None
1230 if expected_type.fail_reason.startswith("\n"):
1231 return f"\n{expected_type!r}: {indent(expected_type.fail_reason, ' ')}"
1232 return f"{expected_type!r}: {expected_type.fail_reason}"
1233
1234 @staticmethod
1235 def _repr_expected(e: type[BaseException] | AbstractRaises[BaseException]) -> str:
1236 """Get the repr of an expected type/RaisesExc/RaisesGroup, but we only want
1237 the name if it's a type"""
1238 if isinstance(e, type):
1239 return _exception_type_name(e)
1240 return repr(e)
1241
1242 @overload
1243 def _check_exceptions(
1244 self: RaisesGroup[ExcT_1],
1245 _exception: Exception,
1246 actual_exceptions: Sequence[Exception],
1247 ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ...
1248 @overload
1249 def _check_exceptions(
1250 self: RaisesGroup[BaseExcT_1],
1251 _exception: BaseException,
1252 actual_exceptions: Sequence[BaseException],
1253 ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ...
1254
1255 def _check_exceptions(
1256 self,
1257 _exception: BaseException,
1258 actual_exceptions: Sequence[BaseException],
1259 ) -> bool:
1260 """Helper method for RaisesGroup.matches that attempts to pair up expected and actual exceptions"""
1261 # The _exception parameter is not used, but necessary for the TypeGuard
1262
1263 # full table with all results
1264 results = ResultHolder(self.expected_exceptions, actual_exceptions)
1265
1266 # (indexes of) raised exceptions that haven't (yet) found an expected
1267 remaining_actual = list(range(len(actual_exceptions)))
1268 # (indexes of) expected exceptions that haven't found a matching raised
1269 failed_expected: list[int] = []
1270 # successful greedy matches
1271 matches: dict[int, int] = {}
1272
1273 # loop over expected exceptions first to get a more predictable result
1274 for i_exp, expected in enumerate(self.expected_exceptions):
1275 for i_rem in remaining_actual:
1276 res = self._check_expected(expected, actual_exceptions[i_rem])
1277 results.set_result(i_exp, i_rem, res)
1278 if res is None:
1279 remaining_actual.remove(i_rem)
1280 matches[i_exp] = i_rem
1281 break
1282 else:
1283 failed_expected.append(i_exp)
1284
1285 # All exceptions matched up successfully
1286 if not remaining_actual and not failed_expected:
1287 return True
1288
1289 # in case of a single expected and single raised we simplify the output
1290 if 1 == len(actual_exceptions) == len(self.expected_exceptions):
1291 assert not matches
1292 self._fail_reason = res
1293 return False
1294
1295 # The test case is failing, so we can do a slow and exhaustive check to find
1296 # duplicate matches etc that will be helpful in debugging
1297 for i_exp, expected in enumerate(self.expected_exceptions):
1298 for i_actual, actual in enumerate(actual_exceptions):
1299 if results.has_result(i_exp, i_actual):
1300 continue
1301 results.set_result(
1302 i_exp, i_actual, self._check_expected(expected, actual)
1303 )
1304
1305 successful_str = (
1306 f"{len(matches)} matched exception{'s' if len(matches) > 1 else ''}. "
1307 if matches
1308 else ""
1309 )
1310
1311 # all expected were found
1312 if not failed_expected and results.no_match_for_actual(remaining_actual):
1313 self._fail_reason = (
1314 f"{successful_str}Unexpected exception(s):"
1315 f" {[actual_exceptions[i] for i in remaining_actual]!r}"
1316 )
1317 return False
1318 # all raised exceptions were expected
1319 if not remaining_actual and results.no_match_for_expected(failed_expected):
1320 no_match_for_str = ", ".join(
1321 self._repr_expected(self.expected_exceptions[i])
1322 for i in failed_expected
1323 )
1324 self._fail_reason = f"{successful_str}Too few exceptions raised, found no match for: [{no_match_for_str}]"
1325 return False
1326
1327 # if there's only one remaining and one failed, and the unmatched didn't match anything else,
1328 # we elect to only print why the remaining and the failed didn't match.
1329 if (
1330 1 == len(remaining_actual) == len(failed_expected)
1331 and results.no_match_for_actual(remaining_actual)
1332 and results.no_match_for_expected(failed_expected)
1333 ):
1334 self._fail_reason = f"{successful_str}{results.get_result(failed_expected[0], remaining_actual[0])}"
1335 return False
1336
1337 # there's both expected and raised exceptions without matches
1338 s = ""
1339 if matches:
1340 s += f"\n{successful_str}"
1341 indent_1 = " " * 2
1342 indent_2 = " " * 4
1343
1344 if not remaining_actual:
1345 s += "\nToo few exceptions raised!"
1346 elif not failed_expected:
1347 s += "\nUnexpected exception(s)!"
1348
1349 if failed_expected:
1350 s += "\nThe following expected exceptions did not find a match:"
1351 rev_matches = {v: k for k, v in matches.items()}
1352 for i_failed in failed_expected:
1353 s += (
1354 f"\n{indent_1}{self._repr_expected(self.expected_exceptions[i_failed])}"
1355 )
1356 for i_actual, actual in enumerate(actual_exceptions):
1357 if results.get_result(i_failed, i_actual) is None:
1358 # we print full repr of match target
1359 s += (
1360 f"\n{indent_2}It matches {backquote(repr(actual))} which was paired with "
1361 + backquote(
1362 self._repr_expected(
1363 self.expected_exceptions[rev_matches[i_actual]]
1364 )
1365 )
1366 )
1367
1368 if remaining_actual:
1369 s += "\nThe following raised exceptions did not find a match"
1370 for i_actual in remaining_actual:
1371 s += f"\n{indent_1}{actual_exceptions[i_actual]!r}:"
1372 for i_exp, expected in enumerate(self.expected_exceptions):
1373 res = results.get_result(i_exp, i_actual)
1374 if i_exp in failed_expected:
1375 assert res is not None
1376 if res[0] != "\n":
1377 s += "\n"
1378 s += indent(res, indent_2)
1379 if res is None:
1380 # we print full repr of match target
1381 s += (
1382 f"\n{indent_2}It matches {backquote(self._repr_expected(expected))} "
1383 f"which was paired with {backquote(repr(actual_exceptions[matches[i_exp]]))}"
1384 )
1385
1386 if len(self.expected_exceptions) == len(actual_exceptions) and possible_match(
1387 results
1388 ):
1389 s += (
1390 "\nThere exist a possible match when attempting an exhaustive check,"
1391 " but RaisesGroup uses a greedy algorithm. "
1392 "Please make your expected exceptions more stringent with `RaisesExc` etc"
1393 " so the greedy algorithm can function."
1394 )
1395 self._fail_reason = s
1396 return False
1397
1398 def __exit__(
1399 self,
1400 exc_type: type[BaseException] | None,
1401 exc_val: BaseException | None,
1402 exc_tb: types.TracebackType | None,
1403 ) -> bool:
1404 __tracebackhide__ = True
1405 if exc_type is None:
1406 fail(f"DID NOT RAISE any exception, expected `{self.expected_type()}`")
1407
1408 assert self.excinfo is not None, (
1409 "Internal error - should have been constructed in __enter__"
1410 )
1411
1412 # group_str is the only thing that differs between RaisesExc and RaisesGroup...
1413 # I might just scrap it? Or make it part of fail_reason
1414 group_str = (
1415 "(group)"
1416 if self.allow_unwrapped and not issubclass(exc_type, BaseExceptionGroup)
1417 else "group"
1418 )
1419
1420 if not self.matches(exc_val):
1421 fail(f"Raised exception {group_str} did not match: {self._fail_reason}")
1422
1423 # Cast to narrow the exception type now that it's verified....
1424 # even though the TypeGuard in self.matches should be narrowing
1425 exc_info = cast(
1426 "tuple[type[BaseExceptionGroup[BaseExcT_co]], BaseExceptionGroup[BaseExcT_co], types.TracebackType]",
1427 (exc_type, exc_val, exc_tb),
1428 )
1429 self.excinfo.fill_unfilled(exc_info)
1430 return True
1431
1432 def expected_type(self) -> str:
1433 subexcs = []
1434 for e in self.expected_exceptions:
1435 if isinstance(e, RaisesExc):
1436 subexcs.append(repr(e))
1437 elif isinstance(e, RaisesGroup):
1438 subexcs.append(e.expected_type())
1439 elif isinstance(e, type):
1440 subexcs.append(e.__name__)
1441 else: # pragma: no cover
1442 raise AssertionError("unknown type")
1443 group_type = "Base" if self.is_baseexception else ""
1444 return f"{group_type}ExceptionGroup({', '.join(subexcs)})"
1445
1446
1447 @final
1448 class NotChecked:
1449 """Singleton for unchecked values in ResultHolder"""
1450
1451
1452 class ResultHolder:
1453 """Container for results of checking exceptions.
1454 Used in RaisesGroup._check_exceptions and possible_match.
1455 """
1456
1457 def __init__(
1458 self,
1459 expected_exceptions: tuple[
1460 type[BaseException] | AbstractRaises[BaseException], ...
1461 ],
1462 actual_exceptions: Sequence[BaseException],
1463 ) -> None:
1464 self.results: list[list[str | type[NotChecked] | None]] = [
1465 [NotChecked for _ in expected_exceptions] for _ in actual_exceptions
1466 ]
1467
1468 def set_result(self, expected: int, actual: int, result: str | None) -> None:
1469 self.results[actual][expected] = result
1470
1471 def get_result(self, expected: int, actual: int) -> str | None:
1472 res = self.results[actual][expected]
1473 assert res is not NotChecked
1474 return res
1475
1476 def has_result(self, expected: int, actual: int) -> bool:
1477 return self.results[actual][expected] is not NotChecked
1478
1479 def no_match_for_expected(self, expected: list[int]) -> bool:
1480 for i in expected:
1481 for actual_results in self.results:
1482 assert actual_results[i] is not NotChecked
1483 if actual_results[i] is None:
1484 return False
1485 return True
1486
1487 def no_match_for_actual(self, actual: list[int]) -> bool:
1488 for i in actual:
1489 for res in self.results[i]:
1490 assert res is not NotChecked
1491 if res is None:
1492 return False
1493 return True
1494
1495
1496 def possible_match(results: ResultHolder, used: set[int] | None = None) -> bool:
1497 if used is None:
1498 used = set()
1499 curr_row = len(used)
1500 if curr_row == len(results.results):
1501 return True
1502 return any(
1503 val is None and i not in used and possible_match(results, used | {i})
1504 for (i, val) in enumerate(results.results[curr_row])
1505 )