blob: f92637f9930bfd8a27deecf8f2d43dd7590bbbd9 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Serhiy Storchakab7853962017-04-08 09:55:07 +03003import copy
Pablo Galindo9b648a92020-09-01 19:39:46 +01004import gc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005import os
6import sys
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00007import unittest
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00008import pickle
Barry Warsaw8d109cb2008-05-08 04:26:35 +00009import weakref
Antoine Pitroua7622852011-09-01 21:37:43 +020010import errno
Pablo Galindoa77aac42021-04-23 14:27:05 +010011from textwrap import dedent
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000012
Hai Shi46605972020-08-04 00:49:18 +080013from test.support import (captured_stderr, check_impl_detail,
14 cpython_only, gc_collect,
15 no_tracing, script_helper,
xdegaye56d1f5c2017-10-26 15:09:06 +020016 SuppressCrashReport)
Hai Shi46605972020-08-04 00:49:18 +080017from test.support.import_helper import import_module
18from test.support.os_helper import TESTFN, unlink
19from test.support.warnings_helper import check_warnings
Victor Stinnere4d300e2019-05-22 23:44:02 +020020from test import support
21
22
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010023class NaiveException(Exception):
24 def __init__(self, x):
25 self.x = x
26
27class SlottedNaiveException(Exception):
28 __slots__ = ('x',)
29 def __init__(self, x):
30 self.x = x
31
Martin Panter3263f682016-02-28 03:16:11 +000032class BrokenStrException(Exception):
33 def __str__(self):
34 raise Exception("str() is broken")
35
Guido van Rossum3bead091992-01-27 17:00:37 +000036# XXX This is not really enough, each *operation* should be tested!
37
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000038class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000039
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000040 def raise_catch(self, exc, excname):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +010041 with self.subTest(exc=exc, excname=excname):
42 try:
43 raise exc("spam")
44 except exc as err:
45 buf1 = str(err)
46 try:
47 raise exc("spam")
48 except exc as err:
49 buf2 = str(err)
50 self.assertEqual(buf1, buf2)
51 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000052
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000053 def testRaising(self):
54 self.raise_catch(AttributeError, "AttributeError")
55 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000056
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000057 self.raise_catch(EOFError, "EOFError")
Inada Naoki8bbfeb32021-04-02 12:53:46 +090058 fp = open(TESTFN, 'w', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 fp.close()
Inada Naoki8bbfeb32021-04-02 12:53:46 +090060 fp = open(TESTFN, 'r', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000061 savestdin = sys.stdin
62 try:
63 try:
64 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010065 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 except EOFError:
67 pass
68 finally:
69 sys.stdin = savestdin
70 fp.close()
71 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020073 self.raise_catch(OSError, "OSError")
74 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000075
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000076 self.raise_catch(ImportError, "ImportError")
77 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000078
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000079 self.raise_catch(IndexError, "IndexError")
80 x = []
81 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(KeyError, "KeyError")
84 x = {}
85 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000087 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 self.raise_catch(NameError, "NameError")
92 try: x = undefined_variable
93 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000094
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000095 self.raise_catch(OverflowError, "OverflowError")
96 x = 1
97 for dummy in range(128):
98 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.raise_catch(RuntimeError, "RuntimeError")
Yury Selivanovf488fb42015-07-03 01:04:23 -0400101 self.raise_catch(RecursionError, "RecursionError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +0000104 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000105 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000106
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000107 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +0000110 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
111 '<string>', 'exec')
112 except TabError: pass
113 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000114
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000115 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000116
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117 self.raise_catch(SystemExit, "SystemExit")
118 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000119
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120 self.raise_catch(TypeError, "TypeError")
121 try: [] + ()
122 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000123
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000125 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000127 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
128 try: x = 1/0
129 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000130
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131 self.raise_catch(Exception, "Exception")
132 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000133 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000134
Yury Selivanovccc897f2015-07-03 01:16:04 -0400135 self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
136
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 def testSyntaxErrorMessage(self):
138 # make sure the right exception message is raised for each of
139 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141 def ckmsg(src, msg):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100142 with self.subTest(src=src, msg=msg):
143 try:
144 compile(src, '<fragment>', 'exec')
145 except SyntaxError as e:
146 if e.msg != msg:
147 self.fail("expected %s, got %s" % (msg, e.msg))
148 else:
149 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000150
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000151 s = '''if 1:
152 try:
153 continue
154 except:
155 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000156
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157 ckmsg(s, "'continue' not properly in loop")
158 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000159
Martijn Pieters772d8092017-08-22 21:16:23 +0100160 def testSyntaxErrorMissingParens(self):
161 def ckmsg(src, msg, exception=SyntaxError):
162 try:
163 compile(src, '<fragment>', 'exec')
164 except exception as e:
165 if e.msg != msg:
166 self.fail("expected %s, got %s" % (msg, e.msg))
167 else:
168 self.fail("failed to get expected SyntaxError")
169
170 s = '''print "old style"'''
171 ckmsg(s, "Missing parentheses in call to 'print'. "
172 "Did you mean print(\"old style\")?")
173
174 s = '''print "old style",'''
175 ckmsg(s, "Missing parentheses in call to 'print'. "
176 "Did you mean print(\"old style\", end=\" \")?")
177
178 s = '''exec "old style"'''
179 ckmsg(s, "Missing parentheses in call to 'exec'")
180
181 # should not apply to subclasses, see issue #31161
182 s = '''if True:\nprint "No indent"'''
Pablo Galindo56c95df2021-04-21 15:28:21 +0100183 ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
Martijn Pieters772d8092017-08-22 21:16:23 +0100184
185 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
186 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
187
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300188 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100189 with self.subTest(source=src, lineno=lineno, offset=offset):
190 with self.assertRaises(SyntaxError) as cm:
191 compile(src, '<fragment>', 'exec')
192 self.assertEqual(cm.exception.lineno, lineno)
193 self.assertEqual(cm.exception.offset, offset)
194 if cm.exception.text is not None:
195 if not isinstance(src, str):
196 src = src.decode(encoding, 'replace')
197 line = src.split('\n')[lineno-1]
198 self.assertIn(line, cm.exception.text)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200199
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300200 def testSyntaxErrorOffset(self):
201 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200202 check('def fact(x):\n\treturn x!\n', 2, 10)
203 check('1 +\n', 1, 4)
204 check('def spam():\n print(1)\n print(2)', 3, 10)
205 check('Python = "Python" +', 1, 20)
206 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200207 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
208 2, 19, encoding='cp1251')
209 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300210 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400211 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200212 check('f{a + b + c}', 1, 2)
Miss Islington (bot)756b7b92021-05-03 18:06:45 -0700213 check('[file for str(file) in []\n])', 2, 2)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700214 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200215 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
216 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700217 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700218 check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
Ammar Askar025eb982018-09-24 17:12:49 -0400219
220 # Errors thrown by compile.c
221 check('class foo:return 1', 1, 11)
222 check('def f():\n continue', 2, 3)
223 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100224 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400225
226 # Errors thrown by tokenizer.c
227 check('(0x+1)', 1, 3)
228 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700229 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400230 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700231 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200232 check('\u03b1 = 0xI', 1, 6)
233 check(b'\xce\xb1 = 0xI', 1, 6)
234 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
235 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100236 check(b"""if 1:
237 def foo():
238 '''
239
240 def bar():
241 pass
242
243 def baz():
244 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300245 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100246 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
247 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700248 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700249 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400250
251 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200252 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400253 check('def f():\n from _ import *', 1, 1)
254 check('def f(x, x):\n pass', 1, 1)
255 check('def f(x):\n nonlocal x', 2, 3)
256 check('def f(x):\n x = 1\n global x', 3, 3)
257 check('nonlocal x', 1, 1)
258 check('def f():\n global x\n nonlocal x', 2, 3)
259
Ammar Askar025eb982018-09-24 17:12:49 -0400260 # Errors thrown by future.c
261 check('from __future__ import doesnt_exist', 1, 1)
262 check('from __future__ import braces', 1, 1)
263 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100264 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300265 check('def f():\n x, y: int', 2, 3)
266 check('[*x for x in xs]', 1, 2)
267 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300268 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100269 check('(yield i) = 2', 1, 2)
270 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200271
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000272 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000273 def testSettingException(self):
274 # test that setting an exception at the C level works even if the
275 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000276
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000277 class BadException(Exception):
278 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000279 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000280
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000281 class InvalidException:
282 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000283
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000284 def test_capi1():
285 import _testcapi
286 try:
287 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000288 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000289 exc, err, tb = sys.exc_info()
290 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000291 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000292 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000293 else:
294 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000295
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000296 def test_capi2():
297 import _testcapi
298 try:
299 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000300 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000301 exc, err, tb = sys.exc_info()
302 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000303 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000304 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000305 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000306 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000307 else:
308 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000309
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000310 def test_capi3():
311 import _testcapi
312 self.assertRaises(SystemError, _testcapi.raise_exception,
313 InvalidException, 1)
314
315 if not sys.platform.startswith('java'):
316 test_capi1()
317 test_capi2()
318 test_capi3()
319
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 def test_WindowsError(self):
321 try:
322 WindowsError
323 except NameError:
324 pass
325 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200326 self.assertIs(WindowsError, OSError)
327 self.assertEqual(str(OSError(1001)), "1001")
328 self.assertEqual(str(OSError(1001, "message")),
329 "[Errno 1001] message")
330 # POSIX errno (9 aka EBADF) is untranslated
331 w = OSError(9, 'foo', 'bar')
332 self.assertEqual(w.errno, 9)
333 self.assertEqual(w.winerror, None)
334 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
335 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
336 w = OSError(0, 'foo', 'bar', 3)
337 self.assertEqual(w.errno, 2)
338 self.assertEqual(w.winerror, 3)
339 self.assertEqual(w.strerror, 'foo')
340 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000341 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100342 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200343 # Unknown win error becomes EINVAL (22)
344 w = OSError(0, 'foo', None, 1001)
345 self.assertEqual(w.errno, 22)
346 self.assertEqual(w.winerror, 1001)
347 self.assertEqual(w.strerror, 'foo')
348 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000349 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100350 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200351 # Non-numeric "errno"
352 w = OSError('bar', 'foo')
353 self.assertEqual(w.errno, 'bar')
354 self.assertEqual(w.winerror, None)
355 self.assertEqual(w.strerror, 'foo')
356 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000357 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358
Victor Stinnerd223fa62015-04-02 14:17:38 +0200359 @unittest.skipUnless(sys.platform == 'win32',
360 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300361 def test_windows_message(self):
362 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200363 ctypes = import_module('ctypes')
364 # this error code has no message, Python formats it as hexadecimal
365 code = 3765269347
366 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
367 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300368
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000369 def testAttributes(self):
370 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000371
372 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000373 (BaseException, (), {'args' : ()}),
374 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000375 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000376 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000377 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000378 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000379 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000380 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200381 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000382 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200384 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000385 {'args' : ('foo', 'bar'),
386 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000387 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200388 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000389 {'args' : ('foo', 'bar'),
390 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000391 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800392 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
393 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200394 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000395 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000396 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
397 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200398 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000399 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000400 'strerror' : 'strErrorStr',
401 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000402 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100404 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000405 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000406 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000407 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100408 'filename' : None, 'lineno' : None, 'offset' : None,
409 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000410 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100411 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000412 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000413 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100414 'offsetStr', 'textStr',
415 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000416 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100417 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
418 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000419 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100420 'textStr', 'endLinenoStr', 'endOffsetStr',
421 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000422 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000423 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100424 'textStr', 'endLinenoStr', 'endOffsetStr',
425 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000426 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100427 'filename' : None, 'lineno' : None, 'offset' : None,
428 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000429 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000430 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
431 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000432 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000434 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000435 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000436 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000437 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000438 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000439 'ordinal not in range'),
440 'encoding' : 'ascii', 'object' : b'\xff',
441 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000442 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
443 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000444 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000446 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000448 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000449 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000450 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000451 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100452 (NaiveException, ('foo',),
453 {'args': ('foo',), 'x': 'foo'}),
454 (SlottedNaiveException, ('foo',),
455 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000457 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200458 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000459 exceptionList.append(
460 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000461 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200462 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000463 'errno' : 1,
464 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000465 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000466 except NameError:
467 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000468
Guido van Rossumebe3e162007-05-17 18:20:34 +0000469 for exc, args, expected in exceptionList:
470 try:
471 e = exc(*args)
472 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000473 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100474 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000475 else:
476 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100477 if not type(e).__name__.endswith('NaiveException'):
478 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000479 # Verify no ref leaks in Exc_str()
480 s = str(e)
481 for checkArgName in expected:
482 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000483 self.assertEqual(repr(value),
484 repr(expected[checkArgName]),
485 '%r.%s == %r, expected %r' % (
486 e, checkArgName,
487 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000488
Guido van Rossumebe3e162007-05-17 18:20:34 +0000489 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000490 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000491 for protocol in range(p.HIGHEST_PROTOCOL + 1):
492 s = p.dumps(e, protocol)
493 new = p.loads(s)
494 for checkArgName in expected:
495 got = repr(getattr(new, checkArgName))
496 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000497 self.assertEqual(got, want,
498 'pickled "%r", attribute "%s' %
499 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000500
Collin Winter828f04a2007-08-31 00:04:24 +0000501 def testWithTraceback(self):
502 try:
503 raise IndexError(4)
504 except:
505 tb = sys.exc_info()[2]
506
507 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000508 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000509 self.assertEqual(e.__traceback__, tb)
510
511 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000512 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000513 self.assertEqual(e.__traceback__, tb)
514
515 class MyException(Exception):
516 pass
517
518 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000519 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000520 self.assertEqual(e.__traceback__, tb)
521
522 def testInvalidTraceback(self):
523 try:
524 Exception().__traceback__ = 5
525 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000526 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000527 else:
528 self.fail("No exception raised")
529
Georg Brandlab6f2f62009-03-31 04:16:10 +0000530 def testInvalidAttrs(self):
531 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
532 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
533 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
534 self.assertRaises(TypeError, delattr, Exception(), '__context__')
535
Collin Winter828f04a2007-08-31 00:04:24 +0000536 def testNoneClearsTracebackAttr(self):
537 try:
538 raise IndexError(4)
539 except:
540 tb = sys.exc_info()[2]
541
542 e = Exception()
543 e.__traceback__ = tb
544 e.__traceback__ = None
545 self.assertEqual(e.__traceback__, None)
546
547 def testChainingAttrs(self):
548 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000549 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700550 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000551
552 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000553 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700554 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000555
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200556 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000557 pass
558
559 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000560 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700561 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000562
563 def testChainingDescriptors(self):
564 try:
565 raise Exception()
566 except Exception as exc:
567 e = exc
568
569 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700570 self.assertIsNone(e.__cause__)
571 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000572
573 e.__context__ = NameError()
574 e.__cause__ = None
575 self.assertIsInstance(e.__context__, NameError)
576 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700577 self.assertTrue(e.__suppress_context__)
578 e.__suppress_context__ = False
579 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000580
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000581 def testKeywordArgs(self):
582 # test that builtin exception don't take keyword args,
583 # but user-defined subclasses can if they want
584 self.assertRaises(TypeError, BaseException, a=1)
585
586 class DerivedException(BaseException):
587 def __init__(self, fancy_arg):
588 BaseException.__init__(self)
589 self.fancy_arg = fancy_arg
590
591 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000592 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000593
Brett Cannon31f59292011-02-21 19:29:56 +0000594 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595 def testInfiniteRecursion(self):
596 def f():
597 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400598 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599
600 def g():
601 try:
602 return g()
603 except ValueError:
604 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400605 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000607 def test_str(self):
608 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000609 self.assertTrue(str(Exception))
610 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000611 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000613 def testExceptionCleanupNames(self):
614 # Make sure the local variable bound to the exception instance by
615 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000616 try:
617 raise Exception()
618 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000619 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000620 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000621 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000622
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000623 def testExceptionCleanupState(self):
624 # Make sure exception state is cleaned up as soon as the except
625 # block is left. See #2507
626
627 class MyException(Exception):
628 def __init__(self, obj):
629 self.obj = obj
630 class MyObj:
631 pass
632
633 def inner_raising_func():
634 # Create some references in exception value and traceback
635 local_ref = obj
636 raise MyException(obj)
637
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000638 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000639 obj = MyObj()
640 wr = weakref.ref(obj)
641 try:
642 inner_raising_func()
643 except MyException as e:
644 pass
645 obj = None
646 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300647 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000648
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000649 # Qualified "except" without "as"
650 obj = MyObj()
651 wr = weakref.ref(obj)
652 try:
653 inner_raising_func()
654 except MyException:
655 pass
656 obj = None
657 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300658 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000659
660 # Bare "except"
661 obj = MyObj()
662 wr = weakref.ref(obj)
663 try:
664 inner_raising_func()
665 except:
666 pass
667 obj = None
668 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300669 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000670
671 # "except" with premature block leave
672 obj = MyObj()
673 wr = weakref.ref(obj)
674 for i in [0]:
675 try:
676 inner_raising_func()
677 except:
678 break
679 obj = None
680 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300681 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000682
683 # "except" block raising another exception
684 obj = MyObj()
685 wr = weakref.ref(obj)
686 try:
687 try:
688 inner_raising_func()
689 except:
690 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000691 except KeyError as e:
692 # We want to test that the except block above got rid of
693 # the exception raised in inner_raising_func(), but it
694 # also ends up in the __context__ of the KeyError, so we
695 # must clear the latter manually for our test to succeed.
696 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000697 obj = None
698 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800699 # guarantee no ref cycles on CPython (don't gc_collect)
700 if check_impl_detail(cpython=False):
701 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300702 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000703
704 # Some complicated construct
705 obj = MyObj()
706 wr = weakref.ref(obj)
707 try:
708 inner_raising_func()
709 except MyException:
710 try:
711 try:
712 raise
713 finally:
714 raise
715 except MyException:
716 pass
717 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800718 if check_impl_detail(cpython=False):
719 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000720 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300721 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000722
723 # Inside an exception-silencing "with" block
724 class Context:
725 def __enter__(self):
726 return self
727 def __exit__ (self, exc_type, exc_value, exc_tb):
728 return True
729 obj = MyObj()
730 wr = weakref.ref(obj)
731 with Context():
732 inner_raising_func()
733 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800734 if check_impl_detail(cpython=False):
735 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000736 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300737 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000738
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000739 def test_exception_target_in_nested_scope(self):
740 # issue 4617: This used to raise a SyntaxError
741 # "can not delete variable 'e' referenced in nested scope"
742 def print_error():
743 e
744 try:
745 something
746 except Exception as e:
747 print_error()
748 # implicit "del e" here
749
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000750 def test_generator_leaking(self):
751 # Test that generator exception state doesn't leak into the calling
752 # frame
753 def yield_raise():
754 try:
755 raise KeyError("caught")
756 except KeyError:
757 yield sys.exc_info()[0]
758 yield sys.exc_info()[0]
759 yield sys.exc_info()[0]
760 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000761 self.assertEqual(next(g), KeyError)
762 self.assertEqual(sys.exc_info()[0], None)
763 self.assertEqual(next(g), KeyError)
764 self.assertEqual(sys.exc_info()[0], None)
765 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000766
767 # Same test, but inside an exception handler
768 try:
769 raise TypeError("foo")
770 except TypeError:
771 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000772 self.assertEqual(next(g), KeyError)
773 self.assertEqual(sys.exc_info()[0], TypeError)
774 self.assertEqual(next(g), KeyError)
775 self.assertEqual(sys.exc_info()[0], TypeError)
776 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000777 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000778 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779
Benjamin Peterson83195c32011-07-03 13:44:00 -0500780 def test_generator_leaking2(self):
781 # See issue 12475.
782 def g():
783 yield
784 try:
785 raise RuntimeError
786 except RuntimeError:
787 it = g()
788 next(it)
789 try:
790 next(it)
791 except StopIteration:
792 pass
793 self.assertEqual(sys.exc_info(), (None, None, None))
794
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100795 def test_generator_leaking3(self):
796 # See issue #23353. When gen.throw() is called, the caller's
797 # exception state should be save and restored.
798 def g():
799 try:
800 yield
801 except ZeroDivisionError:
802 yield sys.exc_info()[1]
803 it = g()
804 next(it)
805 try:
806 1/0
807 except ZeroDivisionError as e:
808 self.assertIs(sys.exc_info()[1], e)
809 gen_exc = it.throw(e)
810 self.assertIs(sys.exc_info()[1], e)
811 self.assertIs(gen_exc, e)
812 self.assertEqual(sys.exc_info(), (None, None, None))
813
814 def test_generator_leaking4(self):
815 # See issue #23353. When an exception is raised by a generator,
816 # the caller's exception state should still be restored.
817 def g():
818 try:
819 1/0
820 except ZeroDivisionError:
821 yield sys.exc_info()[0]
822 raise
823 it = g()
824 try:
825 raise TypeError
826 except TypeError:
827 # The caller's exception state (TypeError) is temporarily
828 # saved in the generator.
829 tp = next(it)
830 self.assertIs(tp, ZeroDivisionError)
831 try:
832 next(it)
833 # We can't check it immediately, but while next() returns
834 # with an exception, it shouldn't have restored the old
835 # exception state (TypeError).
836 except ZeroDivisionError as e:
837 self.assertIs(sys.exc_info()[1], e)
838 # We used to find TypeError here.
839 self.assertEqual(sys.exc_info(), (None, None, None))
840
Benjamin Petersonac913412011-07-03 16:25:11 -0500841 def test_generator_doesnt_retain_old_exc(self):
842 def g():
843 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
844 yield
845 self.assertEqual(sys.exc_info(), (None, None, None))
846 it = g()
847 try:
848 raise RuntimeError
849 except RuntimeError:
850 next(it)
851 self.assertRaises(StopIteration, next, it)
852
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000853 def test_generator_finalizing_and_exc_info(self):
854 # See #7173
855 def simple_gen():
856 yield 1
857 def run_gen():
858 gen = simple_gen()
859 try:
860 raise RuntimeError
861 except RuntimeError:
862 return next(gen)
863 run_gen()
864 gc_collect()
865 self.assertEqual(sys.exc_info(), (None, None, None))
866
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200867 def _check_generator_cleanup_exc_state(self, testfunc):
868 # Issue #12791: exception state is cleaned up as soon as a generator
869 # is closed (reference cycles are broken).
870 class MyException(Exception):
871 def __init__(self, obj):
872 self.obj = obj
873 class MyObj:
874 pass
875
876 def raising_gen():
877 try:
878 raise MyException(obj)
879 except MyException:
880 yield
881
882 obj = MyObj()
883 wr = weakref.ref(obj)
884 g = raising_gen()
885 next(g)
886 testfunc(g)
887 g = obj = None
888 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300889 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200890
891 def test_generator_throw_cleanup_exc_state(self):
892 def do_throw(g):
893 try:
894 g.throw(RuntimeError())
895 except RuntimeError:
896 pass
897 self._check_generator_cleanup_exc_state(do_throw)
898
899 def test_generator_close_cleanup_exc_state(self):
900 def do_close(g):
901 g.close()
902 self._check_generator_cleanup_exc_state(do_close)
903
904 def test_generator_del_cleanup_exc_state(self):
905 def do_del(g):
906 g = None
907 self._check_generator_cleanup_exc_state(do_del)
908
909 def test_generator_next_cleanup_exc_state(self):
910 def do_next(g):
911 try:
912 next(g)
913 except StopIteration:
914 pass
915 else:
916 self.fail("should have raised StopIteration")
917 self._check_generator_cleanup_exc_state(do_next)
918
919 def test_generator_send_cleanup_exc_state(self):
920 def do_send(g):
921 try:
922 g.send(None)
923 except StopIteration:
924 pass
925 else:
926 self.fail("should have raised StopIteration")
927 self._check_generator_cleanup_exc_state(do_send)
928
Benjamin Peterson27d63672008-06-15 20:09:12 +0000929 def test_3114(self):
930 # Bug #3114: in its destructor, MyObject retrieves a pointer to
931 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000932 class MyObject:
933 def __del__(self):
934 nonlocal e
935 e = sys.exc_info()
936 e = ()
937 try:
938 raise Exception(MyObject())
939 except:
940 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000941 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000942
Benjamin Peterson24dfb052014-04-02 12:05:35 -0400943 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +0000944 # See issue 7309. This was a crasher.
945
946 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
947 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
948 u.end = 2
949 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
950 u.end = 5
951 u.reason = 0x345345345345345345
952 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
953 u.encoding = 4000
954 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
955 u.start = 1000
956 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
957
958 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
959 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
960 u.end = 2
961 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
962 u.end = 5
963 u.reason = 0x345345345345345345
964 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
965 u.encoding = 4000
966 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
967 u.start = 1000
968 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
969
970 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
971 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
972 u.end = 2
973 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
974 u.end = 5
975 u.reason = 0x345345345345345345
976 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
977 u.start = 1000
978 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000979
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400980 def test_unicode_errors_no_object(self):
981 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -0400982 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400983 for klass in klasses:
984 self.assertEqual(str(klass.__new__(klass)), "")
985
Brett Cannon31f59292011-02-21 19:29:56 +0000986 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000987 def test_badisinstance(self):
988 # Bug #2542: if issubclass(e, MyException) raises an exception,
989 # it should be ignored
990 class Meta(type):
991 def __subclasscheck__(cls, subclass):
992 raise ValueError()
993 class MyException(Exception, metaclass=Meta):
994 pass
995
Martin Panter3263f682016-02-28 03:16:11 +0000996 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000997 try:
998 raise KeyError()
999 except MyException as e:
1000 self.fail("exception should not be a MyException")
1001 except KeyError:
1002 pass
1003 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001004 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001005 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001006 self.fail("Should have raised KeyError")
1007
1008 def g():
1009 try:
1010 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001011 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001012 return sys.exc_info()
1013 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001014 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001015 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001016
xdegaye56d1f5c2017-10-26 15:09:06 +02001017 @cpython_only
1018 def test_recursion_normalizing_exception(self):
1019 # Issue #22898.
1020 # Test that a RecursionError is raised when tstate->recursion_depth is
1021 # equal to recursion_limit in PyErr_NormalizeException() and check
1022 # that a ResourceWarning is printed.
1023 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001024 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001025 # singleton was being used in that case, that held traceback data and
1026 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1027 # finalization of these locals.
1028 code = """if 1:
1029 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001030 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001031
1032 class MyException(Exception): pass
1033
1034 def setrecursionlimit(depth):
1035 while 1:
1036 try:
1037 sys.setrecursionlimit(depth)
1038 return depth
1039 except RecursionError:
1040 # sys.setrecursionlimit() raises a RecursionError if
1041 # the new recursion limit is too low (issue #25274).
1042 depth += 1
1043
1044 def recurse(cnt):
1045 cnt -= 1
1046 if cnt:
1047 recurse(cnt)
1048 else:
1049 generator.throw(MyException)
1050
1051 def gen():
1052 f = open(%a, mode='rb', buffering=0)
1053 yield
1054
1055 generator = gen()
1056 next(generator)
1057 recursionlimit = sys.getrecursionlimit()
1058 depth = get_recursion_depth()
1059 try:
1060 # Upon the last recursive invocation of recurse(),
1061 # tstate->recursion_depth is equal to (recursion_limit - 1)
1062 # and is equal to recursion_limit when _gen_throw() calls
1063 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001064 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001065 finally:
1066 sys.setrecursionlimit(recursionlimit)
1067 print('Done.')
1068 """ % __file__
1069 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1070 # Check that the program does not fail with SIGABRT.
1071 self.assertEqual(rc, 1)
1072 self.assertIn(b'RecursionError', err)
1073 self.assertIn(b'ResourceWarning', err)
1074 self.assertIn(b'Done.', out)
1075
1076 @cpython_only
1077 def test_recursion_normalizing_infinite_exception(self):
1078 # Issue #30697. Test that a RecursionError is raised when
1079 # PyErr_NormalizeException() maximum recursion depth has been
1080 # exceeded.
1081 code = """if 1:
1082 import _testcapi
1083 try:
1084 raise _testcapi.RecursingInfinitelyError
1085 finally:
1086 print('Done.')
1087 """
1088 rc, out, err = script_helper.assert_python_failure("-c", code)
1089 self.assertEqual(rc, 1)
1090 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1091 b'while normalizing an exception', err)
1092 self.assertIn(b'Done.', out)
1093
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001094
1095 def test_recursion_in_except_handler(self):
1096
1097 def set_relative_recursion_limit(n):
1098 depth = 1
1099 while True:
1100 try:
1101 sys.setrecursionlimit(depth)
1102 except RecursionError:
1103 depth += 1
1104 else:
1105 break
1106 sys.setrecursionlimit(depth+n)
1107
1108 def recurse_in_except():
1109 try:
1110 1/0
1111 except:
1112 recurse_in_except()
1113
1114 def recurse_after_except():
1115 try:
1116 1/0
1117 except:
1118 pass
1119 recurse_after_except()
1120
1121 def recurse_in_body_and_except():
1122 try:
1123 recurse_in_body_and_except()
1124 except:
1125 recurse_in_body_and_except()
1126
1127 recursionlimit = sys.getrecursionlimit()
1128 try:
1129 set_relative_recursion_limit(10)
1130 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1131 with self.subTest(func=func):
1132 try:
1133 func()
1134 except RecursionError:
1135 pass
1136 else:
1137 self.fail("Should have raised a RecursionError")
1138 finally:
1139 sys.setrecursionlimit(recursionlimit)
1140
1141
xdegaye56d1f5c2017-10-26 15:09:06 +02001142 @cpython_only
1143 def test_recursion_normalizing_with_no_memory(self):
1144 # Issue #30697. Test that in the abort that occurs when there is no
1145 # memory left and the size of the Python frames stack is greater than
1146 # the size of the list of preallocated MemoryError instances, the
1147 # Fatal Python error message mentions MemoryError.
1148 code = """if 1:
1149 import _testcapi
1150 class C(): pass
1151 def recurse(cnt):
1152 cnt -= 1
1153 if cnt:
1154 recurse(cnt)
1155 else:
1156 _testcapi.set_nomemory(0)
1157 C()
1158 recurse(16)
1159 """
1160 with SuppressCrashReport():
1161 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001162 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1163 b'Cannot recover from MemoryErrors while '
1164 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001165
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001166 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001167 def test_MemoryError(self):
1168 # PyErr_NoMemory always raises the same exception instance.
1169 # Check that the traceback is not doubled.
1170 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001171 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001172 def raiseMemError():
1173 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001174 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001175 except MemoryError as e:
1176 tb = e.__traceback__
1177 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001178 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001179 return traceback.format_tb(tb)
1180
1181 tb1 = raiseMemError()
1182 tb2 = raiseMemError()
1183 self.assertEqual(tb1, tb2)
1184
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001185 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001186 def test_exception_with_doc(self):
1187 import _testcapi
1188 doc2 = "This is a test docstring."
1189 doc4 = "This is another test docstring."
1190
1191 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1192 "error1")
1193
1194 # test basic usage of PyErr_NewException
1195 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1196 self.assertIs(type(error1), type)
1197 self.assertTrue(issubclass(error1, Exception))
1198 self.assertIsNone(error1.__doc__)
1199
1200 # test with given docstring
1201 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1202 self.assertEqual(error2.__doc__, doc2)
1203
1204 # test with explicit base (without docstring)
1205 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1206 base=error2)
1207 self.assertTrue(issubclass(error3, error2))
1208
1209 # test with explicit base tuple
1210 class C(object):
1211 pass
1212 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1213 (error3, C))
1214 self.assertTrue(issubclass(error4, error3))
1215 self.assertTrue(issubclass(error4, C))
1216 self.assertEqual(error4.__doc__, doc4)
1217
1218 # test with explicit dictionary
1219 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1220 error4, {'a': 1})
1221 self.assertTrue(issubclass(error5, error4))
1222 self.assertEqual(error5.a, 1)
1223 self.assertEqual(error5.__doc__, "")
1224
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001225 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001226 def test_memory_error_cleanup(self):
1227 # Issue #5437: preallocated MemoryError instances should not keep
1228 # traceback objects alive.
1229 from _testcapi import raise_memoryerror
1230 class C:
1231 pass
1232 wr = None
1233 def inner():
1234 nonlocal wr
1235 c = C()
1236 wr = weakref.ref(c)
1237 raise_memoryerror()
1238 # We cannot use assertRaises since it manually deletes the traceback
1239 try:
1240 inner()
1241 except MemoryError as e:
1242 self.assertNotEqual(wr(), None)
1243 else:
1244 self.fail("MemoryError not raised")
1245 self.assertEqual(wr(), None)
1246
Brett Cannon31f59292011-02-21 19:29:56 +00001247 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001248 def test_recursion_error_cleanup(self):
1249 # Same test as above, but with "recursion exceeded" errors
1250 class C:
1251 pass
1252 wr = None
1253 def inner():
1254 nonlocal wr
1255 c = C()
1256 wr = weakref.ref(c)
1257 inner()
1258 # We cannot use assertRaises since it manually deletes the traceback
1259 try:
1260 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001261 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001262 self.assertNotEqual(wr(), None)
1263 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001264 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001265 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001266
Antoine Pitroua7622852011-09-01 21:37:43 +02001267 def test_errno_ENOTDIR(self):
1268 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1269 with self.assertRaises(OSError) as cm:
1270 os.listdir(__file__)
1271 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1272
Martin Panter3263f682016-02-28 03:16:11 +00001273 def test_unraisable(self):
1274 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1275 class BrokenDel:
1276 def __del__(self):
1277 exc = ValueError("del is broken")
1278 # The following line is included in the traceback report:
1279 raise exc
1280
Victor Stinnere4d300e2019-05-22 23:44:02 +02001281 obj = BrokenDel()
1282 with support.catch_unraisable_exception() as cm:
1283 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001284
Victor Stinnere4d300e2019-05-22 23:44:02 +02001285 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1286 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001287
1288 def test_unhandled(self):
1289 # Check for sensible reporting of unhandled exceptions
1290 for exc_type in (ValueError, BrokenStrException):
1291 with self.subTest(exc_type):
1292 try:
1293 exc = exc_type("test message")
1294 # The following line is included in the traceback report:
1295 raise exc
1296 except exc_type:
1297 with captured_stderr() as stderr:
1298 sys.__excepthook__(*sys.exc_info())
1299 report = stderr.getvalue()
1300 self.assertIn("test_exceptions.py", report)
1301 self.assertIn("raise exc", report)
1302 self.assertIn(exc_type.__name__, report)
1303 if exc_type is BrokenStrException:
1304 self.assertIn("<exception str() failed>", report)
1305 else:
1306 self.assertIn("test message", report)
1307 self.assertTrue(report.endswith("\n"))
1308
xdegaye66caacf2017-10-23 18:08:41 +02001309 @cpython_only
1310 def test_memory_error_in_PyErr_PrintEx(self):
1311 code = """if 1:
1312 import _testcapi
1313 class C(): pass
1314 _testcapi.set_nomemory(0, %d)
1315 C()
1316 """
1317
1318 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1319 # Span a large range of tests as the CPython code always evolves with
1320 # changes that add or remove memory allocations.
1321 for i in range(1, 20):
1322 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1323 self.assertIn(rc, (1, 120))
1324 self.assertIn(b'MemoryError', err)
1325
Mark Shannonae3087c2017-10-22 22:41:51 +01001326 def test_yield_in_nested_try_excepts(self):
1327 #Issue #25612
1328 class MainError(Exception):
1329 pass
1330
1331 class SubError(Exception):
1332 pass
1333
1334 def main():
1335 try:
1336 raise MainError()
1337 except MainError:
1338 try:
1339 yield
1340 except SubError:
1341 pass
1342 raise
1343
1344 coro = main()
1345 coro.send(None)
1346 with self.assertRaises(MainError):
1347 coro.throw(SubError())
1348
1349 def test_generator_doesnt_retain_old_exc2(self):
1350 #Issue 28884#msg282532
1351 def g():
1352 try:
1353 raise ValueError
1354 except ValueError:
1355 yield 1
1356 self.assertEqual(sys.exc_info(), (None, None, None))
1357 yield 2
1358
1359 gen = g()
1360
1361 try:
1362 raise IndexError
1363 except IndexError:
1364 self.assertEqual(next(gen), 1)
1365 self.assertEqual(next(gen), 2)
1366
1367 def test_raise_in_generator(self):
1368 #Issue 25612#msg304117
1369 def g():
1370 yield 1
1371 raise
1372 yield 2
1373
1374 with self.assertRaises(ZeroDivisionError):
1375 i = g()
1376 try:
1377 1/0
1378 except:
1379 next(i)
1380 next(i)
1381
Zackery Spytzce6a0702019-08-25 03:44:09 -06001382 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1383 def test_assert_shadowing(self):
1384 # Shadowing AssertionError would cause the assert statement to
1385 # misbehave.
1386 global AssertionError
1387 AssertionError = TypeError
1388 try:
1389 assert False, 'hello'
1390 except BaseException as e:
1391 del AssertionError
1392 self.assertIsInstance(e, AssertionError)
1393 self.assertEqual(str(e), 'hello')
1394 else:
1395 del AssertionError
1396 self.fail('Expected exception')
1397
Pablo Galindo9b648a92020-09-01 19:39:46 +01001398 def test_memory_error_subclasses(self):
1399 # bpo-41654: MemoryError instances use a freelist of objects that are
1400 # linked using the 'dict' attribute when they are inactive/dead.
1401 # Subclasses of MemoryError should not participate in the freelist
1402 # schema. This test creates a MemoryError object and keeps it alive
1403 # (therefore advancing the freelist) and then it creates and destroys a
1404 # subclass object. Finally, it checks that creating a new MemoryError
1405 # succeeds, proving that the freelist is not corrupted.
1406
1407 class TestException(MemoryError):
1408 pass
1409
1410 try:
1411 raise MemoryError
1412 except MemoryError as exc:
1413 inst = exc
1414
1415 try:
1416 raise TestException
1417 except Exception:
1418 pass
1419
1420 for _ in range(10):
1421 try:
1422 raise MemoryError
1423 except MemoryError as exc:
1424 pass
1425
1426 gc_collect()
1427
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001428global_for_suggestions = None
1429
1430class NameErrorTests(unittest.TestCase):
1431 def test_name_error_has_name(self):
1432 try:
1433 bluch
1434 except NameError as exc:
1435 self.assertEqual("bluch", exc.name)
1436
1437 def test_name_error_suggestions(self):
1438 def Substitution():
1439 noise = more_noise = a = bc = None
1440 blech = None
1441 print(bluch)
1442
1443 def Elimination():
1444 noise = more_noise = a = bc = None
1445 blch = None
1446 print(bluch)
1447
1448 def Addition():
1449 noise = more_noise = a = bc = None
1450 bluchin = None
1451 print(bluch)
1452
1453 def SubstitutionOverElimination():
1454 blach = None
1455 bluc = None
1456 print(bluch)
1457
1458 def SubstitutionOverAddition():
1459 blach = None
1460 bluchi = None
1461 print(bluch)
1462
1463 def EliminationOverAddition():
1464 blucha = None
1465 bluc = None
1466 print(bluch)
1467
Pablo Galindo7a041162021-04-19 23:35:53 +01001468 for func, suggestion in [(Substitution, "'blech'?"),
1469 (Elimination, "'blch'?"),
1470 (Addition, "'bluchin'?"),
1471 (EliminationOverAddition, "'blucha'?"),
1472 (SubstitutionOverElimination, "'blach'?"),
1473 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001474 err = None
1475 try:
1476 func()
1477 except NameError as exc:
1478 with support.captured_stderr() as err:
1479 sys.__excepthook__(*sys.exc_info())
1480 self.assertIn(suggestion, err.getvalue())
1481
1482 def test_name_error_suggestions_from_globals(self):
1483 def func():
1484 print(global_for_suggestio)
1485 try:
1486 func()
1487 except NameError as exc:
1488 with support.captured_stderr() as err:
1489 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001490 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001491
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001492 def test_name_error_suggestions_from_builtins(self):
1493 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001494 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001495 try:
1496 func()
1497 except NameError as exc:
1498 with support.captured_stderr() as err:
1499 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001500 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001501
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001502 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1503 def f():
1504 somethingverywronghehehehehehe = None
1505 print(somethingverywronghe)
1506
1507 try:
1508 f()
1509 except NameError as exc:
1510 with support.captured_stderr() as err:
1511 sys.__excepthook__(*sys.exc_info())
1512
1513 self.assertNotIn("somethingverywronghehe", err.getvalue())
1514
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001515 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1516 vvv = mom = w = id = pytho = None
1517
1518 with self.subTest(name="b"):
1519 try:
1520 b
1521 except NameError as exc:
1522 with support.captured_stderr() as err:
1523 sys.__excepthook__(*sys.exc_info())
1524 self.assertNotIn("you mean", err.getvalue())
1525 self.assertNotIn("vvv", err.getvalue())
1526 self.assertNotIn("mom", err.getvalue())
1527 self.assertNotIn("'id'", err.getvalue())
1528 self.assertNotIn("'w'", err.getvalue())
1529 self.assertNotIn("'pytho'", err.getvalue())
1530
1531 with self.subTest(name="v"):
1532 try:
1533 v
1534 except NameError as exc:
1535 with support.captured_stderr() as err:
1536 sys.__excepthook__(*sys.exc_info())
1537 self.assertNotIn("you mean", err.getvalue())
1538 self.assertNotIn("vvv", err.getvalue())
1539 self.assertNotIn("mom", err.getvalue())
1540 self.assertNotIn("'id'", err.getvalue())
1541 self.assertNotIn("'w'", err.getvalue())
1542 self.assertNotIn("'pytho'", err.getvalue())
1543
1544 with self.subTest(name="m"):
1545 try:
1546 m
1547 except NameError as exc:
1548 with support.captured_stderr() as err:
1549 sys.__excepthook__(*sys.exc_info())
1550 self.assertNotIn("you mean", err.getvalue())
1551 self.assertNotIn("vvv", err.getvalue())
1552 self.assertNotIn("mom", err.getvalue())
1553 self.assertNotIn("'id'", err.getvalue())
1554 self.assertNotIn("'w'", err.getvalue())
1555 self.assertNotIn("'pytho'", err.getvalue())
1556
1557 with self.subTest(name="py"):
1558 try:
1559 py
1560 except NameError as exc:
1561 with support.captured_stderr() as err:
1562 sys.__excepthook__(*sys.exc_info())
1563 self.assertNotIn("you mean", err.getvalue())
1564 self.assertNotIn("vvv", err.getvalue())
1565 self.assertNotIn("mom", err.getvalue())
1566 self.assertNotIn("'id'", err.getvalue())
1567 self.assertNotIn("'w'", err.getvalue())
1568 self.assertNotIn("'pytho'", err.getvalue())
1569
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001570 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001571 def f():
1572 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001573 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1574 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1575 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1576 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1577 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1578 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1579 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1580 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1581 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1582 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1583 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1584 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1585 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1586 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1587 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1588 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1589 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1590 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1591 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1592 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1593 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1594 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1595 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1596 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1597 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1598 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1599 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1600 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1601 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1602 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1603 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1604 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1605 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1606 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1607 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1608 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1609 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1610 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1611 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1612 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1613 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1614 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1615 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1616 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1617 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1618 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1619 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1620 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1621 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1622 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1623 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1624 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1625 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1626 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1627 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1628 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1629 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1630 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1631 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1632 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1633 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1634 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1635 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1636 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1637 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1638 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1639 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1640 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1641 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1642 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1643 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1644 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1645 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1646 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1647 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1648 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1649 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1650 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1651 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1652 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1653 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001654 print(a0)
1655
1656 try:
1657 f()
1658 except NameError as exc:
1659 with support.captured_stderr() as err:
1660 sys.__excepthook__(*sys.exc_info())
1661
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001662 self.assertNotIn("a1", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001663
1664 def test_name_error_with_custom_exceptions(self):
1665 def f():
1666 blech = None
1667 raise NameError()
1668
1669 try:
1670 f()
1671 except NameError as exc:
1672 with support.captured_stderr() as err:
1673 sys.__excepthook__(*sys.exc_info())
1674
1675 self.assertNotIn("blech", err.getvalue())
1676
1677 def f():
1678 blech = None
1679 raise NameError
1680
1681 try:
1682 f()
1683 except NameError as exc:
1684 with support.captured_stderr() as err:
1685 sys.__excepthook__(*sys.exc_info())
1686
1687 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001688
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001689 def test_unbound_local_error_doesn_not_match(self):
1690 def foo():
1691 something = 3
1692 print(somethong)
1693 somethong = 3
1694
1695 try:
1696 foo()
1697 except UnboundLocalError as exc:
1698 with support.captured_stderr() as err:
1699 sys.__excepthook__(*sys.exc_info())
1700
1701 self.assertNotIn("something", err.getvalue())
1702
1703
Pablo Galindo37494b42021-04-14 02:36:07 +01001704class AttributeErrorTests(unittest.TestCase):
1705 def test_attributes(self):
1706 # Setting 'attr' should not be a problem.
1707 exc = AttributeError('Ouch!')
1708 self.assertIsNone(exc.name)
1709 self.assertIsNone(exc.obj)
1710
1711 sentinel = object()
1712 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1713 self.assertEqual(exc.name, 'carry')
1714 self.assertIs(exc.obj, sentinel)
1715
1716 def test_getattr_has_name_and_obj(self):
1717 class A:
1718 blech = None
1719
1720 obj = A()
1721 try:
1722 obj.bluch
1723 except AttributeError as exc:
1724 self.assertEqual("bluch", exc.name)
1725 self.assertEqual(obj, exc.obj)
1726
1727 def test_getattr_has_name_and_obj_for_method(self):
1728 class A:
1729 def blech(self):
1730 return
1731
1732 obj = A()
1733 try:
1734 obj.bluch()
1735 except AttributeError as exc:
1736 self.assertEqual("bluch", exc.name)
1737 self.assertEqual(obj, exc.obj)
1738
1739 def test_getattr_suggestions(self):
1740 class Substitution:
1741 noise = more_noise = a = bc = None
1742 blech = None
1743
1744 class Elimination:
1745 noise = more_noise = a = bc = None
1746 blch = None
1747
1748 class Addition:
1749 noise = more_noise = a = bc = None
1750 bluchin = None
1751
1752 class SubstitutionOverElimination:
1753 blach = None
1754 bluc = None
1755
1756 class SubstitutionOverAddition:
1757 blach = None
1758 bluchi = None
1759
1760 class EliminationOverAddition:
1761 blucha = None
1762 bluc = None
1763
Pablo Galindo7a041162021-04-19 23:35:53 +01001764 for cls, suggestion in [(Substitution, "'blech'?"),
1765 (Elimination, "'blch'?"),
1766 (Addition, "'bluchin'?"),
1767 (EliminationOverAddition, "'bluc'?"),
1768 (SubstitutionOverElimination, "'blach'?"),
1769 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001770 try:
1771 cls().bluch
1772 except AttributeError as exc:
1773 with support.captured_stderr() as err:
1774 sys.__excepthook__(*sys.exc_info())
1775
1776 self.assertIn(suggestion, err.getvalue())
1777
1778 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1779 class A:
1780 blech = None
1781
1782 try:
1783 A().somethingverywrong
1784 except AttributeError as exc:
1785 with support.captured_stderr() as err:
1786 sys.__excepthook__(*sys.exc_info())
1787
1788 self.assertNotIn("blech", err.getvalue())
1789
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001790 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
1791 class MyClass:
1792 vvv = mom = w = id = pytho = None
1793
1794 with self.subTest(name="b"):
1795 try:
1796 MyClass.b
1797 except AttributeError as exc:
1798 with support.captured_stderr() as err:
1799 sys.__excepthook__(*sys.exc_info())
1800 self.assertNotIn("you mean", err.getvalue())
1801 self.assertNotIn("vvv", err.getvalue())
1802 self.assertNotIn("mom", err.getvalue())
1803 self.assertNotIn("'id'", err.getvalue())
1804 self.assertNotIn("'w'", err.getvalue())
1805 self.assertNotIn("'pytho'", err.getvalue())
1806
1807 with self.subTest(name="v"):
1808 try:
1809 MyClass.v
1810 except AttributeError as exc:
1811 with support.captured_stderr() as err:
1812 sys.__excepthook__(*sys.exc_info())
1813 self.assertNotIn("you mean", err.getvalue())
1814 self.assertNotIn("vvv", err.getvalue())
1815 self.assertNotIn("mom", err.getvalue())
1816 self.assertNotIn("'id'", err.getvalue())
1817 self.assertNotIn("'w'", err.getvalue())
1818 self.assertNotIn("'pytho'", err.getvalue())
1819
1820 with self.subTest(name="m"):
1821 try:
1822 MyClass.m
1823 except AttributeError as exc:
1824 with support.captured_stderr() as err:
1825 sys.__excepthook__(*sys.exc_info())
1826 self.assertNotIn("you mean", err.getvalue())
1827 self.assertNotIn("vvv", err.getvalue())
1828 self.assertNotIn("mom", err.getvalue())
1829 self.assertNotIn("'id'", err.getvalue())
1830 self.assertNotIn("'w'", err.getvalue())
1831 self.assertNotIn("'pytho'", err.getvalue())
1832
1833 with self.subTest(name="py"):
1834 try:
1835 MyClass.py
1836 except AttributeError as exc:
1837 with support.captured_stderr() as err:
1838 sys.__excepthook__(*sys.exc_info())
1839 self.assertNotIn("you mean", err.getvalue())
1840 self.assertNotIn("vvv", err.getvalue())
1841 self.assertNotIn("mom", err.getvalue())
1842 self.assertNotIn("'id'", err.getvalue())
1843 self.assertNotIn("'w'", err.getvalue())
1844 self.assertNotIn("'pytho'", err.getvalue())
1845
1846
Pablo Galindo37494b42021-04-14 02:36:07 +01001847 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
1848 class A:
1849 blech = None
1850 # A class with a very big __dict__ will not be consider
1851 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001852 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01001853 setattr(A, f"index_{index}", None)
1854
1855 try:
1856 A().bluch
1857 except AttributeError as exc:
1858 with support.captured_stderr() as err:
1859 sys.__excepthook__(*sys.exc_info())
1860
1861 self.assertNotIn("blech", err.getvalue())
1862
1863 def test_getattr_suggestions_no_args(self):
1864 class A:
1865 blech = None
1866 def __getattr__(self, attr):
1867 raise AttributeError()
1868
1869 try:
1870 A().bluch
1871 except AttributeError as exc:
1872 with support.captured_stderr() as err:
1873 sys.__excepthook__(*sys.exc_info())
1874
1875 self.assertIn("blech", err.getvalue())
1876
1877 class A:
1878 blech = None
1879 def __getattr__(self, attr):
1880 raise AttributeError
1881
1882 try:
1883 A().bluch
1884 except AttributeError as exc:
1885 with support.captured_stderr() as err:
1886 sys.__excepthook__(*sys.exc_info())
1887
1888 self.assertIn("blech", err.getvalue())
1889
1890 def test_getattr_suggestions_invalid_args(self):
1891 class NonStringifyClass:
1892 __str__ = None
1893 __repr__ = None
1894
1895 class A:
1896 blech = None
1897 def __getattr__(self, attr):
1898 raise AttributeError(NonStringifyClass())
1899
1900 class B:
1901 blech = None
1902 def __getattr__(self, attr):
1903 raise AttributeError("Error", 23)
1904
1905 class C:
1906 blech = None
1907 def __getattr__(self, attr):
1908 raise AttributeError(23)
1909
1910 for cls in [A, B, C]:
1911 try:
1912 cls().bluch
1913 except AttributeError as exc:
1914 with support.captured_stderr() as err:
1915 sys.__excepthook__(*sys.exc_info())
1916
1917 self.assertIn("blech", err.getvalue())
1918
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01001919 def test_attribute_error_with_failing_dict(self):
1920 class T:
1921 bluch = 1
1922 def __dir__(self):
1923 raise AttributeError("oh no!")
1924
1925 try:
1926 T().blich
1927 except AttributeError as exc:
1928 with support.captured_stderr() as err:
1929 sys.__excepthook__(*sys.exc_info())
1930
1931 self.assertNotIn("blech", err.getvalue())
1932 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01001933
Pablo Galindo0b1c1692021-04-17 23:28:45 +01001934 def test_attribute_error_with_bad_name(self):
1935 try:
1936 raise AttributeError(name=12, obj=23)
1937 except AttributeError as exc:
1938 with support.captured_stderr() as err:
1939 sys.__excepthook__(*sys.exc_info())
1940
1941 self.assertNotIn("?", err.getvalue())
1942
1943
Brett Cannon79ec55e2012-04-12 20:24:54 -04001944class ImportErrorTests(unittest.TestCase):
1945
1946 def test_attributes(self):
1947 # Setting 'name' and 'path' should not be a problem.
1948 exc = ImportError('test')
1949 self.assertIsNone(exc.name)
1950 self.assertIsNone(exc.path)
1951
1952 exc = ImportError('test', name='somemodule')
1953 self.assertEqual(exc.name, 'somemodule')
1954 self.assertIsNone(exc.path)
1955
1956 exc = ImportError('test', path='somepath')
1957 self.assertEqual(exc.path, 'somepath')
1958 self.assertIsNone(exc.name)
1959
1960 exc = ImportError('test', path='somepath', name='somename')
1961 self.assertEqual(exc.name, 'somename')
1962 self.assertEqual(exc.path, 'somepath')
1963
Michael Seifert64c8f702017-04-09 09:47:12 +02001964 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001965 with self.assertRaisesRegex(TypeError, msg):
1966 ImportError('test', invalid='keyword')
1967
1968 with self.assertRaisesRegex(TypeError, msg):
1969 ImportError('test', name='name', invalid='keyword')
1970
1971 with self.assertRaisesRegex(TypeError, msg):
1972 ImportError('test', path='path', invalid='keyword')
1973
1974 with self.assertRaisesRegex(TypeError, msg):
1975 ImportError(invalid='keyword')
1976
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001977 with self.assertRaisesRegex(TypeError, msg):
1978 ImportError('test', invalid='keyword', another=True)
1979
Serhiy Storchakae9e44482016-09-28 07:53:32 +03001980 def test_reset_attributes(self):
1981 exc = ImportError('test', name='name', path='path')
1982 self.assertEqual(exc.args, ('test',))
1983 self.assertEqual(exc.msg, 'test')
1984 self.assertEqual(exc.name, 'name')
1985 self.assertEqual(exc.path, 'path')
1986
1987 # Reset not specified attributes
1988 exc.__init__()
1989 self.assertEqual(exc.args, ())
1990 self.assertEqual(exc.msg, None)
1991 self.assertEqual(exc.name, None)
1992 self.assertEqual(exc.path, None)
1993
Brett Cannon07c6e712012-08-24 13:05:09 -04001994 def test_non_str_argument(self):
1995 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02001996 with check_warnings(('', BytesWarning), quiet=True):
1997 arg = b'abc'
1998 exc = ImportError(arg)
1999 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002000
Serhiy Storchakab7853962017-04-08 09:55:07 +03002001 def test_copy_pickle(self):
2002 for kwargs in (dict(),
2003 dict(name='somename'),
2004 dict(path='somepath'),
2005 dict(name='somename', path='somepath')):
2006 orig = ImportError('test', **kwargs)
2007 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2008 exc = pickle.loads(pickle.dumps(orig, proto))
2009 self.assertEqual(exc.args, ('test',))
2010 self.assertEqual(exc.msg, 'test')
2011 self.assertEqual(exc.name, orig.name)
2012 self.assertEqual(exc.path, orig.path)
2013 for c in copy.copy, copy.deepcopy:
2014 exc = c(orig)
2015 self.assertEqual(exc.args, ('test',))
2016 self.assertEqual(exc.msg, 'test')
2017 self.assertEqual(exc.name, orig.name)
2018 self.assertEqual(exc.path, orig.path)
2019
Pablo Galindoa77aac42021-04-23 14:27:05 +01002020class SyntaxErrorTests(unittest.TestCase):
2021 def test_range_of_offsets(self):
2022 cases = [
2023 # Basic range from 2->7
2024 (("bad.py", 1, 2, "abcdefg", 1, 7),
2025 dedent(
2026 """
2027 File "bad.py", line 1
2028 abcdefg
2029 ^^^^^
2030 SyntaxError: bad bad
2031 """)),
2032 # end_offset = start_offset + 1
2033 (("bad.py", 1, 2, "abcdefg", 1, 3),
2034 dedent(
2035 """
2036 File "bad.py", line 1
2037 abcdefg
2038 ^
2039 SyntaxError: bad bad
2040 """)),
2041 # Negative end offset
2042 (("bad.py", 1, 2, "abcdefg", 1, -2),
2043 dedent(
2044 """
2045 File "bad.py", line 1
2046 abcdefg
2047 ^
2048 SyntaxError: bad bad
2049 """)),
2050 # end offset before starting offset
2051 (("bad.py", 1, 4, "abcdefg", 1, 2),
2052 dedent(
2053 """
2054 File "bad.py", line 1
2055 abcdefg
2056 ^
2057 SyntaxError: bad bad
2058 """)),
2059 # Both offsets negative
2060 (("bad.py", 1, -4, "abcdefg", 1, -2),
2061 dedent(
2062 """
2063 File "bad.py", line 1
2064 abcdefg
2065 SyntaxError: bad bad
2066 """)),
2067 # Both offsets negative and the end more negative
2068 (("bad.py", 1, -4, "abcdefg", 1, -5),
2069 dedent(
2070 """
2071 File "bad.py", line 1
2072 abcdefg
2073 SyntaxError: bad bad
2074 """)),
2075 # Both offsets 0
2076 (("bad.py", 1, 0, "abcdefg", 1, 0),
2077 dedent(
2078 """
2079 File "bad.py", line 1
2080 abcdefg
2081 SyntaxError: bad bad
2082 """)),
2083 # Start offset 0 and end offset not 0
2084 (("bad.py", 1, 0, "abcdefg", 1, 5),
2085 dedent(
2086 """
2087 File "bad.py", line 1
2088 abcdefg
2089 SyntaxError: bad bad
2090 """)),
2091 # End offset pass the source lenght
2092 (("bad.py", 1, 2, "abcdefg", 1, 100),
2093 dedent(
2094 """
2095 File "bad.py", line 1
2096 abcdefg
2097 ^^^^^^
2098 SyntaxError: bad bad
2099 """)),
2100 ]
2101 for args, expected in cases:
2102 with self.subTest(args=args):
2103 try:
2104 raise SyntaxError("bad bad", args)
2105 except SyntaxError as exc:
2106 with support.captured_stderr() as err:
2107 sys.__excepthook__(*sys.exc_info())
2108 the_exception = exc
2109
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002110 def test_encodings(self):
2111 source = (
2112 '# -*- coding: cp437 -*-\n'
2113 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2114 )
2115 try:
2116 with open(TESTFN, 'w', encoding='cp437') as testfile:
2117 testfile.write(source)
2118 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2119 err = err.decode('utf-8').splitlines()
2120
2121 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2122 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2123 finally:
2124 unlink(TESTFN)
2125
Pablo Galindoa77aac42021-04-23 14:27:05 +01002126 def test_attributes_new_constructor(self):
2127 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2128 the_exception = SyntaxError("bad bad", args)
2129 filename, lineno, offset, error, end_lineno, end_offset = args
2130 self.assertEqual(filename, the_exception.filename)
2131 self.assertEqual(lineno, the_exception.lineno)
2132 self.assertEqual(end_lineno, the_exception.end_lineno)
2133 self.assertEqual(offset, the_exception.offset)
2134 self.assertEqual(end_offset, the_exception.end_offset)
2135 self.assertEqual(error, the_exception.text)
2136 self.assertEqual("bad bad", the_exception.msg)
2137
2138 def test_attributes_old_constructor(self):
2139 args = ("bad.py", 1, 2, "abcdefg")
2140 the_exception = SyntaxError("bad bad", args)
2141 filename, lineno, offset, error = args
2142 self.assertEqual(filename, the_exception.filename)
2143 self.assertEqual(lineno, the_exception.lineno)
2144 self.assertEqual(None, the_exception.end_lineno)
2145 self.assertEqual(offset, the_exception.offset)
2146 self.assertEqual(None, the_exception.end_offset)
2147 self.assertEqual(error, the_exception.text)
2148 self.assertEqual("bad bad", the_exception.msg)
2149
2150 def test_incorrect_constructor(self):
2151 args = ("bad.py", 1, 2)
2152 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2153
2154 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2155 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2156
2157 args = ("bad.py", 1, 2, "abcdefg", 1)
2158 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2159
Brett Cannon79ec55e2012-04-12 20:24:54 -04002160
Mark Shannonbf353f32020-12-17 13:55:28 +00002161class PEP626Tests(unittest.TestCase):
2162
Mark Shannon0b6b2862021-06-24 13:09:14 +01002163 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002164 try:
2165 f()
2166 except Exception as ex:
2167 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002168 else:
2169 self.fail("No exception raised")
2170 lines = []
2171 t = t.tb_next # Skip this function
2172 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002173 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002174 lines.append(
2175 None if frame.f_lineno is None else
2176 frame.f_lineno-frame.f_code.co_firstlineno
2177 )
2178 t = t.tb_next
2179 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002180
2181 def test_lineno_after_raise_simple(self):
2182 def simple():
2183 1/0
2184 pass
2185 self.lineno_after_raise(simple, 1)
2186
2187 def test_lineno_after_raise_in_except(self):
2188 def in_except():
2189 try:
2190 1/0
2191 except:
2192 1/0
2193 pass
2194 self.lineno_after_raise(in_except, 4)
2195
2196 def test_lineno_after_other_except(self):
2197 def other_except():
2198 try:
2199 1/0
2200 except TypeError as ex:
2201 pass
2202 self.lineno_after_raise(other_except, 3)
2203
2204 def test_lineno_in_named_except(self):
2205 def in_named_except():
2206 try:
2207 1/0
2208 except Exception as ex:
2209 1/0
2210 pass
2211 self.lineno_after_raise(in_named_except, 4)
2212
2213 def test_lineno_in_try(self):
2214 def in_try():
2215 try:
2216 1/0
2217 finally:
2218 pass
2219 self.lineno_after_raise(in_try, 4)
2220
2221 def test_lineno_in_finally_normal(self):
2222 def in_finally_normal():
2223 try:
2224 pass
2225 finally:
2226 1/0
2227 pass
2228 self.lineno_after_raise(in_finally_normal, 4)
2229
2230 def test_lineno_in_finally_except(self):
2231 def in_finally_except():
2232 try:
2233 1/0
2234 finally:
2235 1/0
2236 pass
2237 self.lineno_after_raise(in_finally_except, 4)
2238
2239 def test_lineno_after_with(self):
2240 class Noop:
2241 def __enter__(self):
2242 return self
2243 def __exit__(self, *args):
2244 pass
2245 def after_with():
2246 with Noop():
2247 1/0
2248 pass
2249 self.lineno_after_raise(after_with, 2)
2250
Mark Shannon088a15c2021-04-29 19:28:50 +01002251 def test_missing_lineno_shows_as_none(self):
2252 def f():
2253 1/0
2254 self.lineno_after_raise(f, 1)
2255 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2256 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002257
Mark Shannon0b6b2862021-06-24 13:09:14 +01002258 def test_lineno_after_raise_in_with_exit(self):
2259 class ExitFails:
2260 def __enter__(self):
2261 return self
2262 def __exit__(self, *args):
2263 raise ValueError
2264
2265 def after_with():
2266 with ExitFails():
2267 1/0
2268 self.lineno_after_raise(after_with, 1, 1)
2269
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002270if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002271 unittest.main()