blob: 8caac2c3a9d6df05ce8896a5cba6cf0900c91370 [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
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100178 s = 'print f(a+b,c)'
179 ckmsg(s, "Missing parentheses in call to 'print'.")
180
Martijn Pieters772d8092017-08-22 21:16:23 +0100181 s = '''exec "old style"'''
182 ckmsg(s, "Missing parentheses in call to 'exec'")
183
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100184 s = 'exec f(a+b,c)'
185 ckmsg(s, "Missing parentheses in call to 'exec'.")
186
Martijn Pieters772d8092017-08-22 21:16:23 +0100187 # should not apply to subclasses, see issue #31161
188 s = '''if True:\nprint "No indent"'''
Pablo Galindo56c95df2021-04-21 15:28:21 +0100189 ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
Martijn Pieters772d8092017-08-22 21:16:23 +0100190
191 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
192 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
193
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300194 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100195 with self.subTest(source=src, lineno=lineno, offset=offset):
196 with self.assertRaises(SyntaxError) as cm:
197 compile(src, '<fragment>', 'exec')
198 self.assertEqual(cm.exception.lineno, lineno)
199 self.assertEqual(cm.exception.offset, offset)
200 if cm.exception.text is not None:
201 if not isinstance(src, str):
202 src = src.decode(encoding, 'replace')
203 line = src.split('\n')[lineno-1]
204 self.assertIn(line, cm.exception.text)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200205
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300206 def testSyntaxErrorOffset(self):
207 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200208 check('def fact(x):\n\treturn x!\n', 2, 10)
209 check('1 +\n', 1, 4)
210 check('def spam():\n print(1)\n print(2)', 3, 10)
211 check('Python = "Python" +', 1, 20)
212 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200213 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
214 2, 19, encoding='cp1251')
215 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300216 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400217 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200218 check('f{a + b + c}', 1, 2)
Miss Islington (bot)756b7b92021-05-03 18:06:45 -0700219 check('[file for str(file) in []\n])', 2, 2)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700220 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200221 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
222 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700223 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700224 check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
Ammar Askar025eb982018-09-24 17:12:49 -0400225
226 # Errors thrown by compile.c
227 check('class foo:return 1', 1, 11)
228 check('def f():\n continue', 2, 3)
229 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100230 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400231
232 # Errors thrown by tokenizer.c
233 check('(0x+1)', 1, 3)
234 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700235 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400236 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700237 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200238 check('\u03b1 = 0xI', 1, 6)
239 check(b'\xce\xb1 = 0xI', 1, 6)
240 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
241 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100242 check(b"""if 1:
243 def foo():
244 '''
245
246 def bar():
247 pass
248
249 def baz():
250 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300251 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100252 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
253 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700254 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700255 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400256
257 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200258 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400259 check('def f():\n from _ import *', 1, 1)
260 check('def f(x, x):\n pass', 1, 1)
261 check('def f(x):\n nonlocal x', 2, 3)
262 check('def f(x):\n x = 1\n global x', 3, 3)
263 check('nonlocal x', 1, 1)
264 check('def f():\n global x\n nonlocal x', 2, 3)
265
Ammar Askar025eb982018-09-24 17:12:49 -0400266 # Errors thrown by future.c
267 check('from __future__ import doesnt_exist', 1, 1)
268 check('from __future__ import braces', 1, 1)
269 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100270 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300271 check('def f():\n x, y: int', 2, 3)
272 check('[*x for x in xs]', 1, 2)
273 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300274 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100275 check('(yield i) = 2', 1, 2)
276 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200277
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000278 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000279 def testSettingException(self):
280 # test that setting an exception at the C level works even if the
281 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000282
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000283 class BadException(Exception):
284 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000285 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000286
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000287 class InvalidException:
288 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000289
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000290 def test_capi1():
291 import _testcapi
292 try:
293 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000294 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000295 exc, err, tb = sys.exc_info()
296 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000297 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000298 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000299 else:
300 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000301
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000302 def test_capi2():
303 import _testcapi
304 try:
305 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000306 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000307 exc, err, tb = sys.exc_info()
308 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000309 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000311 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000312 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000313 else:
314 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000315
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000316 def test_capi3():
317 import _testcapi
318 self.assertRaises(SystemError, _testcapi.raise_exception,
319 InvalidException, 1)
320
321 if not sys.platform.startswith('java'):
322 test_capi1()
323 test_capi2()
324 test_capi3()
325
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 def test_WindowsError(self):
327 try:
328 WindowsError
329 except NameError:
330 pass
331 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200332 self.assertIs(WindowsError, OSError)
333 self.assertEqual(str(OSError(1001)), "1001")
334 self.assertEqual(str(OSError(1001, "message")),
335 "[Errno 1001] message")
336 # POSIX errno (9 aka EBADF) is untranslated
337 w = OSError(9, 'foo', 'bar')
338 self.assertEqual(w.errno, 9)
339 self.assertEqual(w.winerror, None)
340 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
341 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
342 w = OSError(0, 'foo', 'bar', 3)
343 self.assertEqual(w.errno, 2)
344 self.assertEqual(w.winerror, 3)
345 self.assertEqual(w.strerror, 'foo')
346 self.assertEqual(w.filename, 'bar')
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 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200349 # Unknown win error becomes EINVAL (22)
350 w = OSError(0, 'foo', None, 1001)
351 self.assertEqual(w.errno, 22)
352 self.assertEqual(w.winerror, 1001)
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)
Richard Oudkerk30147712012-08-28 19:33:26 +0100356 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200357 # Non-numeric "errno"
358 w = OSError('bar', 'foo')
359 self.assertEqual(w.errno, 'bar')
360 self.assertEqual(w.winerror, None)
361 self.assertEqual(w.strerror, 'foo')
362 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000363 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364
Victor Stinnerd223fa62015-04-02 14:17:38 +0200365 @unittest.skipUnless(sys.platform == 'win32',
366 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300367 def test_windows_message(self):
368 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200369 ctypes = import_module('ctypes')
370 # this error code has no message, Python formats it as hexadecimal
371 code = 3765269347
372 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
373 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300374
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000375 def testAttributes(self):
376 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000377
378 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000379 (BaseException, (), {'args' : ()}),
380 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000381 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000382 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000383 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000384 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000385 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000386 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200387 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000388 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200390 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000391 {'args' : ('foo', 'bar'),
392 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000393 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200394 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000395 {'args' : ('foo', 'bar'),
396 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800398 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
399 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200400 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000401 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000402 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
403 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200404 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000405 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000406 'strerror' : 'strErrorStr',
407 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000408 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000409 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100410 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000411 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000412 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000413 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100414 'filename' : None, 'lineno' : None, 'offset' : None,
415 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000416 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100417 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000418 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000419 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100420 'offsetStr', 'textStr',
421 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000422 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100423 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
424 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000425 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100426 'textStr', 'endLinenoStr', 'endOffsetStr',
427 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000428 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000429 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100430 'textStr', 'endLinenoStr', 'endOffsetStr',
431 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100433 'filename' : None, 'lineno' : None, 'offset' : None,
434 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000435 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000436 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
437 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000438 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000440 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000442 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000443 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000444 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000445 'ordinal not in range'),
446 'encoding' : 'ascii', 'object' : b'\xff',
447 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000448 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
449 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000450 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000451 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000452 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000454 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000455 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000456 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000457 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100458 (NaiveException, ('foo',),
459 {'args': ('foo',), 'x': 'foo'}),
460 (SlottedNaiveException, ('foo',),
461 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000463 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200464 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000465 exceptionList.append(
466 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000467 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200468 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000469 'errno' : 1,
470 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000471 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000472 except NameError:
473 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000474
Guido van Rossumebe3e162007-05-17 18:20:34 +0000475 for exc, args, expected in exceptionList:
476 try:
477 e = exc(*args)
478 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000479 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100480 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000481 else:
482 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100483 if not type(e).__name__.endswith('NaiveException'):
484 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000485 # Verify no ref leaks in Exc_str()
486 s = str(e)
487 for checkArgName in expected:
488 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000489 self.assertEqual(repr(value),
490 repr(expected[checkArgName]),
491 '%r.%s == %r, expected %r' % (
492 e, checkArgName,
493 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000494
Guido van Rossumebe3e162007-05-17 18:20:34 +0000495 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000496 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000497 for protocol in range(p.HIGHEST_PROTOCOL + 1):
498 s = p.dumps(e, protocol)
499 new = p.loads(s)
500 for checkArgName in expected:
501 got = repr(getattr(new, checkArgName))
502 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000503 self.assertEqual(got, want,
504 'pickled "%r", attribute "%s' %
505 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000506
Collin Winter828f04a2007-08-31 00:04:24 +0000507 def testWithTraceback(self):
508 try:
509 raise IndexError(4)
510 except:
511 tb = sys.exc_info()[2]
512
513 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000514 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000515 self.assertEqual(e.__traceback__, tb)
516
517 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000518 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000519 self.assertEqual(e.__traceback__, tb)
520
521 class MyException(Exception):
522 pass
523
524 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000525 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000526 self.assertEqual(e.__traceback__, tb)
527
528 def testInvalidTraceback(self):
529 try:
530 Exception().__traceback__ = 5
531 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000532 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000533 else:
534 self.fail("No exception raised")
535
Georg Brandlab6f2f62009-03-31 04:16:10 +0000536 def testInvalidAttrs(self):
537 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
538 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
539 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
540 self.assertRaises(TypeError, delattr, Exception(), '__context__')
541
Collin Winter828f04a2007-08-31 00:04:24 +0000542 def testNoneClearsTracebackAttr(self):
543 try:
544 raise IndexError(4)
545 except:
546 tb = sys.exc_info()[2]
547
548 e = Exception()
549 e.__traceback__ = tb
550 e.__traceback__ = None
551 self.assertEqual(e.__traceback__, None)
552
553 def testChainingAttrs(self):
554 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000555 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700556 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000557
558 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000559 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700560 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000561
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200562 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000563 pass
564
565 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000566 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700567 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000568
569 def testChainingDescriptors(self):
570 try:
571 raise Exception()
572 except Exception as exc:
573 e = exc
574
575 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700576 self.assertIsNone(e.__cause__)
577 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000578
579 e.__context__ = NameError()
580 e.__cause__ = None
581 self.assertIsInstance(e.__context__, NameError)
582 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700583 self.assertTrue(e.__suppress_context__)
584 e.__suppress_context__ = False
585 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000586
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000587 def testKeywordArgs(self):
588 # test that builtin exception don't take keyword args,
589 # but user-defined subclasses can if they want
590 self.assertRaises(TypeError, BaseException, a=1)
591
592 class DerivedException(BaseException):
593 def __init__(self, fancy_arg):
594 BaseException.__init__(self)
595 self.fancy_arg = fancy_arg
596
597 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000598 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000599
Brett Cannon31f59292011-02-21 19:29:56 +0000600 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000601 def testInfiniteRecursion(self):
602 def f():
603 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400604 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605
606 def g():
607 try:
608 return g()
609 except ValueError:
610 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400611 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000613 def test_str(self):
614 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000615 self.assertTrue(str(Exception))
616 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000617 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000619 def testExceptionCleanupNames(self):
620 # Make sure the local variable bound to the exception instance by
621 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000622 try:
623 raise Exception()
624 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000625 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000626 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000627 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000628
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000629 def testExceptionCleanupState(self):
630 # Make sure exception state is cleaned up as soon as the except
631 # block is left. See #2507
632
633 class MyException(Exception):
634 def __init__(self, obj):
635 self.obj = obj
636 class MyObj:
637 pass
638
639 def inner_raising_func():
640 # Create some references in exception value and traceback
641 local_ref = obj
642 raise MyException(obj)
643
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000644 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000645 obj = MyObj()
646 wr = weakref.ref(obj)
647 try:
648 inner_raising_func()
649 except MyException as e:
650 pass
651 obj = None
652 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300653 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000654
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000655 # Qualified "except" without "as"
656 obj = MyObj()
657 wr = weakref.ref(obj)
658 try:
659 inner_raising_func()
660 except MyException:
661 pass
662 obj = None
663 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300664 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000665
666 # Bare "except"
667 obj = MyObj()
668 wr = weakref.ref(obj)
669 try:
670 inner_raising_func()
671 except:
672 pass
673 obj = None
674 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300675 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000676
677 # "except" with premature block leave
678 obj = MyObj()
679 wr = weakref.ref(obj)
680 for i in [0]:
681 try:
682 inner_raising_func()
683 except:
684 break
685 obj = None
686 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300687 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000688
689 # "except" block raising another exception
690 obj = MyObj()
691 wr = weakref.ref(obj)
692 try:
693 try:
694 inner_raising_func()
695 except:
696 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000697 except KeyError as e:
698 # We want to test that the except block above got rid of
699 # the exception raised in inner_raising_func(), but it
700 # also ends up in the __context__ of the KeyError, so we
701 # must clear the latter manually for our test to succeed.
702 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000703 obj = None
704 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800705 # guarantee no ref cycles on CPython (don't gc_collect)
706 if check_impl_detail(cpython=False):
707 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300708 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000709
710 # Some complicated construct
711 obj = MyObj()
712 wr = weakref.ref(obj)
713 try:
714 inner_raising_func()
715 except MyException:
716 try:
717 try:
718 raise
719 finally:
720 raise
721 except MyException:
722 pass
723 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800724 if check_impl_detail(cpython=False):
725 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000726 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300727 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000728
729 # Inside an exception-silencing "with" block
730 class Context:
731 def __enter__(self):
732 return self
733 def __exit__ (self, exc_type, exc_value, exc_tb):
734 return True
735 obj = MyObj()
736 wr = weakref.ref(obj)
737 with Context():
738 inner_raising_func()
739 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800740 if check_impl_detail(cpython=False):
741 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000742 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300743 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000744
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000745 def test_exception_target_in_nested_scope(self):
746 # issue 4617: This used to raise a SyntaxError
747 # "can not delete variable 'e' referenced in nested scope"
748 def print_error():
749 e
750 try:
751 something
752 except Exception as e:
753 print_error()
754 # implicit "del e" here
755
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000756 def test_generator_leaking(self):
757 # Test that generator exception state doesn't leak into the calling
758 # frame
759 def yield_raise():
760 try:
761 raise KeyError("caught")
762 except KeyError:
763 yield sys.exc_info()[0]
764 yield sys.exc_info()[0]
765 yield sys.exc_info()[0]
766 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000767 self.assertEqual(next(g), KeyError)
768 self.assertEqual(sys.exc_info()[0], None)
769 self.assertEqual(next(g), KeyError)
770 self.assertEqual(sys.exc_info()[0], None)
771 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000772
773 # Same test, but inside an exception handler
774 try:
775 raise TypeError("foo")
776 except TypeError:
777 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000778 self.assertEqual(next(g), KeyError)
779 self.assertEqual(sys.exc_info()[0], TypeError)
780 self.assertEqual(next(g), KeyError)
781 self.assertEqual(sys.exc_info()[0], TypeError)
782 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000783 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000784 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000785
Benjamin Peterson83195c32011-07-03 13:44:00 -0500786 def test_generator_leaking2(self):
787 # See issue 12475.
788 def g():
789 yield
790 try:
791 raise RuntimeError
792 except RuntimeError:
793 it = g()
794 next(it)
795 try:
796 next(it)
797 except StopIteration:
798 pass
799 self.assertEqual(sys.exc_info(), (None, None, None))
800
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100801 def test_generator_leaking3(self):
802 # See issue #23353. When gen.throw() is called, the caller's
803 # exception state should be save and restored.
804 def g():
805 try:
806 yield
807 except ZeroDivisionError:
808 yield sys.exc_info()[1]
809 it = g()
810 next(it)
811 try:
812 1/0
813 except ZeroDivisionError as e:
814 self.assertIs(sys.exc_info()[1], e)
815 gen_exc = it.throw(e)
816 self.assertIs(sys.exc_info()[1], e)
817 self.assertIs(gen_exc, e)
818 self.assertEqual(sys.exc_info(), (None, None, None))
819
820 def test_generator_leaking4(self):
821 # See issue #23353. When an exception is raised by a generator,
822 # the caller's exception state should still be restored.
823 def g():
824 try:
825 1/0
826 except ZeroDivisionError:
827 yield sys.exc_info()[0]
828 raise
829 it = g()
830 try:
831 raise TypeError
832 except TypeError:
833 # The caller's exception state (TypeError) is temporarily
834 # saved in the generator.
835 tp = next(it)
836 self.assertIs(tp, ZeroDivisionError)
837 try:
838 next(it)
839 # We can't check it immediately, but while next() returns
840 # with an exception, it shouldn't have restored the old
841 # exception state (TypeError).
842 except ZeroDivisionError as e:
843 self.assertIs(sys.exc_info()[1], e)
844 # We used to find TypeError here.
845 self.assertEqual(sys.exc_info(), (None, None, None))
846
Benjamin Petersonac913412011-07-03 16:25:11 -0500847 def test_generator_doesnt_retain_old_exc(self):
848 def g():
849 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
850 yield
851 self.assertEqual(sys.exc_info(), (None, None, None))
852 it = g()
853 try:
854 raise RuntimeError
855 except RuntimeError:
856 next(it)
857 self.assertRaises(StopIteration, next, it)
858
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000859 def test_generator_finalizing_and_exc_info(self):
860 # See #7173
861 def simple_gen():
862 yield 1
863 def run_gen():
864 gen = simple_gen()
865 try:
866 raise RuntimeError
867 except RuntimeError:
868 return next(gen)
869 run_gen()
870 gc_collect()
871 self.assertEqual(sys.exc_info(), (None, None, None))
872
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200873 def _check_generator_cleanup_exc_state(self, testfunc):
874 # Issue #12791: exception state is cleaned up as soon as a generator
875 # is closed (reference cycles are broken).
876 class MyException(Exception):
877 def __init__(self, obj):
878 self.obj = obj
879 class MyObj:
880 pass
881
882 def raising_gen():
883 try:
884 raise MyException(obj)
885 except MyException:
886 yield
887
888 obj = MyObj()
889 wr = weakref.ref(obj)
890 g = raising_gen()
891 next(g)
892 testfunc(g)
893 g = obj = None
894 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300895 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200896
897 def test_generator_throw_cleanup_exc_state(self):
898 def do_throw(g):
899 try:
900 g.throw(RuntimeError())
901 except RuntimeError:
902 pass
903 self._check_generator_cleanup_exc_state(do_throw)
904
905 def test_generator_close_cleanup_exc_state(self):
906 def do_close(g):
907 g.close()
908 self._check_generator_cleanup_exc_state(do_close)
909
910 def test_generator_del_cleanup_exc_state(self):
911 def do_del(g):
912 g = None
913 self._check_generator_cleanup_exc_state(do_del)
914
915 def test_generator_next_cleanup_exc_state(self):
916 def do_next(g):
917 try:
918 next(g)
919 except StopIteration:
920 pass
921 else:
922 self.fail("should have raised StopIteration")
923 self._check_generator_cleanup_exc_state(do_next)
924
925 def test_generator_send_cleanup_exc_state(self):
926 def do_send(g):
927 try:
928 g.send(None)
929 except StopIteration:
930 pass
931 else:
932 self.fail("should have raised StopIteration")
933 self._check_generator_cleanup_exc_state(do_send)
934
Benjamin Peterson27d63672008-06-15 20:09:12 +0000935 def test_3114(self):
936 # Bug #3114: in its destructor, MyObject retrieves a pointer to
937 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000938 class MyObject:
939 def __del__(self):
940 nonlocal e
941 e = sys.exc_info()
942 e = ()
943 try:
944 raise Exception(MyObject())
945 except:
946 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000947 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000948
Benjamin Peterson24dfb052014-04-02 12:05:35 -0400949 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +0000950 # See issue 7309. This was a crasher.
951
952 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
953 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
954 u.end = 2
955 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
956 u.end = 5
957 u.reason = 0x345345345345345345
958 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
959 u.encoding = 4000
960 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
961 u.start = 1000
962 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
963
964 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
965 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
966 u.end = 2
967 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
968 u.end = 5
969 u.reason = 0x345345345345345345
970 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
971 u.encoding = 4000
972 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
973 u.start = 1000
974 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
975
976 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
977 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
978 u.end = 2
979 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
980 u.end = 5
981 u.reason = 0x345345345345345345
982 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
983 u.start = 1000
984 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000985
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400986 def test_unicode_errors_no_object(self):
987 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -0400988 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400989 for klass in klasses:
990 self.assertEqual(str(klass.__new__(klass)), "")
991
Brett Cannon31f59292011-02-21 19:29:56 +0000992 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000993 def test_badisinstance(self):
994 # Bug #2542: if issubclass(e, MyException) raises an exception,
995 # it should be ignored
996 class Meta(type):
997 def __subclasscheck__(cls, subclass):
998 raise ValueError()
999 class MyException(Exception, metaclass=Meta):
1000 pass
1001
Martin Panter3263f682016-02-28 03:16:11 +00001002 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001003 try:
1004 raise KeyError()
1005 except MyException as e:
1006 self.fail("exception should not be a MyException")
1007 except KeyError:
1008 pass
1009 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001010 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001011 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001012 self.fail("Should have raised KeyError")
1013
1014 def g():
1015 try:
1016 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001017 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001018 return sys.exc_info()
1019 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001020 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001021 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001022
xdegaye56d1f5c2017-10-26 15:09:06 +02001023 @cpython_only
1024 def test_recursion_normalizing_exception(self):
1025 # Issue #22898.
1026 # Test that a RecursionError is raised when tstate->recursion_depth is
1027 # equal to recursion_limit in PyErr_NormalizeException() and check
1028 # that a ResourceWarning is printed.
1029 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001030 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001031 # singleton was being used in that case, that held traceback data and
1032 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1033 # finalization of these locals.
1034 code = """if 1:
1035 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001036 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001037
1038 class MyException(Exception): pass
1039
1040 def setrecursionlimit(depth):
1041 while 1:
1042 try:
1043 sys.setrecursionlimit(depth)
1044 return depth
1045 except RecursionError:
1046 # sys.setrecursionlimit() raises a RecursionError if
1047 # the new recursion limit is too low (issue #25274).
1048 depth += 1
1049
1050 def recurse(cnt):
1051 cnt -= 1
1052 if cnt:
1053 recurse(cnt)
1054 else:
1055 generator.throw(MyException)
1056
1057 def gen():
1058 f = open(%a, mode='rb', buffering=0)
1059 yield
1060
1061 generator = gen()
1062 next(generator)
1063 recursionlimit = sys.getrecursionlimit()
1064 depth = get_recursion_depth()
1065 try:
1066 # Upon the last recursive invocation of recurse(),
1067 # tstate->recursion_depth is equal to (recursion_limit - 1)
1068 # and is equal to recursion_limit when _gen_throw() calls
1069 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001070 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001071 finally:
1072 sys.setrecursionlimit(recursionlimit)
1073 print('Done.')
1074 """ % __file__
1075 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1076 # Check that the program does not fail with SIGABRT.
1077 self.assertEqual(rc, 1)
1078 self.assertIn(b'RecursionError', err)
1079 self.assertIn(b'ResourceWarning', err)
1080 self.assertIn(b'Done.', out)
1081
1082 @cpython_only
1083 def test_recursion_normalizing_infinite_exception(self):
1084 # Issue #30697. Test that a RecursionError is raised when
1085 # PyErr_NormalizeException() maximum recursion depth has been
1086 # exceeded.
1087 code = """if 1:
1088 import _testcapi
1089 try:
1090 raise _testcapi.RecursingInfinitelyError
1091 finally:
1092 print('Done.')
1093 """
1094 rc, out, err = script_helper.assert_python_failure("-c", code)
1095 self.assertEqual(rc, 1)
1096 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1097 b'while normalizing an exception', err)
1098 self.assertIn(b'Done.', out)
1099
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001100
1101 def test_recursion_in_except_handler(self):
1102
1103 def set_relative_recursion_limit(n):
1104 depth = 1
1105 while True:
1106 try:
1107 sys.setrecursionlimit(depth)
1108 except RecursionError:
1109 depth += 1
1110 else:
1111 break
1112 sys.setrecursionlimit(depth+n)
1113
1114 def recurse_in_except():
1115 try:
1116 1/0
1117 except:
1118 recurse_in_except()
1119
1120 def recurse_after_except():
1121 try:
1122 1/0
1123 except:
1124 pass
1125 recurse_after_except()
1126
1127 def recurse_in_body_and_except():
1128 try:
1129 recurse_in_body_and_except()
1130 except:
1131 recurse_in_body_and_except()
1132
1133 recursionlimit = sys.getrecursionlimit()
1134 try:
1135 set_relative_recursion_limit(10)
1136 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1137 with self.subTest(func=func):
1138 try:
1139 func()
1140 except RecursionError:
1141 pass
1142 else:
1143 self.fail("Should have raised a RecursionError")
1144 finally:
1145 sys.setrecursionlimit(recursionlimit)
1146
1147
xdegaye56d1f5c2017-10-26 15:09:06 +02001148 @cpython_only
1149 def test_recursion_normalizing_with_no_memory(self):
1150 # Issue #30697. Test that in the abort that occurs when there is no
1151 # memory left and the size of the Python frames stack is greater than
1152 # the size of the list of preallocated MemoryError instances, the
1153 # Fatal Python error message mentions MemoryError.
1154 code = """if 1:
1155 import _testcapi
1156 class C(): pass
1157 def recurse(cnt):
1158 cnt -= 1
1159 if cnt:
1160 recurse(cnt)
1161 else:
1162 _testcapi.set_nomemory(0)
1163 C()
1164 recurse(16)
1165 """
1166 with SuppressCrashReport():
1167 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001168 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1169 b'Cannot recover from MemoryErrors while '
1170 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001171
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001172 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001173 def test_MemoryError(self):
1174 # PyErr_NoMemory always raises the same exception instance.
1175 # Check that the traceback is not doubled.
1176 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001177 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001178 def raiseMemError():
1179 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001180 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001181 except MemoryError as e:
1182 tb = e.__traceback__
1183 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001184 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001185 return traceback.format_tb(tb)
1186
1187 tb1 = raiseMemError()
1188 tb2 = raiseMemError()
1189 self.assertEqual(tb1, tb2)
1190
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001191 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001192 def test_exception_with_doc(self):
1193 import _testcapi
1194 doc2 = "This is a test docstring."
1195 doc4 = "This is another test docstring."
1196
1197 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1198 "error1")
1199
1200 # test basic usage of PyErr_NewException
1201 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1202 self.assertIs(type(error1), type)
1203 self.assertTrue(issubclass(error1, Exception))
1204 self.assertIsNone(error1.__doc__)
1205
1206 # test with given docstring
1207 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1208 self.assertEqual(error2.__doc__, doc2)
1209
1210 # test with explicit base (without docstring)
1211 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1212 base=error2)
1213 self.assertTrue(issubclass(error3, error2))
1214
1215 # test with explicit base tuple
1216 class C(object):
1217 pass
1218 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1219 (error3, C))
1220 self.assertTrue(issubclass(error4, error3))
1221 self.assertTrue(issubclass(error4, C))
1222 self.assertEqual(error4.__doc__, doc4)
1223
1224 # test with explicit dictionary
1225 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1226 error4, {'a': 1})
1227 self.assertTrue(issubclass(error5, error4))
1228 self.assertEqual(error5.a, 1)
1229 self.assertEqual(error5.__doc__, "")
1230
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001231 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001232 def test_memory_error_cleanup(self):
1233 # Issue #5437: preallocated MemoryError instances should not keep
1234 # traceback objects alive.
1235 from _testcapi import raise_memoryerror
1236 class C:
1237 pass
1238 wr = None
1239 def inner():
1240 nonlocal wr
1241 c = C()
1242 wr = weakref.ref(c)
1243 raise_memoryerror()
1244 # We cannot use assertRaises since it manually deletes the traceback
1245 try:
1246 inner()
1247 except MemoryError as e:
1248 self.assertNotEqual(wr(), None)
1249 else:
1250 self.fail("MemoryError not raised")
1251 self.assertEqual(wr(), None)
1252
Brett Cannon31f59292011-02-21 19:29:56 +00001253 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001254 def test_recursion_error_cleanup(self):
1255 # Same test as above, but with "recursion exceeded" errors
1256 class C:
1257 pass
1258 wr = None
1259 def inner():
1260 nonlocal wr
1261 c = C()
1262 wr = weakref.ref(c)
1263 inner()
1264 # We cannot use assertRaises since it manually deletes the traceback
1265 try:
1266 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001267 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001268 self.assertNotEqual(wr(), None)
1269 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001270 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001271 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001272
Antoine Pitroua7622852011-09-01 21:37:43 +02001273 def test_errno_ENOTDIR(self):
1274 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1275 with self.assertRaises(OSError) as cm:
1276 os.listdir(__file__)
1277 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1278
Martin Panter3263f682016-02-28 03:16:11 +00001279 def test_unraisable(self):
1280 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1281 class BrokenDel:
1282 def __del__(self):
1283 exc = ValueError("del is broken")
1284 # The following line is included in the traceback report:
1285 raise exc
1286
Victor Stinnere4d300e2019-05-22 23:44:02 +02001287 obj = BrokenDel()
1288 with support.catch_unraisable_exception() as cm:
1289 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001290
Victor Stinnere4d300e2019-05-22 23:44:02 +02001291 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1292 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001293
1294 def test_unhandled(self):
1295 # Check for sensible reporting of unhandled exceptions
1296 for exc_type in (ValueError, BrokenStrException):
1297 with self.subTest(exc_type):
1298 try:
1299 exc = exc_type("test message")
1300 # The following line is included in the traceback report:
1301 raise exc
1302 except exc_type:
1303 with captured_stderr() as stderr:
1304 sys.__excepthook__(*sys.exc_info())
1305 report = stderr.getvalue()
1306 self.assertIn("test_exceptions.py", report)
1307 self.assertIn("raise exc", report)
1308 self.assertIn(exc_type.__name__, report)
1309 if exc_type is BrokenStrException:
1310 self.assertIn("<exception str() failed>", report)
1311 else:
1312 self.assertIn("test message", report)
1313 self.assertTrue(report.endswith("\n"))
1314
xdegaye66caacf2017-10-23 18:08:41 +02001315 @cpython_only
1316 def test_memory_error_in_PyErr_PrintEx(self):
1317 code = """if 1:
1318 import _testcapi
1319 class C(): pass
1320 _testcapi.set_nomemory(0, %d)
1321 C()
1322 """
1323
1324 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1325 # Span a large range of tests as the CPython code always evolves with
1326 # changes that add or remove memory allocations.
1327 for i in range(1, 20):
1328 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1329 self.assertIn(rc, (1, 120))
1330 self.assertIn(b'MemoryError', err)
1331
Mark Shannonae3087c2017-10-22 22:41:51 +01001332 def test_yield_in_nested_try_excepts(self):
1333 #Issue #25612
1334 class MainError(Exception):
1335 pass
1336
1337 class SubError(Exception):
1338 pass
1339
1340 def main():
1341 try:
1342 raise MainError()
1343 except MainError:
1344 try:
1345 yield
1346 except SubError:
1347 pass
1348 raise
1349
1350 coro = main()
1351 coro.send(None)
1352 with self.assertRaises(MainError):
1353 coro.throw(SubError())
1354
1355 def test_generator_doesnt_retain_old_exc2(self):
1356 #Issue 28884#msg282532
1357 def g():
1358 try:
1359 raise ValueError
1360 except ValueError:
1361 yield 1
1362 self.assertEqual(sys.exc_info(), (None, None, None))
1363 yield 2
1364
1365 gen = g()
1366
1367 try:
1368 raise IndexError
1369 except IndexError:
1370 self.assertEqual(next(gen), 1)
1371 self.assertEqual(next(gen), 2)
1372
1373 def test_raise_in_generator(self):
1374 #Issue 25612#msg304117
1375 def g():
1376 yield 1
1377 raise
1378 yield 2
1379
1380 with self.assertRaises(ZeroDivisionError):
1381 i = g()
1382 try:
1383 1/0
1384 except:
1385 next(i)
1386 next(i)
1387
Zackery Spytzce6a0702019-08-25 03:44:09 -06001388 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1389 def test_assert_shadowing(self):
1390 # Shadowing AssertionError would cause the assert statement to
1391 # misbehave.
1392 global AssertionError
1393 AssertionError = TypeError
1394 try:
1395 assert False, 'hello'
1396 except BaseException as e:
1397 del AssertionError
1398 self.assertIsInstance(e, AssertionError)
1399 self.assertEqual(str(e), 'hello')
1400 else:
1401 del AssertionError
1402 self.fail('Expected exception')
1403
Pablo Galindo9b648a92020-09-01 19:39:46 +01001404 def test_memory_error_subclasses(self):
1405 # bpo-41654: MemoryError instances use a freelist of objects that are
1406 # linked using the 'dict' attribute when they are inactive/dead.
1407 # Subclasses of MemoryError should not participate in the freelist
1408 # schema. This test creates a MemoryError object and keeps it alive
1409 # (therefore advancing the freelist) and then it creates and destroys a
1410 # subclass object. Finally, it checks that creating a new MemoryError
1411 # succeeds, proving that the freelist is not corrupted.
1412
1413 class TestException(MemoryError):
1414 pass
1415
1416 try:
1417 raise MemoryError
1418 except MemoryError as exc:
1419 inst = exc
1420
1421 try:
1422 raise TestException
1423 except Exception:
1424 pass
1425
1426 for _ in range(10):
1427 try:
1428 raise MemoryError
1429 except MemoryError as exc:
1430 pass
1431
1432 gc_collect()
1433
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001434global_for_suggestions = None
1435
1436class NameErrorTests(unittest.TestCase):
1437 def test_name_error_has_name(self):
1438 try:
1439 bluch
1440 except NameError as exc:
1441 self.assertEqual("bluch", exc.name)
1442
1443 def test_name_error_suggestions(self):
1444 def Substitution():
1445 noise = more_noise = a = bc = None
1446 blech = None
1447 print(bluch)
1448
1449 def Elimination():
1450 noise = more_noise = a = bc = None
1451 blch = None
1452 print(bluch)
1453
1454 def Addition():
1455 noise = more_noise = a = bc = None
1456 bluchin = None
1457 print(bluch)
1458
1459 def SubstitutionOverElimination():
1460 blach = None
1461 bluc = None
1462 print(bluch)
1463
1464 def SubstitutionOverAddition():
1465 blach = None
1466 bluchi = None
1467 print(bluch)
1468
1469 def EliminationOverAddition():
1470 blucha = None
1471 bluc = None
1472 print(bluch)
1473
Pablo Galindo7a041162021-04-19 23:35:53 +01001474 for func, suggestion in [(Substitution, "'blech'?"),
1475 (Elimination, "'blch'?"),
1476 (Addition, "'bluchin'?"),
1477 (EliminationOverAddition, "'blucha'?"),
1478 (SubstitutionOverElimination, "'blach'?"),
1479 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001480 err = None
1481 try:
1482 func()
1483 except NameError as exc:
1484 with support.captured_stderr() as err:
1485 sys.__excepthook__(*sys.exc_info())
1486 self.assertIn(suggestion, err.getvalue())
1487
1488 def test_name_error_suggestions_from_globals(self):
1489 def func():
1490 print(global_for_suggestio)
1491 try:
1492 func()
1493 except NameError as exc:
1494 with support.captured_stderr() as err:
1495 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001496 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001497
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001498 def test_name_error_suggestions_from_builtins(self):
1499 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001500 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001501 try:
1502 func()
1503 except NameError as exc:
1504 with support.captured_stderr() as err:
1505 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001506 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001507
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001508 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1509 def f():
1510 somethingverywronghehehehehehe = None
1511 print(somethingverywronghe)
1512
1513 try:
1514 f()
1515 except NameError as exc:
1516 with support.captured_stderr() as err:
1517 sys.__excepthook__(*sys.exc_info())
1518
1519 self.assertNotIn("somethingverywronghehe", err.getvalue())
1520
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001521 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1522 vvv = mom = w = id = pytho = None
1523
1524 with self.subTest(name="b"):
1525 try:
1526 b
1527 except NameError as exc:
1528 with support.captured_stderr() as err:
1529 sys.__excepthook__(*sys.exc_info())
1530 self.assertNotIn("you mean", err.getvalue())
1531 self.assertNotIn("vvv", err.getvalue())
1532 self.assertNotIn("mom", err.getvalue())
1533 self.assertNotIn("'id'", err.getvalue())
1534 self.assertNotIn("'w'", err.getvalue())
1535 self.assertNotIn("'pytho'", err.getvalue())
1536
1537 with self.subTest(name="v"):
1538 try:
1539 v
1540 except NameError as exc:
1541 with support.captured_stderr() as err:
1542 sys.__excepthook__(*sys.exc_info())
1543 self.assertNotIn("you mean", err.getvalue())
1544 self.assertNotIn("vvv", err.getvalue())
1545 self.assertNotIn("mom", err.getvalue())
1546 self.assertNotIn("'id'", err.getvalue())
1547 self.assertNotIn("'w'", err.getvalue())
1548 self.assertNotIn("'pytho'", err.getvalue())
1549
1550 with self.subTest(name="m"):
1551 try:
1552 m
1553 except NameError as exc:
1554 with support.captured_stderr() as err:
1555 sys.__excepthook__(*sys.exc_info())
1556 self.assertNotIn("you mean", err.getvalue())
1557 self.assertNotIn("vvv", err.getvalue())
1558 self.assertNotIn("mom", err.getvalue())
1559 self.assertNotIn("'id'", err.getvalue())
1560 self.assertNotIn("'w'", err.getvalue())
1561 self.assertNotIn("'pytho'", err.getvalue())
1562
1563 with self.subTest(name="py"):
1564 try:
1565 py
1566 except NameError as exc:
1567 with support.captured_stderr() as err:
1568 sys.__excepthook__(*sys.exc_info())
1569 self.assertNotIn("you mean", err.getvalue())
1570 self.assertNotIn("vvv", err.getvalue())
1571 self.assertNotIn("mom", err.getvalue())
1572 self.assertNotIn("'id'", err.getvalue())
1573 self.assertNotIn("'w'", err.getvalue())
1574 self.assertNotIn("'pytho'", err.getvalue())
1575
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001576 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001577 def f():
1578 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001579 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1580 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1581 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1582 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1583 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1584 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1585 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1586 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1587 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1588 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1589 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1590 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1591 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1592 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1593 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1594 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1595 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1596 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1597 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1598 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1599 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1600 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1601 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1602 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1603 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1604 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1605 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1606 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1607 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1608 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1609 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1610 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1611 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1612 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1613 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1614 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1615 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1616 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1617 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1618 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1619 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1620 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1621 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1622 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1623 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1624 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1625 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1626 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1627 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1628 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1629 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1630 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1631 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1632 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1633 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1634 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1635 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1636 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1637 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1638 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1639 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1640 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1641 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1642 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1643 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1644 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1645 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1646 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1647 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1648 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1649 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1650 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1651 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1652 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1653 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1654 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1655 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1656 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1657 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1658 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1659 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001660 print(a0)
1661
1662 try:
1663 f()
1664 except NameError as exc:
1665 with support.captured_stderr() as err:
1666 sys.__excepthook__(*sys.exc_info())
1667
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001668 self.assertNotIn("a1", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001669
1670 def test_name_error_with_custom_exceptions(self):
1671 def f():
1672 blech = None
1673 raise NameError()
1674
1675 try:
1676 f()
1677 except NameError as exc:
1678 with support.captured_stderr() as err:
1679 sys.__excepthook__(*sys.exc_info())
1680
1681 self.assertNotIn("blech", err.getvalue())
1682
1683 def f():
1684 blech = None
1685 raise NameError
1686
1687 try:
1688 f()
1689 except NameError as exc:
1690 with support.captured_stderr() as err:
1691 sys.__excepthook__(*sys.exc_info())
1692
1693 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001694
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001695 def test_unbound_local_error_doesn_not_match(self):
1696 def foo():
1697 something = 3
1698 print(somethong)
1699 somethong = 3
1700
1701 try:
1702 foo()
1703 except UnboundLocalError as exc:
1704 with support.captured_stderr() as err:
1705 sys.__excepthook__(*sys.exc_info())
1706
1707 self.assertNotIn("something", err.getvalue())
1708
1709
Pablo Galindo37494b42021-04-14 02:36:07 +01001710class AttributeErrorTests(unittest.TestCase):
1711 def test_attributes(self):
1712 # Setting 'attr' should not be a problem.
1713 exc = AttributeError('Ouch!')
1714 self.assertIsNone(exc.name)
1715 self.assertIsNone(exc.obj)
1716
1717 sentinel = object()
1718 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1719 self.assertEqual(exc.name, 'carry')
1720 self.assertIs(exc.obj, sentinel)
1721
1722 def test_getattr_has_name_and_obj(self):
1723 class A:
1724 blech = None
1725
1726 obj = A()
1727 try:
1728 obj.bluch
1729 except AttributeError as exc:
1730 self.assertEqual("bluch", exc.name)
1731 self.assertEqual(obj, exc.obj)
1732
1733 def test_getattr_has_name_and_obj_for_method(self):
1734 class A:
1735 def blech(self):
1736 return
1737
1738 obj = A()
1739 try:
1740 obj.bluch()
1741 except AttributeError as exc:
1742 self.assertEqual("bluch", exc.name)
1743 self.assertEqual(obj, exc.obj)
1744
1745 def test_getattr_suggestions(self):
1746 class Substitution:
1747 noise = more_noise = a = bc = None
1748 blech = None
1749
1750 class Elimination:
1751 noise = more_noise = a = bc = None
1752 blch = None
1753
1754 class Addition:
1755 noise = more_noise = a = bc = None
1756 bluchin = None
1757
1758 class SubstitutionOverElimination:
1759 blach = None
1760 bluc = None
1761
1762 class SubstitutionOverAddition:
1763 blach = None
1764 bluchi = None
1765
1766 class EliminationOverAddition:
1767 blucha = None
1768 bluc = None
1769
Pablo Galindo7a041162021-04-19 23:35:53 +01001770 for cls, suggestion in [(Substitution, "'blech'?"),
1771 (Elimination, "'blch'?"),
1772 (Addition, "'bluchin'?"),
1773 (EliminationOverAddition, "'bluc'?"),
1774 (SubstitutionOverElimination, "'blach'?"),
1775 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001776 try:
1777 cls().bluch
1778 except AttributeError as exc:
1779 with support.captured_stderr() as err:
1780 sys.__excepthook__(*sys.exc_info())
1781
1782 self.assertIn(suggestion, err.getvalue())
1783
1784 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1785 class A:
1786 blech = None
1787
1788 try:
1789 A().somethingverywrong
1790 except AttributeError as exc:
1791 with support.captured_stderr() as err:
1792 sys.__excepthook__(*sys.exc_info())
1793
1794 self.assertNotIn("blech", err.getvalue())
1795
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001796 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
1797 class MyClass:
1798 vvv = mom = w = id = pytho = None
1799
1800 with self.subTest(name="b"):
1801 try:
1802 MyClass.b
1803 except AttributeError as exc:
1804 with support.captured_stderr() as err:
1805 sys.__excepthook__(*sys.exc_info())
1806 self.assertNotIn("you mean", err.getvalue())
1807 self.assertNotIn("vvv", err.getvalue())
1808 self.assertNotIn("mom", err.getvalue())
1809 self.assertNotIn("'id'", err.getvalue())
1810 self.assertNotIn("'w'", err.getvalue())
1811 self.assertNotIn("'pytho'", err.getvalue())
1812
1813 with self.subTest(name="v"):
1814 try:
1815 MyClass.v
1816 except AttributeError as exc:
1817 with support.captured_stderr() as err:
1818 sys.__excepthook__(*sys.exc_info())
1819 self.assertNotIn("you mean", err.getvalue())
1820 self.assertNotIn("vvv", err.getvalue())
1821 self.assertNotIn("mom", err.getvalue())
1822 self.assertNotIn("'id'", err.getvalue())
1823 self.assertNotIn("'w'", err.getvalue())
1824 self.assertNotIn("'pytho'", err.getvalue())
1825
1826 with self.subTest(name="m"):
1827 try:
1828 MyClass.m
1829 except AttributeError as exc:
1830 with support.captured_stderr() as err:
1831 sys.__excepthook__(*sys.exc_info())
1832 self.assertNotIn("you mean", err.getvalue())
1833 self.assertNotIn("vvv", err.getvalue())
1834 self.assertNotIn("mom", err.getvalue())
1835 self.assertNotIn("'id'", err.getvalue())
1836 self.assertNotIn("'w'", err.getvalue())
1837 self.assertNotIn("'pytho'", err.getvalue())
1838
1839 with self.subTest(name="py"):
1840 try:
1841 MyClass.py
1842 except AttributeError as exc:
1843 with support.captured_stderr() as err:
1844 sys.__excepthook__(*sys.exc_info())
1845 self.assertNotIn("you mean", err.getvalue())
1846 self.assertNotIn("vvv", err.getvalue())
1847 self.assertNotIn("mom", err.getvalue())
1848 self.assertNotIn("'id'", err.getvalue())
1849 self.assertNotIn("'w'", err.getvalue())
1850 self.assertNotIn("'pytho'", err.getvalue())
1851
1852
Pablo Galindo37494b42021-04-14 02:36:07 +01001853 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
1854 class A:
1855 blech = None
1856 # A class with a very big __dict__ will not be consider
1857 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001858 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01001859 setattr(A, f"index_{index}", None)
1860
1861 try:
1862 A().bluch
1863 except AttributeError as exc:
1864 with support.captured_stderr() as err:
1865 sys.__excepthook__(*sys.exc_info())
1866
1867 self.assertNotIn("blech", err.getvalue())
1868
1869 def test_getattr_suggestions_no_args(self):
1870 class A:
1871 blech = None
1872 def __getattr__(self, attr):
1873 raise AttributeError()
1874
1875 try:
1876 A().bluch
1877 except AttributeError as exc:
1878 with support.captured_stderr() as err:
1879 sys.__excepthook__(*sys.exc_info())
1880
1881 self.assertIn("blech", err.getvalue())
1882
1883 class A:
1884 blech = None
1885 def __getattr__(self, attr):
1886 raise AttributeError
1887
1888 try:
1889 A().bluch
1890 except AttributeError as exc:
1891 with support.captured_stderr() as err:
1892 sys.__excepthook__(*sys.exc_info())
1893
1894 self.assertIn("blech", err.getvalue())
1895
1896 def test_getattr_suggestions_invalid_args(self):
1897 class NonStringifyClass:
1898 __str__ = None
1899 __repr__ = None
1900
1901 class A:
1902 blech = None
1903 def __getattr__(self, attr):
1904 raise AttributeError(NonStringifyClass())
1905
1906 class B:
1907 blech = None
1908 def __getattr__(self, attr):
1909 raise AttributeError("Error", 23)
1910
1911 class C:
1912 blech = None
1913 def __getattr__(self, attr):
1914 raise AttributeError(23)
1915
1916 for cls in [A, B, C]:
1917 try:
1918 cls().bluch
1919 except AttributeError as exc:
1920 with support.captured_stderr() as err:
1921 sys.__excepthook__(*sys.exc_info())
1922
1923 self.assertIn("blech", err.getvalue())
1924
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07001925 def test_getattr_suggestions_for_same_name(self):
1926 class A:
1927 def __dir__(self):
1928 return ['blech']
1929 try:
1930 A().blech
1931 except AttributeError as exc:
1932 with support.captured_stderr() as err:
1933 sys.__excepthook__(*sys.exc_info())
1934
1935 self.assertNotIn("Did you mean", err.getvalue())
1936
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01001937 def test_attribute_error_with_failing_dict(self):
1938 class T:
1939 bluch = 1
1940 def __dir__(self):
1941 raise AttributeError("oh no!")
1942
1943 try:
1944 T().blich
1945 except AttributeError as exc:
1946 with support.captured_stderr() as err:
1947 sys.__excepthook__(*sys.exc_info())
1948
1949 self.assertNotIn("blech", err.getvalue())
1950 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01001951
Pablo Galindo0b1c1692021-04-17 23:28:45 +01001952 def test_attribute_error_with_bad_name(self):
1953 try:
1954 raise AttributeError(name=12, obj=23)
1955 except AttributeError as exc:
1956 with support.captured_stderr() as err:
1957 sys.__excepthook__(*sys.exc_info())
1958
1959 self.assertNotIn("?", err.getvalue())
1960
1961
Brett Cannon79ec55e2012-04-12 20:24:54 -04001962class ImportErrorTests(unittest.TestCase):
1963
1964 def test_attributes(self):
1965 # Setting 'name' and 'path' should not be a problem.
1966 exc = ImportError('test')
1967 self.assertIsNone(exc.name)
1968 self.assertIsNone(exc.path)
1969
1970 exc = ImportError('test', name='somemodule')
1971 self.assertEqual(exc.name, 'somemodule')
1972 self.assertIsNone(exc.path)
1973
1974 exc = ImportError('test', path='somepath')
1975 self.assertEqual(exc.path, 'somepath')
1976 self.assertIsNone(exc.name)
1977
1978 exc = ImportError('test', path='somepath', name='somename')
1979 self.assertEqual(exc.name, 'somename')
1980 self.assertEqual(exc.path, 'somepath')
1981
Michael Seifert64c8f702017-04-09 09:47:12 +02001982 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001983 with self.assertRaisesRegex(TypeError, msg):
1984 ImportError('test', invalid='keyword')
1985
1986 with self.assertRaisesRegex(TypeError, msg):
1987 ImportError('test', name='name', invalid='keyword')
1988
1989 with self.assertRaisesRegex(TypeError, msg):
1990 ImportError('test', path='path', invalid='keyword')
1991
1992 with self.assertRaisesRegex(TypeError, msg):
1993 ImportError(invalid='keyword')
1994
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001995 with self.assertRaisesRegex(TypeError, msg):
1996 ImportError('test', invalid='keyword', another=True)
1997
Serhiy Storchakae9e44482016-09-28 07:53:32 +03001998 def test_reset_attributes(self):
1999 exc = ImportError('test', name='name', path='path')
2000 self.assertEqual(exc.args, ('test',))
2001 self.assertEqual(exc.msg, 'test')
2002 self.assertEqual(exc.name, 'name')
2003 self.assertEqual(exc.path, 'path')
2004
2005 # Reset not specified attributes
2006 exc.__init__()
2007 self.assertEqual(exc.args, ())
2008 self.assertEqual(exc.msg, None)
2009 self.assertEqual(exc.name, None)
2010 self.assertEqual(exc.path, None)
2011
Brett Cannon07c6e712012-08-24 13:05:09 -04002012 def test_non_str_argument(self):
2013 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002014 with check_warnings(('', BytesWarning), quiet=True):
2015 arg = b'abc'
2016 exc = ImportError(arg)
2017 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002018
Serhiy Storchakab7853962017-04-08 09:55:07 +03002019 def test_copy_pickle(self):
2020 for kwargs in (dict(),
2021 dict(name='somename'),
2022 dict(path='somepath'),
2023 dict(name='somename', path='somepath')):
2024 orig = ImportError('test', **kwargs)
2025 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2026 exc = pickle.loads(pickle.dumps(orig, proto))
2027 self.assertEqual(exc.args, ('test',))
2028 self.assertEqual(exc.msg, 'test')
2029 self.assertEqual(exc.name, orig.name)
2030 self.assertEqual(exc.path, orig.path)
2031 for c in copy.copy, copy.deepcopy:
2032 exc = c(orig)
2033 self.assertEqual(exc.args, ('test',))
2034 self.assertEqual(exc.msg, 'test')
2035 self.assertEqual(exc.name, orig.name)
2036 self.assertEqual(exc.path, orig.path)
2037
Pablo Galindoa77aac42021-04-23 14:27:05 +01002038class SyntaxErrorTests(unittest.TestCase):
2039 def test_range_of_offsets(self):
2040 cases = [
2041 # Basic range from 2->7
2042 (("bad.py", 1, 2, "abcdefg", 1, 7),
2043 dedent(
2044 """
2045 File "bad.py", line 1
2046 abcdefg
2047 ^^^^^
2048 SyntaxError: bad bad
2049 """)),
2050 # end_offset = start_offset + 1
2051 (("bad.py", 1, 2, "abcdefg", 1, 3),
2052 dedent(
2053 """
2054 File "bad.py", line 1
2055 abcdefg
2056 ^
2057 SyntaxError: bad bad
2058 """)),
2059 # Negative end offset
2060 (("bad.py", 1, 2, "abcdefg", 1, -2),
2061 dedent(
2062 """
2063 File "bad.py", line 1
2064 abcdefg
2065 ^
2066 SyntaxError: bad bad
2067 """)),
2068 # end offset before starting offset
2069 (("bad.py", 1, 4, "abcdefg", 1, 2),
2070 dedent(
2071 """
2072 File "bad.py", line 1
2073 abcdefg
2074 ^
2075 SyntaxError: bad bad
2076 """)),
2077 # Both offsets negative
2078 (("bad.py", 1, -4, "abcdefg", 1, -2),
2079 dedent(
2080 """
2081 File "bad.py", line 1
2082 abcdefg
2083 SyntaxError: bad bad
2084 """)),
2085 # Both offsets negative and the end more negative
2086 (("bad.py", 1, -4, "abcdefg", 1, -5),
2087 dedent(
2088 """
2089 File "bad.py", line 1
2090 abcdefg
2091 SyntaxError: bad bad
2092 """)),
2093 # Both offsets 0
2094 (("bad.py", 1, 0, "abcdefg", 1, 0),
2095 dedent(
2096 """
2097 File "bad.py", line 1
2098 abcdefg
2099 SyntaxError: bad bad
2100 """)),
2101 # Start offset 0 and end offset not 0
2102 (("bad.py", 1, 0, "abcdefg", 1, 5),
2103 dedent(
2104 """
2105 File "bad.py", line 1
2106 abcdefg
2107 SyntaxError: bad bad
2108 """)),
2109 # End offset pass the source lenght
2110 (("bad.py", 1, 2, "abcdefg", 1, 100),
2111 dedent(
2112 """
2113 File "bad.py", line 1
2114 abcdefg
2115 ^^^^^^
2116 SyntaxError: bad bad
2117 """)),
2118 ]
2119 for args, expected in cases:
2120 with self.subTest(args=args):
2121 try:
2122 raise SyntaxError("bad bad", args)
2123 except SyntaxError as exc:
2124 with support.captured_stderr() as err:
2125 sys.__excepthook__(*sys.exc_info())
2126 the_exception = exc
2127
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002128 def test_encodings(self):
2129 source = (
2130 '# -*- coding: cp437 -*-\n'
2131 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2132 )
2133 try:
2134 with open(TESTFN, 'w', encoding='cp437') as testfile:
2135 testfile.write(source)
2136 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2137 err = err.decode('utf-8').splitlines()
2138
2139 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2140 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2141 finally:
2142 unlink(TESTFN)
2143
Pablo Galindoa77aac42021-04-23 14:27:05 +01002144 def test_attributes_new_constructor(self):
2145 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2146 the_exception = SyntaxError("bad bad", args)
2147 filename, lineno, offset, error, end_lineno, end_offset = args
2148 self.assertEqual(filename, the_exception.filename)
2149 self.assertEqual(lineno, the_exception.lineno)
2150 self.assertEqual(end_lineno, the_exception.end_lineno)
2151 self.assertEqual(offset, the_exception.offset)
2152 self.assertEqual(end_offset, the_exception.end_offset)
2153 self.assertEqual(error, the_exception.text)
2154 self.assertEqual("bad bad", the_exception.msg)
2155
2156 def test_attributes_old_constructor(self):
2157 args = ("bad.py", 1, 2, "abcdefg")
2158 the_exception = SyntaxError("bad bad", args)
2159 filename, lineno, offset, error = args
2160 self.assertEqual(filename, the_exception.filename)
2161 self.assertEqual(lineno, the_exception.lineno)
2162 self.assertEqual(None, the_exception.end_lineno)
2163 self.assertEqual(offset, the_exception.offset)
2164 self.assertEqual(None, the_exception.end_offset)
2165 self.assertEqual(error, the_exception.text)
2166 self.assertEqual("bad bad", the_exception.msg)
2167
2168 def test_incorrect_constructor(self):
2169 args = ("bad.py", 1, 2)
2170 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2171
2172 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2173 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2174
2175 args = ("bad.py", 1, 2, "abcdefg", 1)
2176 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2177
Brett Cannon79ec55e2012-04-12 20:24:54 -04002178
Mark Shannonbf353f32020-12-17 13:55:28 +00002179class PEP626Tests(unittest.TestCase):
2180
Mark Shannon0b6b2862021-06-24 13:09:14 +01002181 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002182 try:
2183 f()
2184 except Exception as ex:
2185 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002186 else:
2187 self.fail("No exception raised")
2188 lines = []
2189 t = t.tb_next # Skip this function
2190 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002191 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002192 lines.append(
2193 None if frame.f_lineno is None else
2194 frame.f_lineno-frame.f_code.co_firstlineno
2195 )
2196 t = t.tb_next
2197 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002198
2199 def test_lineno_after_raise_simple(self):
2200 def simple():
2201 1/0
2202 pass
2203 self.lineno_after_raise(simple, 1)
2204
2205 def test_lineno_after_raise_in_except(self):
2206 def in_except():
2207 try:
2208 1/0
2209 except:
2210 1/0
2211 pass
2212 self.lineno_after_raise(in_except, 4)
2213
2214 def test_lineno_after_other_except(self):
2215 def other_except():
2216 try:
2217 1/0
2218 except TypeError as ex:
2219 pass
2220 self.lineno_after_raise(other_except, 3)
2221
2222 def test_lineno_in_named_except(self):
2223 def in_named_except():
2224 try:
2225 1/0
2226 except Exception as ex:
2227 1/0
2228 pass
2229 self.lineno_after_raise(in_named_except, 4)
2230
2231 def test_lineno_in_try(self):
2232 def in_try():
2233 try:
2234 1/0
2235 finally:
2236 pass
2237 self.lineno_after_raise(in_try, 4)
2238
2239 def test_lineno_in_finally_normal(self):
2240 def in_finally_normal():
2241 try:
2242 pass
2243 finally:
2244 1/0
2245 pass
2246 self.lineno_after_raise(in_finally_normal, 4)
2247
2248 def test_lineno_in_finally_except(self):
2249 def in_finally_except():
2250 try:
2251 1/0
2252 finally:
2253 1/0
2254 pass
2255 self.lineno_after_raise(in_finally_except, 4)
2256
2257 def test_lineno_after_with(self):
2258 class Noop:
2259 def __enter__(self):
2260 return self
2261 def __exit__(self, *args):
2262 pass
2263 def after_with():
2264 with Noop():
2265 1/0
2266 pass
2267 self.lineno_after_raise(after_with, 2)
2268
Mark Shannon088a15c2021-04-29 19:28:50 +01002269 def test_missing_lineno_shows_as_none(self):
2270 def f():
2271 1/0
2272 self.lineno_after_raise(f, 1)
2273 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2274 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002275
Mark Shannon0b6b2862021-06-24 13:09:14 +01002276 def test_lineno_after_raise_in_with_exit(self):
2277 class ExitFails:
2278 def __enter__(self):
2279 return self
2280 def __exit__(self, *args):
2281 raise ValueError
2282
2283 def after_with():
2284 with ExitFails():
2285 1/0
2286 self.lineno_after_raise(after_with, 1, 1)
2287
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002288if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002289 unittest.main()