Debian Codegraph @

Lib/test/test_exception_group.py

raw
1 import collections
2 import types
3 import unittest
4 from test.support import get_c_recursion_limit
5
6 class TestExceptionGroupTypeHierarchy(unittest.TestCase):
7 def test_exception_group_types(self):
8 self.assertTrue(issubclass(ExceptionGroup, Exception))
9 self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup))
10 self.assertTrue(issubclass(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(get_c_recursion_limit() + 1):
535 e = ExceptionGroup('eg', [e])
536 return e
537
538 def test_deep_split(self):
539 e = self.make_deep_eg()
540 with self.assertRaises(RecursionError):
541 e.split(TypeError)
542
543 def test_deep_subgroup(self):
544 e = self.make_deep_eg()
545 with self.assertRaises(RecursionError):
546 e.subgroup(TypeError)
547
548
549 def leaf_generator(exc, tbs=None):
550 if tbs is None:
551 tbs = []
552 tbs.append(exc.__traceback__)
553 if isinstance(exc, BaseExceptionGroup):
554 for e in exc.exceptions:
555 yield from leaf_generator(e, tbs)
556 else:
557 # exc is a leaf exception and its traceback
558 # is the concatenation of the traceback
559 # segments in tbs
560 yield exc, tbs
561 tbs.pop()
562
563
564 class LeafGeneratorTest(unittest.TestCase):
565 # The leaf_generator is mentioned in PEP 654 as a suggestion
566 # on how to iterate over leaf nodes of an EG. Is is also
567 # used below as a test utility. So we test it here.
568
569 def test_leaf_generator(self):
570 eg = create_simple_eg()
571
572 self.assertSequenceEqual(
573 [e for e, _ in leaf_generator(eg)],
574 eg.exceptions)
575
576 for e, tbs in leaf_generator(eg):
577 self.assertSequenceEqual(
578 tbs, [eg.__traceback__, e.__traceback__])
579
580
581 def create_nested_eg():
582 excs = []
583 try:
584 try:
585 raise TypeError(bytes)
586 except TypeError as e:
587 raise ExceptionGroup("nested", [e])
588 except ExceptionGroup as e:
589 excs.append(e)
590
591 try:
592 try:
593 raise MemoryError('out of memory')
594 except MemoryError as e:
595 raise ValueError(1) from e
596 except ValueError as e:
597 excs.append(e)
598
599 try:
600 raise ExceptionGroup("root", excs)
601 except ExceptionGroup as eg:
602 return eg
603
604
605 class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase):
606 def test_nested_group_matches_template(self):
607 eg = create_nested_eg()
608 self.assertMatchesTemplate(
609 eg,
610 ExceptionGroup,
611 [[TypeError(bytes)], ValueError(1)])
612
613 def test_nested_group_chaining(self):
614 eg = create_nested_eg()
615 self.assertIsInstance(eg.exceptions[1].__context__, MemoryError)
616 self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError)
617 self.assertIsInstance(eg.exceptions[0].__context__, TypeError)
618
619 def test_nested_exception_group_tracebacks(self):
620 eg = create_nested_eg()
621
622 line0 = create_nested_eg.__code__.co_firstlineno
623 for (tb, expected) in [
624 (eg.__traceback__, line0 + 19),
625 (eg.exceptions[0].__traceback__, line0 + 6),
626 (eg.exceptions[1].__traceback__, line0 + 14),
627 (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4),
628 ]:
629 self.assertEqual(tb.tb_lineno, expected)
630 self.assertIsNone(tb.tb_next)
631
632 def test_iteration_full_tracebacks(self):
633 eg = create_nested_eg()
634 # check that iteration over leaves
635 # produces the expected tracebacks
636 self.assertEqual(len(list(leaf_generator(eg))), 2)
637
638 line0 = create_nested_eg.__code__.co_firstlineno
639 expected_tbs = [ [line0 + 19, line0 + 6, line0 + 4],
640 [line0 + 19, line0 + 14]]
641
642 for (i, (_, tbs)) in enumerate(leaf_generator(eg)):
643 self.assertSequenceEqual(
644 [tb.tb_lineno for tb in tbs],
645 expected_tbs[i])
646
647
648 class ExceptionGroupSplitTestBase(ExceptionGroupTestBase):
649
650 def split_exception_group(self, eg, types):
651 """ Split an EG and do some sanity checks on the result """
652 self.assertIsInstance(eg, BaseExceptionGroup)
653
654 match, rest = eg.split(types)
655 sg = eg.subgroup(types)
656
657 if match is not None:
658 self.assertIsInstance(match, BaseExceptionGroup)
659 for e,_ in leaf_generator(match):
660 self.assertIsInstance(e, types)
661
662 self.assertIsNotNone(sg)
663 self.assertIsInstance(sg, BaseExceptionGroup)
664 for e,_ in leaf_generator(sg):
665 self.assertIsInstance(e, types)
666
667 if rest is not None:
668 self.assertIsInstance(rest, BaseExceptionGroup)
669
670 def leaves(exc):
671 return [] if exc is None else [e for e,_ in leaf_generator(exc)]
672
673 # match and subgroup have the same leaves
674 self.assertSequenceEqual(leaves(match), leaves(sg))
675
676 match_leaves = leaves(match)
677 rest_leaves = leaves(rest)
678 # each leaf exception of eg is in exactly one of match and rest
679 self.assertEqual(
680 len(leaves(eg)),
681 len(leaves(match)) + len(leaves(rest)))
682
683 for e in leaves(eg):
684 self.assertNotEqual(
685 match and e in match_leaves,
686 rest and e in rest_leaves)
687
688 # message, cause and context, traceback and note equal to eg
689 for part in [match, rest, sg]:
690 if part is not None:
691 self.assertEqual(eg.message, part.message)
692 self.assertIs(eg.__cause__, part.__cause__)
693 self.assertIs(eg.__context__, part.__context__)
694 self.assertIs(eg.__traceback__, part.__traceback__)
695 self.assertEqual(
696 getattr(eg, '__notes__', None),
697 getattr(part, '__notes__', None))
698
699 def tbs_for_leaf(leaf, eg):
700 for e, tbs in leaf_generator(eg):
701 if e is leaf:
702 return tbs
703
704 def tb_linenos(tbs):
705 return [tb.tb_lineno for tb in tbs if tb]
706
707 # full tracebacks match
708 for part in [match, rest, sg]:
709 for e in leaves(part):
710 self.assertSequenceEqual(
711 tb_linenos(tbs_for_leaf(e, eg)),
712 tb_linenos(tbs_for_leaf(e, part)))
713
714 return match, rest
715
716
717 class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase):
718
719 def test_split_by_type(self):
720 class MyExceptionGroup(ExceptionGroup):
721 pass
722
723 def raiseVE(v):
724 raise ValueError(v)
725
726 def raiseTE(t):
727 raise TypeError(t)
728
729 def nested_group():
730 def level1(i):
731 excs = []
732 for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i+1)]:
733 try:
734 f(arg)
735 except Exception as e:
736 excs.append(e)
737 raise ExceptionGroup('msg1', excs)
738
739 def level2(i):
740 excs = []
741 for f, arg in [(level1, i), (level1, i+1), (raiseVE, i+2)]:
742 try:
743 f(arg)
744 except Exception as e:
745 excs.append(e)
746 raise MyExceptionGroup('msg2', excs)
747
748 def level3(i):
749 excs = []
750 for f, arg in [(level2, i+1), (raiseVE, i+2)]:
751 try:
752 f(arg)
753 except Exception as e:
754 excs.append(e)
755 raise ExceptionGroup('msg3', excs)
756
757 level3(5)
758
759 try:
760 nested_group()
761 except ExceptionGroup as e:
762 e.add_note(f"the note: {id(e)}")
763 eg = e
764
765 eg_template = [
766 [
767 [ValueError(6), TypeError(int), ValueError(7)],
768 [ValueError(7), TypeError(int), ValueError(8)],
769 ValueError(8),
770 ],
771 ValueError(7)]
772
773 valueErrors_template = [
774 [
775 [ValueError(6), ValueError(7)],
776 [ValueError(7), ValueError(8)],
777 ValueError(8),
778 ],
779 ValueError(7)]
780
781 typeErrors_template = [[[TypeError(int)], [TypeError(int)]]]
782
783 self.assertMatchesTemplate(eg, ExceptionGroup, eg_template)
784
785 # Match Nothing
786 match, rest = self.split_exception_group(eg, SyntaxError)
787 self.assertIsNone(match)
788 self.assertMatchesTemplate(rest, ExceptionGroup, eg_template)
789
790 # Match Everything
791 match, rest = self.split_exception_group(eg, BaseException)
792 self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
793 self.assertIsNone(rest)
794 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
795 self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
796 self.assertIsNone(rest)
797
798 # Match ValueErrors
799 match, rest = self.split_exception_group(eg, ValueError)
800 self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template)
801 self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template)
802
803 # Match TypeErrors
804 match, rest = self.split_exception_group(eg, (TypeError, SyntaxError))
805 self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template)
806 self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template)
807
808 # Match ExceptionGroup
809 match, rest = eg.split(ExceptionGroup)
810 self.assertIs(match, eg)
811 self.assertIsNone(rest)
812
813 # Match MyExceptionGroup (ExceptionGroup subclass)
814 match, rest = eg.split(MyExceptionGroup)
815 self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]])
816 self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]])
817
818 def test_split_BaseExceptionGroup(self):
819 def exc(ex):
820 try:
821 raise ex
822 except BaseException as e:
823 return e
824
825 try:
826 raise BaseExceptionGroup(
827 "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))])
828 except BaseExceptionGroup as e:
829 beg = e
830
831 # Match Nothing
832 match, rest = self.split_exception_group(beg, TypeError)
833 self.assertIsNone(match)
834 self.assertMatchesTemplate(
835 rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
836
837 # Match Everything
838 match, rest = self.split_exception_group(
839 beg, (ValueError, KeyboardInterrupt))
840 self.assertMatchesTemplate(
841 match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
842 self.assertIsNone(rest)
843
844 # Match ValueErrors
845 match, rest = self.split_exception_group(beg, ValueError)
846 self.assertMatchesTemplate(
847 match, ExceptionGroup, [ValueError(1)])
848 self.assertMatchesTemplate(
849 rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
850
851 # Match KeyboardInterrupts
852 match, rest = self.split_exception_group(beg, KeyboardInterrupt)
853 self.assertMatchesTemplate(
854 match, BaseExceptionGroup, [KeyboardInterrupt(2)])
855 self.assertMatchesTemplate(
856 rest, ExceptionGroup, [ValueError(1)])
857
858 def test_split_copies_notes(self):
859 # make sure each exception group after a split has its own __notes__ list
860 eg = ExceptionGroup("eg", [ValueError(1), TypeError(2)])
861 eg.add_note("note1")
862 eg.add_note("note2")
863 orig_notes = list(eg.__notes__)
864 match, rest = eg.split(TypeError)
865 self.assertEqual(eg.__notes__, orig_notes)
866 self.assertEqual(match.__notes__, orig_notes)
867 self.assertEqual(rest.__notes__, orig_notes)
868 self.assertIsNot(eg.__notes__, match.__notes__)
869 self.assertIsNot(eg.__notes__, rest.__notes__)
870 self.assertIsNot(match.__notes__, rest.__notes__)
871 eg.add_note("eg")
872 match.add_note("match")
873 rest.add_note("rest")
874 self.assertEqual(eg.__notes__, orig_notes + ["eg"])
875 self.assertEqual(match.__notes__, orig_notes + ["match"])
876 self.assertEqual(rest.__notes__, orig_notes + ["rest"])
877
878 def test_split_does_not_copy_non_sequence_notes(self):
879 # __notes__ should be a sequence, which is shallow copied.
880 # If it is not a sequence, the split parts don't get any notes.
881 eg = ExceptionGroup("eg", [ValueError(1), TypeError(2)])
882 eg.__notes__ = 123
883 match, rest = eg.split(TypeError)
884 self.assertFalse(hasattr(match, '__notes__'))
885 self.assertFalse(hasattr(rest, '__notes__'))
886
887 def test_drive_invalid_return_value(self):
888 class MyEg(ExceptionGroup):
889 def derive(self, excs):
890 return 42
891
892 eg = MyEg('eg', [TypeError(1), ValueError(2)])
893 msg = "derive must return an instance of BaseExceptionGroup"
894 with self.assertRaisesRegex(TypeError, msg):
895 eg.split(TypeError)
896 with self.assertRaisesRegex(TypeError, msg):
897 eg.subgroup(TypeError)
898
899
900 class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase):
901
902 def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self):
903 class EG(ExceptionGroup):
904 pass
905
906 try:
907 try:
908 try:
909 raise TypeError(2)
910 except TypeError as te:
911 raise EG("nested", [te])
912 except EG as nested:
913 try:
914 raise ValueError(1)
915 except ValueError as ve:
916 raise EG("eg", [ve, nested])
917 except EG as e:
918 eg = e
919
920 self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
921
922 # Match Nothing
923 match, rest = self.split_exception_group(eg, OSError)
924 self.assertIsNone(match)
925 self.assertMatchesTemplate(
926 rest, ExceptionGroup, [ValueError(1), [TypeError(2)]])
927
928 # Match Everything
929 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
930 self.assertMatchesTemplate(
931 match, ExceptionGroup, [ValueError(1), [TypeError(2)]])
932 self.assertIsNone(rest)
933
934 # Match ValueErrors
935 match, rest = self.split_exception_group(eg, ValueError)
936 self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
937 self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]])
938
939 # Match TypeErrors
940 match, rest = self.split_exception_group(eg, TypeError)
941 self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]])
942 self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
943
944 def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self):
945 class EG(BaseExceptionGroup):
946 def __new__(cls, message, excs, unused):
947 # The "unused" arg is here to show that split() doesn't call
948 # the actual class constructor from the default derive()
949 # implementation (it would fail on unused arg if so because
950 # it assumes the BaseExceptionGroup.__new__ signature).
951 return super().__new__(cls, message, excs)
952
953 try:
954 raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused")
955 except EG as e:
956 eg = e
957
958 self.assertMatchesTemplate(
959 eg, EG, [ValueError(1), KeyboardInterrupt(2)])
960
961 # Match Nothing
962 match, rest = self.split_exception_group(eg, OSError)
963 self.assertIsNone(match)
964 self.assertMatchesTemplate(
965 rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
966
967 # Match Everything
968 match, rest = self.split_exception_group(
969 eg, (ValueError, KeyboardInterrupt))
970 self.assertMatchesTemplate(
971 match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)])
972 self.assertIsNone(rest)
973
974 # Match ValueErrors
975 match, rest = self.split_exception_group(eg, ValueError)
976 self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
977 self.assertMatchesTemplate(
978 rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
979
980 # Match KeyboardInterrupt
981 match, rest = self.split_exception_group(eg, KeyboardInterrupt)
982 self.assertMatchesTemplate(
983 match, BaseExceptionGroup, [KeyboardInterrupt(2)])
984 self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
985
986 def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self):
987 class EG(ExceptionGroup):
988 def __new__(cls, message, excs, code):
989 obj = super().__new__(cls, message, excs)
990 obj.code = code
991 return obj
992
993 def derive(self, excs):
994 return EG(self.message, excs, self.code)
995
996 try:
997 try:
998 try:
999 raise TypeError(2)
1000 except TypeError as te:
1001 raise EG("nested", [te], 101)
1002 except EG as nested:
1003 try:
1004 raise ValueError(1)
1005 except ValueError as ve:
1006 raise EG("eg", [ve, nested], 42)
1007 except EG as e:
1008 eg = e
1009
1010 self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
1011
1012 # Match Nothing
1013 match, rest = self.split_exception_group(eg, OSError)
1014 self.assertIsNone(match)
1015 self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]])
1016 self.assertEqual(rest.code, 42)
1017 self.assertEqual(rest.exceptions[1].code, 101)
1018
1019 # Match Everything
1020 match, rest = self.split_exception_group(eg, (ValueError, TypeError))
1021 self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]])
1022 self.assertEqual(match.code, 42)
1023 self.assertEqual(match.exceptions[1].code, 101)
1024 self.assertIsNone(rest)
1025
1026 # Match ValueErrors
1027 match, rest = self.split_exception_group(eg, ValueError)
1028 self.assertMatchesTemplate(match, EG, [ValueError(1)])
1029 self.assertEqual(match.code, 42)
1030 self.assertMatchesTemplate(rest, EG, [[TypeError(2)]])
1031 self.assertEqual(rest.code, 42)
1032 self.assertEqual(rest.exceptions[0].code, 101)
1033
1034 # Match TypeErrors
1035 match, rest = self.split_exception_group(eg, TypeError)
1036 self.assertMatchesTemplate(match, EG, [[TypeError(2)]])
1037 self.assertEqual(match.code, 42)
1038 self.assertEqual(match.exceptions[0].code, 101)
1039 self.assertMatchesTemplate(rest, EG, [ValueError(1)])
1040 self.assertEqual(rest.code, 42)
1041
1042
1043 if __name__ == '__main__':
1044 unittest.main()