Debian Codegraph @

Lib/test/test_exception_group.py

raw
1 import collections
2 import types
3 import unittest
4 from test.support import skip_emscripten_stack_overflow, skip_wasi_stack_overflow, exceeds_recursion_limit
5
6 class TestExceptionGroupTypeHierarchy(unittest.TestCase):
7 def test_exception_group_types(self):
8 self.assertIsSubclass(ExceptionGroup, Exception)
9 self.assertIsSubclass(ExceptionGroup, BaseExceptionGroup)
10 self.assertIsSubclass(BaseExceptionGroup, BaseException)
11
12 def test_exception_is_not_generic_type(self):
13 with self.assertRaisesRegex(TypeError, 'Exception'):
14 Exception[OSError]
15
16 def test_exception_group_is_generic_type(self):
17 E = OSError
18 self.assertIsInstance(ExceptionGroup[E], types.GenericAlias)
19 self.assertIsInstance(BaseExceptionGroup[E], types.GenericAlias)
20
21
22 class BadConstructorArgs(unittest.TestCase):
23 def test_bad_EG_construction__too_many_args(self):
24 MSG = r'BaseExceptionGroup.__new__\(\) takes exactly 2 arguments'
25 with self.assertRaisesRegex(TypeError, MSG):
26 ExceptionGroup('no errors')
27 with self.assertRaisesRegex(TypeError, MSG):
28 ExceptionGroup([ValueError('no msg')])
29 with self.assertRaisesRegex(TypeError, MSG):
30 ExceptionGroup('eg', [ValueError('too')], [TypeError('many')])
31
32 def test_bad_EG_construction__bad_message(self):
33 MSG = 'argument 1 must be str, not '
34 with self.assertRaisesRegex(TypeError, MSG):
35 ExceptionGroup(ValueError(12), SyntaxError('bad syntax'))
36 with self.assertRaisesRegex(TypeError, MSG):
37 ExceptionGroup(None, [ValueError(12)])
38
39 def test_bad_EG_construction__bad_excs_sequence(self):
40 MSG = r'second argument \(exceptions\) must be a sequence'
41 with self.assertRaisesRegex(TypeError, MSG):
42 ExceptionGroup('errors not sequence', {ValueError(42)})
43 with self.assertRaisesRegex(TypeError, MSG):
44 ExceptionGroup("eg", None)
45
46 MSG = r'second argument \(exceptions\) must be a non-empty sequence'
47 with self.assertRaisesRegex(ValueError, MSG):
48 ExceptionGroup("eg", [])
49
50 def test_bad_EG_construction__nested_non_exceptions(self):
51 MSG = (r'Item [0-9]+ of second argument \(exceptions\)'
52 ' is not an exception')
53 with self.assertRaisesRegex(ValueError, MSG):
54 ExceptionGroup('expect instance, not type', [OSError]);
55 with self.assertRaisesRegex(ValueError, MSG):
56 ExceptionGroup('bad error', ["not an exception"])
57
58
59 class InstanceCreation(unittest.TestCase):
60 def test_EG_wraps_Exceptions__creates_EG(self):
61 excs = [ValueError(1), TypeError(2)]
62 self.assertIs(
63 type(ExceptionGroup("eg", excs)),
64 ExceptionGroup)
65
66 def test_BEG_wraps_Exceptions__creates_EG(self):
67 excs = [ValueError(1), TypeError(2)]
68 self.assertIs(
69 type(BaseExceptionGroup("beg", excs)),
70 ExceptionGroup)
71
72 def test_EG_wraps_BaseException__raises_TypeError(self):
73 MSG= "Cannot nest BaseExceptions in an ExceptionGroup"
74 with self.assertRaisesRegex(TypeError, MSG):
75 eg = ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)])
76
77 def test_BEG_wraps_BaseException__creates_BEG(self):
78 beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)])
79 self.assertIs(type(beg), BaseExceptionGroup)
80
81 def test_EG_subclass_wraps_non_base_exceptions(self):
82 class MyEG(ExceptionGroup):
83 pass
84
85 self.assertIs(
86 type(MyEG("eg", [ValueError(12), TypeError(42)])),
87 MyEG)
88
89 def test_EG_subclass_does_not_wrap_base_exceptions(self):
90 class MyEG(ExceptionGroup):
91 pass
92
93 msg = "Cannot nest BaseExceptions in 'MyEG'"
94 with self.assertRaisesRegex(TypeError, msg):
95 MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
96
97 def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self):
98 class MyEG(BaseExceptionGroup, ValueError):
99 pass
100
101 msg = "Cannot nest BaseExceptions in 'MyEG'"
102 with self.assertRaisesRegex(TypeError, msg):
103 MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
104
105 def test_EG_and_specific_subclass_can_wrap_any_nonbase_exception(self):
106 class MyEG(ExceptionGroup, ValueError):
107 pass
108
109 # The restriction is specific to Exception, not "the other base class"
110 MyEG("eg", [ValueError(12), Exception()])
111
112 def test_BEG_and_specific_subclass_can_wrap_any_nonbase_exception(self):
113 class MyEG(BaseExceptionGroup, ValueError):
114 pass
115
116 # The restriction is specific to Exception, not "the other base class"
117 MyEG("eg", [ValueError(12), Exception()])
118
119
120 def test_BEG_subclass_wraps_anything(self):
121 class MyBEG(BaseExceptionGroup):
122 pass
123
124 self.assertIs(
125 type(MyBEG("eg", [ValueError(12), TypeError(42)])),
126 MyBEG)
127 self.assertIs(
128 type(MyBEG("eg", [ValueError(12), KeyboardInterrupt(42)])),
129 MyBEG)
130
131
132 class StrAndReprTests(unittest.TestCase):
133 def test_ExceptionGroup(self):
134 eg = BaseExceptionGroup(
135 'flat', [ValueError(1), TypeError(2)])
136
137 self.assertEqual(str(eg), "flat (2 sub-exceptions)")
138 self.assertEqual(repr(eg),
139 "ExceptionGroup('flat', [ValueError(1), TypeError(2)])")
140
141 eg = BaseExceptionGroup(
142 'nested', [eg, ValueError(1), eg, TypeError(2)])
143
144 self.assertEqual(str(eg), "nested (4 sub-exceptions)")
145 self.assertEqual(repr(eg),
146 "ExceptionGroup('nested', "
147 "[ExceptionGroup('flat', "
148 "[ValueError(1), TypeError(2)]), "
149 "ValueError(1), "
150 "ExceptionGroup('flat', "
151 "[ValueError(1), TypeError(2)]), TypeError(2)])")
152
153 def test_BaseExceptionGroup(self):
154 eg = BaseExceptionGroup(
155 'flat', [ValueError(1), KeyboardInterrupt(2)])
156
157 self.assertEqual(str(eg), "flat (2 sub-exceptions)")
158 self.assertEqual(repr(eg),
159 "BaseExceptionGroup("
160 "'flat', "
161 "[ValueError(1), KeyboardInterrupt(2)])")
162
163 eg = BaseExceptionGroup(
164 'nested', [eg, ValueError(1), eg])
165
166 self.assertEqual(str(eg), "nested (3 sub-exceptions)")
167 self.assertEqual(repr(eg),
168 "BaseExceptionGroup('nested', "
169 "[BaseExceptionGroup('flat', "
170 "[ValueError(1), KeyboardInterrupt(2)]), "
171 "ValueError(1), "
172 "BaseExceptionGroup('flat', "
173 "[ValueError(1), KeyboardInterrupt(2)])])")
174
175 def test_custom_exception(self):
176 class MyEG(ExceptionGroup):
177 pass
178
179 eg = MyEG(
180 'flat', [ValueError(1), TypeError(2)])
181
182 self.assertEqual(str(eg), "flat (2 sub-exceptions)")
183 self.assertEqual(repr(eg), "MyEG('flat', [ValueError(1), TypeError(2)])")
184
185 eg = MyEG(
186 'nested', [eg, ValueError(1), eg, TypeError(2)])
187
188 self.assertEqual(str(eg), "nested (4 sub-exceptions)")
189 self.assertEqual(repr(eg), (
190 "MyEG('nested', "
191 "[MyEG('flat', [ValueError(1), TypeError(2)]), "
192 "ValueError(1), "
193 "MyEG('flat', [ValueError(1), TypeError(2)]), "
194 "TypeError(2)])"))
195
196 def test_exceptions_mutation(self):
197 class MyEG(ExceptionGroup):
198 pass
199
200 excs = [ValueError(1), TypeError(2)]
201 eg = MyEG('test', excs)
202
203 self.assertEqual(repr(eg), "MyEG('test', [ValueError(1), TypeError(2)])")
204 excs.clear()
205
206 # Ensure that clearing the exceptions sequence doesn't change the repr.
207 self.assertEqual(repr(eg), "MyEG('test', [ValueError(1), TypeError(2)])")
208
209 # Ensure that the args are still as passed.
210 self.assertEqual(eg.args, ('test', []))
211
212 excs = (ValueError(1), KeyboardInterrupt(2))
213 eg = BaseExceptionGroup('test', excs)
214
215 # Ensure that immutable sequences still work fine.
216 self.assertEqual(
217 repr(eg),
218 "BaseExceptionGroup('test', (ValueError(1), KeyboardInterrupt(2)))"
219 )
220
221 # Test non-standard custom sequences.
222 excs = collections.deque([ValueError(1), TypeError(2)])
223 eg = ExceptionGroup('test', excs)
224
225 self.assertEqual(
226 repr(eg),
227 "ExceptionGroup('test', deque([ValueError(1), TypeError(2)]))"
228 )
229 excs.clear()
230
231 # Ensure that clearing the exceptions sequence doesn't change the repr.
232 self.assertEqual(
233 repr(eg),
234 "ExceptionGroup('test', deque([ValueError(1), TypeError(2)]))"
235 )
236
237 def test_repr_raises(self):
238 class MySeq(collections.abc.Sequence):
239 def __init__(self, raises):
240 self.raises = raises
241
242 def __len__(self):
243 return 1
244
245 def __getitem__(self, index):
246 if index == 0:
247 return ValueError(1)
248 raise IndexError
249
250 def __repr__(self):
251 if self.raises:
252 raise self.raises
253 return None
254
255 seq = MySeq(None)
256 with self.assertRaisesRegex(
257 TypeError,
258 r"__repr__ returned non-string \(type NoneType\)"
259 ):
260 ExceptionGroup("test", seq)
261
262 seq = MySeq(ValueError)
263 with self.assertRaises(ValueError):
264 BaseExceptionGroup("test", seq)
265
266
267
268 def create_simple_eg():
269 excs = []
270 try:
271 try:
272 raise MemoryError("context and cause for ValueError(1)")
273 except MemoryError as e:
274 raise ValueError(1) from e
275 except ValueError as e:
276 excs.append(e)
277
278 try:
279 try:
280 raise OSError("context for TypeError")
281 except OSError as e:
282 raise TypeError(int)
283 except TypeError as e:
284 excs.append(e)
285
286 try:
287 try:
288 raise ImportError("context for ValueError(2)")
289 except ImportError as e:
290 raise ValueError(2)
291 except ValueError as e:
292 excs.append(e)
293
294 try:
295 raise ExceptionGroup('simple eg', excs)
296 except ExceptionGroup as e:
297 return e
298
299
300 class ExceptionGroupFields(unittest.TestCase):
301 def test_basics_ExceptionGroup_fields(self):
302 eg = create_simple_eg()
303
304 # check msg
305 self.assertEqual(eg.message, 'simple eg')
306 self.assertEqual(eg.args[0], 'simple eg')
307
308 # check cause and context
309 self.assertIsInstance(eg.exceptions[0], ValueError)
310 self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError)
311 self.assertIsInstance(eg.exceptions[0].__context__, MemoryError)
312 self.assertIsInstance(eg.exceptions[1], TypeError)
313 self.assertIsNone(eg.exceptions[1].__cause__)
314 self.assertIsInstance(eg.exceptions[1].__context__, OSError)
315 self.assertIsInstance(eg.exceptions[2], ValueError)
316 self.assertIsNone(eg.exceptions[2].__cause__)
317 self.assertIsInstance(eg.exceptions[2].__context__, ImportError)
318
319 # check tracebacks
320 line0 = create_simple_eg.__code__.co_firstlineno
321 tb_linenos = [line0 + 27,
322 [line0 + 6, line0 + 14, line0 + 22]]
323 self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0])
324 self.assertIsNone(eg.__traceback__.tb_next)
325 for i in range(3):
326 tb = eg.exceptions[i].__traceback__
327 self.assertIsNone(tb.tb_next)
328 self.assertEqual(tb.tb_lineno, tb_linenos[1][i])
329
330 def test_fields_are_readonly(self):
331 eg = ExceptionGroup('eg', [TypeError(1), OSError(2)])
332
333 self.assertEqual(type(eg.exceptions), tuple)
334
335 eg.message
336 with self.assertRaises(AttributeError):
337 eg.message = "new msg"
338
339 eg.exceptions
340 with self.assertRaises(AttributeError):
341 eg.exceptions = [OSError('xyz')]
342
343
344 class ExceptionGroupTestBase(unittest.TestCase):
345 def assertMatchesTemplate(self, exc, exc_type, template):
346 """ Assert that the exception matches the template
347
348 A template describes the shape of exc. If exc is a
349 leaf exception (i.e., not an exception group) then
350 template is an exception instance that has the
351 expected type and args value of exc. If exc is an
352 exception group, then template is a list of the
353 templates of its nested exceptions.
354 """
355 if exc_type is not None:
356 self.assertIs(type(exc), exc_type)
357
358 if isinstance(exc, BaseExceptionGroup):
359 self.assertIsInstance(template, collections.abc.Sequence)
360 self.assertEqual(len(exc.exceptions), len(template))
361 for e, t in zip(exc.exceptions, template):
362 self.assertMatchesTemplate(e, None, t)
363 else:
364 self.assertIsInstance(template, BaseException)
365 self.assertEqual(type(exc), type(template))
366 self.assertEqual(exc.args, template.args)
367
368 class Predicate:
369 def __init__(self, func):
370 self.func = func
371
372 def __call__(self, e):
373 return self.func(e)
374
375 def method(self, e):
376 return self.func(e)
377
378 class ExceptionGroupSubgroupTests(ExceptionGroupTestBase):
379 def setUp(self):
380 self.eg = create_simple_eg()
381 self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
382
383 def test_basics_subgroup_split__bad_arg_type(self):
384 class C:
385 pass
386
387 bad_args = ["bad arg",
388 C,
389 OSError('instance not type'),
390 [OSError, TypeError],
391 (OSError, 42),
392 ]
393 for arg in bad_args:
394 with self.assertRaises(TypeError):
395 self.eg.subgroup(arg)
396 with self.assertRaises(TypeError):
397 self.eg.split(arg)
398
399 def test_basics_subgroup_by_type__passthrough(self):
400 eg = self.eg
401 self.assertIs(eg, eg.subgroup(BaseException))
402 self.assertIs(eg, eg.subgroup(Exception))
403 self.assertIs(eg, eg.subgroup(BaseExceptionGroup))
404 self.assertIs(eg, eg.subgroup(ExceptionGroup))
405
406 def test_basics_subgroup_by_type__no_match(self):
407 self.assertIsNone(self.eg.subgroup(OSError))
408
409 def test_basics_subgroup_by_type__match(self):
410 eg = self.eg
411 testcases = [
412 # (match_type, result_template)
413 (ValueError, [ValueError(1), ValueError(2)]),
414 (TypeError, [TypeError(int)]),
415 ((ValueError, TypeError), self.eg_template)]
416
417 for match_type, template in testcases:
418 with self.subTest(match=match_type):
419 subeg = eg.subgroup(match_type)
420 self.assertEqual(subeg.message, eg.message)
421 self.assertMatchesTemplate(subeg, ExceptionGroup, template)
422
423 def test_basics_subgroup_by_predicate__passthrough(self):
424 f = lambda e: True
425 for callable in [f, Predicate(f), Predicate(f).method]:
426 self.assertIs(self.eg, self.eg.subgroup(callable))
427
428 def test_basics_subgroup_by_predicate__no_match(self):
429 f = lambda e: False
430 for callable in [f, Predicate(f), Predicate(f).method]:
431 self.assertIsNone(self.eg.subgroup(callable))
432
433 def test_basics_subgroup_by_predicate__match(self):
434 eg = self.eg
435 testcases = [
436 # (match_type, result_template)
437 (ValueError, [ValueError(1), ValueError(2)]),
438 (TypeError, [TypeError(int)]),
439 ((ValueError, TypeError), self.eg_template)]
440
441 for match_type, template in testcases:
442 f = lambda e: isinstance(e, match_type)
443 for callable in [f, Predicate(f), Predicate(f).method]:
444 with self.subTest(callable=callable):
445 subeg = eg.subgroup(f)
446 self.assertEqual(subeg.message, eg.message)
447 self.assertMatchesTemplate(subeg, ExceptionGroup, template)
448
449
450 class ExceptionGroupSplitTests(ExceptionGroupTestBase):
451 def setUp(self):
452 self.eg = create_simple_eg()
453 self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
454
455 def test_basics_split_by_type__passthrough(self):
456 for E in [BaseException, Exception,
457 BaseExceptionGroup, ExceptionGroup]:
458 match, rest = self.eg.split(E)
459 self.assertMatchesTemplate(
460 match, ExceptionGroup, self.eg_template)
461 self.assertIsNone(rest)
462
463 def test_basics_split_by_type__no_match(self):
464 match, rest = self.eg.split(OSError)
465 self.assertIsNone(match)
466 self.assertMatchesTemplate(
467 rest, ExceptionGroup, self.eg_template)
468
469 def test_basics_split_by_type__match(self):
470 eg = self.eg
471 VE = ValueError
472 TE = TypeError
473 testcases = [
474 # (matcher, match_template, rest_template)
475 (VE, [VE(1), VE(2)], [TE(int)]),
476 (TE, [TE(int)], [VE(1), VE(2)]),
477 ((VE, TE), self.eg_template, None),
478 ((OSError, VE), [VE(1), VE(2)], [TE(int)]),
479 ]
480
481 for match_type, match_template, rest_template in testcases:
482 match, rest = eg.split(match_type)
483 self.assertEqual(match.message, eg.message)
484 self.assertMatchesTemplate(
485 match, ExceptionGroup, match_template)
486 if rest_template is not None:
487 self.assertEqual(rest.message, eg.message)
488 self.assertMatchesTemplate(
489 rest, ExceptionGroup, rest_template)
490 else:
491 self.assertIsNone(rest)
492
493 def test_basics_split_by_predicate__passthrough(self):
494 f = lambda e: True
495 for callable in [f, Predicate(f), Predicate(f).method]:
496 match, rest = self.eg.split(callable)
497 self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template)
498 self.assertIsNone(rest)
499
500 def test_basics_split_by_predicate__no_match(self):
501 f = lambda e: False
502 for callable in [f, Predicate(f), Predicate(f).method]:
503 match, rest = self.eg.split(callable)
504 self.assertIsNone(match)
505 self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template)
506
507 def test_basics_split_by_predicate__match(self):
508 eg = self.eg
509 VE = ValueError
510 TE = TypeError
511 testcases = [
512 # (matcher, match_template, rest_template)
513 (VE, [VE(1), VE(2)], [TE(int)]),
514 (TE, [TE(int)], [VE(1), VE(2)]),
515 ((VE, TE), self.eg_template, None),
516 ]
517
518 for match_type, match_template, rest_template in testcases:
519 f = lambda e: isinstance(e, match_type)
520 for callable in [f, Predicate(f), Predicate(f).method]:
521 match, rest = eg.split(callable)
522 self.assertEqual(match.message, eg.message)
523 self.assertMatchesTemplate(
524 match, ExceptionGroup, match_template)
525 if rest_template is not None:
526 self.assertEqual(rest.message, eg.message)
527 self.assertMatchesTemplate(
528 rest, ExceptionGroup, rest_template)
529
530
531 class DeepRecursionInSplitAndSubgroup(unittest.TestCase):
532 def make_deep_eg(self):
533 e = TypeError(1)
534 for i in range(exceeds_recursion_limit()):
535 e = ExceptionGroup('eg', [e])
536 return e
537
538 @skip_emscripten_stack_overflow()
539 @skip_wasi_stack_overflow()
540 def test_deep_split(self):
541 e = self.make_deep_eg()
542 with self.assertRaises(RecursionError):
543 e.split(TypeError)
544
545 @skip_emscripten_stack_overflow()
546 @skip_wasi_stack_overflow()
547 def test_deep_subgroup(self):
548 e = self.make_deep_eg()
549 with self.assertRaises(RecursionError):
550 e.subgroup(TypeError)
551
552
553 def leaf_generator(exc, tbs=None):
554 if tbs is None:
555 tbs = []
556 tbs.append(exc.__traceback__)
557 if isinstance(exc, BaseExceptionGroup):
558 for e in exc.exceptions:
559 yield from leaf_generator(e, tbs)
560 else:
561 # exc is a leaf exception and its traceback
562 # is the concatenation of the traceback
563 # segments in tbs
564 yield exc, tbs
565 tbs.pop()
566
567
568 class LeafGeneratorTest(unittest.TestCase):
569 # The leaf_generator is mentioned in PEP 654 as a suggestion
570 # on how to iterate over leaf nodes of an EG. Is is also
571 # used below as a test utility. So we test it here.
572
573 def test_leaf_generator(self):
574 eg = create_simple_eg()
575
576 self.assertSequenceEqual(
577 [e for e, _ in leaf_generator(eg)],
578 eg.exceptions)
579
580 for e, tbs in leaf_generator(eg):
581 self.assertSequenceEqual(
582 tbs, [eg.__traceback__, e.__traceback__])
583
584
585 def create_nested_eg():
586 excs = []
587 try:
588 try:
589 raise TypeError(bytes)
590 except TypeError as e:
591 raise ExceptionGroup("nested", [e])
592 except ExceptionGroup as e:
593 excs.append(e)
594
595 try:
596 try:
597 raise MemoryError('out of memory')
598 except MemoryError as e:
599 raise ValueError(1) from e
600 except ValueError as e:
601 excs.append(e)
602
603 try:
604 raise ExceptionGroup("root", excs)
605 except ExceptionGroup as eg:
606 return eg
607
608
609 class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase):
610 def test_nested_group_matches_template(self):
611 eg = create_nested_eg()
612 self.assertMatchesTemplate(
613 eg,
614 ExceptionGroup,
615 [[TypeError(bytes)], ValueError(1)])
616
617 def test_nested_group_chaining(self):
618 eg = create_nested_eg()
619 self.assertIsInstance(eg.exceptions[1].__context__, MemoryError)
620 self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError)
621 self.assertIsInstance(eg.exceptions[0].__context__, TypeError)
622
623 def test_nested_exception_group_tracebacks(self):
624 eg = create_nested_eg()
625
626 line0 = create_nested_eg.__code__.co_firstlineno
627 for (tb, expected) in [
628 (eg.__traceback__, line0 + 19),
629 (eg.exceptions[0].__traceback__, line0 + 6),
630 (eg.exceptions[1].__traceback__, line0 + 14),
631 (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4),
632 ]:
633 self.assertEqual(tb.tb_lineno, expected)
634 self.assertIsNone(tb.tb_next)
635
636 def test_iteration_full_tracebacks(self):
637 eg = create_nested_eg()
638 # check that iteration over leaves
639 # produces the expected tracebacks
640 self.assertEqual(len(list(leaf_generator(eg))), 2)
641
642 line0 = create_nested_eg.__code__.co_firstlineno
643 expected_tbs = [ [line0 + 19, line0 + 6, line0 + 4],
644 [line0 + 19, line0 + 14]]
645
646 for (i, (_, tbs)) in enumerate(leaf_generator(eg)):
647 self.assertSequenceEqual(
648 [tb.tb_lineno for tb in tbs],
649 expected_tbs[i])
650
651
652 class ExceptionGroupSplitTestBase(ExceptionGroupTestBase):
653
654 def split_exception_group(self, eg, types):
655 """ Split an EG and do some sanity checks on the result """
656 self.assertIsInstance(eg, BaseExceptionGroup)
657
658 match, rest = eg.split(types)
659 sg = eg.subgroup(types)
660
661 if match is not None:
662 self.assertIsInstance(match, BaseExceptionGroup)
663 for e,_ in leaf_generator(match):
664 self.assertIsInstance(e, types)
665
666 self.assertIsNotNone(sg)
667 self.assertIsInstance(sg, BaseExceptionGroup)
668 for e,_ in leaf_generator(sg):
669 self.assertIsInstance(e, types)
670
671 if rest is not None:
672 self.assertIsInstance(rest, BaseExceptionGroup)
673
674 def leaves(exc):
675 return [] if exc is None else [e for e,_ in leaf_generator(exc)]
676
677 # match and subgroup have the same leaves
678 self.assertSequenceEqual(leaves(match), leaves(sg))
679
680 match_leaves = leaves(match)
681 rest_leaves = leaves(rest)
682 # each leaf exception of eg is in exactly one of match and rest
683 self.assertEqual(
684 len(leaves(eg)),
685 len(leaves(match)) + len(leaves(rest)))
686
687 for e in leaves(eg):
688 self.assertNotEqual(
689 match and e in match_leaves,
690 rest and e in rest_leaves)
691
692 # message, cause and context, traceback and note equal to eg
693 for part in [match, rest, sg]:
694 if part is not None:
695 self.assertEqual(eg.message, part.message)
696 self.assertIs(eg.__cause__, part.__cause__)
697 self.assertIs(eg.__context__, part.__context__)
698 self.assertIs(eg.__traceback__, part.__traceback__)
699 self.assertEqual(
700 getattr(eg, '__notes__', None),
701 getattr(part, '__notes__', None))
702
703 def tbs_for_leaf(leaf, eg):
704 for e, tbs in leaf_generator(eg):
705 if e is leaf:
706 return tbs
707
708 def tb_linenos(tbs):
709 return [tb.tb_lineno for tb in tbs if tb]
710
711 # full tracebacks match
712 for part in [match, rest, sg]:
713 for e in leaves(part):
714 self.assertSequenceEqual(
715 tb_linenos(tbs_for_leaf(e, eg)),
716 tb_linenos(tbs_for_leaf(e, part)))
717
718 return match, rest
719
720
721 class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase):
722
723 def test_split_by_type(self):
724 class MyExceptionGroup(ExceptionGroup):
725 pass
726
727 def raiseVE(v):
728 raise ValueError(v)
729
730 def raiseTE(t):
731 raise TypeError(t)
732
733 def nested_group():
734 def level1(i):
735 excs = []
736 for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i+1)]:
737 try:
738 f(arg)
739 except Exception as e:
740 excs.append(e)
741 raise ExceptionGroup('msg1', excs)
742
743 def level2(i):
744 excs = []
745 for f, arg in [(level1, i), (level1, i+1), (raiseVE, i+2)]:
746 try:
747 f(arg)
748 except Exception as e:
749 excs.append(e)
750 raise MyExceptionGroup('msg2', excs)
751
752 def level3(i):
753 excs = []
754 for f, arg in [(level2, i+1), (raiseVE, i+2)]:
755 try:
756 f(arg)
757 except Exception as e:
758 excs.append(e)
759 raise ExceptionGroup('msg3', excs)
760
761 level3(5)
762
763 try:
764 nested_group()
765 except ExceptionGroup as e:
766 e.add_note(f"the note: {id(e)}")
767 eg = e
768
769 eg_template = [
770 [
771 [ValueError(6), TypeError(int), ValueError(7)],
772 [ValueError(7), TypeError(int), ValueError(8)],
773 ValueError(8),
774 ],
775 ValueError(7)]
776
777 valueErrors_template = [
778 [
779 [ValueError(6), ValueError(7)],
780 [ValueError(7), ValueError(8)],
781 ValueError(8),
782 ],
783 ValueError(7)]
784
785 typeErrors_template = [[[TypeError(int)], [TypeError(int)]]]
786
787 self.assertMatchesTemplate(eg, ExceptionGroup, eg_template)
788
789 # Match Nothing
790 match, rest = self.split_exception_group(eg, SyntaxError)
791 self.assertIsNone(match)
792 self.assertMatchesTemplate(rest, ExceptionGroup, eg_template)
793
794 # Match Everything
795 match, rest = self.split_exception_group(eg, BaseException)
796 self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
797 self.assertIsNone(rest)
798 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
799 self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
800 self.assertIsNone(rest)
801
802 # Match ValueErrors
803 match, rest = self.split_exception_group(eg, ValueError)
804 self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template)
805 self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template)
806
807 # Match TypeErrors
808 match, rest = self.split_exception_group(eg, (TypeError, SyntaxError))
809 self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template)
810 self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template)
811
812 # Match ExceptionGroup
813 match, rest = eg.split(ExceptionGroup)
814 self.assertIs(match, eg)
815 self.assertIsNone(rest)
816
817 # Match MyExceptionGroup (ExceptionGroup subclass)
818 match, rest = eg.split(MyExceptionGroup)
819 self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]])
820 self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]])
821
822 def test_split_BaseExceptionGroup(self):
823 def exc(ex):
824 try:
825 raise ex
826 except BaseException as e:
827 return e
828
829 try:
830 raise BaseExceptionGroup(
831 "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))])
832 except BaseExceptionGroup as e:
833 beg = e
834
835 # Match Nothing
836 match, rest = self.split_exception_group(beg, TypeError)
837 self.assertIsNone(match)
838 self.assertMatchesTemplate(
839 rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
840
841 # Match Everything
842 match, rest = self.split_exception_group(
843 beg, (ValueError, KeyboardInterrupt))
844 self.assertMatchesTemplate(
845 match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
846 self.assertIsNone(rest)
847
848 # Match ValueErrors
849 match, rest = self.split_exception_group(beg, ValueError)
850 self.assertMatchesTemplate(
851 match, ExceptionGroup, [ValueError(1)])
852 self.assertMatchesTemplate(
853 rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
854
855 # Match KeyboardInterrupts
856 match, rest = self.split_exception_group(beg, KeyboardInterrupt)
857 self.assertMatchesTemplate(
858 match, BaseExceptionGroup, [KeyboardInterrupt(2)])
859 self.assertMatchesTemplate(
860 rest, ExceptionGroup, [ValueError(1)])
861
862 def test_split_copies_notes(self):
863 # make sure each exception group after a split has its own __notes__ list
864 eg = ExceptionGroup("eg", [ValueError(1), TypeError(2)])
865 eg.add_note("note1")
866 eg.add_note("note2")
867 orig_notes = list(eg.__notes__)
868 match, rest = eg.split(TypeError)
869 self.assertEqual(eg.__notes__, orig_notes)
870 self.assertEqual(match.__notes__, orig_notes)
871 self.assertEqual(rest.__notes__, orig_notes)
872 self.assertIsNot(eg.__notes__, match.__notes__)
873 self.assertIsNot(eg.__notes__, rest.__notes__)
874 self.assertIsNot(match.__notes__, rest.__notes__)
875 eg.add_note("eg")
876 match.add_note("match")
877 rest.add_note("rest")
878 self.assertEqual(eg.__notes__, orig_notes + ["eg"])
879 self.assertEqual(match.__notes__, orig_notes + ["match"])
880 self.assertEqual(rest.__notes__, orig_notes + ["rest"])
881
882 def test_split_does_not_copy_non_sequence_notes(self):
883 # __notes__ should be a sequence, which is shallow copied.
884 # If it is not a sequence, the split parts don't get any notes.
885 eg = ExceptionGroup("eg", [ValueError(1), TypeError(2)])
886 eg.__notes__ = 123
887 match, rest = eg.split(TypeError)
888 self.assertNotHasAttr(match, '__notes__')
889 self.assertNotHasAttr(rest, '__notes__')
890
891 def test_drive_invalid_return_value(self):
892 class MyEg(ExceptionGroup):
893 def derive(self, excs):
894 return 42
895
896 eg = MyEg('eg', [TypeError(1), ValueError(2)])
897 msg = "derive must return an instance of BaseExceptionGroup"
898 with self.assertRaisesRegex(TypeError, msg):
899 eg.split(TypeError)
900 with self.assertRaisesRegex(TypeError, msg):
901 eg.subgroup(TypeError)
902
903
904 class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase):
905
906 def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self):
907 class EG(ExceptionGroup):
908 pass
909
910 try:
911 try:
912 try:
913 raise TypeError(2)
914 except TypeError as te:
915 raise EG("nested", [te])
916 except EG as nested:
917 try:
918 raise ValueError(1)
919 except ValueError as ve:
920 raise EG("eg", [ve, nested])
921 except EG as e:
922 eg = e
923
924 self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
925
926 # Match Nothing
927 match, rest = self.split_exception_group(eg, OSError)
928 self.assertIsNone(match)
929 self.assertMatchesTemplate(
930 rest, ExceptionGroup, [ValueError(1), [TypeError(2)]])
931
932 # Match Everything
933 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
934 self.assertMatchesTemplate(
935 match, ExceptionGroup, [ValueError(1), [TypeError(2)]])
936 self.assertIsNone(rest)
937
938 # Match ValueErrors
939 match, rest = self.split_exception_group(eg, ValueError)
940 self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
941 self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]])
942
943 # Match TypeErrors
944 match, rest = self.split_exception_group(eg, TypeError)
945 self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]])
946 self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
947
948 def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self):
949 class EG(BaseExceptionGroup):
950 def __new__(cls, message, excs, unused):
951 # The "unused" arg is here to show that split() doesn't call
952 # the actual class constructor from the default derive()
953 # implementation (it would fail on unused arg if so because
954 # it assumes the BaseExceptionGroup.__new__ signature).
955 return super().__new__(cls, message, excs)
956
957 try:
958 raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused")
959 except EG as e:
960 eg = e
961
962 self.assertMatchesTemplate(
963 eg, EG, [ValueError(1), KeyboardInterrupt(2)])
964
965 # Match Nothing
966 match, rest = self.split_exception_group(eg, OSError)
967 self.assertIsNone(match)
968 self.assertMatchesTemplate(
969 rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
970
971 # Match Everything
972 match, rest = self.split_exception_group(
973 eg, (ValueError, KeyboardInterrupt))
974 self.assertMatchesTemplate(
975 match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
976 self.assertIsNone(rest)
977
978 # Match ValueErrors
979 match, rest = self.split_exception_group(eg, ValueError)
980 self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
981 self.assertMatchesTemplate(
982 rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
983
984 # Match KeyboardInterrupt
985 match, rest = self.split_exception_group(eg, KeyboardInterrupt)
986 self.assertMatchesTemplate(
987 match, BaseExceptionGroup, [KeyboardInterrupt(2)])
988 self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
989
990 def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self):
991 class EG(ExceptionGroup):
992 def __new__(cls, message, excs, code):
993 obj = super().__new__(cls, message, excs)
994 obj.code = code
995 return obj
996
997 def derive(self, excs):
998 return EG(self.message, excs, self.code)
999
1000 try:
1001 try:
1002 try:
1003 raise TypeError(2)
1004 except TypeError as te:
1005 raise EG("nested", [te], 101)
1006 except EG as nested:
1007 try:
1008 raise ValueError(1)
1009 except ValueError as ve:
1010 raise EG("eg", [ve, nested], 42)
1011 except EG as e:
1012 eg = e
1013
1014 self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
1015
1016 # Match Nothing
1017 match, rest = self.split_exception_group(eg, OSError)
1018 self.assertIsNone(match)
1019 self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]])
1020 self.assertEqual(rest.code, 42)
1021 self.assertEqual(rest.exceptions[1].code, 101)
1022
1023 # Match Everything
1024 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
1025 self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]])
1026 self.assertEqual(match.code, 42)
1027 self.assertEqual(match.exceptions[1].code, 101)
1028 self.assertIsNone(rest)
1029
1030 # Match ValueErrors
1031 match, rest = self.split_exception_group(eg, ValueError)
1032 self.assertMatchesTemplate(match, EG, [ValueError(1)])
1033 self.assertEqual(match.code, 42)
1034 self.assertMatchesTemplate(rest, EG, [[TypeError(2)]])
1035 self.assertEqual(rest.code, 42)
1036 self.assertEqual(rest.exceptions[0].code, 101)
1037
1038 # Match TypeErrors
1039 match, rest = self.split_exception_group(eg, TypeError)
1040 self.assertMatchesTemplate(match, EG, [[TypeError(2)]])
1041 self.assertEqual(match.code, 42)
1042 self.assertEqual(match.exceptions[0].code, 101)
1043 self.assertMatchesTemplate(rest, EG, [ValueError(1)])
1044 self.assertEqual(rest.code, 42)
1045
1046
1047 if __name__ == '__main__':
1048 unittest.main()