@@ -142,6 +142,71 @@ def f():
142142 self .assertIsInstance (e , ValueError )
143143 self .assertIs (exc , e )
144144
145+ class SetExceptionTests (unittest .TestCase ):
146+
147+ def tearDown (self ):
148+ # make sure we don't leave the global exception set
149+ sys ._set_exception (None );
150+
151+ def test_set_exc_invalid_values (self ):
152+ for x in (0 , "1" , b"2" ):
153+ with self .assertRaises (TypeError ):
154+ sys ._set_exception (x );
155+
156+ def test_clear_exc (self ):
157+ try :
158+ raise ValueError ()
159+ except ValueError :
160+ self .assertIsInstance (sys .exception (), ValueError )
161+ sys ._set_exception (None )
162+ self .assertIsNone (sys .exception ())
163+
164+ def test_set_exc (self ):
165+ exc = ValueError ()
166+ self .assertIsNone (sys .exception ())
167+ sys ._set_exception (exc )
168+ self .assertIs (sys .exception (), exc )
169+
170+ def test_set_exc_replaced_by_new_exception_and_restored (self ):
171+ exc = ValueError ()
172+ sys ._set_exception (exc )
173+ self .assertIs (sys .exception (), exc )
174+ try :
175+ raise TypeError ()
176+ except TypeError :
177+ self .assertIsInstance (sys .exception (), TypeError )
178+ self .assertIs (sys .exception ().__context__ , exc )
179+
180+ self .assertIs (sys .exception (), exc )
181+
182+ def test_set_exc_popped_on_exit_except (self ):
183+ exc = ValueError ()
184+ try :
185+ raise TypeError ()
186+ except TypeError :
187+ self .assertIsInstance (sys .exception (), TypeError )
188+ sys ._set_exception (exc )
189+ self .assertIs (sys .exception (), exc )
190+ self .assertIsNone (sys .exception ())
191+
192+ def test_cleared_exc_overridden_and_restored (self ):
193+ try :
194+ raise ValueError ()
195+ except ValueError :
196+ try :
197+ raise TypeError ()
198+ except TypeError :
199+ self .assertIsInstance (sys .exception (), TypeError )
200+ sys ._set_exception (None )
201+ self .assertIsNone (sys .exception ())
202+ try :
203+ raise IndexError ()
204+ except IndexError :
205+ self .assertIsInstance (sys .exception (), IndexError )
206+ self .assertIsNone (sys .exception ().__context__ )
207+ self .assertIsNone (sys .exception ())
208+ self .assertIsInstance (sys .exception (), ValueError )
209+ self .assertIsNone (sys .exception ())
145210
146211class ExceptHookTest (unittest .TestCase ):
147212
0 commit comments