Debian Codegraph @

Lib/test/test_except_star.py

raw
1 import sys
2 import unittest
3 import textwrap
4 from test.support.testcase import ExceptionIsLikeMixin
5
6 class TestInvalidExceptStar(unittest.TestCase):
7 def test_mixed_except_and_except_star_is_syntax_error(self):
8 errors = [
9 "try: pass\nexcept ValueError: pass\nexcept* TypeError: pass\n",
10 "try: pass\nexcept* ValueError: pass\nexcept TypeError: pass\n",
11 "try: pass\nexcept ValueError as e: pass\nexcept* TypeError: pass\n",
12 "try: pass\nexcept* ValueError as e: pass\nexcept TypeError: pass\n",
13 "try: pass\nexcept ValueError: pass\nexcept* TypeError as e: pass\n",
14 "try: pass\nexcept* ValueError: pass\nexcept TypeError as e: pass\n",
15 "try: pass\nexcept ValueError: pass\nexcept*: pass\n",
16 "try: pass\nexcept* ValueError: pass\nexcept: pass\n",
17 ]
18
19 for err in errors:
20 with self.assertRaises(SyntaxError):
21 compile(err, "<string>", "exec")
22
23 def test_except_star_ExceptionGroup_is_runtime_error_single(self):
24 with self.assertRaises(TypeError):
25 try:
26 raise OSError("blah")
27 except* ExceptionGroup as e:
28 pass
29
30 def test_except_star_ExceptionGroup_is_runtime_error_tuple(self):
31 with self.assertRaises(TypeError):
32 try:
33 raise ExceptionGroup("eg", [ValueError(42)])
34 except* (TypeError, ExceptionGroup):
35 pass
36
37 def test_except_star_invalid_exception_type(self):
38 with self.assertRaises(TypeError):
39 try:
40 raise ValueError
41 except* 42:
42 pass
43
44 with self.assertRaises(TypeError):
45 try:
46 raise ValueError
47 except* (ValueError, 42):
48 pass
49
50
51 class TestBreakContinueReturnInExceptStarBlock(unittest.TestCase):
52 MSG = (r"'break', 'continue' and 'return'"
53 r" cannot appear in an except\* block")
54
55 def check_invalid(self, src):
56 with self.assertRaisesRegex(SyntaxError, self.MSG):
57 compile(textwrap.dedent(src), "<string>", "exec")
58
59 def test_break_in_except_star(self):
60 self.check_invalid(
61 """
62 try:
63 raise ValueError
64 except* Exception as e:
65 break
66 """)
67
68 self.check_invalid(
69 """
70 for i in range(5):
71 try:
72 pass
73 except* Exception as e:
74 if i == 2:
75 break
76 """)
77
78 self.check_invalid(
79 """
80 for i in range(5):
81 try:
82 pass
83 except* Exception as e:
84 if i == 2:
85 break
86 finally:
87 pass
88 return 0
89 """)
90
91
92 def test_continue_in_except_star_block_invalid(self):
93 self.check_invalid(
94 """
95 for i in range(5):
96 try:
97 raise ValueError
98 except* Exception as e:
99 continue
100 """)
101
102 self.check_invalid(
103 """
104 for i in range(5):
105 try:
106 pass
107 except* Exception as e:
108 if i == 2:
109 continue
110 """)
111
112 self.check_invalid(
113 """
114 for i in range(5):
115 try:
116 pass
117 except* Exception as e:
118 if i == 2:
119 continue
120 finally:
121 pass
122 return 0
123 """)
124
125 def test_return_in_except_star_block_invalid(self):
126 self.check_invalid(
127 """
128 def f():
129 try:
130 raise ValueError
131 except* Exception as e:
132 return 42
133 """)
134
135 self.check_invalid(
136 """
137 def f():
138 try:
139 pass
140 except* Exception as e:
141 return 42
142 finally:
143 finished = True
144 """)
145
146 def test_break_continue_in_except_star_block_valid(self):
147 try:
148 raise ValueError(42)
149 except* Exception as e:
150 count = 0
151 for i in range(5):
152 if i == 0:
153 continue
154 if i == 4:
155 break
156 count += 1
157
158 self.assertEqual(count, 3)
159 self.assertEqual(i, 4)
160 exc = e
161 self.assertIsInstance(exc, ExceptionGroup)
162
163 def test_return_in_except_star_block_valid(self):
164 try:
165 raise ValueError(42)
166 except* Exception as e:
167 def f(x):
168 return 2*x
169 r = f(3)
170 exc = e
171 self.assertEqual(r, 6)
172 self.assertIsInstance(exc, ExceptionGroup)
173
174
175 class ExceptStarTest(ExceptionIsLikeMixin, unittest.TestCase):
176 def assertMetadataEqual(self, e1, e2):
177 if e1 is None or e2 is None:
178 self.assertTrue(e1 is None and e2 is None)
179 else:
180 self.assertEqual(e1.__context__, e2.__context__)
181 self.assertEqual(e1.__cause__, e2.__cause__)
182 self.assertEqual(e1.__traceback__, e2.__traceback__)
183
184 def assertMetadataNotEqual(self, e1, e2):
185 if e1 is None or e2 is None:
186 self.assertNotEqual(e1, e2)
187 else:
188 return not (e1.__context__ == e2.__context__
189 and e1.__cause__ == e2.__cause__
190 and e1.__traceback__ == e2.__traceback__)
191
192
193 class TestExceptStarSplitSemantics(ExceptStarTest):
194 def doSplitTestNamed(self, exc, T, match_template, rest_template):
195 initial_sys_exception = sys.exception()
196 sys_exception = match = rest = None
197 try:
198 try:
199 raise exc
200 except* T as e:
201 sys_exception = sys.exception()
202 match = e
203 except BaseException as e:
204 rest = e
205
206 self.assertEqual(sys_exception, match)
207 self.assertExceptionIsLike(match, match_template)
208 self.assertExceptionIsLike(rest, rest_template)
209 self.assertEqual(sys.exception(), initial_sys_exception)
210
211 def doSplitTestUnnamed(self, exc, T, match_template, rest_template):
212 initial_sys_exception = sys.exception()
213 sys_exception = match = rest = None
214 try:
215 try:
216 raise exc
217 except* T:
218 sys_exception = match = sys.exception()
219 else:
220 if rest_template:
221 self.fail("Exception not raised")
222 except BaseException as e:
223 rest = e
224 self.assertExceptionIsLike(match, match_template)
225 self.assertExceptionIsLike(rest, rest_template)
226 self.assertEqual(sys.exception(), initial_sys_exception)
227
228 def doSplitTestInExceptHandler(self, exc, T, match_template, rest_template):
229 try:
230 raise ExceptionGroup('eg', [TypeError(1), ValueError(2)])
231 except Exception:
232 self.doSplitTestNamed(exc, T, match_template, rest_template)
233 self.doSplitTestUnnamed(exc, T, match_template, rest_template)
234
235 def doSplitTestInExceptStarHandler(self, exc, T, match_template, rest_template):
236 try:
237 raise ExceptionGroup('eg', [TypeError(1), ValueError(2)])
238 except* Exception:
239 self.doSplitTestNamed(exc, T, match_template, rest_template)
240 self.doSplitTestUnnamed(exc, T, match_template, rest_template)
241
242 def doSplitTest(self, exc, T, match_template, rest_template):
243 self.doSplitTestNamed(exc, T, match_template, rest_template)
244 self.doSplitTestUnnamed(exc, T, match_template, rest_template)
245 self.doSplitTestInExceptHandler(exc, T, match_template, rest_template)
246 self.doSplitTestInExceptStarHandler(exc, T, match_template, rest_template)
247
248 def test_no_match_single_type(self):
249 self.doSplitTest(
250 ExceptionGroup("test1", [ValueError("V"), TypeError("T")]),
251 SyntaxError,
252 None,
253 ExceptionGroup("test1", [ValueError("V"), TypeError("T")]))
254
255 def test_match_single_type(self):
256 self.doSplitTest(
257 ExceptionGroup("test2", [ValueError("V1"), ValueError("V2")]),
258 ValueError,
259 ExceptionGroup("test2", [ValueError("V1"), ValueError("V2")]),
260 None)
261
262 def test_match_single_type_partial_match(self):
263 self.doSplitTest(
264 ExceptionGroup(
265 "test3",
266 [ValueError("V1"), OSError("OS"), ValueError("V2")]),
267 ValueError,
268 ExceptionGroup("test3", [ValueError("V1"), ValueError("V2")]),
269 ExceptionGroup("test3", [OSError("OS")]))
270
271 def test_match_single_type_nested(self):
272 self.doSplitTest(
273 ExceptionGroup(
274 "g1", [
275 ValueError("V1"),
276 OSError("OS1"),
277 ExceptionGroup(
278 "g2", [
279 OSError("OS2"),
280 ValueError("V2"),
281 TypeError("T")])]),
282 ValueError,
283 ExceptionGroup(
284 "g1", [
285 ValueError("V1"),
286 ExceptionGroup("g2", [ValueError("V2")])]),
287 ExceptionGroup("g1", [
288 OSError("OS1"),
289 ExceptionGroup("g2", [
290 OSError("OS2"), TypeError("T")])]))
291
292 def test_match_type_tuple_nested(self):
293 self.doSplitTest(
294 ExceptionGroup(
295 "h1", [
296 ValueError("V1"),
297 OSError("OS1"),
298 ExceptionGroup(
299 "h2", [OSError("OS2"), ValueError("V2"), TypeError("T")])]),
300 (ValueError, TypeError),
301 ExceptionGroup(
302 "h1", [
303 ValueError("V1"),
304 ExceptionGroup("h2", [ValueError("V2"), TypeError("T")])]),
305 ExceptionGroup(
306 "h1", [
307 OSError("OS1"),
308 ExceptionGroup("h2", [OSError("OS2")])]))
309
310 def test_empty_groups_removed(self):
311 self.doSplitTest(
312 ExceptionGroup(
313 "eg", [
314 ExceptionGroup("i1", [ValueError("V1")]),
315 ExceptionGroup("i2", [ValueError("V2"), TypeError("T1")]),
316 ExceptionGroup("i3", [TypeError("T2")])]),
317 TypeError,
318 ExceptionGroup("eg", [
319 ExceptionGroup("i2", [TypeError("T1")]),
320 ExceptionGroup("i3", [TypeError("T2")])]),
321 ExceptionGroup("eg", [
322 ExceptionGroup("i1", [ValueError("V1")]),
323 ExceptionGroup("i2", [ValueError("V2")])]))
324
325 def test_singleton_groups_are_kept(self):
326 self.doSplitTest(
327 ExceptionGroup("j1", [
328 ExceptionGroup("j2", [
329 ExceptionGroup("j3", [ValueError("V1")]),
330 ExceptionGroup("j4", [TypeError("T")])])]),
331 TypeError,
332 ExceptionGroup(
333 "j1",
334 [ExceptionGroup("j2", [ExceptionGroup("j4", [TypeError("T")])])]),
335 ExceptionGroup(
336 "j1",
337 [ExceptionGroup("j2", [ExceptionGroup("j3", [ValueError("V1")])])]))
338
339 def test_naked_exception_matched_wrapped1(self):
340 self.doSplitTest(
341 ValueError("V"),
342 ValueError,
343 ExceptionGroup("", [ValueError("V")]),
344 None)
345
346 def test_naked_exception_matched_wrapped2(self):
347 self.doSplitTest(
348 ValueError("V"),
349 Exception,
350 ExceptionGroup("", [ValueError("V")]),
351 None)
352
353 def test_exception_group_except_star_Exception_not_wrapped(self):
354 self.doSplitTest(
355 ExceptionGroup("eg", [ValueError("V")]),
356 Exception,
357 ExceptionGroup("eg", [ValueError("V")]),
358 None)
359
360 def test_plain_exception_not_matched(self):
361 self.doSplitTest(
362 ValueError("V"),
363 TypeError,
364 None,
365 ValueError("V"))
366
367 def test_match__supertype(self):
368 self.doSplitTest(
369 ExceptionGroup("st", [BlockingIOError("io"), TypeError("T")]),
370 OSError,
371 ExceptionGroup("st", [BlockingIOError("io")]),
372 ExceptionGroup("st", [TypeError("T")]))
373
374 def test_multiple_matches_named(self):
375 try:
376 raise ExceptionGroup("mmn", [OSError("os"), BlockingIOError("io")])
377 except* BlockingIOError as e:
378 self.assertExceptionIsLike(e,
379 ExceptionGroup("mmn", [BlockingIOError("io")]))
380 except* OSError as e:
381 self.assertExceptionIsLike(e,
382 ExceptionGroup("mmn", [OSError("os")]))
383 else:
384 self.fail("Exception not raised")
385
386 def test_multiple_matches_unnamed(self):
387 try:
388 raise ExceptionGroup("mmu", [OSError("os"), BlockingIOError("io")])
389 except* BlockingIOError:
390 e = sys.exception()
391 self.assertExceptionIsLike(e,
392 ExceptionGroup("mmu", [BlockingIOError("io")]))
393 except* OSError:
394 e = sys.exception()
395 self.assertExceptionIsLike(e,
396 ExceptionGroup("mmu", [OSError("os")]))
397 else:
398 self.fail("Exception not raised")
399
400 def test_first_match_wins_named(self):
401 try:
402 raise ExceptionGroup("fst", [BlockingIOError("io")])
403 except* OSError as e:
404 self.assertExceptionIsLike(e,
405 ExceptionGroup("fst", [BlockingIOError("io")]))
406 except* BlockingIOError:
407 self.fail("Should have been matched as OSError")
408 else:
409 self.fail("Exception not raised")
410
411 def test_first_match_wins_unnamed(self):
412 try:
413 raise ExceptionGroup("fstu", [BlockingIOError("io")])
414 except* OSError:
415 e = sys.exception()
416 self.assertExceptionIsLike(e,
417 ExceptionGroup("fstu", [BlockingIOError("io")]))
418 except* BlockingIOError:
419 pass
420 else:
421 self.fail("Exception not raised")
422
423 def test_nested_except_stars(self):
424 try:
425 raise ExceptionGroup("n", [BlockingIOError("io")])
426 except* BlockingIOError:
427 try:
428 raise ExceptionGroup("n", [ValueError("io")])
429 except* ValueError:
430 pass
431 else:
432 self.fail("Exception not raised")
433 e = sys.exception()
434 self.assertExceptionIsLike(e,
435 ExceptionGroup("n", [BlockingIOError("io")]))
436 else:
437 self.fail("Exception not raised")
438
439 def test_nested_in_loop(self):
440 for _ in range(2):
441 try:
442 raise ExceptionGroup("nl", [BlockingIOError("io")])
443 except* BlockingIOError:
444 pass
445 else:
446 self.fail("Exception not raised")
447
448
449 class TestExceptStarReraise(ExceptStarTest):
450 def test_reraise_all_named(self):
451 try:
452 try:
453 raise ExceptionGroup(
454 "eg", [TypeError(1), ValueError(2), OSError(3)])
455 except* TypeError as e:
456 raise
457 except* ValueError as e:
458 raise
459 # OSError not handled
460 except ExceptionGroup as e:
461 exc = e
462
463 self.assertExceptionIsLike(
464 exc,
465 ExceptionGroup("eg", [TypeError(1), ValueError(2), OSError(3)]))
466
467 def test_reraise_all_unnamed(self):
468 try:
469 try:
470 raise ExceptionGroup(
471 "eg", [TypeError(1), ValueError(2), OSError(3)])
472 except* TypeError:
473 raise
474 except* ValueError:
475 raise
476 # OSError not handled
477 except ExceptionGroup as e:
478 exc = e
479
480 self.assertExceptionIsLike(
481 exc,
482 ExceptionGroup("eg", [TypeError(1), ValueError(2), OSError(3)]))
483
484 def test_reraise_some_handle_all_named(self):
485 try:
486 try:
487 raise ExceptionGroup(
488 "eg", [TypeError(1), ValueError(2), OSError(3)])
489 except* TypeError as e:
490 raise
491 except* ValueError as e:
492 pass
493 # OSError not handled
494 except ExceptionGroup as e:
495 exc = e
496
497 self.assertExceptionIsLike(
498 exc, ExceptionGroup("eg", [TypeError(1), OSError(3)]))
499
500 def test_reraise_partial_handle_all_unnamed(self):
501 try:
502 try:
503 raise ExceptionGroup(
504 "eg", [TypeError(1), ValueError(2)])
505 except* TypeError:
506 raise
507 except* ValueError:
508 pass
509 except ExceptionGroup as e:
510 exc = e
511
512 self.assertExceptionIsLike(
513 exc, ExceptionGroup("eg", [TypeError(1)]))
514
515 def test_reraise_partial_handle_some_named(self):
516 try:
517 try:
518 raise ExceptionGroup(
519 "eg", [TypeError(1), ValueError(2), OSError(3)])
520 except* TypeError as e:
521 raise
522 except* ValueError as e:
523 pass
524 # OSError not handled
525 except ExceptionGroup as e:
526 exc = e
527
528 self.assertExceptionIsLike(
529 exc, ExceptionGroup("eg", [TypeError(1), OSError(3)]))
530
531 def test_reraise_partial_handle_some_unnamed(self):
532 try:
533 try:
534 raise ExceptionGroup(
535 "eg", [TypeError(1), ValueError(2), OSError(3)])
536 except* TypeError:
537 raise
538 except* ValueError:
539 pass
540 except ExceptionGroup as e:
541 exc = e
542
543 self.assertExceptionIsLike(
544 exc, ExceptionGroup("eg", [TypeError(1), OSError(3)]))
545
546 def test_reraise_plain_exception_named(self):
547 try:
548 try:
549 raise ValueError(42)
550 except* ValueError as e:
551 raise
552 except ExceptionGroup as e:
553 exc = e
554
555 self.assertExceptionIsLike(
556 exc, ExceptionGroup("", [ValueError(42)]))
557
558 def test_reraise_plain_exception_unnamed(self):
559 try:
560 try:
561 raise ValueError(42)
562 except* ValueError:
563 raise
564 except ExceptionGroup as e:
565 exc = e
566
567 self.assertExceptionIsLike(
568 exc, ExceptionGroup("", [ValueError(42)]))
569
570
571 class TestExceptStarRaise(ExceptStarTest):
572 def test_raise_named(self):
573 orig = ExceptionGroup("eg", [ValueError(1), OSError(2)])
574 try:
575 try:
576 raise orig
577 except* OSError as e:
578 raise TypeError(3)
579 except ExceptionGroup as e:
580 exc = e
581
582 self.assertExceptionIsLike(
583 exc,
584 ExceptionGroup(
585 "", [TypeError(3), ExceptionGroup("eg", [ValueError(1)])]))
586
587 self.assertExceptionIsLike(
588 exc.exceptions[0].__context__,
589 ExceptionGroup("eg", [OSError(2)]))
590
591 self.assertMetadataNotEqual(orig, exc)
592 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
593
594 def test_raise_unnamed(self):
595 orig = ExceptionGroup("eg", [ValueError(1), OSError(2)])
596 try:
597 try:
598 raise orig
599 except* OSError:
600 raise TypeError(3)
601 except ExceptionGroup as e:
602 exc = e
603
604 self.assertExceptionIsLike(
605 exc,
606 ExceptionGroup(
607 "", [TypeError(3), ExceptionGroup("eg", [ValueError(1)])]))
608
609 self.assertExceptionIsLike(
610 exc.exceptions[0].__context__,
611 ExceptionGroup("eg", [OSError(2)]))
612
613 self.assertMetadataNotEqual(orig, exc)
614 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
615
616 def test_raise_handle_all_raise_one_named(self):
617 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
618 try:
619 try:
620 raise orig
621 except* (TypeError, ValueError) as e:
622 raise SyntaxError(3)
623 except SyntaxError as e:
624 exc = e
625
626 self.assertExceptionIsLike(exc, SyntaxError(3))
627
628 self.assertExceptionIsLike(
629 exc.__context__,
630 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
631
632 self.assertMetadataNotEqual(orig, exc)
633 self.assertMetadataEqual(orig, exc.__context__)
634
635 def test_raise_handle_all_raise_one_unnamed(self):
636 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
637 try:
638 try:
639 raise orig
640 except* (TypeError, ValueError) as e:
641 raise SyntaxError(3)
642 except SyntaxError as e:
643 exc = e
644
645 self.assertExceptionIsLike(exc, SyntaxError(3))
646
647 self.assertExceptionIsLike(
648 exc.__context__,
649 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
650
651 self.assertMetadataNotEqual(orig, exc)
652 self.assertMetadataEqual(orig, exc.__context__)
653
654 def test_raise_handle_all_raise_two_named(self):
655 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
656 try:
657 try:
658 raise orig
659 except* TypeError as e:
660 raise SyntaxError(3)
661 except* ValueError as e:
662 raise SyntaxError(4)
663 except ExceptionGroup as e:
664 exc = e
665
666 self.assertExceptionIsLike(
667 exc, ExceptionGroup("", [SyntaxError(3), SyntaxError(4)]))
668
669 self.assertExceptionIsLike(
670 exc.exceptions[0].__context__,
671 ExceptionGroup("eg", [TypeError(1)]))
672
673 self.assertExceptionIsLike(
674 exc.exceptions[1].__context__,
675 ExceptionGroup("eg", [ValueError(2)]))
676
677 self.assertMetadataNotEqual(orig, exc)
678 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
679 self.assertMetadataEqual(orig, exc.exceptions[1].__context__)
680
681 def test_raise_handle_all_raise_two_unnamed(self):
682 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
683 try:
684 try:
685 raise orig
686 except* TypeError:
687 raise SyntaxError(3)
688 except* ValueError:
689 raise SyntaxError(4)
690 except ExceptionGroup as e:
691 exc = e
692
693 self.assertExceptionIsLike(
694 exc, ExceptionGroup("", [SyntaxError(3), SyntaxError(4)]))
695
696 self.assertExceptionIsLike(
697 exc.exceptions[0].__context__,
698 ExceptionGroup("eg", [TypeError(1)]))
699
700 self.assertExceptionIsLike(
701 exc.exceptions[1].__context__,
702 ExceptionGroup("eg", [ValueError(2)]))
703
704 self.assertMetadataNotEqual(orig, exc)
705 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
706 self.assertMetadataEqual(orig, exc.exceptions[1].__context__)
707
708
709 class TestExceptStarRaiseFrom(ExceptStarTest):
710 def test_raise_named(self):
711 orig = ExceptionGroup("eg", [ValueError(1), OSError(2)])
712 try:
713 try:
714 raise orig
715 except* OSError as e:
716 raise TypeError(3) from e
717 except ExceptionGroup as e:
718 exc = e
719
720 self.assertExceptionIsLike(
721 exc,
722 ExceptionGroup(
723 "", [TypeError(3), ExceptionGroup("eg", [ValueError(1)])]))
724
725 self.assertExceptionIsLike(
726 exc.exceptions[0].__context__,
727 ExceptionGroup("eg", [OSError(2)]))
728
729 self.assertExceptionIsLike(
730 exc.exceptions[0].__cause__,
731 ExceptionGroup("eg", [OSError(2)]))
732
733 self.assertMetadataNotEqual(orig, exc)
734 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
735 self.assertMetadataEqual(orig, exc.exceptions[0].__cause__)
736 self.assertMetadataNotEqual(orig, exc.exceptions[1].__context__)
737 self.assertMetadataNotEqual(orig, exc.exceptions[1].__cause__)
738
739 def test_raise_unnamed(self):
740 orig = ExceptionGroup("eg", [ValueError(1), OSError(2)])
741 try:
742 try:
743 raise orig
744 except* OSError:
745 e = sys.exception()
746 raise TypeError(3) from e
747 except ExceptionGroup as e:
748 exc = e
749
750 self.assertExceptionIsLike(
751 exc,
752 ExceptionGroup(
753 "", [TypeError(3), ExceptionGroup("eg", [ValueError(1)])]))
754
755 self.assertExceptionIsLike(
756 exc.exceptions[0].__context__,
757 ExceptionGroup("eg", [OSError(2)]))
758
759 self.assertExceptionIsLike(
760 exc.exceptions[0].__cause__,
761 ExceptionGroup("eg", [OSError(2)]))
762
763 self.assertMetadataNotEqual(orig, exc)
764 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
765 self.assertMetadataEqual(orig, exc.exceptions[0].__cause__)
766 self.assertMetadataNotEqual(orig, exc.exceptions[1].__context__)
767 self.assertMetadataNotEqual(orig, exc.exceptions[1].__cause__)
768
769 def test_raise_handle_all_raise_one_named(self):
770 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
771 try:
772 try:
773 raise orig
774 except* (TypeError, ValueError) as e:
775 raise SyntaxError(3) from e
776 except SyntaxError as e:
777 exc = e
778
779 self.assertExceptionIsLike(exc, SyntaxError(3))
780
781 self.assertExceptionIsLike(
782 exc.__context__,
783 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
784
785 self.assertExceptionIsLike(
786 exc.__cause__,
787 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
788
789 self.assertMetadataNotEqual(orig, exc)
790 self.assertMetadataEqual(orig, exc.__context__)
791 self.assertMetadataEqual(orig, exc.__cause__)
792
793 def test_raise_handle_all_raise_one_unnamed(self):
794 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
795 try:
796 try:
797 raise orig
798 except* (TypeError, ValueError) as e:
799 e = sys.exception()
800 raise SyntaxError(3) from e
801 except SyntaxError as e:
802 exc = e
803
804 self.assertExceptionIsLike(exc, SyntaxError(3))
805
806 self.assertExceptionIsLike(
807 exc.__context__,
808 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
809
810 self.assertExceptionIsLike(
811 exc.__cause__,
812 ExceptionGroup("eg", [TypeError(1), ValueError(2)]))
813
814 self.assertMetadataNotEqual(orig, exc)
815 self.assertMetadataEqual(orig, exc.__context__)
816 self.assertMetadataEqual(orig, exc.__cause__)
817
818 def test_raise_handle_all_raise_two_named(self):
819 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
820 try:
821 try:
822 raise orig
823 except* TypeError as e:
824 raise SyntaxError(3) from e
825 except* ValueError as e:
826 raise SyntaxError(4) from e
827 except ExceptionGroup as e:
828 exc = e
829
830 self.assertExceptionIsLike(
831 exc, ExceptionGroup("", [SyntaxError(3), SyntaxError(4)]))
832
833 self.assertExceptionIsLike(
834 exc.exceptions[0].__context__,
835 ExceptionGroup("eg", [TypeError(1)]))
836
837 self.assertExceptionIsLike(
838 exc.exceptions[0].__cause__,
839 ExceptionGroup("eg", [TypeError(1)]))
840
841 self.assertExceptionIsLike(
842 exc.exceptions[1].__context__,
843 ExceptionGroup("eg", [ValueError(2)]))
844
845 self.assertExceptionIsLike(
846 exc.exceptions[1].__cause__,
847 ExceptionGroup("eg", [ValueError(2)]))
848
849 self.assertMetadataNotEqual(orig, exc)
850 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
851 self.assertMetadataEqual(orig, exc.exceptions[0].__cause__)
852
853 def test_raise_handle_all_raise_two_unnamed(self):
854 orig = ExceptionGroup("eg", [TypeError(1), ValueError(2)])
855 try:
856 try:
857 raise orig
858 except* TypeError:
859 e = sys.exception()
860 raise SyntaxError(3) from e
861 except* ValueError:
862 e = sys.exception()
863 raise SyntaxError(4) from e
864 except ExceptionGroup as e:
865 exc = e
866
867 self.assertExceptionIsLike(
868 exc, ExceptionGroup("", [SyntaxError(3), SyntaxError(4)]))
869
870 self.assertExceptionIsLike(
871 exc.exceptions[0].__context__,
872 ExceptionGroup("eg", [TypeError(1)]))
873
874 self.assertExceptionIsLike(
875 exc.exceptions[0].__cause__,
876 ExceptionGroup("eg", [TypeError(1)]))
877
878 self.assertExceptionIsLike(
879 exc.exceptions[1].__context__,
880 ExceptionGroup("eg", [ValueError(2)]))
881
882 self.assertExceptionIsLike(
883 exc.exceptions[1].__cause__,
884 ExceptionGroup("eg", [ValueError(2)]))
885
886 self.assertMetadataNotEqual(orig, exc)
887 self.assertMetadataEqual(orig, exc.exceptions[0].__context__)
888 self.assertMetadataEqual(orig, exc.exceptions[0].__cause__)
889 self.assertMetadataEqual(orig, exc.exceptions[1].__context__)
890 self.assertMetadataEqual(orig, exc.exceptions[1].__cause__)
891
892
893 class TestExceptStarExceptionGroupSubclass(ExceptStarTest):
894 def test_except_star_EG_subclass(self):
895 class EG(ExceptionGroup):
896 def __new__(cls, message, excs, code):
897 obj = super().__new__(cls, message, excs)
898 obj.code = code
899 return obj
900
901 def derive(self, excs):
902 return EG(self.message, excs, self.code)
903
904 try:
905 try:
906 try:
907 try:
908 raise TypeError(2)
909 except TypeError as te:
910 raise EG("nested", [te], 101) from None
911 except EG as nested:
912 try:
913 raise ValueError(1)
914 except ValueError as ve:
915 raise EG("eg", [ve, nested], 42)
916 except* ValueError as eg:
917 veg = eg
918 except EG as eg:
919 teg = eg
920
921 self.assertIsInstance(veg, EG)
922 self.assertIsInstance(teg, EG)
923 self.assertIsInstance(teg.exceptions[0], EG)
924 self.assertMetadataEqual(veg, teg)
925 self.assertEqual(veg.code, 42)
926 self.assertEqual(teg.code, 42)
927 self.assertEqual(teg.exceptions[0].code, 101)
928
929 def test_falsy_exception_group_subclass(self):
930 class FalsyEG(ExceptionGroup):
931 def __bool__(self):
932 return False
933
934 def derive(self, excs):
935 return FalsyEG(self.message, excs)
936
937 try:
938 try:
939 raise FalsyEG("eg", [TypeError(1), ValueError(2)])
940 except *TypeError as e:
941 tes = e
942 raise
943 except *ValueError as e:
944 ves = e
945 pass
946 except Exception as e:
947 exc = e
948
949 for e in [tes, ves, exc]:
950 self.assertFalse(e)
951 self.assertIsInstance(e, FalsyEG)
952
953 self.assertExceptionIsLike(exc, FalsyEG("eg", [TypeError(1)]))
954 self.assertExceptionIsLike(tes, FalsyEG("eg", [TypeError(1)]))
955 self.assertExceptionIsLike(ves, FalsyEG("eg", [ValueError(2)]))
956
957 def test_exception_group_subclass_with_bad_split_func(self):
958 # see gh-128049.
959 class BadEG1(ExceptionGroup):
960 def split(self, *args):
961 return "NOT A 2-TUPLE!"
962
963 class BadEG2(ExceptionGroup):
964 def split(self, *args):
965 return ("NOT A 2-TUPLE!",)
966
967 eg_list = [
968 (BadEG1("eg", [OSError(123), ValueError(456)]),
969 r"split must return a tuple, not str"),
970 (BadEG2("eg", [OSError(123), ValueError(456)]),
971 r"split must return a 2-tuple, got tuple of size 1")
972 ]
973
974 for eg_class, msg in eg_list:
975 with self.assertRaisesRegex(TypeError, msg) as m:
976 try:
977 raise eg_class
978 except* ValueError:
979 pass
980 except* OSError:
981 pass
982
983 self.assertExceptionIsLike(m.exception.__context__, eg_class)
984
985 # we allow tuples of length > 2 for backwards compatibility
986 class WeirdEG(ExceptionGroup):
987 def split(self, *args):
988 return super().split(*args) + ("anything", 123456, None)
989
990 try:
991 raise WeirdEG("eg", [OSError(123), ValueError(456)])
992 except* OSError as e:
993 oeg = e
994 except* ValueError as e:
995 veg = e
996
997 self.assertExceptionIsLike(oeg, WeirdEG("eg", [OSError(123)]))
998 self.assertExceptionIsLike(veg, WeirdEG("eg", [ValueError(456)]))
999
1000
1001 class TestExceptStarCleanup(ExceptStarTest):
1002 def test_sys_exception_restored(self):
1003 try:
1004 try:
1005 raise ValueError(42)
1006 except:
1007 try:
1008 raise TypeError(int)
1009 except* Exception:
1010 pass
1011 1/0
1012 except Exception as e:
1013 exc = e
1014
1015 self.assertExceptionIsLike(exc, ZeroDivisionError('division by zero'))
1016 self.assertExceptionIsLike(exc.__context__, ValueError(42))
1017 self.assertEqual(sys.exception(), None)
1018
1019
1020 class TestExceptStar_WeirdLeafExceptions(ExceptStarTest):
1021 # Test that except* works when leaf exceptions are
1022 # unhashable or have a bad custom __eq__
1023
1024 class UnhashableExc(ValueError):
1025 __hash__ = None
1026
1027 class AlwaysEqualExc(ValueError):
1028 def __eq__(self, other):
1029 return True
1030
1031 class NeverEqualExc(ValueError):
1032 def __eq__(self, other):
1033 return False
1034
1035 class BrokenEqualExc(ValueError):
1036 def __eq__(self, other):
1037 raise RuntimeError()
1038
1039 def setUp(self):
1040 self.bad_types = [self.UnhashableExc,
1041 self.AlwaysEqualExc,
1042 self.NeverEqualExc,
1043 self.BrokenEqualExc]
1044
1045 def except_type(self, eg, type):
1046 match, rest = None, None
1047 try:
1048 try:
1049 raise eg
1050 except* type as e:
1051 match = e
1052 except Exception as e:
1053 rest = e
1054 return match, rest
1055
1056 def test_catch_unhashable_leaf_exception(self):
1057 for Bad in self.bad_types:
1058 with self.subTest(Bad):
1059 eg = ExceptionGroup("eg", [TypeError(1), Bad(2)])
1060 match, rest = self.except_type(eg, Bad)
1061 self.assertExceptionIsLike(
1062 match, ExceptionGroup("eg", [Bad(2)]))
1063 self.assertExceptionIsLike(
1064 rest, ExceptionGroup("eg", [TypeError(1)]))
1065
1066 def test_propagate_unhashable_leaf(self):
1067 for Bad in self.bad_types:
1068 with self.subTest(Bad):
1069 eg = ExceptionGroup("eg", [TypeError(1), Bad(2)])
1070 match, rest = self.except_type(eg, TypeError)
1071 self.assertExceptionIsLike(
1072 match, ExceptionGroup("eg", [TypeError(1)]))
1073 self.assertExceptionIsLike(
1074 rest, ExceptionGroup("eg", [Bad(2)]))
1075
1076 def test_catch_nothing_unhashable_leaf(self):
1077 for Bad in self.bad_types:
1078 with self.subTest(Bad):
1079 eg = ExceptionGroup("eg", [TypeError(1), Bad(2)])
1080 match, rest = self.except_type(eg, OSError)
1081 self.assertIsNone(match)
1082 self.assertExceptionIsLike(rest, eg)
1083
1084 def test_catch_everything_unhashable_leaf(self):
1085 for Bad in self.bad_types:
1086 with self.subTest(Bad):
1087 eg = ExceptionGroup("eg", [TypeError(1), Bad(2)])
1088 match, rest = self.except_type(eg, Exception)
1089 self.assertExceptionIsLike(match, eg)
1090 self.assertIsNone(rest)
1091
1092 def test_reraise_unhashable_leaf(self):
1093 for Bad in self.bad_types:
1094 with self.subTest(Bad):
1095 eg = ExceptionGroup(
1096 "eg", [TypeError(1), Bad(2), ValueError(3)])
1097
1098 try:
1099 try:
1100 raise eg
1101 except* TypeError:
1102 pass
1103 except* Bad:
1104 raise
1105 except Exception as e:
1106 exc = e
1107
1108 self.assertExceptionIsLike(
1109 exc, ExceptionGroup("eg", [Bad(2), ValueError(3)]))
1110
1111
1112 class TestExceptStar_WeirdExceptionGroupSubclass(ExceptStarTest):
1113 # Test that except* works with exception groups that are
1114 # unhashable or have a bad custom __eq__
1115
1116 class UnhashableEG(ExceptionGroup):
1117 __hash__ = None
1118
1119 def derive(self, excs):
1120 return type(self)(self.message, excs)
1121
1122 class AlwaysEqualEG(ExceptionGroup):
1123 def __eq__(self, other):
1124 return True
1125
1126 def derive(self, excs):
1127 return type(self)(self.message, excs)
1128
1129 class NeverEqualEG(ExceptionGroup):
1130 def __eq__(self, other):
1131 return False
1132
1133 def derive(self, excs):
1134 return type(self)(self.message, excs)
1135
1136 class BrokenEqualEG(ExceptionGroup):
1137 def __eq__(self, other):
1138 raise RuntimeError()
1139
1140 def derive(self, excs):
1141 return type(self)(self.message, excs)
1142
1143 def setUp(self):
1144 self.bad_types = [self.UnhashableEG,
1145 self.AlwaysEqualEG,
1146 self.NeverEqualEG,
1147 self.BrokenEqualEG]
1148
1149 def except_type(self, eg, type):
1150 match, rest = None, None
1151 try:
1152 try:
1153 raise eg
1154 except* type as e:
1155 match = e
1156 except Exception as e:
1157 rest = e
1158 return match, rest
1159
1160 def test_catch_some_unhashable_exception_group_subclass(self):
1161 for BadEG in self.bad_types:
1162 with self.subTest(BadEG):
1163 eg = BadEG("eg",
1164 [TypeError(1),
1165 BadEG("nested", [ValueError(2)])])
1166
1167 match, rest = self.except_type(eg, TypeError)
1168 self.assertExceptionIsLike(match, BadEG("eg", [TypeError(1)]))
1169 self.assertExceptionIsLike(rest,
1170 BadEG("eg", [BadEG("nested", [ValueError(2)])]))
1171
1172 def test_catch_none_unhashable_exception_group_subclass(self):
1173 for BadEG in self.bad_types:
1174 with self.subTest(BadEG):
1175
1176 eg = BadEG("eg",
1177 [TypeError(1),
1178 BadEG("nested", [ValueError(2)])])
1179
1180 match, rest = self.except_type(eg, OSError)
1181 self.assertIsNone(match)
1182 self.assertExceptionIsLike(rest, eg)
1183
1184 def test_catch_all_unhashable_exception_group_subclass(self):
1185 for BadEG in self.bad_types:
1186 with self.subTest(BadEG):
1187
1188 eg = BadEG("eg",
1189 [TypeError(1),
1190 BadEG("nested", [ValueError(2)])])
1191
1192 match, rest = self.except_type(eg, Exception)
1193 self.assertExceptionIsLike(match, eg)
1194 self.assertIsNone(rest)
1195
1196 def test_reraise_unhashable_eg(self):
1197 for BadEG in self.bad_types:
1198 with self.subTest(BadEG):
1199
1200 eg = BadEG("eg",
1201 [TypeError(1), ValueError(2),
1202 BadEG("nested", [ValueError(3), OSError(4)])])
1203
1204 try:
1205 try:
1206 raise eg
1207 except* ValueError:
1208 pass
1209 except* OSError:
1210 raise
1211 except Exception as e:
1212 exc = e
1213
1214 self.assertExceptionIsLike(
1215 exc, BadEG("eg", [TypeError(1),
1216 BadEG("nested", [OSError(4)])]))
1217
1218
1219 if __name__ == '__main__':
1220 unittest.main()