Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes
test.test_exceptions.ExceptionTests Class Reference

List of all members.

Public Member Functions

def raise_catch
def testRaising
def testSyntaxErrorMessage
def testSettingException
def test_WindowsError
def testAttributes
def testWithTraceback
def testInvalidTraceback
def testInvalidAttrs
def testNoneClearsTracebackAttr
def testChainingAttrs
def testKeywordArgs
def testInfiniteRecursion
def test_str
def testExceptionCleanupNames
def testExceptionCleanupState
def test_exception_target_in_nested_scope
def test_generator_leaking
def test_generator_leaking2
def test_generator_doesnt_retain_old_exc
def test_generator_finalizing_and_exc_info
def test_3114
def testUnicodeChangeAttributes
def test_badisinstance
def test_MemoryError
def test_exception_with_doc
def test_memory_error_cleanup
def test_recursion_error_cleanup

Public Attributes

 fancy_arg
 obj

Detailed Description

Definition at line 14 of file test_exceptions.py.


Member Function Documentation

def test.test_exceptions.ExceptionTests.raise_catch (   self,
  exc,
  excname 
)

Definition at line 16 of file test_exceptions.py.

00016 
00017     def raise_catch(self, exc, excname):
00018         try:
00019             raise exc("spam")
00020         except exc as err:
00021             buf1 = str(err)
00022         try:
00023             raise exc("spam")
00024         except exc as err:
00025             buf2 = str(err)
00026         self.assertEqual(buf1, buf2)
00027         self.assertEqual(exc.__name__, excname)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 610 of file test_exceptions.py.

00610 
00611     def test_3114(self):
00612         # Bug #3114: in its destructor, MyObject retrieves a pointer to
00613         # obsolete and/or deallocated objects.
00614         class MyObject:
00615             def __del__(self):
00616                 nonlocal e
00617                 e = sys.exc_info()
00618         e = ()
00619         try:
00620             raise Exception(MyObject())
00621         except:
00622             pass
00623         self.assertEqual(e, (None, None, None))

Here is the call graph for this function:

Definition at line 661 of file test_exceptions.py.

00661 
00662     def test_badisinstance(self):
00663         # Bug #2542: if issubclass(e, MyException) raises an exception,
00664         # it should be ignored
00665         class Meta(type):
00666             def __subclasscheck__(cls, subclass):
00667                 raise ValueError()
00668         class MyException(Exception, metaclass=Meta):
00669             pass
00670 
00671         with captured_output("stderr") as stderr:
00672             try:
00673                 raise KeyError()
00674             except MyException as e:
00675                 self.fail("exception should not be a MyException")
00676             except KeyError:
00677                 pass
00678             except:
00679                 self.fail("Should have raised KeyError")
00680             else:
00681                 self.fail("Should have raised KeyError")
00682 
00683         def g():
00684             try:
00685                 return g()
00686             except RuntimeError:
00687                 return sys.exc_info()
00688         e, v, tb = g()
00689         self.assertTrue(isinstance(v, RuntimeError), type(v))
00690         self.assertIn("maximum recursion depth exceeded", str(v))
00691 

Here is the call graph for this function:

Definition at line 528 of file test_exceptions.py.

00528 
00529     def test_exception_target_in_nested_scope(self):
00530         # issue 4617: This used to raise a SyntaxError
00531         # "can not delete variable 'e' referenced in nested scope"
00532         def print_error():
00533             e
00534         try:
00535             something
00536         except Exception as e:
00537             print_error()
00538             # implicit "del e" here

Definition at line 711 of file test_exceptions.py.

00711 
00712     def test_exception_with_doc(self):
00713         import _testcapi
00714         doc2 = "This is a test docstring."
00715         doc4 = "This is another test docstring."
00716 
00717         self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
00718                           "error1")
00719 
00720         # test basic usage of PyErr_NewException
00721         error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
00722         self.assertIs(type(error1), type)
00723         self.assertTrue(issubclass(error1, Exception))
00724         self.assertIsNone(error1.__doc__)
00725 
00726         # test with given docstring
00727         error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
00728         self.assertEqual(error2.__doc__, doc2)
00729 
00730         # test with explicit base (without docstring)
00731         error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
00732                                                    base=error2)
00733         self.assertTrue(issubclass(error3, error2))
00734 
00735         # test with explicit base tuple
00736         class C(object):
00737             pass
00738         error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
00739                                                    (error3, C))
00740         self.assertTrue(issubclass(error4, error3))
00741         self.assertTrue(issubclass(error4, C))
00742         self.assertEqual(error4.__doc__, doc4)
00743 
00744         # test with explicit dictionary
00745         error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
00746                                                    error4, {'a': 1})
00747         self.assertTrue(issubclass(error5, error4))
00748         self.assertEqual(error5.a, 1)
00749         self.assertEqual(error5.__doc__, "")

Here is the call graph for this function:

Definition at line 584 of file test_exceptions.py.

00584 
00585     def test_generator_doesnt_retain_old_exc(self):
00586         def g():
00587             self.assertIsInstance(sys.exc_info()[1], RuntimeError)
00588             yield
00589             self.assertEqual(sys.exc_info(), (None, None, None))
00590         it = g()
00591         try:
00592             raise RuntimeError
00593         except RuntimeError:
00594             next(it)
00595         self.assertRaises(StopIteration, next, it)

Here is the call graph for this function:

Definition at line 596 of file test_exceptions.py.

00596 
00597     def test_generator_finalizing_and_exc_info(self):
00598         # See #7173
00599         def simple_gen():
00600             yield 1
00601         def run_gen():
00602             gen = simple_gen()
00603             try:
00604                 raise RuntimeError
00605             except RuntimeError:
00606                 return next(gen)
00607         run_gen()
00608         gc_collect()
00609         self.assertEqual(sys.exc_info(), (None, None, None))

Here is the call graph for this function:

Definition at line 539 of file test_exceptions.py.

00539 
00540     def test_generator_leaking(self):
00541         # Test that generator exception state doesn't leak into the calling
00542         # frame
00543         def yield_raise():
00544             try:
00545                 raise KeyError("caught")
00546             except KeyError:
00547                 yield sys.exc_info()[0]
00548                 yield sys.exc_info()[0]
00549             yield sys.exc_info()[0]
00550         g = yield_raise()
00551         self.assertEqual(next(g), KeyError)
00552         self.assertEqual(sys.exc_info()[0], None)
00553         self.assertEqual(next(g), KeyError)
00554         self.assertEqual(sys.exc_info()[0], None)
00555         self.assertEqual(next(g), None)
00556 
00557         # Same test, but inside an exception handler
00558         try:
00559             raise TypeError("foo")
00560         except TypeError:
00561             g = yield_raise()
00562             self.assertEqual(next(g), KeyError)
00563             self.assertEqual(sys.exc_info()[0], TypeError)
00564             self.assertEqual(next(g), KeyError)
00565             self.assertEqual(sys.exc_info()[0], TypeError)
00566             self.assertEqual(next(g), TypeError)
00567             del g
00568             self.assertEqual(sys.exc_info()[0], TypeError)

Here is the call graph for this function:

Definition at line 569 of file test_exceptions.py.

00569 
00570     def test_generator_leaking2(self):
00571         # See issue 12475.
00572         def g():
00573             yield
00574         try:
00575             raise RuntimeError
00576         except RuntimeError:
00577             it = g()
00578             next(it)
00579         try:
00580             next(it)
00581         except StopIteration:
00582             pass
00583         self.assertEqual(sys.exc_info(), (None, None, None))

Definition at line 750 of file test_exceptions.py.

00750 
00751     def test_memory_error_cleanup(self):
00752         # Issue #5437: preallocated MemoryError instances should not keep
00753         # traceback objects alive.
00754         from _testcapi import raise_memoryerror
00755         class C:
00756             pass
00757         wr = None
00758         def inner():
00759             nonlocal wr
00760             c = C()
00761             wr = weakref.ref(c)
00762             raise_memoryerror()
00763         # We cannot use assertRaises since it manually deletes the traceback
00764         try:
00765             inner()
00766         except MemoryError as e:
00767             self.assertNotEqual(wr(), None)
00768         else:
00769             self.fail("MemoryError not raised")
00770         self.assertEqual(wr(), None)

Definition at line 692 of file test_exceptions.py.

00692 
00693     def test_MemoryError(self):
00694         # PyErr_NoMemory always raises the same exception instance.
00695         # Check that the traceback is not doubled.
00696         import traceback
00697         from _testcapi import raise_memoryerror
00698         def raiseMemError():
00699             try:
00700                 raise_memoryerror()
00701             except MemoryError as e:
00702                 tb = e.__traceback__
00703             else:
00704                 self.fail("Should have raises a MemoryError")
00705             return traceback.format_tb(tb)
00706 
00707         tb1 = raiseMemError()
00708         tb2 = raiseMemError()
00709         self.assertEqual(tb1, tb2)

Here is the call graph for this function:

Definition at line 771 of file test_exceptions.py.

00771 
00772     def test_recursion_error_cleanup(self):
00773         # Same test as above, but with "recursion exceeded" errors
00774         class C:
00775             pass
00776         wr = None
00777         def inner():
00778             nonlocal wr
00779             c = C()
00780             wr = weakref.ref(c)
00781             inner()
00782         # We cannot use assertRaises since it manually deletes the traceback
00783         try:
00784             inner()
00785         except RuntimeError as e:
00786             self.assertNotEqual(wr(), None)
00787         else:
00788             self.fail("RuntimeError not raised")
00789         self.assertEqual(wr(), None)

Definition at line 403 of file test_exceptions.py.

00403 
00404     def test_str(self):
00405         # Make sure both instances and classes have a str representation.
00406         self.assertTrue(str(Exception))
00407         self.assertTrue(str(Exception('a')))
00408         self.assertTrue(str(Exception('a', 'b')))

Here is the call graph for this function:

Definition at line 188 of file test_exceptions.py.

00188 
00189     def test_WindowsError(self):
00190         try:
00191             WindowsError
00192         except NameError:
00193             pass
00194         else:
00195             self.assertEqual(str(WindowsError(1001)), "1001")
00196             self.assertEqual(str(WindowsError(1001, "message")),
00197                              "[Error 1001] message")
00198             self.assertEqual(WindowsError(1001, "message").errno, 22)
00199             self.assertEqual(WindowsError(1001, "message").winerror, 1001)

Here is the call graph for this function:

Definition at line 200 of file test_exceptions.py.

00200 
00201     def testAttributes(self):
00202         # test that exception attributes are happy
00203 
00204         exceptionList = [
00205             (BaseException, (), {'args' : ()}),
00206             (BaseException, (1, ), {'args' : (1,)}),
00207             (BaseException, ('foo',),
00208                 {'args' : ('foo',)}),
00209             (BaseException, ('foo', 1),
00210                 {'args' : ('foo', 1)}),
00211             (SystemExit, ('foo',),
00212                 {'args' : ('foo',), 'code' : 'foo'}),
00213             (IOError, ('foo',),
00214                 {'args' : ('foo',), 'filename' : None,
00215                  'errno' : None, 'strerror' : None}),
00216             (IOError, ('foo', 'bar'),
00217                 {'args' : ('foo', 'bar'), 'filename' : None,
00218                  'errno' : 'foo', 'strerror' : 'bar'}),
00219             (IOError, ('foo', 'bar', 'baz'),
00220                 {'args' : ('foo', 'bar'), 'filename' : 'baz',
00221                  'errno' : 'foo', 'strerror' : 'bar'}),
00222             (IOError, ('foo', 'bar', 'baz', 'quux'),
00223                 {'args' : ('foo', 'bar', 'baz', 'quux')}),
00224             (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
00225                 {'args' : ('errnoStr', 'strErrorStr'),
00226                  'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
00227                  'filename' : 'filenameStr'}),
00228             (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
00229                 {'args' : (1, 'strErrorStr'), 'errno' : 1,
00230                  'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
00231             (SyntaxError, (), {'msg' : None, 'text' : None,
00232                 'filename' : None, 'lineno' : None, 'offset' : None,
00233                 'print_file_and_line' : None}),
00234             (SyntaxError, ('msgStr',),
00235                 {'args' : ('msgStr',), 'text' : None,
00236                  'print_file_and_line' : None, 'msg' : 'msgStr',
00237                  'filename' : None, 'lineno' : None, 'offset' : None}),
00238             (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
00239                            'textStr')),
00240                 {'offset' : 'offsetStr', 'text' : 'textStr',
00241                  'args' : ('msgStr', ('filenameStr', 'linenoStr',
00242                                       'offsetStr', 'textStr')),
00243                  'print_file_and_line' : None, 'msg' : 'msgStr',
00244                  'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
00245             (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
00246                            'textStr', 'print_file_and_lineStr'),
00247                 {'text' : None,
00248                  'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
00249                            'textStr', 'print_file_and_lineStr'),
00250                  'print_file_and_line' : None, 'msg' : 'msgStr',
00251                  'filename' : None, 'lineno' : None, 'offset' : None}),
00252             (UnicodeError, (), {'args' : (),}),
00253             (UnicodeEncodeError, ('ascii', 'a', 0, 1,
00254                                   'ordinal not in range'),
00255                 {'args' : ('ascii', 'a', 0, 1,
00256                                            'ordinal not in range'),
00257                  'encoding' : 'ascii', 'object' : 'a',
00258                  'start' : 0, 'reason' : 'ordinal not in range'}),
00259             (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
00260                                   'ordinal not in range'),
00261                 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
00262                                            'ordinal not in range'),
00263                  'encoding' : 'ascii', 'object' : b'\xff',
00264                  'start' : 0, 'reason' : 'ordinal not in range'}),
00265             (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
00266                                   'ordinal not in range'),
00267                 {'args' : ('ascii', b'\xff', 0, 1,
00268                                            'ordinal not in range'),
00269                  'encoding' : 'ascii', 'object' : b'\xff',
00270                  'start' : 0, 'reason' : 'ordinal not in range'}),
00271             (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
00272                 {'args' : ('\u3042', 0, 1, 'ouch'),
00273                  'object' : '\u3042', 'reason' : 'ouch',
00274                  'start' : 0, 'end' : 1}),
00275         ]
00276         try:
00277             exceptionList.append(
00278                 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
00279                     {'args' : (1, 'strErrorStr'),
00280                      'strerror' : 'strErrorStr', 'winerror' : 1,
00281                      'errno' : 22, 'filename' : 'filenameStr'})
00282             )
00283         except NameError:
00284             pass
00285 
00286         for exc, args, expected in exceptionList:
00287             try:
00288                 e = exc(*args)
00289             except:
00290                 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
00291                 raise
00292             else:
00293                 # Verify module name
00294                 self.assertEqual(type(e).__module__, 'builtins')
00295                 # Verify no ref leaks in Exc_str()
00296                 s = str(e)
00297                 for checkArgName in expected:
00298                     value = getattr(e, checkArgName)
00299                     self.assertEqual(repr(value),
00300                                      repr(expected[checkArgName]),
00301                                      '%r.%s == %r, expected %r' % (
00302                                      e, checkArgName,
00303                                      value, expected[checkArgName]))
00304 
00305                 # test for pickling support
00306                 for p in [pickle]:
00307                     for protocol in range(p.HIGHEST_PROTOCOL + 1):
00308                         s = p.dumps(e, protocol)
00309                         new = p.loads(s)
00310                         for checkArgName in expected:
00311                             got = repr(getattr(new, checkArgName))
00312                             want = repr(expected[checkArgName])
00313                             self.assertEqual(got, want,
00314                                              'pickled "%r", attribute "%s' %
00315                                              (e, checkArgName))

Here is the call graph for this function:

Definition at line 362 of file test_exceptions.py.

00362 
00363     def testChainingAttrs(self):
00364         e = Exception()
00365         self.assertEqual(e.__context__, None)
00366         self.assertEqual(e.__cause__, None)
00367 
00368         e = TypeError()
00369         self.assertEqual(e.__context__, None)
00370         self.assertEqual(e.__cause__, None)
00371 
00372         class MyException(EnvironmentError):
00373             pass
00374 
00375         e = MyException()
00376         self.assertEqual(e.__context__, None)
00377         self.assertEqual(e.__cause__, None)

Here is the call graph for this function:

Definition at line 409 of file test_exceptions.py.

00409 
00410     def testExceptionCleanupNames(self):
00411         # Make sure the local variable bound to the exception instance by
00412         # an "except" statement is only visible inside the except block.
00413         try:
00414             raise Exception()
00415         except Exception as e:
00416             self.assertTrue(e)
00417             del e
00418         self.assertNotIn('e', locals())

Here is the call graph for this function:

Definition at line 419 of file test_exceptions.py.

00419 
00420     def testExceptionCleanupState(self):
00421         # Make sure exception state is cleaned up as soon as the except
00422         # block is left. See #2507
00423 
00424         class MyException(Exception):
00425             def __init__(self, obj):
00426                 self.obj = obj
00427         class MyObj:
00428             pass
00429 
00430         def inner_raising_func():
00431             # Create some references in exception value and traceback
00432             local_ref = obj
00433             raise MyException(obj)
00434 
00435         # Qualified "except" with "as"
00436         obj = MyObj()
00437         wr = weakref.ref(obj)
00438         try:
00439             inner_raising_func()
00440         except MyException as e:
00441             pass
00442         obj = None
00443         obj = wr()
00444         self.assertTrue(obj is None, "%s" % obj)
00445 
00446         # Qualified "except" without "as"
00447         obj = MyObj()
00448         wr = weakref.ref(obj)
00449         try:
00450             inner_raising_func()
00451         except MyException:
00452             pass
00453         obj = None
00454         obj = wr()
00455         self.assertTrue(obj is None, "%s" % obj)
00456 
00457         # Bare "except"
00458         obj = MyObj()
00459         wr = weakref.ref(obj)
00460         try:
00461             inner_raising_func()
00462         except:
00463             pass
00464         obj = None
00465         obj = wr()
00466         self.assertTrue(obj is None, "%s" % obj)
00467 
00468         # "except" with premature block leave
00469         obj = MyObj()
00470         wr = weakref.ref(obj)
00471         for i in [0]:
00472             try:
00473                 inner_raising_func()
00474             except:
00475                 break
00476         obj = None
00477         obj = wr()
00478         self.assertTrue(obj is None, "%s" % obj)
00479 
00480         # "except" block raising another exception
00481         obj = MyObj()
00482         wr = weakref.ref(obj)
00483         try:
00484             try:
00485                 inner_raising_func()
00486             except:
00487                 raise KeyError
00488         except KeyError as e:
00489             # We want to test that the except block above got rid of
00490             # the exception raised in inner_raising_func(), but it
00491             # also ends up in the __context__ of the KeyError, so we
00492             # must clear the latter manually for our test to succeed.
00493             e.__context__ = None
00494             obj = None
00495             obj = wr()
00496             self.assertTrue(obj is None, "%s" % obj)
00497 
00498         # Some complicated construct
00499         obj = MyObj()
00500         wr = weakref.ref(obj)
00501         try:
00502             inner_raising_func()
00503         except MyException:
00504             try:
00505                 try:
00506                     raise
00507                 finally:
00508                     raise
00509             except MyException:
00510                 pass
00511         obj = None
00512         obj = wr()
00513         self.assertTrue(obj is None, "%s" % obj)
00514 
00515         # Inside an exception-silencing "with" block
00516         class Context:
00517             def __enter__(self):
00518                 return self
00519             def __exit__ (self, exc_type, exc_value, exc_tb):
00520                 return True
00521         obj = MyObj()
00522         wr = weakref.ref(obj)
00523         with Context():
00524             inner_raising_func()
00525         obj = None
00526         obj = wr()
00527         self.assertTrue(obj is None, "%s" % obj)

Here is the call graph for this function:

Definition at line 391 of file test_exceptions.py.

00391 
00392     def testInfiniteRecursion(self):
00393         def f():
00394             return f()
00395         self.assertRaises(RuntimeError, f)
00396 
00397         def g():
00398             try:
00399                 return g()
00400             except ValueError:
00401                 return -1
00402         self.assertRaises(RuntimeError, g)

Here is the call graph for this function:

Definition at line 345 of file test_exceptions.py.

00345 
00346     def testInvalidAttrs(self):
00347         self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
00348         self.assertRaises(TypeError, delattr, Exception(), '__cause__')
00349         self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
00350         self.assertRaises(TypeError, delattr, Exception(), '__context__')

Here is the call graph for this function:

Definition at line 337 of file test_exceptions.py.

00337 
00338     def testInvalidTraceback(self):
00339         try:
00340             Exception().__traceback__ = 5
00341         except TypeError as e:
00342             self.assertIn("__traceback__ must be a traceback", str(e))
00343         else:
00344             self.fail("No exception raised")

Here is the call graph for this function:

Definition at line 378 of file test_exceptions.py.

00378 
00379     def testKeywordArgs(self):
00380         # test that builtin exception don't take keyword args,
00381         # but user-defined subclasses can if they want
00382         self.assertRaises(TypeError, BaseException, a=1)
00383 
00384         class DerivedException(BaseException):
00385             def __init__(self, fancy_arg):
00386                 BaseException.__init__(self)
00387                 self.fancy_arg = fancy_arg
00388 
00389         x = DerivedException(fancy_arg=42)
00390         self.assertEqual(x.fancy_arg, 42)

Here is the call graph for this function:

Definition at line 351 of file test_exceptions.py.

00351 
00352     def testNoneClearsTracebackAttr(self):
00353         try:
00354             raise IndexError(4)
00355         except:
00356             tb = sys.exc_info()[2]
00357 
00358         e = Exception()
00359         e.__traceback__ = tb
00360         e.__traceback__ = None
00361         self.assertEqual(e.__traceback__, None)

Here is the call graph for this function:

Definition at line 28 of file test_exceptions.py.

00028 
00029     def testRaising(self):
00030         self.raise_catch(AttributeError, "AttributeError")
00031         self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
00032 
00033         self.raise_catch(EOFError, "EOFError")
00034         fp = open(TESTFN, 'w')
00035         fp.close()
00036         fp = open(TESTFN, 'r')
00037         savestdin = sys.stdin
00038         try:
00039             try:
00040                 import marshal
00041                 marshal.loads('')
00042             except EOFError:
00043                 pass
00044         finally:
00045             sys.stdin = savestdin
00046             fp.close()
00047             unlink(TESTFN)
00048 
00049         self.raise_catch(IOError, "IOError")
00050         self.assertRaises(IOError, open, 'this file does not exist', 'r')
00051 
00052         self.raise_catch(ImportError, "ImportError")
00053         self.assertRaises(ImportError, __import__, "undefined_module")
00054 
00055         self.raise_catch(IndexError, "IndexError")
00056         x = []
00057         self.assertRaises(IndexError, x.__getitem__, 10)
00058 
00059         self.raise_catch(KeyError, "KeyError")
00060         x = {}
00061         self.assertRaises(KeyError, x.__getitem__, 'key')
00062 
00063         self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
00064 
00065         self.raise_catch(MemoryError, "MemoryError")
00066 
00067         self.raise_catch(NameError, "NameError")
00068         try: x = undefined_variable
00069         except NameError: pass
00070 
00071         self.raise_catch(OverflowError, "OverflowError")
00072         x = 1
00073         for dummy in range(128):
00074             x += x  # this simply shouldn't blow up
00075 
00076         self.raise_catch(RuntimeError, "RuntimeError")
00077 
00078         self.raise_catch(SyntaxError, "SyntaxError")
00079         try: exec('/\n')
00080         except SyntaxError: pass
00081 
00082         self.raise_catch(IndentationError, "IndentationError")
00083 
00084         self.raise_catch(TabError, "TabError")
00085         try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n",
00086                      '<string>', 'exec')
00087         except TabError: pass
00088         else: self.fail("TabError not raised")
00089 
00090         self.raise_catch(SystemError, "SystemError")
00091 
00092         self.raise_catch(SystemExit, "SystemExit")
00093         self.assertRaises(SystemExit, sys.exit, 0)
00094 
00095         self.raise_catch(TypeError, "TypeError")
00096         try: [] + ()
00097         except TypeError: pass
00098 
00099         self.raise_catch(ValueError, "ValueError")
00100         self.assertRaises(ValueError, chr, 17<<16)
00101 
00102         self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
00103         try: x = 1/0
00104         except ZeroDivisionError: pass
00105 
00106         self.raise_catch(Exception, "Exception")
00107         try: x = 1/0
00108         except Exception as e: pass

Here is the call graph for this function:

Definition at line 141 of file test_exceptions.py.

00141 
00142     def testSettingException(self):
00143         # test that setting an exception at the C level works even if the
00144         # exception object can't be constructed.
00145 
00146         class BadException(Exception):
00147             def __init__(self_):
00148                 raise RuntimeError("can't instantiate BadException")
00149 
00150         class InvalidException:
00151             pass
00152 
00153         def test_capi1():
00154             import _testcapi
00155             try:
00156                 _testcapi.raise_exception(BadException, 1)
00157             except TypeError as err:
00158                 exc, err, tb = sys.exc_info()
00159                 co = tb.tb_frame.f_code
00160                 self.assertEqual(co.co_name, "test_capi1")
00161                 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
00162             else:
00163                 self.fail("Expected exception")
00164 
00165         def test_capi2():
00166             import _testcapi
00167             try:
00168                 _testcapi.raise_exception(BadException, 0)
00169             except RuntimeError as err:
00170                 exc, err, tb = sys.exc_info()
00171                 co = tb.tb_frame.f_code
00172                 self.assertEqual(co.co_name, "__init__")
00173                 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
00174                 co2 = tb.tb_frame.f_back.f_code
00175                 self.assertEqual(co2.co_name, "test_capi2")
00176             else:
00177                 self.fail("Expected exception")
00178 
00179         def test_capi3():
00180             import _testcapi
00181             self.assertRaises(SystemError, _testcapi.raise_exception,
00182                               InvalidException, 1)
00183 
00184         if not sys.platform.startswith('java'):
00185             test_capi1()
00186             test_capi2()
00187             test_capi3()

Here is the call graph for this function:

Definition at line 109 of file test_exceptions.py.

00109 
00110     def testSyntaxErrorMessage(self):
00111         # make sure the right exception message is raised for each of
00112         # these code fragments
00113 
00114         def ckmsg(src, msg):
00115             try:
00116                 compile(src, '<fragment>', 'exec')
00117             except SyntaxError as e:
00118                 if e.msg != msg:
00119                     self.fail("expected %s, got %s" % (msg, e.msg))
00120             else:
00121                 self.fail("failed to get expected SyntaxError")
00122 
00123         s = '''while 1:
00124             try:
00125                 pass
00126             finally:
00127                 continue'''
00128 
00129         if not sys.platform.startswith('java'):
00130             ckmsg(s, "'continue' not supported inside 'finally' clause")
00131 
00132         s = '''if 1:
00133         try:
00134             continue
00135         except:
00136             pass'''
00137 
00138         ckmsg(s, "'continue' not properly in loop")
00139         ckmsg("continue\n", "'continue' not properly in loop")

Here is the call graph for this function:

Definition at line 624 of file test_exceptions.py.

00624 
00625     def testUnicodeChangeAttributes(self):
00626         # See issue 7309. This was a crasher.
00627 
00628         u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
00629         self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
00630         u.end = 2
00631         self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
00632         u.end = 5
00633         u.reason = 0x345345345345345345
00634         self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
00635         u.encoding = 4000
00636         self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
00637         u.start = 1000
00638         self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
00639 
00640         u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
00641         self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
00642         u.end = 2
00643         self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
00644         u.end = 5
00645         u.reason = 0x345345345345345345
00646         self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
00647         u.encoding = 4000
00648         self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
00649         u.start = 1000
00650         self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
00651 
00652         u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
00653         self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
00654         u.end = 2
00655         self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
00656         u.end = 5
00657         u.reason = 0x345345345345345345
00658         self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
00659         u.start = 1000
00660         self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")

Here is the call graph for this function:

Definition at line 316 of file test_exceptions.py.

00316 
00317     def testWithTraceback(self):
00318         try:
00319             raise IndexError(4)
00320         except:
00321             tb = sys.exc_info()[2]
00322 
00323         e = BaseException().with_traceback(tb)
00324         self.assertIsInstance(e, BaseException)
00325         self.assertEqual(e.__traceback__, tb)
00326 
00327         e = IndexError(5).with_traceback(tb)
00328         self.assertIsInstance(e, IndexError)
00329         self.assertEqual(e.__traceback__, tb)
00330 
00331         class MyException(Exception):
00332             pass
00333 
00334         e = MyException().with_traceback(tb)
00335         self.assertIsInstance(e, MyException)
00336         self.assertEqual(e.__traceback__, tb)

Here is the call graph for this function:


Member Data Documentation

Definition at line 386 of file test_exceptions.py.

Definition at line 425 of file test_exceptions.py.


The documentation for this class was generated from the following file: