2007 google inc licensed to psf under a contributor agreement tests for the raise statement from test import support import sys import types import unittest def gettb try raise oserror except oserror as e return e traceback class context def enterself return self def exitself exctype excvalue exctb return true class testraiseunittest testcase def testinvalidreraiseself try raise except runtimeerror as e self assertinno active exception stre else self failno exception raised def testreraiseself try try raise indexerror except indexerror as e exc1 e raise except indexerror as exc2 self assertisexc1 exc2 else self failno exception raised def testexceptreraiseself def reraise try raise typeerrorfoo except try raise keyerrorcaught except keyerror pass raise self assertraisestypeerror reraise def testfinallyreraiseself def reraise try raise typeerrorfoo except try raise keyerrorcaught finally raise self assertraiseskeyerror reraise def testnestedreraiseself def nestedreraise raise def reraise try raise typeerrorfoo except nestedreraise self assertraisestypeerror reraise def testraisefromnoneself try try raise typeerrorfoo except raise valueerror from none except valueerror as e self assertisinstancee context typeerror self assertisnonee cause def testwithreraise1self def reraise try raise typeerrorfoo except with context pass raise self assertraisestypeerror reraise def testwithreraise2self def reraise try raise typeerrorfoo except with context raise keyerrorcaught raise self assertraisestypeerror reraise def testyieldreraiseself def reraise try raise typeerrorfoo except yield 1 raise g reraise nextg self assertraisestypeerror lambda nextg self assertraisesstopiteration lambda nextg def testerroneousexceptionself class myexceptionexception def initself raise runtimeerror try raise myexception except runtimeerror pass else self failno exception raised def testnewreturnsinvalidinstanceself see issue 11627 class myexceptionexception def newcls args return object with self assertraisestypeerror raise myexception def testassertwithtupleargself try assert false 3 except assertionerror as e self assertequalstre 3 class testcauseunittest testcase def testcausesyntaxself try try try raise typeerror except exception raise valueerror from none except valueerror as exc self assertisnoneexc cause self asserttrueexc suppresscontext exc suppresscontext false raise exc except valueerror as exc e exc self assertisnonee cause self assertfalsee suppresscontext self assertisinstancee context typeerror def testinvalidcauseself try raise indexerror from 5 except typeerror as e self assertinexception cause stre else self failno exception raised def testclasscauseself try raise indexerror from keyerror except indexerror as e self assertisinstancee cause keyerror else self failno exception raised def testclasscausenonexceptionresultself class constructsnonebaseexception classmethod def newargs kwargs return none try raise indexerror from constructsnone except typeerror as e self assertinshould have returned an instance of baseexception stre except indexerror self failwrong kind of exception raised else self failno exception raised def testinstancecauseself cause keyerror try raise indexerror from cause except indexerror as e self assertise cause cause else self failno exception raised def testerroneouscauseself class myexceptionexception def initself raise runtimeerror try raise indexerror from myexception except runtimeerror pass else self failno exception raised class testtracebackunittest testcase def testsetstracebackself try raise indexerror except indexerror as e self assertisinstancee traceback types tracebacktype else self failno exception raised def testacceptstracebackself tb gettb try raise indexerror withtracebacktb except indexerror as e self assertnotequale traceback tb self assertequale traceback tbnext tb else self failno exception raised class testtracebacktypeunittest testcase def raiserself raise valueerror def testattrsself try self raiser except exception as exc tb exc traceback self assertisinstancetb tbnext types tracebacktype self assertistb tbframe sys getframe self assertisinstancetb tblasti int self assertisinstancetb tblineno int self assertistb tbnext tbnext none invalid assignments with self assertraisestypeerror del tb tbnext with self assertraisestypeerror tb tbnext asdf loops with self assertraisesvalueerror tb tbnext tb with self assertraisesvalueerror tb tbnext tbnext tb valid assignments tb tbnext none self assertistb tbnext none newtb gettb tb tbnext newtb self assertistb tbnext newtb def testconstructorself othertb gettb frame sys getframe tb types tracebacktypeothertb frame 1 2 self assertequaltb tbnext othertb self assertequaltb tbframe frame self assertequaltb tblasti 1 self assertequaltb tblineno 2 tb types tracebacktypenone frame 1 2 self assertequaltb tbnext none with self assertraisestypeerror types tracebacktypeno frame 1 2 with self assertraisestypeerror types tracebacktypeothertb no 1 2 with self assertraisestypeerror types tracebacktypeothertb frame no 2 with self assertraisestypeerror types tracebacktypeothertb frame 1 nuhuh class testcontextunittest testcase def testinstancecontextinstanceraiseself context indexerror try try raise context except raise oserror except oserror as e self assertise context context else self failno exception raised def testclasscontextinstanceraiseself context indexerror try try raise context except raise oserror except oserror as e self assertisnote context context self assertisinstancee context context else self failno exception raised def testclasscontextclassraiseself context indexerror try try raise context except raise oserror except oserror as e self assertisnote context context self assertisinstancee context context else self failno exception raised def testcexceptioncontextself try try 10 except raise oserror except oserror as e self assertisinstancee context zerodivisionerror else self failno exception raised def testcexceptionraiseself try try 10 except xyzzy except nameerror as e self assertisinstancee context zerodivisionerror else self failno exception raised def testnoraisefinallyself try try pass finally raise oserror except oserror as e self assertisnonee context else self failno exception raised def testraisefinallyself try try 10 finally raise oserror except oserror as e self assertisinstancee context zerodivisionerror else self failno exception raised def testcontextmanagerself class contextmanager def enterself pass def exitself t v tb xyzzy try with contextmanager 10 except nameerror as e self assertisinstancee context zerodivisionerror else self failno exception raised def testcyclebrokenself selfcycles when reraising a caught exception are broken try try 10 except zerodivisionerror as e raise e except zerodivisionerror as e self assertisnonee context def testreraisecyclebrokenself nontrivial context cycles through reraising a previous exception are broken too try try xyzzy except nameerror as a try 10 except zerodivisionerror raise a except nameerror as e self assertisnonee context context def testnotlastself context is not necessarily the last exception context exceptioncontext try raise context except exception try raise exceptioncaught except exception pass try raise exceptionnew except exception as exc raised exc self assertisraised context context def test3118self deleting the generator caused the context to be cleared def gen try yield 1 finally pass def f g gen nextg try try raise valueerror except del g raise keyerror except exception as e self assertisinstancee context valueerror f def test3611self import gc a reraised exception in a del caused the context to be cleared class c def delself try 10 except raise def f x c try try f x except attributeerror make x del trigger del x gc collect for pypy or other gcs raise typeerror except exception as e self assertnotequale context none self assertisinstancee context attributeerror with support catchunraisableexception as cm f self assertequalzerodivisionerror cm unraisable exctype class testremovedfunctionalityunittest testcase def testtuplesself try raise indexerror keyerror this should be a tuple except typeerror pass else self failno exception raised def teststringsself try raise foo except typeerror pass else self failno exception raised if name main unittest main 2007 google inc licensed to psf under a contributor agreement tests for the raise statement see issue 11627 invalid assignments loops valid assignments self cycles when re raising a caught exception are broken non trivial context cycles through re raising a previous exception are broken too context is not necessarily the last exception deleting the generator caused the __context__ to be cleared a re raised exception in a __del__ caused the __context__ to be cleared make x __del__ trigger for pypy or other gcs this should be a tuple
from test import support
import sys
import types
import unittest


def get_tb():
    try:
        raise OSError()
    except OSError as e:
        return e.__traceback__


class Context:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, exc_tb):
        return True


class TestRaise(unittest.TestCase):
    def test_invalid_reraise(self):
        try:
            raise
        except RuntimeError as e:
            self.assertIn("No active exception", str(e))
        else:
            self.fail("No exception raised")

    def test_reraise(self):
        try:
            try:
                raise IndexError()
            except IndexError as e:
                exc1 = e
                raise
        except IndexError as exc2:
            self.assertIs(exc1, exc2)
        else:
            self.fail("No exception raised")

    def test_except_reraise(self):
        def reraise():
            try:
                raise TypeError("foo")
            except:
                try:
                    raise KeyError("caught")
                except KeyError:
                    pass
                raise
        self.assertRaises(TypeError, reraise)

    def test_finally_reraise(self):
        def reraise():
            try:
                raise TypeError("foo")
            except:
                try:
                    raise KeyError("caught")
                finally:
                    raise
        self.assertRaises(KeyError, reraise)

    def test_nested_reraise(self):
        def nested_reraise():
            raise
        def reraise():
            try:
                raise TypeError("foo")
            except:
                nested_reraise()
        self.assertRaises(TypeError, reraise)

    def test_raise_from_None(self):
        try:
            try:
                raise TypeError("foo")
            except:
                raise ValueError() from None
        except ValueError as e:
            self.assertIsInstance(e.__context__, TypeError)
            self.assertIsNone(e.__cause__)

    def test_with_reraise1(self):
        def reraise():
            try:
                raise TypeError("foo")
            except:
                with Context():
                    pass
                raise
        self.assertRaises(TypeError, reraise)

    def test_with_reraise2(self):
        def reraise():
            try:
                raise TypeError("foo")
            except:
                with Context():
                    raise KeyError("caught")
                raise
        self.assertRaises(TypeError, reraise)

    def test_yield_reraise(self):
        def reraise():
            try:
                raise TypeError("foo")
            except:
                yield 1
                raise
        g = reraise()
        next(g)
        self.assertRaises(TypeError, lambda: next(g))
        self.assertRaises(StopIteration, lambda: next(g))

    def test_erroneous_exception(self):
        class MyException(Exception):
            def __init__(self):
                raise RuntimeError()

        try:
            raise MyException
        except RuntimeError:
            pass
        else:
            self.fail("No exception raised")

    def test_new_returns_invalid_instance(self):
        
        class MyException(Exception):
            def __new__(cls, *args):
                return object()

        with self.assertRaises(TypeError):
            raise MyException

    def test_assert_with_tuple_arg(self):
        try:
            assert False, (3,)
        except AssertionError as e:
            self.assertEqual(str(e), "(3,)")



class TestCause(unittest.TestCase):

    def testCauseSyntax(self):
        try:
            try:
                try:
                    raise TypeError
                except Exception:
                    raise ValueError from None
            except ValueError as exc:
                self.assertIsNone(exc.__cause__)
                self.assertTrue(exc.__suppress_context__)
                exc.__suppress_context__ = False
                raise exc
        except ValueError as exc:
            e = exc

        self.assertIsNone(e.__cause__)
        self.assertFalse(e.__suppress_context__)
        self.assertIsInstance(e.__context__, TypeError)

    def test_invalid_cause(self):
        try:
            raise IndexError from 5
        except TypeError as e:
            self.assertIn("exception cause", str(e))
        else:
            self.fail("No exception raised")

    def test_class_cause(self):
        try:
            raise IndexError from KeyError
        except IndexError as e:
            self.assertIsInstance(e.__cause__, KeyError)
        else:
            self.fail("No exception raised")

    def test_class_cause_nonexception_result(self):
        class ConstructsNone(BaseException):
            @classmethod
            def __new__(*args, **kwargs):
                return None
        try:
            raise IndexError from ConstructsNone
        except TypeError as e:
            self.assertIn("should have returned an instance of BaseException", str(e))
        except IndexError:
            self.fail("Wrong kind of exception raised")
        else:
            self.fail("No exception raised")

    def test_instance_cause(self):
        cause = KeyError()
        try:
            raise IndexError from cause
        except IndexError as e:
            self.assertIs(e.__cause__, cause)
        else:
            self.fail("No exception raised")

    def test_erroneous_cause(self):
        class MyException(Exception):
            def __init__(self):
                raise RuntimeError()

        try:
            raise IndexError from MyException
        except RuntimeError:
            pass
        else:
            self.fail("No exception raised")


class TestTraceback(unittest.TestCase):

    def test_sets_traceback(self):
        try:
            raise IndexError()
        except IndexError as e:
            self.assertIsInstance(e.__traceback__, types.TracebackType)
        else:
            self.fail("No exception raised")

    def test_accepts_traceback(self):
        tb = get_tb()
        try:
            raise IndexError().with_traceback(tb)
        except IndexError as e:
            self.assertNotEqual(e.__traceback__, tb)
            self.assertEqual(e.__traceback__.tb_next, tb)
        else:
            self.fail("No exception raised")


class TestTracebackType(unittest.TestCase):

    def raiser(self):
        raise ValueError

    def test_attrs(self):
        try:
            self.raiser()
        except Exception as exc:
            tb = exc.__traceback__

        self.assertIsInstance(tb.tb_next, types.TracebackType)
        self.assertIs(tb.tb_frame, sys._getframe())
        self.assertIsInstance(tb.tb_lasti, int)
        self.assertIsInstance(tb.tb_lineno, int)

        self.assertIs(tb.tb_next.tb_next, None)

        
        with self.assertRaises(TypeError):
            del tb.tb_next

        with self.assertRaises(TypeError):
            tb.tb_next = "asdf"

        
        with self.assertRaises(ValueError):
            tb.tb_next = tb

        with self.assertRaises(ValueError):
            tb.tb_next.tb_next = tb

        
        tb.tb_next = None
        self.assertIs(tb.tb_next, None)

        new_tb = get_tb()
        tb.tb_next = new_tb
        self.assertIs(tb.tb_next, new_tb)

    def test_constructor(self):
        other_tb = get_tb()
        frame = sys._getframe()

        tb = types.TracebackType(other_tb, frame, 1, 2)
        self.assertEqual(tb.tb_next, other_tb)
        self.assertEqual(tb.tb_frame, frame)
        self.assertEqual(tb.tb_lasti, 1)
        self.assertEqual(tb.tb_lineno, 2)

        tb = types.TracebackType(None, frame, 1, 2)
        self.assertEqual(tb.tb_next, None)

        with self.assertRaises(TypeError):
            types.TracebackType("no", frame, 1, 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, "no", 1, 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, frame, "no", 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, frame, 1, "nuh-uh")


class TestContext(unittest.TestCase):
    def test_instance_context_instance_raise(self):
        context = IndexError()
        try:
            try:
                raise context
            except:
                raise OSError()
        except OSError as e:
            self.assertIs(e.__context__, context)
        else:
            self.fail("No exception raised")

    def test_class_context_instance_raise(self):
        context = IndexError
        try:
            try:
                raise context
            except:
                raise OSError()
        except OSError as e:
            self.assertIsNot(e.__context__, context)
            self.assertIsInstance(e.__context__, context)
        else:
            self.fail("No exception raised")

    def test_class_context_class_raise(self):
        context = IndexError
        try:
            try:
                raise context
            except:
                raise OSError
        except OSError as e:
            self.assertIsNot(e.__context__, context)
            self.assertIsInstance(e.__context__, context)
        else:
            self.fail("No exception raised")

    def test_c_exception_context(self):
        try:
            try:
                1/0
            except:
                raise OSError
        except OSError as e:
            self.assertIsInstance(e.__context__, ZeroDivisionError)
        else:
            self.fail("No exception raised")

    def test_c_exception_raise(self):
        try:
            try:
                1/0
            except:
                xyzzy
        except NameError as e:
            self.assertIsInstance(e.__context__, ZeroDivisionError)
        else:
            self.fail("No exception raised")

    def test_noraise_finally(self):
        try:
            try:
                pass
            finally:
                raise OSError
        except OSError as e:
            self.assertIsNone(e.__context__)
        else:
            self.fail("No exception raised")

    def test_raise_finally(self):
        try:
            try:
                1/0
            finally:
                raise OSError
        except OSError as e:
            self.assertIsInstance(e.__context__, ZeroDivisionError)
        else:
            self.fail("No exception raised")

    def test_context_manager(self):
        class ContextManager:
            def __enter__(self):
                pass
            def __exit__(self, t, v, tb):
                xyzzy
        try:
            with ContextManager():
                1/0
        except NameError as e:
            self.assertIsInstance(e.__context__, ZeroDivisionError)
        else:
            self.fail("No exception raised")

    def test_cycle_broken(self):
        
        try:
            try:
                1/0
            except ZeroDivisionError as e:
                raise e
        except ZeroDivisionError as e:
            self.assertIsNone(e.__context__)

    def test_reraise_cycle_broken(self):
        
        
        try:
            try:
                xyzzy
            except NameError as a:
                try:
                    1/0
                except ZeroDivisionError:
                    raise a
        except NameError as e:
            self.assertIsNone(e.__context__.__context__)

    def test_not_last(self):
        
        context = Exception("context")
        try:
            raise context
        except Exception:
            try:
                raise Exception("caught")
            except Exception:
                pass
            try:
                raise Exception("new")
            except Exception as exc:
                raised = exc
        self.assertIs(raised.__context__, context)

    def test_3118(self):
        
        def gen():
            try:
                yield 1
            finally:
                pass

        def f():
            g = gen()
            next(g)
            try:
                try:
                    raise ValueError
                except:
                    del g
                    raise KeyError
            except Exception as e:
                self.assertIsInstance(e.__context__, ValueError)

        f()

    def test_3611(self):
        import gc
        
        
        class C:
            def __del__(self):
                try:
                    1/0
                except:
                    raise

        def f():
            x = C()
            try:
                try:
                    f.x
                except AttributeError:
                    
                    del x
                    gc.collect()  
                    raise TypeError
            except Exception as e:
                self.assertNotEqual(e.__context__, None)
                self.assertIsInstance(e.__context__, AttributeError)

        with support.catch_unraisable_exception() as cm:
            f()

            self.assertEqual(ZeroDivisionError, cm.unraisable.exc_type)


class TestRemovedFunctionality(unittest.TestCase):
    def test_tuples(self):
        try:
            raise (IndexError, KeyError) 
        except TypeError:
            pass
        else:
            self.fail("No exception raised")

    def test_strings(self):
        try:
            raise "foo"
        except TypeError:
            pass
        else:
            self.fail("No exception raised")


if __name__ == "__main__":
    unittest.main()