@@ -3408,6 +3408,19 @@ class Unrepresentable:
3408
3408
def __repr__ (self ) -> str :
3409
3409
raise Exception ("Unrepresentable" )
3410
3410
3411
+
3412
+ # Used in test_dont_swallow_cause_or_context_of_falsey_exception and
3413
+ # test_dont_swallow_subexceptions_of_falsey_exceptiongroup.
3414
+ class FalseyException (Exception ):
3415
+ def __bool__ (self ):
3416
+ return False
3417
+
3418
+
3419
+ class FalseyExceptionGroup (ExceptionGroup ):
3420
+ def __bool__ (self ):
3421
+ return False
3422
+
3423
+
3411
3424
class TestTracebackException (unittest .TestCase ):
3412
3425
def do_test_smoke (self , exc , expected_type_str ):
3413
3426
try :
@@ -3753,6 +3766,24 @@ def f():
3753
3766
'ZeroDivisionError: division by zero' ,
3754
3767
'' ])
3755
3768
3769
+ def test_dont_swallow_cause_or_context_of_falsey_exception (self ):
3770
+ # see gh-132308: Ensure that __cause__ or __context__ attributes of exceptions
3771
+ # that evaluate as falsey are included in the output. For falsey term,
3772
+ # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
3773
+
3774
+ try :
3775
+ raise FalseyException from KeyError
3776
+ except FalseyException as e :
3777
+ self .assertIn (cause_message , traceback .format_exception (e ))
3778
+
3779
+ try :
3780
+ try :
3781
+ 1 / 0
3782
+ except ZeroDivisionError :
3783
+ raise FalseyException
3784
+ except FalseyException as e :
3785
+ self .assertIn (context_message , traceback .format_exception (e ))
3786
+
3756
3787
3757
3788
class TestTracebackException_ExceptionGroups (unittest .TestCase ):
3758
3789
def setUp (self ):
@@ -3954,6 +3985,26 @@ def test_comparison(self):
3954
3985
self .assertNotEqual (exc , object ())
3955
3986
self .assertEqual (exc , ALWAYS_EQ )
3956
3987
3988
+ def test_dont_swallow_subexceptions_of_falsey_exceptiongroup (self ):
3989
+ # see gh-132308: Ensure that subexceptions of exception groups
3990
+ # that evaluate as falsey are displayed in the output. For falsey term,
3991
+ # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
3992
+
3993
+ try :
3994
+ raise FalseyExceptionGroup ("Gih" , (KeyError (), NameError ()))
3995
+ except Exception as ee :
3996
+ str_exc = '' .join (traceback .format_exception (ee ))
3997
+ self .assertIn ('+---------------- 1 ----------------' , str_exc )
3998
+ self .assertIn ('+---------------- 2 ----------------' , str_exc )
3999
+
4000
+ # Test with a falsey exception, in last position, as sub-exceptions.
4001
+ msg = 'bool'
4002
+ try :
4003
+ raise FalseyExceptionGroup ("Gah" , (KeyError (), FalseyException (msg )))
4004
+ except Exception as ee :
4005
+ str_exc = traceback .format_exception (ee )
4006
+ self .assertIn (f'{ FalseyException .__name__ } : { msg } ' , str_exc [- 2 ])
4007
+
3957
4008
3958
4009
global_for_suggestions = None
3959
4010
0 commit comments