Debian Codegraph @

lib-python/3/test/test_except_star.py

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