Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1 | # Python test set -- part 5, built-in exceptions |
| 2 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 3 | import os |
| 4 | import sys |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 5 | import unittest |
Guido van Rossum | bf12cdb | 2006-08-17 20:24:18 +0000 | [diff] [blame] | 6 | import pickle |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 7 | import weakref |
Antoine Pitrou | a762285 | 2011-09-01 21:37:43 +0200 | [diff] [blame] | 8 | import errno |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 9 | |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 10 | from test.support import (TESTFN, captured_output, check_impl_detail, |
Philip Jenvey | 21c95eb | 2012-11-14 14:49:49 -0800 | [diff] [blame] | 11 | cpython_only, gc_collect, run_unittest, no_tracing, |
| 12 | unlink) |
Guido van Rossum | 83b120d | 2001-08-23 03:23:03 +0000 | [diff] [blame] | 13 | |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 14 | class NaiveException(Exception): |
| 15 | def __init__(self, x): |
| 16 | self.x = x |
| 17 | |
| 18 | class SlottedNaiveException(Exception): |
| 19 | __slots__ = ('x',) |
| 20 | def __init__(self, x): |
| 21 | self.x = x |
| 22 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 23 | # XXX This is not really enough, each *operation* should be tested! |
| 24 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 25 | class ExceptionTests(unittest.TestCase): |
Barry Warsaw | b9c1d3d | 2001-08-13 23:07:00 +0000 | [diff] [blame] | 26 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 27 | def raise_catch(self, exc, excname): |
| 28 | try: |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 29 | raise exc("spam") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 30 | except exc as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 31 | buf1 = str(err) |
| 32 | try: |
| 33 | raise exc("spam") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 34 | except exc as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 35 | buf2 = str(err) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 36 | self.assertEqual(buf1, buf2) |
| 37 | self.assertEqual(exc.__name__, excname) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 38 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 39 | def testRaising(self): |
| 40 | self.raise_catch(AttributeError, "AttributeError") |
| 41 | self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 42 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 43 | self.raise_catch(EOFError, "EOFError") |
| 44 | fp = open(TESTFN, 'w') |
| 45 | fp.close() |
| 46 | fp = open(TESTFN, 'r') |
| 47 | savestdin = sys.stdin |
| 48 | try: |
| 49 | try: |
| 50 | import marshal |
Antoine Pitrou | 4a90ef0 | 2012-03-03 02:35:32 +0100 | [diff] [blame] | 51 | marshal.loads(b'') |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 52 | except EOFError: |
| 53 | pass |
| 54 | finally: |
| 55 | sys.stdin = savestdin |
| 56 | fp.close() |
| 57 | unlink(TESTFN) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 58 | |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 59 | self.raise_catch(OSError, "OSError") |
| 60 | self.assertRaises(OSError, open, 'this file does not exist', 'r') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 61 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 62 | self.raise_catch(ImportError, "ImportError") |
| 63 | self.assertRaises(ImportError, __import__, "undefined_module") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 64 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 65 | self.raise_catch(IndexError, "IndexError") |
| 66 | x = [] |
| 67 | self.assertRaises(IndexError, x.__getitem__, 10) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 68 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 69 | self.raise_catch(KeyError, "KeyError") |
| 70 | x = {} |
| 71 | self.assertRaises(KeyError, x.__getitem__, 'key') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 72 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 73 | self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 74 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 75 | self.raise_catch(MemoryError, "MemoryError") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 76 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 77 | self.raise_catch(NameError, "NameError") |
| 78 | try: x = undefined_variable |
| 79 | except NameError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 80 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 81 | self.raise_catch(OverflowError, "OverflowError") |
| 82 | x = 1 |
| 83 | for dummy in range(128): |
| 84 | x += x # this simply shouldn't blow up |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 85 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 86 | self.raise_catch(RuntimeError, "RuntimeError") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 87 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 88 | self.raise_catch(SyntaxError, "SyntaxError") |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 89 | try: exec('/\n') |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 90 | except SyntaxError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 91 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 92 | self.raise_catch(IndentationError, "IndentationError") |
Fred Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 93 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 94 | self.raise_catch(TabError, "TabError") |
Georg Brandl | e1b5ac6 | 2008-06-04 13:06:58 +0000 | [diff] [blame] | 95 | try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", |
| 96 | '<string>', 'exec') |
| 97 | except TabError: pass |
| 98 | else: self.fail("TabError not raised") |
Fred Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 99 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 100 | self.raise_catch(SystemError, "SystemError") |
Fred Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 101 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 102 | self.raise_catch(SystemExit, "SystemExit") |
| 103 | self.assertRaises(SystemExit, sys.exit, 0) |
Fred Drake | 85f3639 | 2000-07-11 17:53:00 +0000 | [diff] [blame] | 104 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 105 | self.raise_catch(TypeError, "TypeError") |
| 106 | try: [] + () |
| 107 | except TypeError: pass |
Fred Drake | 85f3639 | 2000-07-11 17:53:00 +0000 | [diff] [blame] | 108 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 109 | self.raise_catch(ValueError, "ValueError") |
Guido van Rossum | e63bae6 | 2007-07-17 00:34:25 +0000 | [diff] [blame] | 110 | self.assertRaises(ValueError, chr, 17<<16) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 111 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 112 | self.raise_catch(ZeroDivisionError, "ZeroDivisionError") |
| 113 | try: x = 1/0 |
| 114 | except ZeroDivisionError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 115 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 116 | self.raise_catch(Exception, "Exception") |
| 117 | try: x = 1/0 |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 118 | except Exception as e: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 119 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 120 | def testSyntaxErrorMessage(self): |
| 121 | # make sure the right exception message is raised for each of |
| 122 | # these code fragments |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 123 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 124 | def ckmsg(src, msg): |
| 125 | try: |
| 126 | compile(src, '<fragment>', 'exec') |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 127 | except SyntaxError as e: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 128 | if e.msg != msg: |
| 129 | self.fail("expected %s, got %s" % (msg, e.msg)) |
| 130 | else: |
| 131 | self.fail("failed to get expected SyntaxError") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 132 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 133 | s = '''while 1: |
| 134 | try: |
| 135 | pass |
| 136 | finally: |
| 137 | continue''' |
Barry Warsaw | 992cb8a | 2000-05-25 23:16:54 +0000 | [diff] [blame] | 138 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 139 | if not sys.platform.startswith('java'): |
| 140 | ckmsg(s, "'continue' not supported inside 'finally' clause") |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 141 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 142 | s = '''if 1: |
| 143 | try: |
| 144 | continue |
| 145 | except: |
| 146 | pass''' |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 147 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 148 | ckmsg(s, "'continue' not properly in loop") |
| 149 | ckmsg("continue\n", "'continue' not properly in loop") |
Thomas Wouters | 303de6a | 2006-04-20 22:42:37 +0000 | [diff] [blame] | 150 | |
Benjamin Peterson | 17e0bbc | 2010-06-28 15:39:55 +0000 | [diff] [blame] | 151 | @cpython_only |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 152 | def testSettingException(self): |
| 153 | # test that setting an exception at the C level works even if the |
| 154 | # exception object can't be constructed. |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 155 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 156 | class BadException(Exception): |
| 157 | def __init__(self_): |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 158 | raise RuntimeError("can't instantiate BadException") |
Finn Bock | aa3dc45 | 2001-12-08 10:15:48 +0000 | [diff] [blame] | 159 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 160 | class InvalidException: |
| 161 | pass |
Thomas Wouters | 303de6a | 2006-04-20 22:42:37 +0000 | [diff] [blame] | 162 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 163 | def test_capi1(): |
| 164 | import _testcapi |
| 165 | try: |
| 166 | _testcapi.raise_exception(BadException, 1) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 167 | except TypeError as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 168 | exc, err, tb = sys.exc_info() |
| 169 | co = tb.tb_frame.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 170 | self.assertEqual(co.co_name, "test_capi1") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 171 | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 172 | else: |
| 173 | self.fail("Expected exception") |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 174 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 175 | def test_capi2(): |
| 176 | import _testcapi |
| 177 | try: |
| 178 | _testcapi.raise_exception(BadException, 0) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 179 | except RuntimeError as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 180 | exc, err, tb = sys.exc_info() |
| 181 | co = tb.tb_frame.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 182 | self.assertEqual(co.co_name, "__init__") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 183 | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 184 | co2 = tb.tb_frame.f_back.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 185 | self.assertEqual(co2.co_name, "test_capi2") |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 186 | else: |
| 187 | self.fail("Expected exception") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 188 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 189 | def test_capi3(): |
| 190 | import _testcapi |
| 191 | self.assertRaises(SystemError, _testcapi.raise_exception, |
| 192 | InvalidException, 1) |
| 193 | |
| 194 | if not sys.platform.startswith('java'): |
| 195 | test_capi1() |
| 196 | test_capi2() |
| 197 | test_capi3() |
| 198 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 199 | def test_WindowsError(self): |
| 200 | try: |
| 201 | WindowsError |
| 202 | except NameError: |
| 203 | pass |
| 204 | else: |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 205 | self.assertIs(WindowsError, OSError) |
| 206 | self.assertEqual(str(OSError(1001)), "1001") |
| 207 | self.assertEqual(str(OSError(1001, "message")), |
| 208 | "[Errno 1001] message") |
| 209 | # POSIX errno (9 aka EBADF) is untranslated |
| 210 | w = OSError(9, 'foo', 'bar') |
| 211 | self.assertEqual(w.errno, 9) |
| 212 | self.assertEqual(w.winerror, None) |
| 213 | self.assertEqual(str(w), "[Errno 9] foo: 'bar'") |
| 214 | # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) |
| 215 | w = OSError(0, 'foo', 'bar', 3) |
| 216 | self.assertEqual(w.errno, 2) |
| 217 | self.assertEqual(w.winerror, 3) |
| 218 | self.assertEqual(w.strerror, 'foo') |
| 219 | self.assertEqual(w.filename, 'bar') |
Richard Oudkerk | 3014771 | 2012-08-28 19:33:26 +0100 | [diff] [blame] | 220 | self.assertEqual(str(w), "[WinError 3] foo: 'bar'") |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 221 | # Unknown win error becomes EINVAL (22) |
| 222 | w = OSError(0, 'foo', None, 1001) |
| 223 | self.assertEqual(w.errno, 22) |
| 224 | self.assertEqual(w.winerror, 1001) |
| 225 | self.assertEqual(w.strerror, 'foo') |
| 226 | self.assertEqual(w.filename, None) |
Richard Oudkerk | 3014771 | 2012-08-28 19:33:26 +0100 | [diff] [blame] | 227 | self.assertEqual(str(w), "[WinError 1001] foo") |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 228 | # Non-numeric "errno" |
| 229 | w = OSError('bar', 'foo') |
| 230 | self.assertEqual(w.errno, 'bar') |
| 231 | self.assertEqual(w.winerror, None) |
| 232 | self.assertEqual(w.strerror, 'foo') |
| 233 | self.assertEqual(w.filename, None) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 234 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 235 | def testAttributes(self): |
| 236 | # test that exception attributes are happy |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 237 | |
| 238 | exceptionList = [ |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 239 | (BaseException, (), {'args' : ()}), |
| 240 | (BaseException, (1, ), {'args' : (1,)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 241 | (BaseException, ('foo',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 242 | {'args' : ('foo',)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 243 | (BaseException, ('foo', 1), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 244 | {'args' : ('foo', 1)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 245 | (SystemExit, ('foo',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 246 | {'args' : ('foo',), 'code' : 'foo'}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 247 | (IOError, ('foo',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 248 | {'args' : ('foo',), 'filename' : None, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 249 | 'errno' : None, 'strerror' : None}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 250 | (IOError, ('foo', 'bar'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 251 | {'args' : ('foo', 'bar'), 'filename' : None, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 252 | 'errno' : 'foo', 'strerror' : 'bar'}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 253 | (IOError, ('foo', 'bar', 'baz'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 254 | {'args' : ('foo', 'bar'), 'filename' : 'baz', |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 255 | 'errno' : 'foo', 'strerror' : 'bar'}), |
| 256 | (IOError, ('foo', 'bar', 'baz', 'quux'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 257 | {'args' : ('foo', 'bar', 'baz', 'quux')}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 258 | (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 259 | {'args' : ('errnoStr', 'strErrorStr'), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 260 | 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', |
| 261 | 'filename' : 'filenameStr'}), |
| 262 | (EnvironmentError, (1, 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 263 | {'args' : (1, 'strErrorStr'), 'errno' : 1, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 264 | 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 265 | (SyntaxError, (), {'msg' : None, 'text' : None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 266 | 'filename' : None, 'lineno' : None, 'offset' : None, |
| 267 | 'print_file_and_line' : None}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 268 | (SyntaxError, ('msgStr',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 269 | {'args' : ('msgStr',), 'text' : None, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 270 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
| 271 | 'filename' : None, 'lineno' : None, 'offset' : None}), |
| 272 | (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', |
| 273 | 'textStr')), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 274 | {'offset' : 'offsetStr', 'text' : 'textStr', |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 275 | 'args' : ('msgStr', ('filenameStr', 'linenoStr', |
| 276 | 'offsetStr', 'textStr')), |
| 277 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
| 278 | 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}), |
| 279 | (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
| 280 | 'textStr', 'print_file_and_lineStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 281 | {'text' : None, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 282 | 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
| 283 | 'textStr', 'print_file_and_lineStr'), |
| 284 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
| 285 | 'filename' : None, 'lineno' : None, 'offset' : None}), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 286 | (UnicodeError, (), {'args' : (),}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 287 | (UnicodeEncodeError, ('ascii', 'a', 0, 1, |
| 288 | 'ordinal not in range'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 289 | {'args' : ('ascii', 'a', 0, 1, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 290 | 'ordinal not in range'), |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 291 | 'encoding' : 'ascii', 'object' : 'a', |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 292 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 293 | (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 294 | 'ordinal not in range'), |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 295 | {'args' : ('ascii', bytearray(b'\xff'), 0, 1, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 296 | 'ordinal not in range'), |
| 297 | 'encoding' : 'ascii', 'object' : b'\xff', |
| 298 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 299 | (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, |
| 300 | 'ordinal not in range'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 301 | {'args' : ('ascii', b'\xff', 0, 1, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 302 | 'ordinal not in range'), |
Guido van Rossum | b8142c3 | 2007-05-08 17:49:10 +0000 | [diff] [blame] | 303 | 'encoding' : 'ascii', 'object' : b'\xff', |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 304 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 305 | (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 306 | {'args' : ('\u3042', 0, 1, 'ouch'), |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 307 | 'object' : '\u3042', 'reason' : 'ouch', |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 308 | 'start' : 0, 'end' : 1}), |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 309 | (NaiveException, ('foo',), |
| 310 | {'args': ('foo',), 'x': 'foo'}), |
| 311 | (SlottedNaiveException, ('foo',), |
| 312 | {'args': ('foo',), 'x': 'foo'}), |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 313 | ] |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 314 | try: |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 315 | # More tests are in test_WindowsError |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 316 | exceptionList.append( |
| 317 | (WindowsError, (1, 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 318 | {'args' : (1, 'strErrorStr'), |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 319 | 'strerror' : 'strErrorStr', 'winerror' : None, |
| 320 | 'errno' : 1, 'filename' : 'filenameStr'}) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 321 | ) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 322 | except NameError: |
| 323 | pass |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 324 | |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 325 | for exc, args, expected in exceptionList: |
| 326 | try: |
| 327 | e = exc(*args) |
| 328 | except: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 329 | print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr) |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 330 | raise |
| 331 | else: |
| 332 | # Verify module name |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 333 | if not type(e).__name__.endswith('NaiveException'): |
| 334 | self.assertEqual(type(e).__module__, 'builtins') |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 335 | # Verify no ref leaks in Exc_str() |
| 336 | s = str(e) |
| 337 | for checkArgName in expected: |
| 338 | value = getattr(e, checkArgName) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 339 | self.assertEqual(repr(value), |
| 340 | repr(expected[checkArgName]), |
| 341 | '%r.%s == %r, expected %r' % ( |
| 342 | e, checkArgName, |
| 343 | value, expected[checkArgName])) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 344 | |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 345 | # test for pickling support |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 346 | for p in [pickle]: |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 347 | for protocol in range(p.HIGHEST_PROTOCOL + 1): |
| 348 | s = p.dumps(e, protocol) |
| 349 | new = p.loads(s) |
| 350 | for checkArgName in expected: |
| 351 | got = repr(getattr(new, checkArgName)) |
| 352 | want = repr(expected[checkArgName]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 353 | self.assertEqual(got, want, |
| 354 | 'pickled "%r", attribute "%s' % |
| 355 | (e, checkArgName)) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 356 | |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 357 | def testWithTraceback(self): |
| 358 | try: |
| 359 | raise IndexError(4) |
| 360 | except: |
| 361 | tb = sys.exc_info()[2] |
| 362 | |
| 363 | e = BaseException().with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 364 | self.assertIsInstance(e, BaseException) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 365 | self.assertEqual(e.__traceback__, tb) |
| 366 | |
| 367 | e = IndexError(5).with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 368 | self.assertIsInstance(e, IndexError) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 369 | self.assertEqual(e.__traceback__, tb) |
| 370 | |
| 371 | class MyException(Exception): |
| 372 | pass |
| 373 | |
| 374 | e = MyException().with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 375 | self.assertIsInstance(e, MyException) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 376 | self.assertEqual(e.__traceback__, tb) |
| 377 | |
| 378 | def testInvalidTraceback(self): |
| 379 | try: |
| 380 | Exception().__traceback__ = 5 |
| 381 | except TypeError as e: |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 382 | self.assertIn("__traceback__ must be a traceback", str(e)) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 383 | else: |
| 384 | self.fail("No exception raised") |
| 385 | |
Georg Brandl | ab6f2f6 | 2009-03-31 04:16:10 +0000 | [diff] [blame] | 386 | def testInvalidAttrs(self): |
| 387 | self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1) |
| 388 | self.assertRaises(TypeError, delattr, Exception(), '__cause__') |
| 389 | self.assertRaises(TypeError, setattr, Exception(), '__context__', 1) |
| 390 | self.assertRaises(TypeError, delattr, Exception(), '__context__') |
| 391 | |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 392 | def testNoneClearsTracebackAttr(self): |
| 393 | try: |
| 394 | raise IndexError(4) |
| 395 | except: |
| 396 | tb = sys.exc_info()[2] |
| 397 | |
| 398 | e = Exception() |
| 399 | e.__traceback__ = tb |
| 400 | e.__traceback__ = None |
| 401 | self.assertEqual(e.__traceback__, None) |
| 402 | |
| 403 | def testChainingAttrs(self): |
| 404 | e = Exception() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 405 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 406 | self.assertIsNone(e.__cause__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 407 | |
| 408 | e = TypeError() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 409 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 410 | self.assertIsNone(e.__cause__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 411 | |
| 412 | class MyException(EnvironmentError): |
| 413 | pass |
| 414 | |
| 415 | e = MyException() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 416 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 417 | self.assertIsNone(e.__cause__) |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 418 | |
| 419 | def testChainingDescriptors(self): |
| 420 | try: |
| 421 | raise Exception() |
| 422 | except Exception as exc: |
| 423 | e = exc |
| 424 | |
| 425 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 426 | self.assertIsNone(e.__cause__) |
| 427 | self.assertFalse(e.__suppress_context__) |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 428 | |
| 429 | e.__context__ = NameError() |
| 430 | e.__cause__ = None |
| 431 | self.assertIsInstance(e.__context__, NameError) |
| 432 | self.assertIsNone(e.__cause__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 433 | self.assertTrue(e.__suppress_context__) |
| 434 | e.__suppress_context__ = False |
| 435 | self.assertFalse(e.__suppress_context__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 436 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 437 | def testKeywordArgs(self): |
| 438 | # test that builtin exception don't take keyword args, |
| 439 | # but user-defined subclasses can if they want |
| 440 | self.assertRaises(TypeError, BaseException, a=1) |
| 441 | |
| 442 | class DerivedException(BaseException): |
| 443 | def __init__(self, fancy_arg): |
| 444 | BaseException.__init__(self) |
| 445 | self.fancy_arg = fancy_arg |
| 446 | |
| 447 | x = DerivedException(fancy_arg=42) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 448 | self.assertEqual(x.fancy_arg, 42) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 449 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 450 | @no_tracing |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 451 | def testInfiniteRecursion(self): |
| 452 | def f(): |
| 453 | return f() |
| 454 | self.assertRaises(RuntimeError, f) |
| 455 | |
| 456 | def g(): |
| 457 | try: |
| 458 | return g() |
| 459 | except ValueError: |
| 460 | return -1 |
| 461 | self.assertRaises(RuntimeError, g) |
| 462 | |
Ezio Melotti | 2f5a78c | 2009-12-24 22:54:06 +0000 | [diff] [blame] | 463 | def test_str(self): |
| 464 | # Make sure both instances and classes have a str representation. |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 465 | self.assertTrue(str(Exception)) |
| 466 | self.assertTrue(str(Exception('a'))) |
Ezio Melotti | 2f5a78c | 2009-12-24 22:54:06 +0000 | [diff] [blame] | 467 | self.assertTrue(str(Exception('a', 'b'))) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 468 | |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 469 | def testExceptionCleanupNames(self): |
| 470 | # Make sure the local variable bound to the exception instance by |
| 471 | # an "except" statement is only visible inside the except block. |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 472 | try: |
| 473 | raise Exception() |
| 474 | except Exception as e: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 475 | self.assertTrue(e) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 476 | del e |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 477 | self.assertNotIn('e', locals()) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 478 | |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 479 | def testExceptionCleanupState(self): |
| 480 | # Make sure exception state is cleaned up as soon as the except |
| 481 | # block is left. See #2507 |
| 482 | |
| 483 | class MyException(Exception): |
| 484 | def __init__(self, obj): |
| 485 | self.obj = obj |
| 486 | class MyObj: |
| 487 | pass |
| 488 | |
| 489 | def inner_raising_func(): |
| 490 | # Create some references in exception value and traceback |
| 491 | local_ref = obj |
| 492 | raise MyException(obj) |
| 493 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 494 | # Qualified "except" with "as" |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 495 | obj = MyObj() |
| 496 | wr = weakref.ref(obj) |
| 497 | try: |
| 498 | inner_raising_func() |
| 499 | except MyException as e: |
| 500 | pass |
| 501 | obj = None |
| 502 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 503 | self.assertTrue(obj is None, "%s" % obj) |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 504 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 505 | # Qualified "except" without "as" |
| 506 | obj = MyObj() |
| 507 | wr = weakref.ref(obj) |
| 508 | try: |
| 509 | inner_raising_func() |
| 510 | except MyException: |
| 511 | pass |
| 512 | obj = None |
| 513 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 514 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 515 | |
| 516 | # Bare "except" |
| 517 | obj = MyObj() |
| 518 | wr = weakref.ref(obj) |
| 519 | try: |
| 520 | inner_raising_func() |
| 521 | except: |
| 522 | pass |
| 523 | obj = None |
| 524 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 525 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 526 | |
| 527 | # "except" with premature block leave |
| 528 | obj = MyObj() |
| 529 | wr = weakref.ref(obj) |
| 530 | for i in [0]: |
| 531 | try: |
| 532 | inner_raising_func() |
| 533 | except: |
| 534 | break |
| 535 | obj = None |
| 536 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 537 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 538 | |
| 539 | # "except" block raising another exception |
| 540 | obj = MyObj() |
| 541 | wr = weakref.ref(obj) |
| 542 | try: |
| 543 | try: |
| 544 | inner_raising_func() |
| 545 | except: |
| 546 | raise KeyError |
Guido van Rossum | b4fb6e4 | 2008-06-14 20:20:24 +0000 | [diff] [blame] | 547 | except KeyError as e: |
| 548 | # We want to test that the except block above got rid of |
| 549 | # the exception raised in inner_raising_func(), but it |
| 550 | # also ends up in the __context__ of the KeyError, so we |
| 551 | # must clear the latter manually for our test to succeed. |
| 552 | e.__context__ = None |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 553 | obj = None |
| 554 | obj = wr() |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 555 | # guarantee no ref cycles on CPython (don't gc_collect) |
| 556 | if check_impl_detail(cpython=False): |
| 557 | gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 558 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 559 | |
| 560 | # Some complicated construct |
| 561 | obj = MyObj() |
| 562 | wr = weakref.ref(obj) |
| 563 | try: |
| 564 | inner_raising_func() |
| 565 | except MyException: |
| 566 | try: |
| 567 | try: |
| 568 | raise |
| 569 | finally: |
| 570 | raise |
| 571 | except MyException: |
| 572 | pass |
| 573 | obj = None |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 574 | if check_impl_detail(cpython=False): |
| 575 | gc_collect() |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 576 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 577 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 578 | |
| 579 | # Inside an exception-silencing "with" block |
| 580 | class Context: |
| 581 | def __enter__(self): |
| 582 | return self |
| 583 | def __exit__ (self, exc_type, exc_value, exc_tb): |
| 584 | return True |
| 585 | obj = MyObj() |
| 586 | wr = weakref.ref(obj) |
| 587 | with Context(): |
| 588 | inner_raising_func() |
| 589 | obj = None |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 590 | if check_impl_detail(cpython=False): |
| 591 | gc_collect() |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 592 | obj = wr() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 593 | self.assertTrue(obj is None, "%s" % obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 594 | |
Amaury Forgeot d'Arc | ba117ef | 2010-09-10 21:39:53 +0000 | [diff] [blame] | 595 | def test_exception_target_in_nested_scope(self): |
| 596 | # issue 4617: This used to raise a SyntaxError |
| 597 | # "can not delete variable 'e' referenced in nested scope" |
| 598 | def print_error(): |
| 599 | e |
| 600 | try: |
| 601 | something |
| 602 | except Exception as e: |
| 603 | print_error() |
| 604 | # implicit "del e" here |
| 605 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 606 | def test_generator_leaking(self): |
| 607 | # Test that generator exception state doesn't leak into the calling |
| 608 | # frame |
| 609 | def yield_raise(): |
| 610 | try: |
| 611 | raise KeyError("caught") |
| 612 | except KeyError: |
| 613 | yield sys.exc_info()[0] |
| 614 | yield sys.exc_info()[0] |
| 615 | yield sys.exc_info()[0] |
| 616 | g = yield_raise() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 617 | self.assertEqual(next(g), KeyError) |
| 618 | self.assertEqual(sys.exc_info()[0], None) |
| 619 | self.assertEqual(next(g), KeyError) |
| 620 | self.assertEqual(sys.exc_info()[0], None) |
| 621 | self.assertEqual(next(g), None) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 622 | |
| 623 | # Same test, but inside an exception handler |
| 624 | try: |
| 625 | raise TypeError("foo") |
| 626 | except TypeError: |
| 627 | g = yield_raise() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 628 | self.assertEqual(next(g), KeyError) |
| 629 | self.assertEqual(sys.exc_info()[0], TypeError) |
| 630 | self.assertEqual(next(g), KeyError) |
| 631 | self.assertEqual(sys.exc_info()[0], TypeError) |
| 632 | self.assertEqual(next(g), TypeError) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 633 | del g |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 634 | self.assertEqual(sys.exc_info()[0], TypeError) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 635 | |
Benjamin Peterson | 83195c3 | 2011-07-03 13:44:00 -0500 | [diff] [blame] | 636 | def test_generator_leaking2(self): |
| 637 | # See issue 12475. |
| 638 | def g(): |
| 639 | yield |
| 640 | try: |
| 641 | raise RuntimeError |
| 642 | except RuntimeError: |
| 643 | it = g() |
| 644 | next(it) |
| 645 | try: |
| 646 | next(it) |
| 647 | except StopIteration: |
| 648 | pass |
| 649 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 650 | |
Benjamin Peterson | ac91341 | 2011-07-03 16:25:11 -0500 | [diff] [blame] | 651 | def test_generator_doesnt_retain_old_exc(self): |
| 652 | def g(): |
| 653 | self.assertIsInstance(sys.exc_info()[1], RuntimeError) |
| 654 | yield |
| 655 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 656 | it = g() |
| 657 | try: |
| 658 | raise RuntimeError |
| 659 | except RuntimeError: |
| 660 | next(it) |
| 661 | self.assertRaises(StopIteration, next, it) |
| 662 | |
Benjamin Peterson | ae5f2f4 | 2010-03-07 17:10:51 +0000 | [diff] [blame] | 663 | def test_generator_finalizing_and_exc_info(self): |
| 664 | # See #7173 |
| 665 | def simple_gen(): |
| 666 | yield 1 |
| 667 | def run_gen(): |
| 668 | gen = simple_gen() |
| 669 | try: |
| 670 | raise RuntimeError |
| 671 | except RuntimeError: |
| 672 | return next(gen) |
| 673 | run_gen() |
| 674 | gc_collect() |
| 675 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 676 | |
Antoine Pitrou | a370fcf | 2011-08-20 14:15:03 +0200 | [diff] [blame] | 677 | def _check_generator_cleanup_exc_state(self, testfunc): |
| 678 | # Issue #12791: exception state is cleaned up as soon as a generator |
| 679 | # is closed (reference cycles are broken). |
| 680 | class MyException(Exception): |
| 681 | def __init__(self, obj): |
| 682 | self.obj = obj |
| 683 | class MyObj: |
| 684 | pass |
| 685 | |
| 686 | def raising_gen(): |
| 687 | try: |
| 688 | raise MyException(obj) |
| 689 | except MyException: |
| 690 | yield |
| 691 | |
| 692 | obj = MyObj() |
| 693 | wr = weakref.ref(obj) |
| 694 | g = raising_gen() |
| 695 | next(g) |
| 696 | testfunc(g) |
| 697 | g = obj = None |
| 698 | obj = wr() |
| 699 | self.assertIs(obj, None) |
| 700 | |
| 701 | def test_generator_throw_cleanup_exc_state(self): |
| 702 | def do_throw(g): |
| 703 | try: |
| 704 | g.throw(RuntimeError()) |
| 705 | except RuntimeError: |
| 706 | pass |
| 707 | self._check_generator_cleanup_exc_state(do_throw) |
| 708 | |
| 709 | def test_generator_close_cleanup_exc_state(self): |
| 710 | def do_close(g): |
| 711 | g.close() |
| 712 | self._check_generator_cleanup_exc_state(do_close) |
| 713 | |
| 714 | def test_generator_del_cleanup_exc_state(self): |
| 715 | def do_del(g): |
| 716 | g = None |
| 717 | self._check_generator_cleanup_exc_state(do_del) |
| 718 | |
| 719 | def test_generator_next_cleanup_exc_state(self): |
| 720 | def do_next(g): |
| 721 | try: |
| 722 | next(g) |
| 723 | except StopIteration: |
| 724 | pass |
| 725 | else: |
| 726 | self.fail("should have raised StopIteration") |
| 727 | self._check_generator_cleanup_exc_state(do_next) |
| 728 | |
| 729 | def test_generator_send_cleanup_exc_state(self): |
| 730 | def do_send(g): |
| 731 | try: |
| 732 | g.send(None) |
| 733 | except StopIteration: |
| 734 | pass |
| 735 | else: |
| 736 | self.fail("should have raised StopIteration") |
| 737 | self._check_generator_cleanup_exc_state(do_send) |
| 738 | |
Benjamin Peterson | 27d6367 | 2008-06-15 20:09:12 +0000 | [diff] [blame] | 739 | def test_3114(self): |
| 740 | # Bug #3114: in its destructor, MyObject retrieves a pointer to |
| 741 | # obsolete and/or deallocated objects. |
Benjamin Peterson | 979f311 | 2008-06-15 00:05:44 +0000 | [diff] [blame] | 742 | class MyObject: |
| 743 | def __del__(self): |
| 744 | nonlocal e |
| 745 | e = sys.exc_info() |
| 746 | e = () |
| 747 | try: |
| 748 | raise Exception(MyObject()) |
| 749 | except: |
| 750 | pass |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 751 | self.assertEqual(e, (None, None, None)) |
Benjamin Peterson | 979f311 | 2008-06-15 00:05:44 +0000 | [diff] [blame] | 752 | |
Eric Smith | 0facd77 | 2010-02-24 15:42:29 +0000 | [diff] [blame] | 753 | def testUnicodeChangeAttributes(self): |
| 754 | # See issue 7309. This was a crasher. |
| 755 | |
| 756 | u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') |
| 757 | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") |
| 758 | u.end = 2 |
| 759 | self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") |
| 760 | u.end = 5 |
| 761 | u.reason = 0x345345345345345345 |
| 762 | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") |
| 763 | u.encoding = 4000 |
| 764 | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") |
| 765 | u.start = 1000 |
| 766 | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") |
| 767 | |
| 768 | u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') |
| 769 | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") |
| 770 | u.end = 2 |
| 771 | self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") |
| 772 | u.end = 5 |
| 773 | u.reason = 0x345345345345345345 |
| 774 | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 775 | u.encoding = 4000 |
| 776 | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 777 | u.start = 1000 |
| 778 | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") |
| 779 | |
| 780 | u = UnicodeTranslateError('xxxx', 1, 5, 'foo') |
| 781 | self.assertEqual(str(u), "can't translate characters in position 1-4: foo") |
| 782 | u.end = 2 |
| 783 | self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") |
| 784 | u.end = 5 |
| 785 | u.reason = 0x345345345345345345 |
| 786 | self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") |
| 787 | u.start = 1000 |
| 788 | self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") |
Benjamin Peterson | 6e7740c | 2008-08-20 23:23:34 +0000 | [diff] [blame] | 789 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 790 | @no_tracing |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 791 | def test_badisinstance(self): |
| 792 | # Bug #2542: if issubclass(e, MyException) raises an exception, |
| 793 | # it should be ignored |
| 794 | class Meta(type): |
| 795 | def __subclasscheck__(cls, subclass): |
| 796 | raise ValueError() |
| 797 | class MyException(Exception, metaclass=Meta): |
| 798 | pass |
| 799 | |
| 800 | with captured_output("stderr") as stderr: |
| 801 | try: |
| 802 | raise KeyError() |
| 803 | except MyException as e: |
| 804 | self.fail("exception should not be a MyException") |
| 805 | except KeyError: |
| 806 | pass |
| 807 | except: |
Antoine Pitrou | ec569b7 | 2008-08-26 22:40:48 +0000 | [diff] [blame] | 808 | self.fail("Should have raised KeyError") |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 809 | else: |
Antoine Pitrou | ec569b7 | 2008-08-26 22:40:48 +0000 | [diff] [blame] | 810 | self.fail("Should have raised KeyError") |
| 811 | |
| 812 | def g(): |
| 813 | try: |
| 814 | return g() |
| 815 | except RuntimeError: |
| 816 | return sys.exc_info() |
| 817 | e, v, tb = g() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 818 | self.assertTrue(isinstance(v, RuntimeError), type(v)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 819 | self.assertIn("maximum recursion depth exceeded", str(v)) |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 820 | |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 821 | |
| 822 | def test_MemoryError(self): |
| 823 | # PyErr_NoMemory always raises the same exception instance. |
| 824 | # Check that the traceback is not doubled. |
| 825 | import traceback |
Benjamin Peterson | 0067bd6 | 2008-08-16 16:11:03 +0000 | [diff] [blame] | 826 | from _testcapi import raise_memoryerror |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 827 | def raiseMemError(): |
| 828 | try: |
Benjamin Peterson | 0067bd6 | 2008-08-16 16:11:03 +0000 | [diff] [blame] | 829 | raise_memoryerror() |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 830 | except MemoryError as e: |
| 831 | tb = e.__traceback__ |
| 832 | else: |
| 833 | self.fail("Should have raises a MemoryError") |
| 834 | return traceback.format_tb(tb) |
| 835 | |
| 836 | tb1 = raiseMemError() |
| 837 | tb2 = raiseMemError() |
| 838 | self.assertEqual(tb1, tb2) |
| 839 | |
Benjamin Peterson | 17e0bbc | 2010-06-28 15:39:55 +0000 | [diff] [blame] | 840 | @cpython_only |
Georg Brandl | 1e28a27 | 2009-12-28 08:41:01 +0000 | [diff] [blame] | 841 | def test_exception_with_doc(self): |
| 842 | import _testcapi |
| 843 | doc2 = "This is a test docstring." |
| 844 | doc4 = "This is another test docstring." |
| 845 | |
| 846 | self.assertRaises(SystemError, _testcapi.make_exception_with_doc, |
| 847 | "error1") |
| 848 | |
| 849 | # test basic usage of PyErr_NewException |
| 850 | error1 = _testcapi.make_exception_with_doc("_testcapi.error1") |
| 851 | self.assertIs(type(error1), type) |
| 852 | self.assertTrue(issubclass(error1, Exception)) |
| 853 | self.assertIsNone(error1.__doc__) |
| 854 | |
| 855 | # test with given docstring |
| 856 | error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) |
| 857 | self.assertEqual(error2.__doc__, doc2) |
| 858 | |
| 859 | # test with explicit base (without docstring) |
| 860 | error3 = _testcapi.make_exception_with_doc("_testcapi.error3", |
| 861 | base=error2) |
| 862 | self.assertTrue(issubclass(error3, error2)) |
| 863 | |
| 864 | # test with explicit base tuple |
| 865 | class C(object): |
| 866 | pass |
| 867 | error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, |
| 868 | (error3, C)) |
| 869 | self.assertTrue(issubclass(error4, error3)) |
| 870 | self.assertTrue(issubclass(error4, C)) |
| 871 | self.assertEqual(error4.__doc__, doc4) |
| 872 | |
| 873 | # test with explicit dictionary |
| 874 | error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", |
| 875 | error4, {'a': 1}) |
| 876 | self.assertTrue(issubclass(error5, error4)) |
| 877 | self.assertEqual(error5.a, 1) |
| 878 | self.assertEqual(error5.__doc__, "") |
| 879 | |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 880 | def test_memory_error_cleanup(self): |
| 881 | # Issue #5437: preallocated MemoryError instances should not keep |
| 882 | # traceback objects alive. |
| 883 | from _testcapi import raise_memoryerror |
| 884 | class C: |
| 885 | pass |
| 886 | wr = None |
| 887 | def inner(): |
| 888 | nonlocal wr |
| 889 | c = C() |
| 890 | wr = weakref.ref(c) |
| 891 | raise_memoryerror() |
| 892 | # We cannot use assertRaises since it manually deletes the traceback |
| 893 | try: |
| 894 | inner() |
| 895 | except MemoryError as e: |
| 896 | self.assertNotEqual(wr(), None) |
| 897 | else: |
| 898 | self.fail("MemoryError not raised") |
| 899 | self.assertEqual(wr(), None) |
| 900 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 901 | @no_tracing |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 902 | def test_recursion_error_cleanup(self): |
| 903 | # Same test as above, but with "recursion exceeded" errors |
| 904 | class C: |
| 905 | pass |
| 906 | wr = None |
| 907 | def inner(): |
| 908 | nonlocal wr |
| 909 | c = C() |
| 910 | wr = weakref.ref(c) |
| 911 | inner() |
| 912 | # We cannot use assertRaises since it manually deletes the traceback |
| 913 | try: |
| 914 | inner() |
| 915 | except RuntimeError as e: |
| 916 | self.assertNotEqual(wr(), None) |
| 917 | else: |
| 918 | self.fail("RuntimeError not raised") |
| 919 | self.assertEqual(wr(), None) |
Georg Brandl | 1e28a27 | 2009-12-28 08:41:01 +0000 | [diff] [blame] | 920 | |
Antoine Pitrou | a762285 | 2011-09-01 21:37:43 +0200 | [diff] [blame] | 921 | def test_errno_ENOTDIR(self): |
| 922 | # Issue #12802: "not a directory" errors are ENOTDIR even on Windows |
| 923 | with self.assertRaises(OSError) as cm: |
| 924 | os.listdir(__file__) |
| 925 | self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) |
| 926 | |
| 927 | |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 928 | class ImportErrorTests(unittest.TestCase): |
| 929 | |
| 930 | def test_attributes(self): |
| 931 | # Setting 'name' and 'path' should not be a problem. |
| 932 | exc = ImportError('test') |
| 933 | self.assertIsNone(exc.name) |
| 934 | self.assertIsNone(exc.path) |
| 935 | |
| 936 | exc = ImportError('test', name='somemodule') |
| 937 | self.assertEqual(exc.name, 'somemodule') |
| 938 | self.assertIsNone(exc.path) |
| 939 | |
| 940 | exc = ImportError('test', path='somepath') |
| 941 | self.assertEqual(exc.path, 'somepath') |
| 942 | self.assertIsNone(exc.name) |
| 943 | |
| 944 | exc = ImportError('test', path='somepath', name='somename') |
| 945 | self.assertEqual(exc.name, 'somename') |
| 946 | self.assertEqual(exc.path, 'somepath') |
| 947 | |
Brett Cannon | 07c6e71 | 2012-08-24 13:05:09 -0400 | [diff] [blame] | 948 | def test_non_str_argument(self): |
| 949 | # Issue #15778 |
| 950 | arg = b'abc' |
| 951 | exc = ImportError(arg) |
| 952 | self.assertEqual(str(arg), str(exc)) |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 953 | |
| 954 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 955 | def test_main(): |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 956 | run_unittest(ExceptionTests, ImportErrorTests) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 957 | |
| 958 | if __name__ == '__main__': |
Guido van Rossum | b8142c3 | 2007-05-08 17:49:10 +0000 | [diff] [blame] | 959 | unittest.main() |