Debian Codegraph @

lib-python/3/test/test_exception_group.py

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