1212def get_tb ():
1313 try :
1414 raise OSError ()
15- except :
16- return sys . exc_info ()[ 2 ]
15+ except OSError as e :
16+ return e . __traceback__
1717
1818
1919class Context :
@@ -307,7 +307,7 @@ def test_instance_context_instance_raise(self):
307307 except :
308308 raise OSError ()
309309 except OSError as e :
310- self .assertEqual (e .__context__ , context )
310+ self .assertIs (e .__context__ , context )
311311 else :
312312 self .fail ("No exception raised" )
313313
@@ -319,7 +319,7 @@ def test_class_context_instance_raise(self):
319319 except :
320320 raise OSError ()
321321 except OSError as e :
322- self .assertNotEqual (e .__context__ , context )
322+ self .assertIsNot (e .__context__ , context )
323323 self .assertIsInstance (e .__context__ , context )
324324 else :
325325 self .fail ("No exception raised" )
@@ -332,7 +332,7 @@ def test_class_context_class_raise(self):
332332 except :
333333 raise OSError
334334 except OSError as e :
335- self .assertNotEqual (e .__context__ , context )
335+ self .assertIsNot (e .__context__ , context )
336336 self .assertIsInstance (e .__context__ , context )
337337 else :
338338 self .fail ("No exception raised" )
@@ -419,6 +419,22 @@ def test_reraise_cycle_broken(self):
419419 except NameError as e :
420420 self .assertIsNone (e .__context__ .__context__ )
421421
422+ def test_not_last (self ):
423+ # Context is not necessarily the last exception
424+ context = Exception ("context" )
425+ try :
426+ raise context
427+ except Exception :
428+ try :
429+ raise Exception ("caught" )
430+ except Exception :
431+ pass
432+ try :
433+ raise Exception ("new" )
434+ except Exception as exc :
435+ raised = exc
436+ self .assertIs (raised .__context__ , context )
437+
422438 def test_3118 (self ):
423439 # deleting the generator caused the __context__ to be cleared
424440 def gen ():
@@ -442,6 +458,7 @@ def f():
442458 f ()
443459
444460 def test_3611 (self ):
461+ import gc
445462 # A re-raised exception in a __del__ caused the __context__
446463 # to be cleared
447464 class C :
@@ -455,17 +472,22 @@ def f():
455472 x = C ()
456473 try :
457474 try :
458- x .x
475+ f .x
459476 except AttributeError :
477+ # make x.__del__ trigger
460478 del x
479+ gc .collect () # For PyPy or other GCs.
461480 raise TypeError
462481 except Exception as e :
463482 self .assertNotEqual (e .__context__ , None )
464483 self .assertIsInstance (e .__context__ , AttributeError )
465484
466- with support .captured_output ( "stderr" ) :
485+ with support .catch_unraisable_exception () as cm :
467486 f ()
468487
488+ self .assertEqual (ZeroDivisionError , cm .unraisable .exc_type )
489+
490+
469491class TestRemovedFunctionality (unittest .TestCase ):
470492 def test_tuples (self ):
471493 try :
0 commit comments