blob: b242c082f856820ac1b7a4a9d1759d47c6543eab [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Serhiy Storchakab7853962017-04-08 09:55:07 +03003import copy
Pablo Galindo9b648a92020-09-01 19:39:46 +01004import gc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005import os
6import sys
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00007import unittest
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00008import pickle
Barry Warsaw8d109cb2008-05-08 04:26:35 +00009import weakref
Antoine Pitroua7622852011-09-01 21:37:43 +020010import errno
Pablo Galindoa77aac42021-04-23 14:27:05 +010011from textwrap import dedent
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000012
Hai Shi46605972020-08-04 00:49:18 +080013from test.support import (captured_stderr, check_impl_detail,
14 cpython_only, gc_collect,
15 no_tracing, script_helper,
xdegaye56d1f5c2017-10-26 15:09:06 +020016 SuppressCrashReport)
Hai Shi46605972020-08-04 00:49:18 +080017from test.support.import_helper import import_module
18from test.support.os_helper import TESTFN, unlink
19from test.support.warnings_helper import check_warnings
Victor Stinnere4d300e2019-05-22 23:44:02 +020020from test import support
21
22
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010023class NaiveException(Exception):
24 def __init__(self, x):
25 self.x = x
26
27class SlottedNaiveException(Exception):
28 __slots__ = ('x',)
29 def __init__(self, x):
30 self.x = x
31
Martin Panter3263f682016-02-28 03:16:11 +000032class BrokenStrException(Exception):
33 def __str__(self):
34 raise Exception("str() is broken")
35
Guido van Rossum3bead091992-01-27 17:00:37 +000036# XXX This is not really enough, each *operation* should be tested!
37
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000038class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000039
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000040 def raise_catch(self, exc, excname):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +010041 with self.subTest(exc=exc, excname=excname):
42 try:
43 raise exc("spam")
44 except exc as err:
45 buf1 = str(err)
46 try:
47 raise exc("spam")
48 except exc as err:
49 buf2 = str(err)
50 self.assertEqual(buf1, buf2)
51 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000052
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000053 def testRaising(self):
54 self.raise_catch(AttributeError, "AttributeError")
55 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000056
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000057 self.raise_catch(EOFError, "EOFError")
Inada Naoki8bbfeb32021-04-02 12:53:46 +090058 fp = open(TESTFN, 'w', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 fp.close()
Inada Naoki8bbfeb32021-04-02 12:53:46 +090060 fp = open(TESTFN, 'r', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000061 savestdin = sys.stdin
62 try:
63 try:
64 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010065 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 except EOFError:
67 pass
68 finally:
69 sys.stdin = savestdin
70 fp.close()
71 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020073 self.raise_catch(OSError, "OSError")
74 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000075
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000076 self.raise_catch(ImportError, "ImportError")
77 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000078
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000079 self.raise_catch(IndexError, "IndexError")
80 x = []
81 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(KeyError, "KeyError")
84 x = {}
85 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000087 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 self.raise_catch(NameError, "NameError")
92 try: x = undefined_variable
93 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000094
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000095 self.raise_catch(OverflowError, "OverflowError")
96 x = 1
97 for dummy in range(128):
98 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.raise_catch(RuntimeError, "RuntimeError")
Yury Selivanovf488fb42015-07-03 01:04:23 -0400101 self.raise_catch(RecursionError, "RecursionError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +0000104 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000105 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000106
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000107 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +0000110 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
111 '<string>', 'exec')
112 except TabError: pass
113 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000114
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000115 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000116
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117 self.raise_catch(SystemExit, "SystemExit")
118 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000119
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120 self.raise_catch(TypeError, "TypeError")
121 try: [] + ()
122 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000123
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000125 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000127 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
128 try: x = 1/0
129 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000130
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131 self.raise_catch(Exception, "Exception")
132 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000133 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000134
Yury Selivanovccc897f2015-07-03 01:16:04 -0400135 self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
136
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 def testSyntaxErrorMessage(self):
138 # make sure the right exception message is raised for each of
139 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141 def ckmsg(src, msg):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100142 with self.subTest(src=src, msg=msg):
143 try:
144 compile(src, '<fragment>', 'exec')
145 except SyntaxError as e:
146 if e.msg != msg:
147 self.fail("expected %s, got %s" % (msg, e.msg))
148 else:
149 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000150
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000151 s = '''if 1:
152 try:
153 continue
154 except:
155 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000156
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157 ckmsg(s, "'continue' not properly in loop")
158 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000159
Martijn Pieters772d8092017-08-22 21:16:23 +0100160 def testSyntaxErrorMissingParens(self):
161 def ckmsg(src, msg, exception=SyntaxError):
162 try:
163 compile(src, '<fragment>', 'exec')
164 except exception as e:
165 if e.msg != msg:
166 self.fail("expected %s, got %s" % (msg, e.msg))
167 else:
168 self.fail("failed to get expected SyntaxError")
169
170 s = '''print "old style"'''
171 ckmsg(s, "Missing parentheses in call to 'print'. "
172 "Did you mean print(\"old style\")?")
173
174 s = '''print "old style",'''
175 ckmsg(s, "Missing parentheses in call to 'print'. "
176 "Did you mean print(\"old style\", end=\" \")?")
177
178 s = '''exec "old style"'''
179 ckmsg(s, "Missing parentheses in call to 'exec'")
180
181 # should not apply to subclasses, see issue #31161
182 s = '''if True:\nprint "No indent"'''
Pablo Galindo56c95df2021-04-21 15:28:21 +0100183 ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
Martijn Pieters772d8092017-08-22 21:16:23 +0100184
185 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
186 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
187
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300188 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100189 with self.subTest(source=src, lineno=lineno, offset=offset):
190 with self.assertRaises(SyntaxError) as cm:
191 compile(src, '<fragment>', 'exec')
192 self.assertEqual(cm.exception.lineno, lineno)
193 self.assertEqual(cm.exception.offset, offset)
194 if cm.exception.text is not None:
195 if not isinstance(src, str):
196 src = src.decode(encoding, 'replace')
197 line = src.split('\n')[lineno-1]
198 self.assertIn(line, cm.exception.text)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200199
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300200 def testSyntaxErrorOffset(self):
201 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200202 check('def fact(x):\n\treturn x!\n', 2, 10)
203 check('1 +\n', 1, 4)
204 check('def spam():\n print(1)\n print(2)', 3, 10)
205 check('Python = "Python" +', 1, 20)
206 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200207 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
208 2, 19, encoding='cp1251')
209 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300210 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400211 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200212 check('f{a + b + c}', 1, 2)
Miss Islington (bot)756b7b92021-05-03 18:06:45 -0700213 check('[file for str(file) in []\n])', 2, 2)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700214 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200215 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
216 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700217 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Ammar Askar025eb982018-09-24 17:12:49 -0400218
219 # Errors thrown by compile.c
220 check('class foo:return 1', 1, 11)
221 check('def f():\n continue', 2, 3)
222 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100223 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400224
225 # Errors thrown by tokenizer.c
226 check('(0x+1)', 1, 3)
227 check('x = 0xI', 1, 6)
228 check('0010 + 2', 1, 4)
229 check('x = 32e-+4', 1, 8)
230 check('x = 0o9', 1, 6)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200231 check('\u03b1 = 0xI', 1, 6)
232 check(b'\xce\xb1 = 0xI', 1, 6)
233 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
234 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100235 check(b"""if 1:
236 def foo():
237 '''
238
239 def bar():
240 pass
241
242 def baz():
243 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300244 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100245 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
246 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700247 check("[interesting\nfoo()\n", 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400248
249 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200250 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400251 check('def f():\n from _ import *', 1, 1)
252 check('def f(x, x):\n pass', 1, 1)
253 check('def f(x):\n nonlocal x', 2, 3)
254 check('def f(x):\n x = 1\n global x', 3, 3)
255 check('nonlocal x', 1, 1)
256 check('def f():\n global x\n nonlocal x', 2, 3)
257
Ammar Askar025eb982018-09-24 17:12:49 -0400258 # Errors thrown by future.c
259 check('from __future__ import doesnt_exist', 1, 1)
260 check('from __future__ import braces', 1, 1)
261 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100262 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300263 check('def f():\n x, y: int', 2, 3)
264 check('[*x for x in xs]', 1, 2)
265 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300266 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100267 check('(yield i) = 2', 1, 2)
268 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200269
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000270 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000271 def testSettingException(self):
272 # test that setting an exception at the C level works even if the
273 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000274
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275 class BadException(Exception):
276 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000277 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000278
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000279 class InvalidException:
280 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000281
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000282 def test_capi1():
283 import _testcapi
284 try:
285 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000286 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000287 exc, err, tb = sys.exc_info()
288 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000289 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000290 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000291 else:
292 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000293
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000294 def test_capi2():
295 import _testcapi
296 try:
297 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000298 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000299 exc, err, tb = sys.exc_info()
300 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000301 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000302 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000303 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000304 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000305 else:
306 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000307
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000308 def test_capi3():
309 import _testcapi
310 self.assertRaises(SystemError, _testcapi.raise_exception,
311 InvalidException, 1)
312
313 if not sys.platform.startswith('java'):
314 test_capi1()
315 test_capi2()
316 test_capi3()
317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def test_WindowsError(self):
319 try:
320 WindowsError
321 except NameError:
322 pass
323 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200324 self.assertIs(WindowsError, OSError)
325 self.assertEqual(str(OSError(1001)), "1001")
326 self.assertEqual(str(OSError(1001, "message")),
327 "[Errno 1001] message")
328 # POSIX errno (9 aka EBADF) is untranslated
329 w = OSError(9, 'foo', 'bar')
330 self.assertEqual(w.errno, 9)
331 self.assertEqual(w.winerror, None)
332 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
333 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
334 w = OSError(0, 'foo', 'bar', 3)
335 self.assertEqual(w.errno, 2)
336 self.assertEqual(w.winerror, 3)
337 self.assertEqual(w.strerror, 'foo')
338 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000339 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100340 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200341 # Unknown win error becomes EINVAL (22)
342 w = OSError(0, 'foo', None, 1001)
343 self.assertEqual(w.errno, 22)
344 self.assertEqual(w.winerror, 1001)
345 self.assertEqual(w.strerror, 'foo')
346 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000347 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100348 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200349 # Non-numeric "errno"
350 w = OSError('bar', 'foo')
351 self.assertEqual(w.errno, 'bar')
352 self.assertEqual(w.winerror, None)
353 self.assertEqual(w.strerror, 'foo')
354 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000355 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356
Victor Stinnerd223fa62015-04-02 14:17:38 +0200357 @unittest.skipUnless(sys.platform == 'win32',
358 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300359 def test_windows_message(self):
360 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200361 ctypes = import_module('ctypes')
362 # this error code has no message, Python formats it as hexadecimal
363 code = 3765269347
364 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
365 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300366
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000367 def testAttributes(self):
368 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000369
370 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000371 (BaseException, (), {'args' : ()}),
372 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000373 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000374 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000375 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000376 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000377 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000378 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200379 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000380 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000381 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200382 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000383 {'args' : ('foo', 'bar'),
384 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000385 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200386 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000387 {'args' : ('foo', 'bar'),
388 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800390 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
391 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200392 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000393 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000394 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
395 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200396 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000397 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000398 'strerror' : 'strErrorStr',
399 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000400 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100402 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000403 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000404 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000405 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100406 'filename' : None, 'lineno' : None, 'offset' : None,
407 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000408 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100409 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000410 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000411 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100412 'offsetStr', 'textStr',
413 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000414 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100415 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
416 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000417 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100418 'textStr', 'endLinenoStr', 'endOffsetStr',
419 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000420 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000421 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100422 'textStr', 'endLinenoStr', 'endOffsetStr',
423 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000424 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100425 'filename' : None, 'lineno' : None, 'offset' : None,
426 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000427 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000428 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
429 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000430 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000431 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000432 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000434 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000435 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000436 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000437 'ordinal not in range'),
438 'encoding' : 'ascii', 'object' : b'\xff',
439 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000440 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
441 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000442 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000443 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000444 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000446 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000447 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000448 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000449 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100450 (NaiveException, ('foo',),
451 {'args': ('foo',), 'x': 'foo'}),
452 (SlottedNaiveException, ('foo',),
453 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000455 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200456 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000457 exceptionList.append(
458 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000459 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200460 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000461 'errno' : 1,
462 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000463 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000464 except NameError:
465 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000466
Guido van Rossumebe3e162007-05-17 18:20:34 +0000467 for exc, args, expected in exceptionList:
468 try:
469 e = exc(*args)
470 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000471 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100472 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000473 else:
474 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100475 if not type(e).__name__.endswith('NaiveException'):
476 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000477 # Verify no ref leaks in Exc_str()
478 s = str(e)
479 for checkArgName in expected:
480 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000481 self.assertEqual(repr(value),
482 repr(expected[checkArgName]),
483 '%r.%s == %r, expected %r' % (
484 e, checkArgName,
485 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000486
Guido van Rossumebe3e162007-05-17 18:20:34 +0000487 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000488 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000489 for protocol in range(p.HIGHEST_PROTOCOL + 1):
490 s = p.dumps(e, protocol)
491 new = p.loads(s)
492 for checkArgName in expected:
493 got = repr(getattr(new, checkArgName))
494 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000495 self.assertEqual(got, want,
496 'pickled "%r", attribute "%s' %
497 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000498
Collin Winter828f04a2007-08-31 00:04:24 +0000499 def testWithTraceback(self):
500 try:
501 raise IndexError(4)
502 except:
503 tb = sys.exc_info()[2]
504
505 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000506 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000507 self.assertEqual(e.__traceback__, tb)
508
509 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000510 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000511 self.assertEqual(e.__traceback__, tb)
512
513 class MyException(Exception):
514 pass
515
516 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000517 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000518 self.assertEqual(e.__traceback__, tb)
519
520 def testInvalidTraceback(self):
521 try:
522 Exception().__traceback__ = 5
523 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000524 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000525 else:
526 self.fail("No exception raised")
527
Georg Brandlab6f2f62009-03-31 04:16:10 +0000528 def testInvalidAttrs(self):
529 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
530 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
531 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
532 self.assertRaises(TypeError, delattr, Exception(), '__context__')
533
Collin Winter828f04a2007-08-31 00:04:24 +0000534 def testNoneClearsTracebackAttr(self):
535 try:
536 raise IndexError(4)
537 except:
538 tb = sys.exc_info()[2]
539
540 e = Exception()
541 e.__traceback__ = tb
542 e.__traceback__ = None
543 self.assertEqual(e.__traceback__, None)
544
545 def testChainingAttrs(self):
546 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000547 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700548 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000549
550 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000551 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700552 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000553
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200554 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000555 pass
556
557 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000558 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700559 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000560
561 def testChainingDescriptors(self):
562 try:
563 raise Exception()
564 except Exception as exc:
565 e = exc
566
567 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700568 self.assertIsNone(e.__cause__)
569 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000570
571 e.__context__ = NameError()
572 e.__cause__ = None
573 self.assertIsInstance(e.__context__, NameError)
574 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700575 self.assertTrue(e.__suppress_context__)
576 e.__suppress_context__ = False
577 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000578
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000579 def testKeywordArgs(self):
580 # test that builtin exception don't take keyword args,
581 # but user-defined subclasses can if they want
582 self.assertRaises(TypeError, BaseException, a=1)
583
584 class DerivedException(BaseException):
585 def __init__(self, fancy_arg):
586 BaseException.__init__(self)
587 self.fancy_arg = fancy_arg
588
589 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000590 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000591
Brett Cannon31f59292011-02-21 19:29:56 +0000592 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593 def testInfiniteRecursion(self):
594 def f():
595 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400596 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000597
598 def g():
599 try:
600 return g()
601 except ValueError:
602 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400603 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000605 def test_str(self):
606 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000607 self.assertTrue(str(Exception))
608 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000609 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000611 def testExceptionCleanupNames(self):
612 # Make sure the local variable bound to the exception instance by
613 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000614 try:
615 raise Exception()
616 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000617 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000618 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000619 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000620
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000621 def testExceptionCleanupState(self):
622 # Make sure exception state is cleaned up as soon as the except
623 # block is left. See #2507
624
625 class MyException(Exception):
626 def __init__(self, obj):
627 self.obj = obj
628 class MyObj:
629 pass
630
631 def inner_raising_func():
632 # Create some references in exception value and traceback
633 local_ref = obj
634 raise MyException(obj)
635
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000636 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000637 obj = MyObj()
638 wr = weakref.ref(obj)
639 try:
640 inner_raising_func()
641 except MyException as e:
642 pass
643 obj = None
644 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300645 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000646
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000647 # Qualified "except" without "as"
648 obj = MyObj()
649 wr = weakref.ref(obj)
650 try:
651 inner_raising_func()
652 except MyException:
653 pass
654 obj = None
655 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300656 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000657
658 # Bare "except"
659 obj = MyObj()
660 wr = weakref.ref(obj)
661 try:
662 inner_raising_func()
663 except:
664 pass
665 obj = None
666 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300667 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000668
669 # "except" with premature block leave
670 obj = MyObj()
671 wr = weakref.ref(obj)
672 for i in [0]:
673 try:
674 inner_raising_func()
675 except:
676 break
677 obj = None
678 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300679 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000680
681 # "except" block raising another exception
682 obj = MyObj()
683 wr = weakref.ref(obj)
684 try:
685 try:
686 inner_raising_func()
687 except:
688 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000689 except KeyError as e:
690 # We want to test that the except block above got rid of
691 # the exception raised in inner_raising_func(), but it
692 # also ends up in the __context__ of the KeyError, so we
693 # must clear the latter manually for our test to succeed.
694 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000695 obj = None
696 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800697 # guarantee no ref cycles on CPython (don't gc_collect)
698 if check_impl_detail(cpython=False):
699 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300700 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000701
702 # Some complicated construct
703 obj = MyObj()
704 wr = weakref.ref(obj)
705 try:
706 inner_raising_func()
707 except MyException:
708 try:
709 try:
710 raise
711 finally:
712 raise
713 except MyException:
714 pass
715 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800716 if check_impl_detail(cpython=False):
717 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000718 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300719 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000720
721 # Inside an exception-silencing "with" block
722 class Context:
723 def __enter__(self):
724 return self
725 def __exit__ (self, exc_type, exc_value, exc_tb):
726 return True
727 obj = MyObj()
728 wr = weakref.ref(obj)
729 with Context():
730 inner_raising_func()
731 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800732 if check_impl_detail(cpython=False):
733 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000734 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300735 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000736
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000737 def test_exception_target_in_nested_scope(self):
738 # issue 4617: This used to raise a SyntaxError
739 # "can not delete variable 'e' referenced in nested scope"
740 def print_error():
741 e
742 try:
743 something
744 except Exception as e:
745 print_error()
746 # implicit "del e" here
747
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000748 def test_generator_leaking(self):
749 # Test that generator exception state doesn't leak into the calling
750 # frame
751 def yield_raise():
752 try:
753 raise KeyError("caught")
754 except KeyError:
755 yield sys.exc_info()[0]
756 yield sys.exc_info()[0]
757 yield sys.exc_info()[0]
758 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000759 self.assertEqual(next(g), KeyError)
760 self.assertEqual(sys.exc_info()[0], None)
761 self.assertEqual(next(g), KeyError)
762 self.assertEqual(sys.exc_info()[0], None)
763 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000764
765 # Same test, but inside an exception handler
766 try:
767 raise TypeError("foo")
768 except TypeError:
769 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000770 self.assertEqual(next(g), KeyError)
771 self.assertEqual(sys.exc_info()[0], TypeError)
772 self.assertEqual(next(g), KeyError)
773 self.assertEqual(sys.exc_info()[0], TypeError)
774 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000776 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000777
Benjamin Peterson83195c32011-07-03 13:44:00 -0500778 def test_generator_leaking2(self):
779 # See issue 12475.
780 def g():
781 yield
782 try:
783 raise RuntimeError
784 except RuntimeError:
785 it = g()
786 next(it)
787 try:
788 next(it)
789 except StopIteration:
790 pass
791 self.assertEqual(sys.exc_info(), (None, None, None))
792
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100793 def test_generator_leaking3(self):
794 # See issue #23353. When gen.throw() is called, the caller's
795 # exception state should be save and restored.
796 def g():
797 try:
798 yield
799 except ZeroDivisionError:
800 yield sys.exc_info()[1]
801 it = g()
802 next(it)
803 try:
804 1/0
805 except ZeroDivisionError as e:
806 self.assertIs(sys.exc_info()[1], e)
807 gen_exc = it.throw(e)
808 self.assertIs(sys.exc_info()[1], e)
809 self.assertIs(gen_exc, e)
810 self.assertEqual(sys.exc_info(), (None, None, None))
811
812 def test_generator_leaking4(self):
813 # See issue #23353. When an exception is raised by a generator,
814 # the caller's exception state should still be restored.
815 def g():
816 try:
817 1/0
818 except ZeroDivisionError:
819 yield sys.exc_info()[0]
820 raise
821 it = g()
822 try:
823 raise TypeError
824 except TypeError:
825 # The caller's exception state (TypeError) is temporarily
826 # saved in the generator.
827 tp = next(it)
828 self.assertIs(tp, ZeroDivisionError)
829 try:
830 next(it)
831 # We can't check it immediately, but while next() returns
832 # with an exception, it shouldn't have restored the old
833 # exception state (TypeError).
834 except ZeroDivisionError as e:
835 self.assertIs(sys.exc_info()[1], e)
836 # We used to find TypeError here.
837 self.assertEqual(sys.exc_info(), (None, None, None))
838
Benjamin Petersonac913412011-07-03 16:25:11 -0500839 def test_generator_doesnt_retain_old_exc(self):
840 def g():
841 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
842 yield
843 self.assertEqual(sys.exc_info(), (None, None, None))
844 it = g()
845 try:
846 raise RuntimeError
847 except RuntimeError:
848 next(it)
849 self.assertRaises(StopIteration, next, it)
850
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000851 def test_generator_finalizing_and_exc_info(self):
852 # See #7173
853 def simple_gen():
854 yield 1
855 def run_gen():
856 gen = simple_gen()
857 try:
858 raise RuntimeError
859 except RuntimeError:
860 return next(gen)
861 run_gen()
862 gc_collect()
863 self.assertEqual(sys.exc_info(), (None, None, None))
864
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200865 def _check_generator_cleanup_exc_state(self, testfunc):
866 # Issue #12791: exception state is cleaned up as soon as a generator
867 # is closed (reference cycles are broken).
868 class MyException(Exception):
869 def __init__(self, obj):
870 self.obj = obj
871 class MyObj:
872 pass
873
874 def raising_gen():
875 try:
876 raise MyException(obj)
877 except MyException:
878 yield
879
880 obj = MyObj()
881 wr = weakref.ref(obj)
882 g = raising_gen()
883 next(g)
884 testfunc(g)
885 g = obj = None
886 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300887 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200888
889 def test_generator_throw_cleanup_exc_state(self):
890 def do_throw(g):
891 try:
892 g.throw(RuntimeError())
893 except RuntimeError:
894 pass
895 self._check_generator_cleanup_exc_state(do_throw)
896
897 def test_generator_close_cleanup_exc_state(self):
898 def do_close(g):
899 g.close()
900 self._check_generator_cleanup_exc_state(do_close)
901
902 def test_generator_del_cleanup_exc_state(self):
903 def do_del(g):
904 g = None
905 self._check_generator_cleanup_exc_state(do_del)
906
907 def test_generator_next_cleanup_exc_state(self):
908 def do_next(g):
909 try:
910 next(g)
911 except StopIteration:
912 pass
913 else:
914 self.fail("should have raised StopIteration")
915 self._check_generator_cleanup_exc_state(do_next)
916
917 def test_generator_send_cleanup_exc_state(self):
918 def do_send(g):
919 try:
920 g.send(None)
921 except StopIteration:
922 pass
923 else:
924 self.fail("should have raised StopIteration")
925 self._check_generator_cleanup_exc_state(do_send)
926
Benjamin Peterson27d63672008-06-15 20:09:12 +0000927 def test_3114(self):
928 # Bug #3114: in its destructor, MyObject retrieves a pointer to
929 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000930 class MyObject:
931 def __del__(self):
932 nonlocal e
933 e = sys.exc_info()
934 e = ()
935 try:
936 raise Exception(MyObject())
937 except:
938 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000939 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000940
Benjamin Peterson24dfb052014-04-02 12:05:35 -0400941 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +0000942 # See issue 7309. This was a crasher.
943
944 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
945 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
946 u.end = 2
947 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
948 u.end = 5
949 u.reason = 0x345345345345345345
950 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
951 u.encoding = 4000
952 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
953 u.start = 1000
954 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
955
956 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
957 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
958 u.end = 2
959 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
960 u.end = 5
961 u.reason = 0x345345345345345345
962 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
963 u.encoding = 4000
964 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
965 u.start = 1000
966 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
967
968 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
969 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
970 u.end = 2
971 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
972 u.end = 5
973 u.reason = 0x345345345345345345
974 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
975 u.start = 1000
976 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000977
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400978 def test_unicode_errors_no_object(self):
979 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -0400980 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400981 for klass in klasses:
982 self.assertEqual(str(klass.__new__(klass)), "")
983
Brett Cannon31f59292011-02-21 19:29:56 +0000984 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000985 def test_badisinstance(self):
986 # Bug #2542: if issubclass(e, MyException) raises an exception,
987 # it should be ignored
988 class Meta(type):
989 def __subclasscheck__(cls, subclass):
990 raise ValueError()
991 class MyException(Exception, metaclass=Meta):
992 pass
993
Martin Panter3263f682016-02-28 03:16:11 +0000994 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000995 try:
996 raise KeyError()
997 except MyException as e:
998 self.fail("exception should not be a MyException")
999 except KeyError:
1000 pass
1001 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001002 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001003 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001004 self.fail("Should have raised KeyError")
1005
1006 def g():
1007 try:
1008 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001009 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001010 return sys.exc_info()
1011 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001012 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001013 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001014
xdegaye56d1f5c2017-10-26 15:09:06 +02001015 @cpython_only
1016 def test_recursion_normalizing_exception(self):
1017 # Issue #22898.
1018 # Test that a RecursionError is raised when tstate->recursion_depth is
1019 # equal to recursion_limit in PyErr_NormalizeException() and check
1020 # that a ResourceWarning is printed.
1021 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001022 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001023 # singleton was being used in that case, that held traceback data and
1024 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1025 # finalization of these locals.
1026 code = """if 1:
1027 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001028 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001029
1030 class MyException(Exception): pass
1031
1032 def setrecursionlimit(depth):
1033 while 1:
1034 try:
1035 sys.setrecursionlimit(depth)
1036 return depth
1037 except RecursionError:
1038 # sys.setrecursionlimit() raises a RecursionError if
1039 # the new recursion limit is too low (issue #25274).
1040 depth += 1
1041
1042 def recurse(cnt):
1043 cnt -= 1
1044 if cnt:
1045 recurse(cnt)
1046 else:
1047 generator.throw(MyException)
1048
1049 def gen():
1050 f = open(%a, mode='rb', buffering=0)
1051 yield
1052
1053 generator = gen()
1054 next(generator)
1055 recursionlimit = sys.getrecursionlimit()
1056 depth = get_recursion_depth()
1057 try:
1058 # Upon the last recursive invocation of recurse(),
1059 # tstate->recursion_depth is equal to (recursion_limit - 1)
1060 # and is equal to recursion_limit when _gen_throw() calls
1061 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001062 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001063 finally:
1064 sys.setrecursionlimit(recursionlimit)
1065 print('Done.')
1066 """ % __file__
1067 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1068 # Check that the program does not fail with SIGABRT.
1069 self.assertEqual(rc, 1)
1070 self.assertIn(b'RecursionError', err)
1071 self.assertIn(b'ResourceWarning', err)
1072 self.assertIn(b'Done.', out)
1073
1074 @cpython_only
1075 def test_recursion_normalizing_infinite_exception(self):
1076 # Issue #30697. Test that a RecursionError is raised when
1077 # PyErr_NormalizeException() maximum recursion depth has been
1078 # exceeded.
1079 code = """if 1:
1080 import _testcapi
1081 try:
1082 raise _testcapi.RecursingInfinitelyError
1083 finally:
1084 print('Done.')
1085 """
1086 rc, out, err = script_helper.assert_python_failure("-c", code)
1087 self.assertEqual(rc, 1)
1088 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1089 b'while normalizing an exception', err)
1090 self.assertIn(b'Done.', out)
1091
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001092
1093 def test_recursion_in_except_handler(self):
1094
1095 def set_relative_recursion_limit(n):
1096 depth = 1
1097 while True:
1098 try:
1099 sys.setrecursionlimit(depth)
1100 except RecursionError:
1101 depth += 1
1102 else:
1103 break
1104 sys.setrecursionlimit(depth+n)
1105
1106 def recurse_in_except():
1107 try:
1108 1/0
1109 except:
1110 recurse_in_except()
1111
1112 def recurse_after_except():
1113 try:
1114 1/0
1115 except:
1116 pass
1117 recurse_after_except()
1118
1119 def recurse_in_body_and_except():
1120 try:
1121 recurse_in_body_and_except()
1122 except:
1123 recurse_in_body_and_except()
1124
1125 recursionlimit = sys.getrecursionlimit()
1126 try:
1127 set_relative_recursion_limit(10)
1128 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1129 with self.subTest(func=func):
1130 try:
1131 func()
1132 except RecursionError:
1133 pass
1134 else:
1135 self.fail("Should have raised a RecursionError")
1136 finally:
1137 sys.setrecursionlimit(recursionlimit)
1138
1139
xdegaye56d1f5c2017-10-26 15:09:06 +02001140 @cpython_only
1141 def test_recursion_normalizing_with_no_memory(self):
1142 # Issue #30697. Test that in the abort that occurs when there is no
1143 # memory left and the size of the Python frames stack is greater than
1144 # the size of the list of preallocated MemoryError instances, the
1145 # Fatal Python error message mentions MemoryError.
1146 code = """if 1:
1147 import _testcapi
1148 class C(): pass
1149 def recurse(cnt):
1150 cnt -= 1
1151 if cnt:
1152 recurse(cnt)
1153 else:
1154 _testcapi.set_nomemory(0)
1155 C()
1156 recurse(16)
1157 """
1158 with SuppressCrashReport():
1159 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001160 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1161 b'Cannot recover from MemoryErrors while '
1162 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001163
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001164 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001165 def test_MemoryError(self):
1166 # PyErr_NoMemory always raises the same exception instance.
1167 # Check that the traceback is not doubled.
1168 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001169 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001170 def raiseMemError():
1171 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001172 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001173 except MemoryError as e:
1174 tb = e.__traceback__
1175 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001176 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001177 return traceback.format_tb(tb)
1178
1179 tb1 = raiseMemError()
1180 tb2 = raiseMemError()
1181 self.assertEqual(tb1, tb2)
1182
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001183 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001184 def test_exception_with_doc(self):
1185 import _testcapi
1186 doc2 = "This is a test docstring."
1187 doc4 = "This is another test docstring."
1188
1189 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1190 "error1")
1191
1192 # test basic usage of PyErr_NewException
1193 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1194 self.assertIs(type(error1), type)
1195 self.assertTrue(issubclass(error1, Exception))
1196 self.assertIsNone(error1.__doc__)
1197
1198 # test with given docstring
1199 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1200 self.assertEqual(error2.__doc__, doc2)
1201
1202 # test with explicit base (without docstring)
1203 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1204 base=error2)
1205 self.assertTrue(issubclass(error3, error2))
1206
1207 # test with explicit base tuple
1208 class C(object):
1209 pass
1210 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1211 (error3, C))
1212 self.assertTrue(issubclass(error4, error3))
1213 self.assertTrue(issubclass(error4, C))
1214 self.assertEqual(error4.__doc__, doc4)
1215
1216 # test with explicit dictionary
1217 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1218 error4, {'a': 1})
1219 self.assertTrue(issubclass(error5, error4))
1220 self.assertEqual(error5.a, 1)
1221 self.assertEqual(error5.__doc__, "")
1222
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001223 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001224 def test_memory_error_cleanup(self):
1225 # Issue #5437: preallocated MemoryError instances should not keep
1226 # traceback objects alive.
1227 from _testcapi import raise_memoryerror
1228 class C:
1229 pass
1230 wr = None
1231 def inner():
1232 nonlocal wr
1233 c = C()
1234 wr = weakref.ref(c)
1235 raise_memoryerror()
1236 # We cannot use assertRaises since it manually deletes the traceback
1237 try:
1238 inner()
1239 except MemoryError as e:
1240 self.assertNotEqual(wr(), None)
1241 else:
1242 self.fail("MemoryError not raised")
1243 self.assertEqual(wr(), None)
1244
Brett Cannon31f59292011-02-21 19:29:56 +00001245 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001246 def test_recursion_error_cleanup(self):
1247 # Same test as above, but with "recursion exceeded" errors
1248 class C:
1249 pass
1250 wr = None
1251 def inner():
1252 nonlocal wr
1253 c = C()
1254 wr = weakref.ref(c)
1255 inner()
1256 # We cannot use assertRaises since it manually deletes the traceback
1257 try:
1258 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001259 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001260 self.assertNotEqual(wr(), None)
1261 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001262 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001263 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001264
Antoine Pitroua7622852011-09-01 21:37:43 +02001265 def test_errno_ENOTDIR(self):
1266 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1267 with self.assertRaises(OSError) as cm:
1268 os.listdir(__file__)
1269 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1270
Martin Panter3263f682016-02-28 03:16:11 +00001271 def test_unraisable(self):
1272 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1273 class BrokenDel:
1274 def __del__(self):
1275 exc = ValueError("del is broken")
1276 # The following line is included in the traceback report:
1277 raise exc
1278
Victor Stinnere4d300e2019-05-22 23:44:02 +02001279 obj = BrokenDel()
1280 with support.catch_unraisable_exception() as cm:
1281 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001282
Victor Stinnere4d300e2019-05-22 23:44:02 +02001283 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1284 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001285
1286 def test_unhandled(self):
1287 # Check for sensible reporting of unhandled exceptions
1288 for exc_type in (ValueError, BrokenStrException):
1289 with self.subTest(exc_type):
1290 try:
1291 exc = exc_type("test message")
1292 # The following line is included in the traceback report:
1293 raise exc
1294 except exc_type:
1295 with captured_stderr() as stderr:
1296 sys.__excepthook__(*sys.exc_info())
1297 report = stderr.getvalue()
1298 self.assertIn("test_exceptions.py", report)
1299 self.assertIn("raise exc", report)
1300 self.assertIn(exc_type.__name__, report)
1301 if exc_type is BrokenStrException:
1302 self.assertIn("<exception str() failed>", report)
1303 else:
1304 self.assertIn("test message", report)
1305 self.assertTrue(report.endswith("\n"))
1306
xdegaye66caacf2017-10-23 18:08:41 +02001307 @cpython_only
1308 def test_memory_error_in_PyErr_PrintEx(self):
1309 code = """if 1:
1310 import _testcapi
1311 class C(): pass
1312 _testcapi.set_nomemory(0, %d)
1313 C()
1314 """
1315
1316 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1317 # Span a large range of tests as the CPython code always evolves with
1318 # changes that add or remove memory allocations.
1319 for i in range(1, 20):
1320 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1321 self.assertIn(rc, (1, 120))
1322 self.assertIn(b'MemoryError', err)
1323
Mark Shannonae3087c2017-10-22 22:41:51 +01001324 def test_yield_in_nested_try_excepts(self):
1325 #Issue #25612
1326 class MainError(Exception):
1327 pass
1328
1329 class SubError(Exception):
1330 pass
1331
1332 def main():
1333 try:
1334 raise MainError()
1335 except MainError:
1336 try:
1337 yield
1338 except SubError:
1339 pass
1340 raise
1341
1342 coro = main()
1343 coro.send(None)
1344 with self.assertRaises(MainError):
1345 coro.throw(SubError())
1346
1347 def test_generator_doesnt_retain_old_exc2(self):
1348 #Issue 28884#msg282532
1349 def g():
1350 try:
1351 raise ValueError
1352 except ValueError:
1353 yield 1
1354 self.assertEqual(sys.exc_info(), (None, None, None))
1355 yield 2
1356
1357 gen = g()
1358
1359 try:
1360 raise IndexError
1361 except IndexError:
1362 self.assertEqual(next(gen), 1)
1363 self.assertEqual(next(gen), 2)
1364
1365 def test_raise_in_generator(self):
1366 #Issue 25612#msg304117
1367 def g():
1368 yield 1
1369 raise
1370 yield 2
1371
1372 with self.assertRaises(ZeroDivisionError):
1373 i = g()
1374 try:
1375 1/0
1376 except:
1377 next(i)
1378 next(i)
1379
Zackery Spytzce6a0702019-08-25 03:44:09 -06001380 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1381 def test_assert_shadowing(self):
1382 # Shadowing AssertionError would cause the assert statement to
1383 # misbehave.
1384 global AssertionError
1385 AssertionError = TypeError
1386 try:
1387 assert False, 'hello'
1388 except BaseException as e:
1389 del AssertionError
1390 self.assertIsInstance(e, AssertionError)
1391 self.assertEqual(str(e), 'hello')
1392 else:
1393 del AssertionError
1394 self.fail('Expected exception')
1395
Pablo Galindo9b648a92020-09-01 19:39:46 +01001396 def test_memory_error_subclasses(self):
1397 # bpo-41654: MemoryError instances use a freelist of objects that are
1398 # linked using the 'dict' attribute when they are inactive/dead.
1399 # Subclasses of MemoryError should not participate in the freelist
1400 # schema. This test creates a MemoryError object and keeps it alive
1401 # (therefore advancing the freelist) and then it creates and destroys a
1402 # subclass object. Finally, it checks that creating a new MemoryError
1403 # succeeds, proving that the freelist is not corrupted.
1404
1405 class TestException(MemoryError):
1406 pass
1407
1408 try:
1409 raise MemoryError
1410 except MemoryError as exc:
1411 inst = exc
1412
1413 try:
1414 raise TestException
1415 except Exception:
1416 pass
1417
1418 for _ in range(10):
1419 try:
1420 raise MemoryError
1421 except MemoryError as exc:
1422 pass
1423
1424 gc_collect()
1425
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001426global_for_suggestions = None
1427
1428class NameErrorTests(unittest.TestCase):
1429 def test_name_error_has_name(self):
1430 try:
1431 bluch
1432 except NameError as exc:
1433 self.assertEqual("bluch", exc.name)
1434
1435 def test_name_error_suggestions(self):
1436 def Substitution():
1437 noise = more_noise = a = bc = None
1438 blech = None
1439 print(bluch)
1440
1441 def Elimination():
1442 noise = more_noise = a = bc = None
1443 blch = None
1444 print(bluch)
1445
1446 def Addition():
1447 noise = more_noise = a = bc = None
1448 bluchin = None
1449 print(bluch)
1450
1451 def SubstitutionOverElimination():
1452 blach = None
1453 bluc = None
1454 print(bluch)
1455
1456 def SubstitutionOverAddition():
1457 blach = None
1458 bluchi = None
1459 print(bluch)
1460
1461 def EliminationOverAddition():
1462 blucha = None
1463 bluc = None
1464 print(bluch)
1465
Pablo Galindo7a041162021-04-19 23:35:53 +01001466 for func, suggestion in [(Substitution, "'blech'?"),
1467 (Elimination, "'blch'?"),
1468 (Addition, "'bluchin'?"),
1469 (EliminationOverAddition, "'blucha'?"),
1470 (SubstitutionOverElimination, "'blach'?"),
1471 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001472 err = None
1473 try:
1474 func()
1475 except NameError as exc:
1476 with support.captured_stderr() as err:
1477 sys.__excepthook__(*sys.exc_info())
1478 self.assertIn(suggestion, err.getvalue())
1479
1480 def test_name_error_suggestions_from_globals(self):
1481 def func():
1482 print(global_for_suggestio)
1483 try:
1484 func()
1485 except NameError as exc:
1486 with support.captured_stderr() as err:
1487 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001488 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001489
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001490 def test_name_error_suggestions_from_builtins(self):
1491 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001492 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001493 try:
1494 func()
1495 except NameError as exc:
1496 with support.captured_stderr() as err:
1497 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001498 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001499
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001500 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1501 def f():
1502 somethingverywronghehehehehehe = None
1503 print(somethingverywronghe)
1504
1505 try:
1506 f()
1507 except NameError as exc:
1508 with support.captured_stderr() as err:
1509 sys.__excepthook__(*sys.exc_info())
1510
1511 self.assertNotIn("somethingverywronghehe", err.getvalue())
1512
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001513 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1514 vvv = mom = w = id = pytho = None
1515
1516 with self.subTest(name="b"):
1517 try:
1518 b
1519 except NameError as exc:
1520 with support.captured_stderr() as err:
1521 sys.__excepthook__(*sys.exc_info())
1522 self.assertNotIn("you mean", err.getvalue())
1523 self.assertNotIn("vvv", err.getvalue())
1524 self.assertNotIn("mom", err.getvalue())
1525 self.assertNotIn("'id'", err.getvalue())
1526 self.assertNotIn("'w'", err.getvalue())
1527 self.assertNotIn("'pytho'", err.getvalue())
1528
1529 with self.subTest(name="v"):
1530 try:
1531 v
1532 except NameError as exc:
1533 with support.captured_stderr() as err:
1534 sys.__excepthook__(*sys.exc_info())
1535 self.assertNotIn("you mean", err.getvalue())
1536 self.assertNotIn("vvv", err.getvalue())
1537 self.assertNotIn("mom", err.getvalue())
1538 self.assertNotIn("'id'", err.getvalue())
1539 self.assertNotIn("'w'", err.getvalue())
1540 self.assertNotIn("'pytho'", err.getvalue())
1541
1542 with self.subTest(name="m"):
1543 try:
1544 m
1545 except NameError as exc:
1546 with support.captured_stderr() as err:
1547 sys.__excepthook__(*sys.exc_info())
1548 self.assertNotIn("you mean", err.getvalue())
1549 self.assertNotIn("vvv", err.getvalue())
1550 self.assertNotIn("mom", err.getvalue())
1551 self.assertNotIn("'id'", err.getvalue())
1552 self.assertNotIn("'w'", err.getvalue())
1553 self.assertNotIn("'pytho'", err.getvalue())
1554
1555 with self.subTest(name="py"):
1556 try:
1557 py
1558 except NameError as exc:
1559 with support.captured_stderr() as err:
1560 sys.__excepthook__(*sys.exc_info())
1561 self.assertNotIn("you mean", err.getvalue())
1562 self.assertNotIn("vvv", err.getvalue())
1563 self.assertNotIn("mom", err.getvalue())
1564 self.assertNotIn("'id'", err.getvalue())
1565 self.assertNotIn("'w'", err.getvalue())
1566 self.assertNotIn("'pytho'", err.getvalue())
1567
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001568 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001569 def f():
1570 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001571 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1572 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1573 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1574 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1575 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1576 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1577 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1578 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1579 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1580 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1581 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1582 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1583 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1584 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1585 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1586 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1587 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1588 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1589 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1590 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1591 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1592 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1593 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1594 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1595 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1596 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1597 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1598 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1599 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1600 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1601 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1602 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1603 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1604 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1605 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1606 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1607 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1608 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1609 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1610 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1611 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1612 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1613 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1614 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1615 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1616 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1617 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1618 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1619 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1620 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1621 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1622 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1623 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1624 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1625 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1626 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1627 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1628 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1629 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1630 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1631 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1632 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1633 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1634 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1635 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1636 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1637 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1638 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1639 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1640 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1641 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1642 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1643 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1644 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1645 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1646 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1647 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1648 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1649 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1650 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1651 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001652 print(a0)
1653
1654 try:
1655 f()
1656 except NameError as exc:
1657 with support.captured_stderr() as err:
1658 sys.__excepthook__(*sys.exc_info())
1659
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001660 self.assertNotIn("a1", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001661
1662 def test_name_error_with_custom_exceptions(self):
1663 def f():
1664 blech = None
1665 raise NameError()
1666
1667 try:
1668 f()
1669 except NameError as exc:
1670 with support.captured_stderr() as err:
1671 sys.__excepthook__(*sys.exc_info())
1672
1673 self.assertNotIn("blech", err.getvalue())
1674
1675 def f():
1676 blech = None
1677 raise NameError
1678
1679 try:
1680 f()
1681 except NameError as exc:
1682 with support.captured_stderr() as err:
1683 sys.__excepthook__(*sys.exc_info())
1684
1685 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001686
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001687 def test_unbound_local_error_doesn_not_match(self):
1688 def foo():
1689 something = 3
1690 print(somethong)
1691 somethong = 3
1692
1693 try:
1694 foo()
1695 except UnboundLocalError as exc:
1696 with support.captured_stderr() as err:
1697 sys.__excepthook__(*sys.exc_info())
1698
1699 self.assertNotIn("something", err.getvalue())
1700
1701
Pablo Galindo37494b42021-04-14 02:36:07 +01001702class AttributeErrorTests(unittest.TestCase):
1703 def test_attributes(self):
1704 # Setting 'attr' should not be a problem.
1705 exc = AttributeError('Ouch!')
1706 self.assertIsNone(exc.name)
1707 self.assertIsNone(exc.obj)
1708
1709 sentinel = object()
1710 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1711 self.assertEqual(exc.name, 'carry')
1712 self.assertIs(exc.obj, sentinel)
1713
1714 def test_getattr_has_name_and_obj(self):
1715 class A:
1716 blech = None
1717
1718 obj = A()
1719 try:
1720 obj.bluch
1721 except AttributeError as exc:
1722 self.assertEqual("bluch", exc.name)
1723 self.assertEqual(obj, exc.obj)
1724
1725 def test_getattr_has_name_and_obj_for_method(self):
1726 class A:
1727 def blech(self):
1728 return
1729
1730 obj = A()
1731 try:
1732 obj.bluch()
1733 except AttributeError as exc:
1734 self.assertEqual("bluch", exc.name)
1735 self.assertEqual(obj, exc.obj)
1736
1737 def test_getattr_suggestions(self):
1738 class Substitution:
1739 noise = more_noise = a = bc = None
1740 blech = None
1741
1742 class Elimination:
1743 noise = more_noise = a = bc = None
1744 blch = None
1745
1746 class Addition:
1747 noise = more_noise = a = bc = None
1748 bluchin = None
1749
1750 class SubstitutionOverElimination:
1751 blach = None
1752 bluc = None
1753
1754 class SubstitutionOverAddition:
1755 blach = None
1756 bluchi = None
1757
1758 class EliminationOverAddition:
1759 blucha = None
1760 bluc = None
1761
Pablo Galindo7a041162021-04-19 23:35:53 +01001762 for cls, suggestion in [(Substitution, "'blech'?"),
1763 (Elimination, "'blch'?"),
1764 (Addition, "'bluchin'?"),
1765 (EliminationOverAddition, "'bluc'?"),
1766 (SubstitutionOverElimination, "'blach'?"),
1767 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001768 try:
1769 cls().bluch
1770 except AttributeError as exc:
1771 with support.captured_stderr() as err:
1772 sys.__excepthook__(*sys.exc_info())
1773
1774 self.assertIn(suggestion, err.getvalue())
1775
1776 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1777 class A:
1778 blech = None
1779
1780 try:
1781 A().somethingverywrong
1782 except AttributeError as exc:
1783 with support.captured_stderr() as err:
1784 sys.__excepthook__(*sys.exc_info())
1785
1786 self.assertNotIn("blech", err.getvalue())
1787
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001788 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
1789 class MyClass:
1790 vvv = mom = w = id = pytho = None
1791
1792 with self.subTest(name="b"):
1793 try:
1794 MyClass.b
1795 except AttributeError as exc:
1796 with support.captured_stderr() as err:
1797 sys.__excepthook__(*sys.exc_info())
1798 self.assertNotIn("you mean", err.getvalue())
1799 self.assertNotIn("vvv", err.getvalue())
1800 self.assertNotIn("mom", err.getvalue())
1801 self.assertNotIn("'id'", err.getvalue())
1802 self.assertNotIn("'w'", err.getvalue())
1803 self.assertNotIn("'pytho'", err.getvalue())
1804
1805 with self.subTest(name="v"):
1806 try:
1807 MyClass.v
1808 except AttributeError as exc:
1809 with support.captured_stderr() as err:
1810 sys.__excepthook__(*sys.exc_info())
1811 self.assertNotIn("you mean", err.getvalue())
1812 self.assertNotIn("vvv", err.getvalue())
1813 self.assertNotIn("mom", err.getvalue())
1814 self.assertNotIn("'id'", err.getvalue())
1815 self.assertNotIn("'w'", err.getvalue())
1816 self.assertNotIn("'pytho'", err.getvalue())
1817
1818 with self.subTest(name="m"):
1819 try:
1820 MyClass.m
1821 except AttributeError as exc:
1822 with support.captured_stderr() as err:
1823 sys.__excepthook__(*sys.exc_info())
1824 self.assertNotIn("you mean", err.getvalue())
1825 self.assertNotIn("vvv", err.getvalue())
1826 self.assertNotIn("mom", err.getvalue())
1827 self.assertNotIn("'id'", err.getvalue())
1828 self.assertNotIn("'w'", err.getvalue())
1829 self.assertNotIn("'pytho'", err.getvalue())
1830
1831 with self.subTest(name="py"):
1832 try:
1833 MyClass.py
1834 except AttributeError as exc:
1835 with support.captured_stderr() as err:
1836 sys.__excepthook__(*sys.exc_info())
1837 self.assertNotIn("you mean", err.getvalue())
1838 self.assertNotIn("vvv", err.getvalue())
1839 self.assertNotIn("mom", err.getvalue())
1840 self.assertNotIn("'id'", err.getvalue())
1841 self.assertNotIn("'w'", err.getvalue())
1842 self.assertNotIn("'pytho'", err.getvalue())
1843
1844
Pablo Galindo37494b42021-04-14 02:36:07 +01001845 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
1846 class A:
1847 blech = None
1848 # A class with a very big __dict__ will not be consider
1849 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001850 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01001851 setattr(A, f"index_{index}", None)
1852
1853 try:
1854 A().bluch
1855 except AttributeError as exc:
1856 with support.captured_stderr() as err:
1857 sys.__excepthook__(*sys.exc_info())
1858
1859 self.assertNotIn("blech", err.getvalue())
1860
1861 def test_getattr_suggestions_no_args(self):
1862 class A:
1863 blech = None
1864 def __getattr__(self, attr):
1865 raise AttributeError()
1866
1867 try:
1868 A().bluch
1869 except AttributeError as exc:
1870 with support.captured_stderr() as err:
1871 sys.__excepthook__(*sys.exc_info())
1872
1873 self.assertIn("blech", err.getvalue())
1874
1875 class A:
1876 blech = None
1877 def __getattr__(self, attr):
1878 raise AttributeError
1879
1880 try:
1881 A().bluch
1882 except AttributeError as exc:
1883 with support.captured_stderr() as err:
1884 sys.__excepthook__(*sys.exc_info())
1885
1886 self.assertIn("blech", err.getvalue())
1887
1888 def test_getattr_suggestions_invalid_args(self):
1889 class NonStringifyClass:
1890 __str__ = None
1891 __repr__ = None
1892
1893 class A:
1894 blech = None
1895 def __getattr__(self, attr):
1896 raise AttributeError(NonStringifyClass())
1897
1898 class B:
1899 blech = None
1900 def __getattr__(self, attr):
1901 raise AttributeError("Error", 23)
1902
1903 class C:
1904 blech = None
1905 def __getattr__(self, attr):
1906 raise AttributeError(23)
1907
1908 for cls in [A, B, C]:
1909 try:
1910 cls().bluch
1911 except AttributeError as exc:
1912 with support.captured_stderr() as err:
1913 sys.__excepthook__(*sys.exc_info())
1914
1915 self.assertIn("blech", err.getvalue())
1916
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01001917 def test_attribute_error_with_failing_dict(self):
1918 class T:
1919 bluch = 1
1920 def __dir__(self):
1921 raise AttributeError("oh no!")
1922
1923 try:
1924 T().blich
1925 except AttributeError as exc:
1926 with support.captured_stderr() as err:
1927 sys.__excepthook__(*sys.exc_info())
1928
1929 self.assertNotIn("blech", err.getvalue())
1930 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01001931
Pablo Galindo0b1c1692021-04-17 23:28:45 +01001932 def test_attribute_error_with_bad_name(self):
1933 try:
1934 raise AttributeError(name=12, obj=23)
1935 except AttributeError as exc:
1936 with support.captured_stderr() as err:
1937 sys.__excepthook__(*sys.exc_info())
1938
1939 self.assertNotIn("?", err.getvalue())
1940
1941
Brett Cannon79ec55e2012-04-12 20:24:54 -04001942class ImportErrorTests(unittest.TestCase):
1943
1944 def test_attributes(self):
1945 # Setting 'name' and 'path' should not be a problem.
1946 exc = ImportError('test')
1947 self.assertIsNone(exc.name)
1948 self.assertIsNone(exc.path)
1949
1950 exc = ImportError('test', name='somemodule')
1951 self.assertEqual(exc.name, 'somemodule')
1952 self.assertIsNone(exc.path)
1953
1954 exc = ImportError('test', path='somepath')
1955 self.assertEqual(exc.path, 'somepath')
1956 self.assertIsNone(exc.name)
1957
1958 exc = ImportError('test', path='somepath', name='somename')
1959 self.assertEqual(exc.name, 'somename')
1960 self.assertEqual(exc.path, 'somepath')
1961
Michael Seifert64c8f702017-04-09 09:47:12 +02001962 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001963 with self.assertRaisesRegex(TypeError, msg):
1964 ImportError('test', invalid='keyword')
1965
1966 with self.assertRaisesRegex(TypeError, msg):
1967 ImportError('test', name='name', invalid='keyword')
1968
1969 with self.assertRaisesRegex(TypeError, msg):
1970 ImportError('test', path='path', invalid='keyword')
1971
1972 with self.assertRaisesRegex(TypeError, msg):
1973 ImportError(invalid='keyword')
1974
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001975 with self.assertRaisesRegex(TypeError, msg):
1976 ImportError('test', invalid='keyword', another=True)
1977
Serhiy Storchakae9e44482016-09-28 07:53:32 +03001978 def test_reset_attributes(self):
1979 exc = ImportError('test', name='name', path='path')
1980 self.assertEqual(exc.args, ('test',))
1981 self.assertEqual(exc.msg, 'test')
1982 self.assertEqual(exc.name, 'name')
1983 self.assertEqual(exc.path, 'path')
1984
1985 # Reset not specified attributes
1986 exc.__init__()
1987 self.assertEqual(exc.args, ())
1988 self.assertEqual(exc.msg, None)
1989 self.assertEqual(exc.name, None)
1990 self.assertEqual(exc.path, None)
1991
Brett Cannon07c6e712012-08-24 13:05:09 -04001992 def test_non_str_argument(self):
1993 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02001994 with check_warnings(('', BytesWarning), quiet=True):
1995 arg = b'abc'
1996 exc = ImportError(arg)
1997 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04001998
Serhiy Storchakab7853962017-04-08 09:55:07 +03001999 def test_copy_pickle(self):
2000 for kwargs in (dict(),
2001 dict(name='somename'),
2002 dict(path='somepath'),
2003 dict(name='somename', path='somepath')):
2004 orig = ImportError('test', **kwargs)
2005 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2006 exc = pickle.loads(pickle.dumps(orig, proto))
2007 self.assertEqual(exc.args, ('test',))
2008 self.assertEqual(exc.msg, 'test')
2009 self.assertEqual(exc.name, orig.name)
2010 self.assertEqual(exc.path, orig.path)
2011 for c in copy.copy, copy.deepcopy:
2012 exc = c(orig)
2013 self.assertEqual(exc.args, ('test',))
2014 self.assertEqual(exc.msg, 'test')
2015 self.assertEqual(exc.name, orig.name)
2016 self.assertEqual(exc.path, orig.path)
2017
Pablo Galindoa77aac42021-04-23 14:27:05 +01002018class SyntaxErrorTests(unittest.TestCase):
2019 def test_range_of_offsets(self):
2020 cases = [
2021 # Basic range from 2->7
2022 (("bad.py", 1, 2, "abcdefg", 1, 7),
2023 dedent(
2024 """
2025 File "bad.py", line 1
2026 abcdefg
2027 ^^^^^
2028 SyntaxError: bad bad
2029 """)),
2030 # end_offset = start_offset + 1
2031 (("bad.py", 1, 2, "abcdefg", 1, 3),
2032 dedent(
2033 """
2034 File "bad.py", line 1
2035 abcdefg
2036 ^
2037 SyntaxError: bad bad
2038 """)),
2039 # Negative end offset
2040 (("bad.py", 1, 2, "abcdefg", 1, -2),
2041 dedent(
2042 """
2043 File "bad.py", line 1
2044 abcdefg
2045 ^
2046 SyntaxError: bad bad
2047 """)),
2048 # end offset before starting offset
2049 (("bad.py", 1, 4, "abcdefg", 1, 2),
2050 dedent(
2051 """
2052 File "bad.py", line 1
2053 abcdefg
2054 ^
2055 SyntaxError: bad bad
2056 """)),
2057 # Both offsets negative
2058 (("bad.py", 1, -4, "abcdefg", 1, -2),
2059 dedent(
2060 """
2061 File "bad.py", line 1
2062 abcdefg
2063 SyntaxError: bad bad
2064 """)),
2065 # Both offsets negative and the end more negative
2066 (("bad.py", 1, -4, "abcdefg", 1, -5),
2067 dedent(
2068 """
2069 File "bad.py", line 1
2070 abcdefg
2071 SyntaxError: bad bad
2072 """)),
2073 # Both offsets 0
2074 (("bad.py", 1, 0, "abcdefg", 1, 0),
2075 dedent(
2076 """
2077 File "bad.py", line 1
2078 abcdefg
2079 SyntaxError: bad bad
2080 """)),
2081 # Start offset 0 and end offset not 0
2082 (("bad.py", 1, 0, "abcdefg", 1, 5),
2083 dedent(
2084 """
2085 File "bad.py", line 1
2086 abcdefg
2087 SyntaxError: bad bad
2088 """)),
2089 # End offset pass the source lenght
2090 (("bad.py", 1, 2, "abcdefg", 1, 100),
2091 dedent(
2092 """
2093 File "bad.py", line 1
2094 abcdefg
2095 ^^^^^^
2096 SyntaxError: bad bad
2097 """)),
2098 ]
2099 for args, expected in cases:
2100 with self.subTest(args=args):
2101 try:
2102 raise SyntaxError("bad bad", args)
2103 except SyntaxError as exc:
2104 with support.captured_stderr() as err:
2105 sys.__excepthook__(*sys.exc_info())
2106 the_exception = exc
2107
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002108 def test_encodings(self):
2109 source = (
2110 '# -*- coding: cp437 -*-\n'
2111 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2112 )
2113 try:
2114 with open(TESTFN, 'w', encoding='cp437') as testfile:
2115 testfile.write(source)
2116 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2117 err = err.decode('utf-8').splitlines()
2118
2119 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2120 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2121 finally:
2122 unlink(TESTFN)
2123
Pablo Galindoa77aac42021-04-23 14:27:05 +01002124 def test_attributes_new_constructor(self):
2125 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2126 the_exception = SyntaxError("bad bad", args)
2127 filename, lineno, offset, error, end_lineno, end_offset = args
2128 self.assertEqual(filename, the_exception.filename)
2129 self.assertEqual(lineno, the_exception.lineno)
2130 self.assertEqual(end_lineno, the_exception.end_lineno)
2131 self.assertEqual(offset, the_exception.offset)
2132 self.assertEqual(end_offset, the_exception.end_offset)
2133 self.assertEqual(error, the_exception.text)
2134 self.assertEqual("bad bad", the_exception.msg)
2135
2136 def test_attributes_old_constructor(self):
2137 args = ("bad.py", 1, 2, "abcdefg")
2138 the_exception = SyntaxError("bad bad", args)
2139 filename, lineno, offset, error = args
2140 self.assertEqual(filename, the_exception.filename)
2141 self.assertEqual(lineno, the_exception.lineno)
2142 self.assertEqual(None, the_exception.end_lineno)
2143 self.assertEqual(offset, the_exception.offset)
2144 self.assertEqual(None, the_exception.end_offset)
2145 self.assertEqual(error, the_exception.text)
2146 self.assertEqual("bad bad", the_exception.msg)
2147
2148 def test_incorrect_constructor(self):
2149 args = ("bad.py", 1, 2)
2150 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2151
2152 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2153 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2154
2155 args = ("bad.py", 1, 2, "abcdefg", 1)
2156 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2157
Brett Cannon79ec55e2012-04-12 20:24:54 -04002158
Mark Shannonbf353f32020-12-17 13:55:28 +00002159class PEP626Tests(unittest.TestCase):
2160
2161 def lineno_after_raise(self, f, line):
2162 try:
2163 f()
2164 except Exception as ex:
2165 t = ex.__traceback__
2166 while t.tb_next:
2167 t = t.tb_next
2168 frame = t.tb_frame
Mark Shannon088a15c2021-04-29 19:28:50 +01002169 if line is None:
2170 self.assertEqual(frame.f_lineno, line)
2171 else:
2172 self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line)
Mark Shannonbf353f32020-12-17 13:55:28 +00002173
2174 def test_lineno_after_raise_simple(self):
2175 def simple():
2176 1/0
2177 pass
2178 self.lineno_after_raise(simple, 1)
2179
2180 def test_lineno_after_raise_in_except(self):
2181 def in_except():
2182 try:
2183 1/0
2184 except:
2185 1/0
2186 pass
2187 self.lineno_after_raise(in_except, 4)
2188
2189 def test_lineno_after_other_except(self):
2190 def other_except():
2191 try:
2192 1/0
2193 except TypeError as ex:
2194 pass
2195 self.lineno_after_raise(other_except, 3)
2196
2197 def test_lineno_in_named_except(self):
2198 def in_named_except():
2199 try:
2200 1/0
2201 except Exception as ex:
2202 1/0
2203 pass
2204 self.lineno_after_raise(in_named_except, 4)
2205
2206 def test_lineno_in_try(self):
2207 def in_try():
2208 try:
2209 1/0
2210 finally:
2211 pass
2212 self.lineno_after_raise(in_try, 4)
2213
2214 def test_lineno_in_finally_normal(self):
2215 def in_finally_normal():
2216 try:
2217 pass
2218 finally:
2219 1/0
2220 pass
2221 self.lineno_after_raise(in_finally_normal, 4)
2222
2223 def test_lineno_in_finally_except(self):
2224 def in_finally_except():
2225 try:
2226 1/0
2227 finally:
2228 1/0
2229 pass
2230 self.lineno_after_raise(in_finally_except, 4)
2231
2232 def test_lineno_after_with(self):
2233 class Noop:
2234 def __enter__(self):
2235 return self
2236 def __exit__(self, *args):
2237 pass
2238 def after_with():
2239 with Noop():
2240 1/0
2241 pass
2242 self.lineno_after_raise(after_with, 2)
2243
Mark Shannon088a15c2021-04-29 19:28:50 +01002244 def test_missing_lineno_shows_as_none(self):
2245 def f():
2246 1/0
2247 self.lineno_after_raise(f, 1)
2248 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2249 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002250
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002251if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002252 unittest.main()