blob: b3d1c35274c7192fcfbdbfd2e12571de6b1b4500 [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"'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700171 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100172
173 s = '''print "old style",'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700174 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100175
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100176 s = 'print f(a+b,c)'
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700177 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100178
Martijn Pieters772d8092017-08-22 21:16:23 +0100179 s = '''exec "old style"'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700180 ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100181
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100182 s = 'exec f(a+b,c)'
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700183 ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100184
Miss Islington (bot)35035bc2021-07-31 18:31:44 -0700185 # Check that we don't incorrectly identify '(...)' as an expression to the right
186 # of 'print'
187
188 s = 'print (a+b,c) $ 42'
189 ckmsg(s, "invalid syntax")
190
191 s = 'exec (a+b,c) $ 42'
192 ckmsg(s, "invalid syntax")
193
Martijn Pieters772d8092017-08-22 21:16:23 +0100194 # should not apply to subclasses, see issue #31161
195 s = '''if True:\nprint "No indent"'''
Pablo Galindo56c95df2021-04-21 15:28:21 +0100196 ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
Martijn Pieters772d8092017-08-22 21:16:23 +0100197
198 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
199 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
200
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300201 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100202 with self.subTest(source=src, lineno=lineno, offset=offset):
203 with self.assertRaises(SyntaxError) as cm:
204 compile(src, '<fragment>', 'exec')
205 self.assertEqual(cm.exception.lineno, lineno)
206 self.assertEqual(cm.exception.offset, offset)
207 if cm.exception.text is not None:
208 if not isinstance(src, str):
209 src = src.decode(encoding, 'replace')
210 line = src.split('\n')[lineno-1]
211 self.assertIn(line, cm.exception.text)
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200212
213 def test_error_offset_continuation_characters(self):
214 check = self.check
215 check('"\\\n"(1 for c in I,\\\n\\', 2, 2)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200216
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300217 def testSyntaxErrorOffset(self):
218 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200219 check('def fact(x):\n\treturn x!\n', 2, 10)
220 check('1 +\n', 1, 4)
221 check('def spam():\n print(1)\n print(2)', 3, 10)
222 check('Python = "Python" +', 1, 20)
223 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200224 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
225 2, 19, encoding='cp1251')
226 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300227 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400228 check('lambda x: x = 2', 1, 1)
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +0000229 check('f{a + b + c}', 1, 2)
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +0100230 check('[file for str(file) in []\n])', 1, 11)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700231 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200232 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
233 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700234 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700235 check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +0000236 check("[a b c d e f]", 1, 2)
Pablo Galindo Salgadoc5214122021-12-07 15:23:33 +0000237 check("for x yfff:", 1, 7)
Ammar Askar025eb982018-09-24 17:12:49 -0400238
239 # Errors thrown by compile.c
240 check('class foo:return 1', 1, 11)
241 check('def f():\n continue', 2, 3)
242 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100243 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400244
245 # Errors thrown by tokenizer.c
246 check('(0x+1)', 1, 3)
247 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700248 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400249 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700250 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200251 check('\u03b1 = 0xI', 1, 6)
252 check(b'\xce\xb1 = 0xI', 1, 6)
253 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
254 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100255 check(b"""if 1:
256 def foo():
257 '''
258
259 def bar():
260 pass
261
262 def baz():
263 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300264 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100265 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
266 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700267 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700268 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Miss Islington (bot)19a85502022-01-11 08:33:08 -0800269 check("""f'''
270 {
271 (123_a)
272 }'''""", 3, 17)
273 check("""f'''
274 {
275 f\"\"\"
276 {
277 (123_a)
278 }
279 \"\"\"
280 }'''""", 5, 17)
Miss Islington (bot)1fb1f5d2022-01-20 05:05:10 -0800281 check('''f"""
282
283
284 {
285 6
286 0="""''', 5, 13)
Ammar Askar025eb982018-09-24 17:12:49 -0400287
288 # Errors thrown by symtable.c
Miss Islington (bot)438817f2021-12-11 17:24:12 -0800289 check('x = [(yield i) for i in range(3)]', 1, 7)
290 check('def f():\n from _ import *', 2, 17)
291 check('def f(x, x):\n pass', 1, 10)
292 check('{i for i in range(5) if (j := 0) for j in range(5)}', 1, 38)
Ammar Askar025eb982018-09-24 17:12:49 -0400293 check('def f(x):\n nonlocal x', 2, 3)
294 check('def f(x):\n x = 1\n global x', 3, 3)
295 check('nonlocal x', 1, 1)
296 check('def f():\n global x\n nonlocal x', 2, 3)
297
Ammar Askar025eb982018-09-24 17:12:49 -0400298 # Errors thrown by future.c
299 check('from __future__ import doesnt_exist', 1, 1)
300 check('from __future__ import braces', 1, 1)
301 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100302 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300303 check('def f():\n x, y: int', 2, 3)
304 check('[*x for x in xs]', 1, 2)
305 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300306 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100307 check('(yield i) = 2', 1, 2)
308 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200309
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000310 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000311 def testSettingException(self):
312 # test that setting an exception at the C level works even if the
313 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000314
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000315 class BadException(Exception):
316 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000317 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000318
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000319 class InvalidException:
320 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000321
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000322 def test_capi1():
323 import _testcapi
324 try:
325 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000326 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000327 exc, err, tb = sys.exc_info()
328 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000329 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000330 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000331 else:
332 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000333
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000334 def test_capi2():
335 import _testcapi
336 try:
337 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000338 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000339 exc, err, tb = sys.exc_info()
340 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000341 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000342 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000343 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000344 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000345 else:
346 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000348 def test_capi3():
349 import _testcapi
350 self.assertRaises(SystemError, _testcapi.raise_exception,
351 InvalidException, 1)
352
353 if not sys.platform.startswith('java'):
354 test_capi1()
355 test_capi2()
356 test_capi3()
357
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358 def test_WindowsError(self):
359 try:
360 WindowsError
361 except NameError:
362 pass
363 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200364 self.assertIs(WindowsError, OSError)
365 self.assertEqual(str(OSError(1001)), "1001")
366 self.assertEqual(str(OSError(1001, "message")),
367 "[Errno 1001] message")
368 # POSIX errno (9 aka EBADF) is untranslated
369 w = OSError(9, 'foo', 'bar')
370 self.assertEqual(w.errno, 9)
371 self.assertEqual(w.winerror, None)
372 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
373 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
374 w = OSError(0, 'foo', 'bar', 3)
375 self.assertEqual(w.errno, 2)
376 self.assertEqual(w.winerror, 3)
377 self.assertEqual(w.strerror, 'foo')
378 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000379 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100380 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200381 # Unknown win error becomes EINVAL (22)
382 w = OSError(0, 'foo', None, 1001)
383 self.assertEqual(w.errno, 22)
384 self.assertEqual(w.winerror, 1001)
385 self.assertEqual(w.strerror, 'foo')
386 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000387 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100388 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200389 # Non-numeric "errno"
390 w = OSError('bar', 'foo')
391 self.assertEqual(w.errno, 'bar')
392 self.assertEqual(w.winerror, None)
393 self.assertEqual(w.strerror, 'foo')
394 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000395 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396
Victor Stinnerd223fa62015-04-02 14:17:38 +0200397 @unittest.skipUnless(sys.platform == 'win32',
398 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300399 def test_windows_message(self):
400 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200401 ctypes = import_module('ctypes')
402 # this error code has no message, Python formats it as hexadecimal
403 code = 3765269347
404 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
405 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300406
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000407 def testAttributes(self):
408 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000409
410 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000411 (BaseException, (), {'args' : ()}),
412 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000413 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000414 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000415 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000416 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000417 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000418 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200419 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000420 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000421 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200422 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000423 {'args' : ('foo', 'bar'),
424 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000425 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200426 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000427 {'args' : ('foo', 'bar'),
428 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800430 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
431 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200432 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000433 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000434 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
435 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200436 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000437 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000438 'strerror' : 'strErrorStr',
439 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000440 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100442 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000443 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000444 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000445 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100446 'filename' : None, 'lineno' : None, 'offset' : None,
447 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000448 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100449 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000450 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000451 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100452 'offsetStr', 'textStr',
453 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000454 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100455 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
456 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000457 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100458 'textStr', 'endLinenoStr', 'endOffsetStr',
459 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000460 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000461 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100462 'textStr', 'endLinenoStr', 'endOffsetStr',
463 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000464 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100465 'filename' : None, 'lineno' : None, 'offset' : None,
466 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000467 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000468 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
469 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000470 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000472 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000474 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000475 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000476 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000477 'ordinal not in range'),
478 'encoding' : 'ascii', 'object' : b'\xff',
479 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000480 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
481 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000482 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000484 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000486 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000487 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000488 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000489 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100490 (NaiveException, ('foo',),
491 {'args': ('foo',), 'x': 'foo'}),
492 (SlottedNaiveException, ('foo',),
493 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000494 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000495 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200496 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000497 exceptionList.append(
498 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000499 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200500 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000501 'errno' : 1,
502 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000503 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000504 except NameError:
505 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000506
Guido van Rossumebe3e162007-05-17 18:20:34 +0000507 for exc, args, expected in exceptionList:
508 try:
509 e = exc(*args)
510 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000511 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100512 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000513 else:
514 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100515 if not type(e).__name__.endswith('NaiveException'):
516 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000517 # Verify no ref leaks in Exc_str()
518 s = str(e)
519 for checkArgName in expected:
520 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000521 self.assertEqual(repr(value),
522 repr(expected[checkArgName]),
523 '%r.%s == %r, expected %r' % (
524 e, checkArgName,
525 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000526
Guido van Rossumebe3e162007-05-17 18:20:34 +0000527 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000528 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000529 for protocol in range(p.HIGHEST_PROTOCOL + 1):
530 s = p.dumps(e, protocol)
531 new = p.loads(s)
532 for checkArgName in expected:
533 got = repr(getattr(new, checkArgName))
534 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000535 self.assertEqual(got, want,
536 'pickled "%r", attribute "%s' %
537 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000538
Collin Winter828f04a2007-08-31 00:04:24 +0000539 def testWithTraceback(self):
540 try:
541 raise IndexError(4)
542 except:
543 tb = sys.exc_info()[2]
544
545 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000546 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000547 self.assertEqual(e.__traceback__, tb)
548
549 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000550 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000551 self.assertEqual(e.__traceback__, tb)
552
553 class MyException(Exception):
554 pass
555
556 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000557 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000558 self.assertEqual(e.__traceback__, tb)
559
560 def testInvalidTraceback(self):
561 try:
562 Exception().__traceback__ = 5
563 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000564 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000565 else:
566 self.fail("No exception raised")
567
Georg Brandlab6f2f62009-03-31 04:16:10 +0000568 def testInvalidAttrs(self):
569 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
570 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
571 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
572 self.assertRaises(TypeError, delattr, Exception(), '__context__')
573
Collin Winter828f04a2007-08-31 00:04:24 +0000574 def testNoneClearsTracebackAttr(self):
575 try:
576 raise IndexError(4)
577 except:
578 tb = sys.exc_info()[2]
579
580 e = Exception()
581 e.__traceback__ = tb
582 e.__traceback__ = None
583 self.assertEqual(e.__traceback__, None)
584
585 def testChainingAttrs(self):
586 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000587 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700588 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000589
590 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000591 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700592 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000593
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200594 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000595 pass
596
597 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000598 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700599 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000600
601 def testChainingDescriptors(self):
602 try:
603 raise Exception()
604 except Exception as exc:
605 e = exc
606
607 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700608 self.assertIsNone(e.__cause__)
609 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000610
611 e.__context__ = NameError()
612 e.__cause__ = None
613 self.assertIsInstance(e.__context__, NameError)
614 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700615 self.assertTrue(e.__suppress_context__)
616 e.__suppress_context__ = False
617 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000618
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000619 def testKeywordArgs(self):
620 # test that builtin exception don't take keyword args,
621 # but user-defined subclasses can if they want
622 self.assertRaises(TypeError, BaseException, a=1)
623
624 class DerivedException(BaseException):
625 def __init__(self, fancy_arg):
626 BaseException.__init__(self)
627 self.fancy_arg = fancy_arg
628
629 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000630 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000631
Brett Cannon31f59292011-02-21 19:29:56 +0000632 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000633 def testInfiniteRecursion(self):
634 def f():
635 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400636 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000637
638 def g():
639 try:
640 return g()
641 except ValueError:
642 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400643 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000644
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000645 def test_str(self):
646 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000647 self.assertTrue(str(Exception))
648 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000649 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000651 def testExceptionCleanupNames(self):
652 # Make sure the local variable bound to the exception instance by
653 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000654 try:
655 raise Exception()
656 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000657 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000658 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000659 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000660
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000661 def testExceptionCleanupState(self):
662 # Make sure exception state is cleaned up as soon as the except
663 # block is left. See #2507
664
665 class MyException(Exception):
666 def __init__(self, obj):
667 self.obj = obj
668 class MyObj:
669 pass
670
671 def inner_raising_func():
672 # Create some references in exception value and traceback
673 local_ref = obj
674 raise MyException(obj)
675
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000676 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000677 obj = MyObj()
678 wr = weakref.ref(obj)
679 try:
680 inner_raising_func()
681 except MyException as e:
682 pass
683 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300684 gc_collect() # For PyPy or other GCs.
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000685 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300686 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000687
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000688 # Qualified "except" without "as"
689 obj = MyObj()
690 wr = weakref.ref(obj)
691 try:
692 inner_raising_func()
693 except MyException:
694 pass
695 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300696 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000697 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300698 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000699
700 # Bare "except"
701 obj = MyObj()
702 wr = weakref.ref(obj)
703 try:
704 inner_raising_func()
705 except:
706 pass
707 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300708 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000709 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300710 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000711
712 # "except" with premature block leave
713 obj = MyObj()
714 wr = weakref.ref(obj)
715 for i in [0]:
716 try:
717 inner_raising_func()
718 except:
719 break
720 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300721 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000722 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300723 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000724
725 # "except" block raising another exception
726 obj = MyObj()
727 wr = weakref.ref(obj)
728 try:
729 try:
730 inner_raising_func()
731 except:
732 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000733 except KeyError as e:
734 # We want to test that the except block above got rid of
735 # the exception raised in inner_raising_func(), but it
736 # also ends up in the __context__ of the KeyError, so we
737 # must clear the latter manually for our test to succeed.
738 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000739 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300740 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000741 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800742 # guarantee no ref cycles on CPython (don't gc_collect)
743 if check_impl_detail(cpython=False):
744 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300745 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000746
747 # Some complicated construct
748 obj = MyObj()
749 wr = weakref.ref(obj)
750 try:
751 inner_raising_func()
752 except MyException:
753 try:
754 try:
755 raise
756 finally:
757 raise
758 except MyException:
759 pass
760 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800761 if check_impl_detail(cpython=False):
762 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000763 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300764 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000765
766 # Inside an exception-silencing "with" block
767 class Context:
768 def __enter__(self):
769 return self
770 def __exit__ (self, exc_type, exc_value, exc_tb):
771 return True
772 obj = MyObj()
773 wr = weakref.ref(obj)
774 with Context():
775 inner_raising_func()
776 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800777 if check_impl_detail(cpython=False):
778 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000779 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300780 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000781
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000782 def test_exception_target_in_nested_scope(self):
783 # issue 4617: This used to raise a SyntaxError
784 # "can not delete variable 'e' referenced in nested scope"
785 def print_error():
786 e
787 try:
788 something
789 except Exception as e:
790 print_error()
791 # implicit "del e" here
792
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000793 def test_generator_leaking(self):
794 # Test that generator exception state doesn't leak into the calling
795 # frame
796 def yield_raise():
797 try:
798 raise KeyError("caught")
799 except KeyError:
800 yield sys.exc_info()[0]
801 yield sys.exc_info()[0]
802 yield sys.exc_info()[0]
803 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000804 self.assertEqual(next(g), KeyError)
805 self.assertEqual(sys.exc_info()[0], None)
806 self.assertEqual(next(g), KeyError)
807 self.assertEqual(sys.exc_info()[0], None)
808 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000809
810 # Same test, but inside an exception handler
811 try:
812 raise TypeError("foo")
813 except TypeError:
814 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000815 self.assertEqual(next(g), KeyError)
816 self.assertEqual(sys.exc_info()[0], TypeError)
817 self.assertEqual(next(g), KeyError)
818 self.assertEqual(sys.exc_info()[0], TypeError)
819 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000820 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000821 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000822
Benjamin Peterson83195c32011-07-03 13:44:00 -0500823 def test_generator_leaking2(self):
824 # See issue 12475.
825 def g():
826 yield
827 try:
828 raise RuntimeError
829 except RuntimeError:
830 it = g()
831 next(it)
832 try:
833 next(it)
834 except StopIteration:
835 pass
836 self.assertEqual(sys.exc_info(), (None, None, None))
837
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100838 def test_generator_leaking3(self):
839 # See issue #23353. When gen.throw() is called, the caller's
840 # exception state should be save and restored.
841 def g():
842 try:
843 yield
844 except ZeroDivisionError:
845 yield sys.exc_info()[1]
846 it = g()
847 next(it)
848 try:
849 1/0
850 except ZeroDivisionError as e:
851 self.assertIs(sys.exc_info()[1], e)
852 gen_exc = it.throw(e)
853 self.assertIs(sys.exc_info()[1], e)
854 self.assertIs(gen_exc, e)
855 self.assertEqual(sys.exc_info(), (None, None, None))
856
857 def test_generator_leaking4(self):
858 # See issue #23353. When an exception is raised by a generator,
859 # the caller's exception state should still be restored.
860 def g():
861 try:
862 1/0
863 except ZeroDivisionError:
864 yield sys.exc_info()[0]
865 raise
866 it = g()
867 try:
868 raise TypeError
869 except TypeError:
870 # The caller's exception state (TypeError) is temporarily
871 # saved in the generator.
872 tp = next(it)
873 self.assertIs(tp, ZeroDivisionError)
874 try:
875 next(it)
876 # We can't check it immediately, but while next() returns
877 # with an exception, it shouldn't have restored the old
878 # exception state (TypeError).
879 except ZeroDivisionError as e:
880 self.assertIs(sys.exc_info()[1], e)
881 # We used to find TypeError here.
882 self.assertEqual(sys.exc_info(), (None, None, None))
883
Benjamin Petersonac913412011-07-03 16:25:11 -0500884 def test_generator_doesnt_retain_old_exc(self):
885 def g():
886 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
887 yield
888 self.assertEqual(sys.exc_info(), (None, None, None))
889 it = g()
890 try:
891 raise RuntimeError
892 except RuntimeError:
893 next(it)
894 self.assertRaises(StopIteration, next, it)
895
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000896 def test_generator_finalizing_and_exc_info(self):
897 # See #7173
898 def simple_gen():
899 yield 1
900 def run_gen():
901 gen = simple_gen()
902 try:
903 raise RuntimeError
904 except RuntimeError:
905 return next(gen)
906 run_gen()
907 gc_collect()
908 self.assertEqual(sys.exc_info(), (None, None, None))
909
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200910 def _check_generator_cleanup_exc_state(self, testfunc):
911 # Issue #12791: exception state is cleaned up as soon as a generator
912 # is closed (reference cycles are broken).
913 class MyException(Exception):
914 def __init__(self, obj):
915 self.obj = obj
916 class MyObj:
917 pass
918
919 def raising_gen():
920 try:
921 raise MyException(obj)
922 except MyException:
923 yield
924
925 obj = MyObj()
926 wr = weakref.ref(obj)
927 g = raising_gen()
928 next(g)
929 testfunc(g)
930 g = obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300931 gc_collect() # For PyPy or other GCs.
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200932 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300933 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200934
935 def test_generator_throw_cleanup_exc_state(self):
936 def do_throw(g):
937 try:
938 g.throw(RuntimeError())
939 except RuntimeError:
940 pass
941 self._check_generator_cleanup_exc_state(do_throw)
942
943 def test_generator_close_cleanup_exc_state(self):
944 def do_close(g):
945 g.close()
946 self._check_generator_cleanup_exc_state(do_close)
947
948 def test_generator_del_cleanup_exc_state(self):
949 def do_del(g):
950 g = None
951 self._check_generator_cleanup_exc_state(do_del)
952
953 def test_generator_next_cleanup_exc_state(self):
954 def do_next(g):
955 try:
956 next(g)
957 except StopIteration:
958 pass
959 else:
960 self.fail("should have raised StopIteration")
961 self._check_generator_cleanup_exc_state(do_next)
962
963 def test_generator_send_cleanup_exc_state(self):
964 def do_send(g):
965 try:
966 g.send(None)
967 except StopIteration:
968 pass
969 else:
970 self.fail("should have raised StopIteration")
971 self._check_generator_cleanup_exc_state(do_send)
972
Benjamin Peterson27d63672008-06-15 20:09:12 +0000973 def test_3114(self):
974 # Bug #3114: in its destructor, MyObject retrieves a pointer to
975 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000976 class MyObject:
977 def __del__(self):
978 nonlocal e
979 e = sys.exc_info()
980 e = ()
981 try:
982 raise Exception(MyObject())
983 except:
984 pass
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300985 gc_collect() # For PyPy or other GCs.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000986 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000987
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700988 def test_raise_does_not_create_context_chain_cycle(self):
989 class A(Exception):
990 pass
991 class B(Exception):
992 pass
993 class C(Exception):
994 pass
995
996 # Create a context chain:
997 # C -> B -> A
998 # Then raise A in context of C.
999 try:
1000 try:
1001 raise A
1002 except A as a_:
1003 a = a_
1004 try:
1005 raise B
1006 except B as b_:
1007 b = b_
1008 try:
1009 raise C
1010 except C as c_:
1011 c = c_
1012 self.assertIsInstance(a, A)
1013 self.assertIsInstance(b, B)
1014 self.assertIsInstance(c, C)
1015 self.assertIsNone(a.__context__)
1016 self.assertIs(b.__context__, a)
1017 self.assertIs(c.__context__, b)
1018 raise a
1019 except A as e:
1020 exc = e
1021
1022 # Expect A -> C -> B, without cycle
1023 self.assertIs(exc, a)
1024 self.assertIs(a.__context__, c)
1025 self.assertIs(c.__context__, b)
1026 self.assertIsNone(b.__context__)
1027
1028 def test_no_hang_on_context_chain_cycle1(self):
1029 # See issue 25782. Cycle in context chain.
1030
1031 def cycle():
1032 try:
1033 raise ValueError(1)
1034 except ValueError as ex:
1035 ex.__context__ = ex
1036 raise TypeError(2)
1037
1038 try:
1039 cycle()
1040 except Exception as e:
1041 exc = e
1042
1043 self.assertIsInstance(exc, TypeError)
1044 self.assertIsInstance(exc.__context__, ValueError)
1045 self.assertIs(exc.__context__.__context__, exc.__context__)
1046
Miss Islington (bot)19604092021-08-16 02:01:14 -07001047 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001048 def test_no_hang_on_context_chain_cycle2(self):
1049 # See issue 25782. Cycle at head of context chain.
1050
1051 class A(Exception):
1052 pass
1053 class B(Exception):
1054 pass
1055 class C(Exception):
1056 pass
1057
1058 # Context cycle:
1059 # +-----------+
1060 # V |
1061 # C --> B --> A
1062 with self.assertRaises(C) as cm:
1063 try:
1064 raise A()
1065 except A as _a:
1066 a = _a
1067 try:
1068 raise B()
1069 except B as _b:
1070 b = _b
1071 try:
1072 raise C()
1073 except C as _c:
1074 c = _c
1075 a.__context__ = c
1076 raise c
1077
1078 self.assertIs(cm.exception, c)
1079 # Verify the expected context chain cycle
1080 self.assertIs(c.__context__, b)
1081 self.assertIs(b.__context__, a)
1082 self.assertIs(a.__context__, c)
1083
1084 def test_no_hang_on_context_chain_cycle3(self):
1085 # See issue 25782. Longer context chain with cycle.
1086
1087 class A(Exception):
1088 pass
1089 class B(Exception):
1090 pass
1091 class C(Exception):
1092 pass
1093 class D(Exception):
1094 pass
1095 class E(Exception):
1096 pass
1097
1098 # Context cycle:
1099 # +-----------+
1100 # V |
1101 # E --> D --> C --> B --> A
1102 with self.assertRaises(E) as cm:
1103 try:
1104 raise A()
1105 except A as _a:
1106 a = _a
1107 try:
1108 raise B()
1109 except B as _b:
1110 b = _b
1111 try:
1112 raise C()
1113 except C as _c:
1114 c = _c
1115 a.__context__ = c
1116 try:
1117 raise D()
1118 except D as _d:
1119 d = _d
1120 e = E()
1121 raise e
1122
1123 self.assertIs(cm.exception, e)
1124 # Verify the expected context chain cycle
1125 self.assertIs(e.__context__, d)
1126 self.assertIs(d.__context__, c)
1127 self.assertIs(c.__context__, b)
1128 self.assertIs(b.__context__, a)
1129 self.assertIs(a.__context__, c)
1130
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001131 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001132 # See issue 7309. This was a crasher.
1133
1134 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1135 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1136 u.end = 2
1137 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1138 u.end = 5
1139 u.reason = 0x345345345345345345
1140 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1141 u.encoding = 4000
1142 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1143 u.start = 1000
1144 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1145
1146 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1147 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1148 u.end = 2
1149 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1150 u.end = 5
1151 u.reason = 0x345345345345345345
1152 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1153 u.encoding = 4000
1154 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1155 u.start = 1000
1156 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1157
1158 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1159 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1160 u.end = 2
1161 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1162 u.end = 5
1163 u.reason = 0x345345345345345345
1164 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1165 u.start = 1000
1166 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001167
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001168 def test_unicode_errors_no_object(self):
1169 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001170 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001171 for klass in klasses:
1172 self.assertEqual(str(klass.__new__(klass)), "")
1173
Brett Cannon31f59292011-02-21 19:29:56 +00001174 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001175 def test_badisinstance(self):
1176 # Bug #2542: if issubclass(e, MyException) raises an exception,
1177 # it should be ignored
1178 class Meta(type):
1179 def __subclasscheck__(cls, subclass):
1180 raise ValueError()
1181 class MyException(Exception, metaclass=Meta):
1182 pass
1183
Martin Panter3263f682016-02-28 03:16:11 +00001184 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001185 try:
1186 raise KeyError()
1187 except MyException as e:
1188 self.fail("exception should not be a MyException")
1189 except KeyError:
1190 pass
1191 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001192 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001193 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001194 self.fail("Should have raised KeyError")
1195
1196 def g():
1197 try:
1198 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001199 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001200 return sys.exc_info()
1201 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001202 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001203 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001204
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001205
1206 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001207 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001208 # See bpo-33930
1209
1210 def foo():
1211 o = object()
1212 for x in range(1_000_000):
1213 # Create a big chain of method objects that will trigger
1214 # a deep chain of calls when they need to be destructed.
1215 o = o.__dir__
1216
1217 foo()
1218 support.gc_collect()
1219
xdegaye56d1f5c2017-10-26 15:09:06 +02001220 @cpython_only
1221 def test_recursion_normalizing_exception(self):
1222 # Issue #22898.
1223 # Test that a RecursionError is raised when tstate->recursion_depth is
1224 # equal to recursion_limit in PyErr_NormalizeException() and check
1225 # that a ResourceWarning is printed.
1226 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001227 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001228 # singleton was being used in that case, that held traceback data and
1229 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1230 # finalization of these locals.
1231 code = """if 1:
1232 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001233 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001234
1235 class MyException(Exception): pass
1236
1237 def setrecursionlimit(depth):
1238 while 1:
1239 try:
1240 sys.setrecursionlimit(depth)
1241 return depth
1242 except RecursionError:
1243 # sys.setrecursionlimit() raises a RecursionError if
1244 # the new recursion limit is too low (issue #25274).
1245 depth += 1
1246
1247 def recurse(cnt):
1248 cnt -= 1
1249 if cnt:
1250 recurse(cnt)
1251 else:
1252 generator.throw(MyException)
1253
1254 def gen():
1255 f = open(%a, mode='rb', buffering=0)
1256 yield
1257
1258 generator = gen()
1259 next(generator)
1260 recursionlimit = sys.getrecursionlimit()
1261 depth = get_recursion_depth()
1262 try:
1263 # Upon the last recursive invocation of recurse(),
1264 # tstate->recursion_depth is equal to (recursion_limit - 1)
1265 # and is equal to recursion_limit when _gen_throw() calls
1266 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001267 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001268 finally:
1269 sys.setrecursionlimit(recursionlimit)
1270 print('Done.')
1271 """ % __file__
1272 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1273 # Check that the program does not fail with SIGABRT.
1274 self.assertEqual(rc, 1)
1275 self.assertIn(b'RecursionError', err)
1276 self.assertIn(b'ResourceWarning', err)
1277 self.assertIn(b'Done.', out)
1278
1279 @cpython_only
1280 def test_recursion_normalizing_infinite_exception(self):
1281 # Issue #30697. Test that a RecursionError is raised when
1282 # PyErr_NormalizeException() maximum recursion depth has been
1283 # exceeded.
1284 code = """if 1:
1285 import _testcapi
1286 try:
1287 raise _testcapi.RecursingInfinitelyError
1288 finally:
1289 print('Done.')
1290 """
1291 rc, out, err = script_helper.assert_python_failure("-c", code)
1292 self.assertEqual(rc, 1)
1293 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1294 b'while normalizing an exception', err)
1295 self.assertIn(b'Done.', out)
1296
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001297
1298 def test_recursion_in_except_handler(self):
1299
1300 def set_relative_recursion_limit(n):
1301 depth = 1
1302 while True:
1303 try:
1304 sys.setrecursionlimit(depth)
1305 except RecursionError:
1306 depth += 1
1307 else:
1308 break
1309 sys.setrecursionlimit(depth+n)
1310
1311 def recurse_in_except():
1312 try:
1313 1/0
1314 except:
1315 recurse_in_except()
1316
1317 def recurse_after_except():
1318 try:
1319 1/0
1320 except:
1321 pass
1322 recurse_after_except()
1323
1324 def recurse_in_body_and_except():
1325 try:
1326 recurse_in_body_and_except()
1327 except:
1328 recurse_in_body_and_except()
1329
1330 recursionlimit = sys.getrecursionlimit()
1331 try:
1332 set_relative_recursion_limit(10)
1333 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1334 with self.subTest(func=func):
1335 try:
1336 func()
1337 except RecursionError:
1338 pass
1339 else:
1340 self.fail("Should have raised a RecursionError")
1341 finally:
1342 sys.setrecursionlimit(recursionlimit)
1343
1344
xdegaye56d1f5c2017-10-26 15:09:06 +02001345 @cpython_only
1346 def test_recursion_normalizing_with_no_memory(self):
1347 # Issue #30697. Test that in the abort that occurs when there is no
1348 # memory left and the size of the Python frames stack is greater than
1349 # the size of the list of preallocated MemoryError instances, the
1350 # Fatal Python error message mentions MemoryError.
1351 code = """if 1:
1352 import _testcapi
1353 class C(): pass
1354 def recurse(cnt):
1355 cnt -= 1
1356 if cnt:
1357 recurse(cnt)
1358 else:
1359 _testcapi.set_nomemory(0)
1360 C()
1361 recurse(16)
1362 """
1363 with SuppressCrashReport():
1364 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001365 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1366 b'Cannot recover from MemoryErrors while '
1367 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001368
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001369 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001370 def test_MemoryError(self):
1371 # PyErr_NoMemory always raises the same exception instance.
1372 # Check that the traceback is not doubled.
1373 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001374 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001375 def raiseMemError():
1376 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001377 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001378 except MemoryError as e:
1379 tb = e.__traceback__
1380 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001381 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001382 return traceback.format_tb(tb)
1383
1384 tb1 = raiseMemError()
1385 tb2 = raiseMemError()
1386 self.assertEqual(tb1, tb2)
1387
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001388 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001389 def test_exception_with_doc(self):
1390 import _testcapi
1391 doc2 = "This is a test docstring."
1392 doc4 = "This is another test docstring."
1393
1394 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1395 "error1")
1396
1397 # test basic usage of PyErr_NewException
1398 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1399 self.assertIs(type(error1), type)
1400 self.assertTrue(issubclass(error1, Exception))
1401 self.assertIsNone(error1.__doc__)
1402
1403 # test with given docstring
1404 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1405 self.assertEqual(error2.__doc__, doc2)
1406
1407 # test with explicit base (without docstring)
1408 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1409 base=error2)
1410 self.assertTrue(issubclass(error3, error2))
1411
1412 # test with explicit base tuple
1413 class C(object):
1414 pass
1415 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1416 (error3, C))
1417 self.assertTrue(issubclass(error4, error3))
1418 self.assertTrue(issubclass(error4, C))
1419 self.assertEqual(error4.__doc__, doc4)
1420
1421 # test with explicit dictionary
1422 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1423 error4, {'a': 1})
1424 self.assertTrue(issubclass(error5, error4))
1425 self.assertEqual(error5.a, 1)
1426 self.assertEqual(error5.__doc__, "")
1427
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001428 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001429 def test_memory_error_cleanup(self):
1430 # Issue #5437: preallocated MemoryError instances should not keep
1431 # traceback objects alive.
1432 from _testcapi import raise_memoryerror
1433 class C:
1434 pass
1435 wr = None
1436 def inner():
1437 nonlocal wr
1438 c = C()
1439 wr = weakref.ref(c)
1440 raise_memoryerror()
1441 # We cannot use assertRaises since it manually deletes the traceback
1442 try:
1443 inner()
1444 except MemoryError as e:
1445 self.assertNotEqual(wr(), None)
1446 else:
1447 self.fail("MemoryError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001448 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001449 self.assertEqual(wr(), None)
1450
Brett Cannon31f59292011-02-21 19:29:56 +00001451 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001452 def test_recursion_error_cleanup(self):
1453 # Same test as above, but with "recursion exceeded" errors
1454 class C:
1455 pass
1456 wr = None
1457 def inner():
1458 nonlocal wr
1459 c = C()
1460 wr = weakref.ref(c)
1461 inner()
1462 # We cannot use assertRaises since it manually deletes the traceback
1463 try:
1464 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001465 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001466 self.assertNotEqual(wr(), None)
1467 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001468 self.fail("RecursionError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001469 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001470 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001471
Antoine Pitroua7622852011-09-01 21:37:43 +02001472 def test_errno_ENOTDIR(self):
1473 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1474 with self.assertRaises(OSError) as cm:
1475 os.listdir(__file__)
1476 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1477
Martin Panter3263f682016-02-28 03:16:11 +00001478 def test_unraisable(self):
1479 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1480 class BrokenDel:
1481 def __del__(self):
1482 exc = ValueError("del is broken")
1483 # The following line is included in the traceback report:
1484 raise exc
1485
Victor Stinnere4d300e2019-05-22 23:44:02 +02001486 obj = BrokenDel()
1487 with support.catch_unraisable_exception() as cm:
1488 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001489
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001490 gc_collect() # For PyPy or other GCs.
Victor Stinnere4d300e2019-05-22 23:44:02 +02001491 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1492 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001493
1494 def test_unhandled(self):
1495 # Check for sensible reporting of unhandled exceptions
1496 for exc_type in (ValueError, BrokenStrException):
1497 with self.subTest(exc_type):
1498 try:
1499 exc = exc_type("test message")
1500 # The following line is included in the traceback report:
1501 raise exc
1502 except exc_type:
1503 with captured_stderr() as stderr:
1504 sys.__excepthook__(*sys.exc_info())
1505 report = stderr.getvalue()
1506 self.assertIn("test_exceptions.py", report)
1507 self.assertIn("raise exc", report)
1508 self.assertIn(exc_type.__name__, report)
1509 if exc_type is BrokenStrException:
1510 self.assertIn("<exception str() failed>", report)
1511 else:
1512 self.assertIn("test message", report)
1513 self.assertTrue(report.endswith("\n"))
1514
xdegaye66caacf2017-10-23 18:08:41 +02001515 @cpython_only
1516 def test_memory_error_in_PyErr_PrintEx(self):
1517 code = """if 1:
1518 import _testcapi
1519 class C(): pass
1520 _testcapi.set_nomemory(0, %d)
1521 C()
1522 """
1523
1524 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1525 # Span a large range of tests as the CPython code always evolves with
1526 # changes that add or remove memory allocations.
1527 for i in range(1, 20):
1528 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1529 self.assertIn(rc, (1, 120))
1530 self.assertIn(b'MemoryError', err)
1531
Mark Shannonae3087c2017-10-22 22:41:51 +01001532 def test_yield_in_nested_try_excepts(self):
1533 #Issue #25612
1534 class MainError(Exception):
1535 pass
1536
1537 class SubError(Exception):
1538 pass
1539
1540 def main():
1541 try:
1542 raise MainError()
1543 except MainError:
1544 try:
1545 yield
1546 except SubError:
1547 pass
1548 raise
1549
1550 coro = main()
1551 coro.send(None)
1552 with self.assertRaises(MainError):
1553 coro.throw(SubError())
1554
1555 def test_generator_doesnt_retain_old_exc2(self):
1556 #Issue 28884#msg282532
1557 def g():
1558 try:
1559 raise ValueError
1560 except ValueError:
1561 yield 1
1562 self.assertEqual(sys.exc_info(), (None, None, None))
1563 yield 2
1564
1565 gen = g()
1566
1567 try:
1568 raise IndexError
1569 except IndexError:
1570 self.assertEqual(next(gen), 1)
1571 self.assertEqual(next(gen), 2)
1572
1573 def test_raise_in_generator(self):
1574 #Issue 25612#msg304117
1575 def g():
1576 yield 1
1577 raise
1578 yield 2
1579
1580 with self.assertRaises(ZeroDivisionError):
1581 i = g()
1582 try:
1583 1/0
1584 except:
1585 next(i)
1586 next(i)
1587
Zackery Spytzce6a0702019-08-25 03:44:09 -06001588 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1589 def test_assert_shadowing(self):
1590 # Shadowing AssertionError would cause the assert statement to
1591 # misbehave.
1592 global AssertionError
1593 AssertionError = TypeError
1594 try:
1595 assert False, 'hello'
1596 except BaseException as e:
1597 del AssertionError
1598 self.assertIsInstance(e, AssertionError)
1599 self.assertEqual(str(e), 'hello')
1600 else:
1601 del AssertionError
1602 self.fail('Expected exception')
1603
Pablo Galindo9b648a92020-09-01 19:39:46 +01001604 def test_memory_error_subclasses(self):
1605 # bpo-41654: MemoryError instances use a freelist of objects that are
1606 # linked using the 'dict' attribute when they are inactive/dead.
1607 # Subclasses of MemoryError should not participate in the freelist
1608 # schema. This test creates a MemoryError object and keeps it alive
1609 # (therefore advancing the freelist) and then it creates and destroys a
1610 # subclass object. Finally, it checks that creating a new MemoryError
1611 # succeeds, proving that the freelist is not corrupted.
1612
1613 class TestException(MemoryError):
1614 pass
1615
1616 try:
1617 raise MemoryError
1618 except MemoryError as exc:
1619 inst = exc
1620
1621 try:
1622 raise TestException
1623 except Exception:
1624 pass
1625
1626 for _ in range(10):
1627 try:
1628 raise MemoryError
1629 except MemoryError as exc:
1630 pass
1631
1632 gc_collect()
1633
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001634global_for_suggestions = None
1635
1636class NameErrorTests(unittest.TestCase):
1637 def test_name_error_has_name(self):
1638 try:
1639 bluch
1640 except NameError as exc:
1641 self.assertEqual("bluch", exc.name)
1642
1643 def test_name_error_suggestions(self):
1644 def Substitution():
1645 noise = more_noise = a = bc = None
1646 blech = None
1647 print(bluch)
1648
1649 def Elimination():
1650 noise = more_noise = a = bc = None
1651 blch = None
1652 print(bluch)
1653
1654 def Addition():
1655 noise = more_noise = a = bc = None
1656 bluchin = None
1657 print(bluch)
1658
1659 def SubstitutionOverElimination():
1660 blach = None
1661 bluc = None
1662 print(bluch)
1663
1664 def SubstitutionOverAddition():
1665 blach = None
1666 bluchi = None
1667 print(bluch)
1668
1669 def EliminationOverAddition():
1670 blucha = None
1671 bluc = None
1672 print(bluch)
1673
Pablo Galindo7a041162021-04-19 23:35:53 +01001674 for func, suggestion in [(Substitution, "'blech'?"),
1675 (Elimination, "'blch'?"),
1676 (Addition, "'bluchin'?"),
1677 (EliminationOverAddition, "'blucha'?"),
1678 (SubstitutionOverElimination, "'blach'?"),
1679 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001680 err = None
1681 try:
1682 func()
1683 except NameError as exc:
1684 with support.captured_stderr() as err:
1685 sys.__excepthook__(*sys.exc_info())
1686 self.assertIn(suggestion, err.getvalue())
1687
1688 def test_name_error_suggestions_from_globals(self):
1689 def func():
1690 print(global_for_suggestio)
1691 try:
1692 func()
1693 except NameError as exc:
1694 with support.captured_stderr() as err:
1695 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001696 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001697
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001698 def test_name_error_suggestions_from_builtins(self):
1699 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001700 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001701 try:
1702 func()
1703 except NameError as exc:
1704 with support.captured_stderr() as err:
1705 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001706 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001707
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001708 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1709 def f():
1710 somethingverywronghehehehehehe = None
1711 print(somethingverywronghe)
1712
1713 try:
1714 f()
1715 except NameError as exc:
1716 with support.captured_stderr() as err:
1717 sys.__excepthook__(*sys.exc_info())
1718
1719 self.assertNotIn("somethingverywronghehe", err.getvalue())
1720
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001721 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1722 vvv = mom = w = id = pytho = None
1723
1724 with self.subTest(name="b"):
1725 try:
1726 b
1727 except NameError as exc:
1728 with support.captured_stderr() as err:
1729 sys.__excepthook__(*sys.exc_info())
1730 self.assertNotIn("you mean", err.getvalue())
1731 self.assertNotIn("vvv", err.getvalue())
1732 self.assertNotIn("mom", err.getvalue())
1733 self.assertNotIn("'id'", err.getvalue())
1734 self.assertNotIn("'w'", err.getvalue())
1735 self.assertNotIn("'pytho'", err.getvalue())
1736
1737 with self.subTest(name="v"):
1738 try:
1739 v
1740 except NameError as exc:
1741 with support.captured_stderr() as err:
1742 sys.__excepthook__(*sys.exc_info())
1743 self.assertNotIn("you mean", err.getvalue())
1744 self.assertNotIn("vvv", err.getvalue())
1745 self.assertNotIn("mom", err.getvalue())
1746 self.assertNotIn("'id'", err.getvalue())
1747 self.assertNotIn("'w'", err.getvalue())
1748 self.assertNotIn("'pytho'", err.getvalue())
1749
1750 with self.subTest(name="m"):
1751 try:
1752 m
1753 except NameError as exc:
1754 with support.captured_stderr() as err:
1755 sys.__excepthook__(*sys.exc_info())
1756 self.assertNotIn("you mean", err.getvalue())
1757 self.assertNotIn("vvv", err.getvalue())
1758 self.assertNotIn("mom", err.getvalue())
1759 self.assertNotIn("'id'", err.getvalue())
1760 self.assertNotIn("'w'", err.getvalue())
1761 self.assertNotIn("'pytho'", err.getvalue())
1762
1763 with self.subTest(name="py"):
1764 try:
1765 py
1766 except NameError as exc:
1767 with support.captured_stderr() as err:
1768 sys.__excepthook__(*sys.exc_info())
1769 self.assertNotIn("you mean", err.getvalue())
1770 self.assertNotIn("vvv", err.getvalue())
1771 self.assertNotIn("mom", err.getvalue())
1772 self.assertNotIn("'id'", err.getvalue())
1773 self.assertNotIn("'w'", err.getvalue())
1774 self.assertNotIn("'pytho'", err.getvalue())
1775
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001776 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001777 def f():
1778 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001779 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1780 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1781 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1782 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1783 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1784 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1785 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1786 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1787 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1788 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1789 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1790 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1791 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1792 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1793 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1794 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1795 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1796 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1797 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1798 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1799 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1800 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1801 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1802 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1803 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1804 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1805 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1806 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1807 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1808 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1809 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1810 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1811 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1812 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1813 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1814 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1815 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1816 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1817 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1818 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1819 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1820 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1821 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1822 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1823 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1824 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1825 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1826 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1827 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1828 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1829 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1830 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1831 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1832 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1833 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1834 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1835 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1836 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1837 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1838 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1839 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1840 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1841 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1842 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1843 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1844 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1845 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1846 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1847 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1848 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1849 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1850 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1851 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1852 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1853 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1854 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1855 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1856 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1857 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1858 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1859 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001860 print(a0)
1861
1862 try:
1863 f()
1864 except NameError as exc:
1865 with support.captured_stderr() as err:
1866 sys.__excepthook__(*sys.exc_info())
1867
Miss Islington (bot)d55bf812021-10-07 05:11:38 -07001868 self.assertNotRegex(err.getvalue(), r"NameError.*a1")
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001869
1870 def test_name_error_with_custom_exceptions(self):
1871 def f():
1872 blech = None
1873 raise NameError()
1874
1875 try:
1876 f()
1877 except NameError as exc:
1878 with support.captured_stderr() as err:
1879 sys.__excepthook__(*sys.exc_info())
1880
1881 self.assertNotIn("blech", err.getvalue())
1882
1883 def f():
1884 blech = None
1885 raise NameError
1886
1887 try:
1888 f()
1889 except NameError as exc:
1890 with support.captured_stderr() as err:
1891 sys.__excepthook__(*sys.exc_info())
1892
1893 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001894
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001895 def test_unbound_local_error_doesn_not_match(self):
1896 def foo():
1897 something = 3
1898 print(somethong)
1899 somethong = 3
1900
1901 try:
1902 foo()
1903 except UnboundLocalError as exc:
1904 with support.captured_stderr() as err:
1905 sys.__excepthook__(*sys.exc_info())
1906
1907 self.assertNotIn("something", err.getvalue())
1908
Łukasz Langa8eabe602021-11-18 01:28:04 +01001909 def test_issue45826(self):
1910 # regression test for bpo-45826
1911 def f():
1912 with self.assertRaisesRegex(NameError, 'aaa'):
1913 aab
1914
1915 try:
1916 f()
1917 except self.failureException:
1918 with support.captured_stderr() as err:
1919 sys.__excepthook__(*sys.exc_info())
1920
1921 self.assertIn("aab", err.getvalue())
1922
1923 def test_issue45826_focused(self):
1924 def f():
1925 try:
1926 nonsense
1927 except BaseException as E:
1928 E.with_traceback(None)
1929 raise ZeroDivisionError()
1930
1931 try:
1932 f()
1933 except ZeroDivisionError:
1934 with support.captured_stderr() as err:
1935 sys.__excepthook__(*sys.exc_info())
1936
1937 self.assertIn("nonsense", err.getvalue())
1938 self.assertIn("ZeroDivisionError", err.getvalue())
1939
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001940
Pablo Galindo37494b42021-04-14 02:36:07 +01001941class AttributeErrorTests(unittest.TestCase):
1942 def test_attributes(self):
1943 # Setting 'attr' should not be a problem.
1944 exc = AttributeError('Ouch!')
1945 self.assertIsNone(exc.name)
1946 self.assertIsNone(exc.obj)
1947
1948 sentinel = object()
1949 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1950 self.assertEqual(exc.name, 'carry')
1951 self.assertIs(exc.obj, sentinel)
1952
1953 def test_getattr_has_name_and_obj(self):
1954 class A:
1955 blech = None
1956
1957 obj = A()
1958 try:
1959 obj.bluch
1960 except AttributeError as exc:
1961 self.assertEqual("bluch", exc.name)
1962 self.assertEqual(obj, exc.obj)
1963
1964 def test_getattr_has_name_and_obj_for_method(self):
1965 class A:
1966 def blech(self):
1967 return
1968
1969 obj = A()
1970 try:
1971 obj.bluch()
1972 except AttributeError as exc:
1973 self.assertEqual("bluch", exc.name)
1974 self.assertEqual(obj, exc.obj)
1975
1976 def test_getattr_suggestions(self):
1977 class Substitution:
1978 noise = more_noise = a = bc = None
1979 blech = None
1980
1981 class Elimination:
1982 noise = more_noise = a = bc = None
1983 blch = None
1984
1985 class Addition:
1986 noise = more_noise = a = bc = None
1987 bluchin = None
1988
1989 class SubstitutionOverElimination:
1990 blach = None
1991 bluc = None
1992
1993 class SubstitutionOverAddition:
1994 blach = None
1995 bluchi = None
1996
1997 class EliminationOverAddition:
1998 blucha = None
1999 bluc = None
2000
Pablo Galindo7a041162021-04-19 23:35:53 +01002001 for cls, suggestion in [(Substitution, "'blech'?"),
2002 (Elimination, "'blch'?"),
2003 (Addition, "'bluchin'?"),
2004 (EliminationOverAddition, "'bluc'?"),
2005 (SubstitutionOverElimination, "'blach'?"),
2006 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01002007 try:
2008 cls().bluch
2009 except AttributeError as exc:
2010 with support.captured_stderr() as err:
2011 sys.__excepthook__(*sys.exc_info())
2012
2013 self.assertIn(suggestion, err.getvalue())
2014
2015 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
2016 class A:
2017 blech = None
2018
2019 try:
2020 A().somethingverywrong
2021 except AttributeError as exc:
2022 with support.captured_stderr() as err:
2023 sys.__excepthook__(*sys.exc_info())
2024
2025 self.assertNotIn("blech", err.getvalue())
2026
Dennis Sweeney284c52d2021-04-26 20:22:27 -04002027 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
2028 class MyClass:
2029 vvv = mom = w = id = pytho = None
2030
2031 with self.subTest(name="b"):
2032 try:
2033 MyClass.b
2034 except AttributeError as exc:
2035 with support.captured_stderr() as err:
2036 sys.__excepthook__(*sys.exc_info())
2037 self.assertNotIn("you mean", err.getvalue())
2038 self.assertNotIn("vvv", err.getvalue())
2039 self.assertNotIn("mom", err.getvalue())
2040 self.assertNotIn("'id'", err.getvalue())
2041 self.assertNotIn("'w'", err.getvalue())
2042 self.assertNotIn("'pytho'", err.getvalue())
2043
2044 with self.subTest(name="v"):
2045 try:
2046 MyClass.v
2047 except AttributeError as exc:
2048 with support.captured_stderr() as err:
2049 sys.__excepthook__(*sys.exc_info())
2050 self.assertNotIn("you mean", err.getvalue())
2051 self.assertNotIn("vvv", err.getvalue())
2052 self.assertNotIn("mom", err.getvalue())
2053 self.assertNotIn("'id'", err.getvalue())
2054 self.assertNotIn("'w'", err.getvalue())
2055 self.assertNotIn("'pytho'", err.getvalue())
2056
2057 with self.subTest(name="m"):
2058 try:
2059 MyClass.m
2060 except AttributeError as exc:
2061 with support.captured_stderr() as err:
2062 sys.__excepthook__(*sys.exc_info())
2063 self.assertNotIn("you mean", err.getvalue())
2064 self.assertNotIn("vvv", err.getvalue())
2065 self.assertNotIn("mom", err.getvalue())
2066 self.assertNotIn("'id'", err.getvalue())
2067 self.assertNotIn("'w'", err.getvalue())
2068 self.assertNotIn("'pytho'", err.getvalue())
2069
2070 with self.subTest(name="py"):
2071 try:
2072 MyClass.py
2073 except AttributeError as exc:
2074 with support.captured_stderr() as err:
2075 sys.__excepthook__(*sys.exc_info())
2076 self.assertNotIn("you mean", err.getvalue())
2077 self.assertNotIn("vvv", err.getvalue())
2078 self.assertNotIn("mom", err.getvalue())
2079 self.assertNotIn("'id'", err.getvalue())
2080 self.assertNotIn("'w'", err.getvalue())
2081 self.assertNotIn("'pytho'", err.getvalue())
2082
2083
Pablo Galindo37494b42021-04-14 02:36:07 +01002084 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2085 class A:
2086 blech = None
2087 # A class with a very big __dict__ will not be consider
2088 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002089 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002090 setattr(A, f"index_{index}", None)
2091
2092 try:
2093 A().bluch
2094 except AttributeError as exc:
2095 with support.captured_stderr() as err:
2096 sys.__excepthook__(*sys.exc_info())
2097
2098 self.assertNotIn("blech", err.getvalue())
2099
2100 def test_getattr_suggestions_no_args(self):
2101 class A:
2102 blech = None
2103 def __getattr__(self, attr):
2104 raise AttributeError()
2105
2106 try:
2107 A().bluch
2108 except AttributeError as exc:
2109 with support.captured_stderr() as err:
2110 sys.__excepthook__(*sys.exc_info())
2111
2112 self.assertIn("blech", err.getvalue())
2113
2114 class A:
2115 blech = None
2116 def __getattr__(self, attr):
2117 raise AttributeError
2118
2119 try:
2120 A().bluch
2121 except AttributeError as exc:
2122 with support.captured_stderr() as err:
2123 sys.__excepthook__(*sys.exc_info())
2124
2125 self.assertIn("blech", err.getvalue())
2126
2127 def test_getattr_suggestions_invalid_args(self):
2128 class NonStringifyClass:
2129 __str__ = None
2130 __repr__ = None
2131
2132 class A:
2133 blech = None
2134 def __getattr__(self, attr):
2135 raise AttributeError(NonStringifyClass())
2136
2137 class B:
2138 blech = None
2139 def __getattr__(self, attr):
2140 raise AttributeError("Error", 23)
2141
2142 class C:
2143 blech = None
2144 def __getattr__(self, attr):
2145 raise AttributeError(23)
2146
2147 for cls in [A, B, C]:
2148 try:
2149 cls().bluch
2150 except AttributeError as exc:
2151 with support.captured_stderr() as err:
2152 sys.__excepthook__(*sys.exc_info())
2153
2154 self.assertIn("blech", err.getvalue())
2155
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002156 def test_getattr_suggestions_for_same_name(self):
2157 class A:
2158 def __dir__(self):
2159 return ['blech']
2160 try:
2161 A().blech
2162 except AttributeError as exc:
2163 with support.captured_stderr() as err:
2164 sys.__excepthook__(*sys.exc_info())
2165
2166 self.assertNotIn("Did you mean", err.getvalue())
2167
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002168 def test_attribute_error_with_failing_dict(self):
2169 class T:
2170 bluch = 1
2171 def __dir__(self):
2172 raise AttributeError("oh no!")
2173
2174 try:
2175 T().blich
2176 except AttributeError as exc:
2177 with support.captured_stderr() as err:
2178 sys.__excepthook__(*sys.exc_info())
2179
2180 self.assertNotIn("blech", err.getvalue())
2181 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002182
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002183 def test_attribute_error_with_bad_name(self):
2184 try:
2185 raise AttributeError(name=12, obj=23)
2186 except AttributeError as exc:
2187 with support.captured_stderr() as err:
2188 sys.__excepthook__(*sys.exc_info())
2189
2190 self.assertNotIn("?", err.getvalue())
2191
2192
Brett Cannon79ec55e2012-04-12 20:24:54 -04002193class ImportErrorTests(unittest.TestCase):
2194
2195 def test_attributes(self):
2196 # Setting 'name' and 'path' should not be a problem.
2197 exc = ImportError('test')
2198 self.assertIsNone(exc.name)
2199 self.assertIsNone(exc.path)
2200
2201 exc = ImportError('test', name='somemodule')
2202 self.assertEqual(exc.name, 'somemodule')
2203 self.assertIsNone(exc.path)
2204
2205 exc = ImportError('test', path='somepath')
2206 self.assertEqual(exc.path, 'somepath')
2207 self.assertIsNone(exc.name)
2208
2209 exc = ImportError('test', path='somepath', name='somename')
2210 self.assertEqual(exc.name, 'somename')
2211 self.assertEqual(exc.path, 'somepath')
2212
Michael Seifert64c8f702017-04-09 09:47:12 +02002213 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002214 with self.assertRaisesRegex(TypeError, msg):
2215 ImportError('test', invalid='keyword')
2216
2217 with self.assertRaisesRegex(TypeError, msg):
2218 ImportError('test', name='name', invalid='keyword')
2219
2220 with self.assertRaisesRegex(TypeError, msg):
2221 ImportError('test', path='path', invalid='keyword')
2222
2223 with self.assertRaisesRegex(TypeError, msg):
2224 ImportError(invalid='keyword')
2225
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002226 with self.assertRaisesRegex(TypeError, msg):
2227 ImportError('test', invalid='keyword', another=True)
2228
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002229 def test_reset_attributes(self):
2230 exc = ImportError('test', name='name', path='path')
2231 self.assertEqual(exc.args, ('test',))
2232 self.assertEqual(exc.msg, 'test')
2233 self.assertEqual(exc.name, 'name')
2234 self.assertEqual(exc.path, 'path')
2235
2236 # Reset not specified attributes
2237 exc.__init__()
2238 self.assertEqual(exc.args, ())
2239 self.assertEqual(exc.msg, None)
2240 self.assertEqual(exc.name, None)
2241 self.assertEqual(exc.path, None)
2242
Brett Cannon07c6e712012-08-24 13:05:09 -04002243 def test_non_str_argument(self):
2244 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002245 with check_warnings(('', BytesWarning), quiet=True):
2246 arg = b'abc'
2247 exc = ImportError(arg)
2248 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002249
Serhiy Storchakab7853962017-04-08 09:55:07 +03002250 def test_copy_pickle(self):
2251 for kwargs in (dict(),
2252 dict(name='somename'),
2253 dict(path='somepath'),
2254 dict(name='somename', path='somepath')):
2255 orig = ImportError('test', **kwargs)
2256 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2257 exc = pickle.loads(pickle.dumps(orig, proto))
2258 self.assertEqual(exc.args, ('test',))
2259 self.assertEqual(exc.msg, 'test')
2260 self.assertEqual(exc.name, orig.name)
2261 self.assertEqual(exc.path, orig.path)
2262 for c in copy.copy, copy.deepcopy:
2263 exc = c(orig)
2264 self.assertEqual(exc.args, ('test',))
2265 self.assertEqual(exc.msg, 'test')
2266 self.assertEqual(exc.name, orig.name)
2267 self.assertEqual(exc.path, orig.path)
2268
Pablo Galindoa77aac42021-04-23 14:27:05 +01002269class SyntaxErrorTests(unittest.TestCase):
2270 def test_range_of_offsets(self):
2271 cases = [
2272 # Basic range from 2->7
2273 (("bad.py", 1, 2, "abcdefg", 1, 7),
2274 dedent(
2275 """
2276 File "bad.py", line 1
2277 abcdefg
2278 ^^^^^
2279 SyntaxError: bad bad
2280 """)),
2281 # end_offset = start_offset + 1
2282 (("bad.py", 1, 2, "abcdefg", 1, 3),
2283 dedent(
2284 """
2285 File "bad.py", line 1
2286 abcdefg
2287 ^
2288 SyntaxError: bad bad
2289 """)),
2290 # Negative end offset
2291 (("bad.py", 1, 2, "abcdefg", 1, -2),
2292 dedent(
2293 """
2294 File "bad.py", line 1
2295 abcdefg
2296 ^
2297 SyntaxError: bad bad
2298 """)),
2299 # end offset before starting offset
2300 (("bad.py", 1, 4, "abcdefg", 1, 2),
2301 dedent(
2302 """
2303 File "bad.py", line 1
2304 abcdefg
2305 ^
2306 SyntaxError: bad bad
2307 """)),
2308 # Both offsets negative
2309 (("bad.py", 1, -4, "abcdefg", 1, -2),
2310 dedent(
2311 """
2312 File "bad.py", line 1
2313 abcdefg
2314 SyntaxError: bad bad
2315 """)),
2316 # Both offsets negative and the end more negative
2317 (("bad.py", 1, -4, "abcdefg", 1, -5),
2318 dedent(
2319 """
2320 File "bad.py", line 1
2321 abcdefg
2322 SyntaxError: bad bad
2323 """)),
2324 # Both offsets 0
2325 (("bad.py", 1, 0, "abcdefg", 1, 0),
2326 dedent(
2327 """
2328 File "bad.py", line 1
2329 abcdefg
2330 SyntaxError: bad bad
2331 """)),
2332 # Start offset 0 and end offset not 0
2333 (("bad.py", 1, 0, "abcdefg", 1, 5),
2334 dedent(
2335 """
2336 File "bad.py", line 1
2337 abcdefg
2338 SyntaxError: bad bad
2339 """)),
Christian Clausscfca4a62021-10-07 17:49:47 +02002340 # End offset pass the source length
Pablo Galindoa77aac42021-04-23 14:27:05 +01002341 (("bad.py", 1, 2, "abcdefg", 1, 100),
2342 dedent(
2343 """
2344 File "bad.py", line 1
2345 abcdefg
2346 ^^^^^^
2347 SyntaxError: bad bad
2348 """)),
2349 ]
2350 for args, expected in cases:
2351 with self.subTest(args=args):
2352 try:
2353 raise SyntaxError("bad bad", args)
2354 except SyntaxError as exc:
2355 with support.captured_stderr() as err:
2356 sys.__excepthook__(*sys.exc_info())
Miss Islington (bot)c800e392021-09-21 15:38:59 -07002357 self.assertIn(expected, err.getvalue())
Pablo Galindoa77aac42021-04-23 14:27:05 +01002358 the_exception = exc
2359
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002360 def test_encodings(self):
2361 source = (
2362 '# -*- coding: cp437 -*-\n'
2363 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2364 )
2365 try:
2366 with open(TESTFN, 'w', encoding='cp437') as testfile:
2367 testfile.write(source)
2368 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2369 err = err.decode('utf-8').splitlines()
2370
2371 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2372 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2373 finally:
2374 unlink(TESTFN)
2375
Łukasz Langa904af3d2021-11-20 16:34:56 +01002376 # Check backwards tokenizer errors
2377 source = '# -*- coding: ascii -*-\n\n(\n'
2378 try:
2379 with open(TESTFN, 'w', encoding='ascii') as testfile:
2380 testfile.write(source)
2381 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2382 err = err.decode('utf-8').splitlines()
2383
2384 self.assertEqual(err[-3], ' (')
2385 self.assertEqual(err[-2], ' ^')
2386 finally:
2387 unlink(TESTFN)
2388
Miss Islington (bot)94483f12021-12-12 08:52:49 -08002389 def test_non_utf8(self):
2390 # Check non utf-8 characters
2391 try:
2392 with open(TESTFN, 'bw') as testfile:
2393 testfile.write(b"\x89")
2394 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2395 err = err.decode('utf-8').splitlines()
2396
2397 self.assertIn("SyntaxError: Non-UTF-8 code starting with '\\x89' in file", err[-1])
2398 finally:
2399 unlink(TESTFN)
2400
Pablo Galindoa77aac42021-04-23 14:27:05 +01002401 def test_attributes_new_constructor(self):
2402 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2403 the_exception = SyntaxError("bad bad", args)
2404 filename, lineno, offset, error, end_lineno, end_offset = args
2405 self.assertEqual(filename, the_exception.filename)
2406 self.assertEqual(lineno, the_exception.lineno)
2407 self.assertEqual(end_lineno, the_exception.end_lineno)
2408 self.assertEqual(offset, the_exception.offset)
2409 self.assertEqual(end_offset, the_exception.end_offset)
2410 self.assertEqual(error, the_exception.text)
2411 self.assertEqual("bad bad", the_exception.msg)
2412
2413 def test_attributes_old_constructor(self):
2414 args = ("bad.py", 1, 2, "abcdefg")
2415 the_exception = SyntaxError("bad bad", args)
2416 filename, lineno, offset, error = args
2417 self.assertEqual(filename, the_exception.filename)
2418 self.assertEqual(lineno, the_exception.lineno)
2419 self.assertEqual(None, the_exception.end_lineno)
2420 self.assertEqual(offset, the_exception.offset)
2421 self.assertEqual(None, the_exception.end_offset)
2422 self.assertEqual(error, the_exception.text)
2423 self.assertEqual("bad bad", the_exception.msg)
2424
2425 def test_incorrect_constructor(self):
2426 args = ("bad.py", 1, 2)
2427 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2428
2429 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2430 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2431
2432 args = ("bad.py", 1, 2, "abcdefg", 1)
2433 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2434
Brett Cannon79ec55e2012-04-12 20:24:54 -04002435
Mark Shannonbf353f32020-12-17 13:55:28 +00002436class PEP626Tests(unittest.TestCase):
2437
Mark Shannon0b6b2862021-06-24 13:09:14 +01002438 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002439 try:
2440 f()
2441 except Exception as ex:
2442 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002443 else:
2444 self.fail("No exception raised")
2445 lines = []
2446 t = t.tb_next # Skip this function
2447 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002448 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002449 lines.append(
2450 None if frame.f_lineno is None else
2451 frame.f_lineno-frame.f_code.co_firstlineno
2452 )
2453 t = t.tb_next
2454 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002455
2456 def test_lineno_after_raise_simple(self):
2457 def simple():
2458 1/0
2459 pass
2460 self.lineno_after_raise(simple, 1)
2461
2462 def test_lineno_after_raise_in_except(self):
2463 def in_except():
2464 try:
2465 1/0
2466 except:
2467 1/0
2468 pass
2469 self.lineno_after_raise(in_except, 4)
2470
2471 def test_lineno_after_other_except(self):
2472 def other_except():
2473 try:
2474 1/0
2475 except TypeError as ex:
2476 pass
2477 self.lineno_after_raise(other_except, 3)
2478
2479 def test_lineno_in_named_except(self):
2480 def in_named_except():
2481 try:
2482 1/0
2483 except Exception as ex:
2484 1/0
2485 pass
2486 self.lineno_after_raise(in_named_except, 4)
2487
2488 def test_lineno_in_try(self):
2489 def in_try():
2490 try:
2491 1/0
2492 finally:
2493 pass
2494 self.lineno_after_raise(in_try, 4)
2495
2496 def test_lineno_in_finally_normal(self):
2497 def in_finally_normal():
2498 try:
2499 pass
2500 finally:
2501 1/0
2502 pass
2503 self.lineno_after_raise(in_finally_normal, 4)
2504
2505 def test_lineno_in_finally_except(self):
2506 def in_finally_except():
2507 try:
2508 1/0
2509 finally:
2510 1/0
2511 pass
2512 self.lineno_after_raise(in_finally_except, 4)
2513
2514 def test_lineno_after_with(self):
2515 class Noop:
2516 def __enter__(self):
2517 return self
2518 def __exit__(self, *args):
2519 pass
2520 def after_with():
2521 with Noop():
2522 1/0
2523 pass
2524 self.lineno_after_raise(after_with, 2)
2525
Mark Shannon088a15c2021-04-29 19:28:50 +01002526 def test_missing_lineno_shows_as_none(self):
2527 def f():
2528 1/0
2529 self.lineno_after_raise(f, 1)
2530 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2531 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002532
Mark Shannon0b6b2862021-06-24 13:09:14 +01002533 def test_lineno_after_raise_in_with_exit(self):
2534 class ExitFails:
2535 def __enter__(self):
2536 return self
2537 def __exit__(self, *args):
2538 raise ValueError
2539
2540 def after_with():
2541 with ExitFails():
2542 1/0
2543 self.lineno_after_raise(after_with, 1, 1)
2544
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002545if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002546 unittest.main()