MCPcopy
hub / github.com/pytest-dev/pytest / test_catch_unwrapped_exceptions

Function test_catch_unwrapped_exceptions

testing/python/raises_group.py:279–356  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

277
278
279def test_catch_unwrapped_exceptions() -> None:
280 # Catches lone exceptions with strict=False
281 # just as except* would
282 with RaisesGroup(ValueError, allow_unwrapped=True):
283 raise ValueError
284
285 # expecting multiple unwrapped exceptions is not possible
286 with pytest.raises(
287 ValueError,
288 match=r"^You cannot specify multiple exceptions with",
289 ):
290 RaisesGroup(SyntaxError, ValueError, allow_unwrapped=True) # type: ignore[call-overload]
291 # if users want one of several exception types they need to use a RaisesExc
292 # (which the error message suggests)
293 with RaisesGroup(
294 RaisesExc(check=lambda e: isinstance(e, SyntaxError | ValueError)),
295 allow_unwrapped=True,
296 ):
297 raise ValueError
298
299 # Unwrapped nested `RaisesGroup` is likely a user error, so we raise an error.
300 with pytest.raises(ValueError, match="has no effect when expecting"):
301 RaisesGroup(RaisesGroup(ValueError), allow_unwrapped=True) # type: ignore[call-overload]
302
303 # But it *can* be used to check for nesting level +- 1 if they move it to
304 # the nested RaisesGroup. Users should probably use `RaisesExc`s instead though.
305 with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
306 raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
307 with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
308 raise ExceptionGroup("", [ValueError()])
309
310 # with allow_unwrapped=False (default) it will not be caught
311 with (
312 fails_raises_group(
313 "`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
314 ),
315 RaisesGroup(ValueError),
316 ):
317 raise ValueError("value error text")
318
319 # allow_unwrapped on its own won't match against nested groups
320 with (
321 fails_raises_group(
322 "Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
323 " Did you mean to use `flatten_subgroups=True`?",
324 ),
325 RaisesGroup(ValueError, allow_unwrapped=True),
326 ):
327 raise ExceptionGroup("foo", [ExceptionGroup("bar", [ValueError()])])
328
329 # you need both allow_unwrapped and flatten_subgroups to fully emulate except*
330 with RaisesGroup(ValueError, allow_unwrapped=True, flatten_subgroups=True):
331 raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
332
333 # code coverage
334 with (
335 fails_raises_group(
336 "Raised exception (group) did not match: `TypeError()` is not an instance of `ValueError`",

Callers

nothing calls this directly

Calls 3

RaisesGroupClass · 0.90
RaisesExcClass · 0.90
fails_raises_groupFunction · 0.85

Tested by

no test coverage detected