blob: ad2864bc41637fcba557bc9f5d9a31354771f1b5 [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)
Ammar Askar025eb982018-09-24 17:12:49 -0400237
238 # Errors thrown by compile.c
239 check('class foo:return 1', 1, 11)
240 check('def f():\n continue', 2, 3)
241 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100242 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400243
244 # Errors thrown by tokenizer.c
245 check('(0x+1)', 1, 3)
246 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700247 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400248 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700249 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200250 check('\u03b1 = 0xI', 1, 6)
251 check(b'\xce\xb1 = 0xI', 1, 6)
252 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
253 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100254 check(b"""if 1:
255 def foo():
256 '''
257
258 def bar():
259 pass
260
261 def baz():
262 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300263 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100264 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
265 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700266 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700267 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400268
269 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200270 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400271 check('def f():\n from _ import *', 1, 1)
272 check('def f(x, x):\n pass', 1, 1)
273 check('def f(x):\n nonlocal x', 2, 3)
274 check('def f(x):\n x = 1\n global x', 3, 3)
275 check('nonlocal x', 1, 1)
276 check('def f():\n global x\n nonlocal x', 2, 3)
277
Ammar Askar025eb982018-09-24 17:12:49 -0400278 # Errors thrown by future.c
279 check('from __future__ import doesnt_exist', 1, 1)
280 check('from __future__ import braces', 1, 1)
281 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100282 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300283 check('def f():\n x, y: int', 2, 3)
284 check('[*x for x in xs]', 1, 2)
285 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300286 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100287 check('(yield i) = 2', 1, 2)
288 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200289
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000290 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000291 def testSettingException(self):
292 # test that setting an exception at the C level works even if the
293 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000294
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000295 class BadException(Exception):
296 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000297 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000298
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000299 class InvalidException:
300 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000301
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000302 def test_capi1():
303 import _testcapi
304 try:
305 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000306 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000307 exc, err, tb = sys.exc_info()
308 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000309 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000311 else:
312 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000313
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000314 def test_capi2():
315 import _testcapi
316 try:
317 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000318 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000319 exc, err, tb = sys.exc_info()
320 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000321 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000322 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000323 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000324 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000325 else:
326 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000327
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000328 def test_capi3():
329 import _testcapi
330 self.assertRaises(SystemError, _testcapi.raise_exception,
331 InvalidException, 1)
332
333 if not sys.platform.startswith('java'):
334 test_capi1()
335 test_capi2()
336 test_capi3()
337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 def test_WindowsError(self):
339 try:
340 WindowsError
341 except NameError:
342 pass
343 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200344 self.assertIs(WindowsError, OSError)
345 self.assertEqual(str(OSError(1001)), "1001")
346 self.assertEqual(str(OSError(1001, "message")),
347 "[Errno 1001] message")
348 # POSIX errno (9 aka EBADF) is untranslated
349 w = OSError(9, 'foo', 'bar')
350 self.assertEqual(w.errno, 9)
351 self.assertEqual(w.winerror, None)
352 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
353 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
354 w = OSError(0, 'foo', 'bar', 3)
355 self.assertEqual(w.errno, 2)
356 self.assertEqual(w.winerror, 3)
357 self.assertEqual(w.strerror, 'foo')
358 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000359 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100360 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200361 # Unknown win error becomes EINVAL (22)
362 w = OSError(0, 'foo', None, 1001)
363 self.assertEqual(w.errno, 22)
364 self.assertEqual(w.winerror, 1001)
365 self.assertEqual(w.strerror, 'foo')
366 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000367 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100368 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200369 # Non-numeric "errno"
370 w = OSError('bar', 'foo')
371 self.assertEqual(w.errno, 'bar')
372 self.assertEqual(w.winerror, None)
373 self.assertEqual(w.strerror, 'foo')
374 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000375 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000376
Victor Stinnerd223fa62015-04-02 14:17:38 +0200377 @unittest.skipUnless(sys.platform == 'win32',
378 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300379 def test_windows_message(self):
380 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200381 ctypes = import_module('ctypes')
382 # this error code has no message, Python formats it as hexadecimal
383 code = 3765269347
384 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
385 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300386
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000387 def testAttributes(self):
388 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000389
390 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000391 (BaseException, (), {'args' : ()}),
392 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000393 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000394 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000395 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000396 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000397 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000398 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200399 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000400 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000401 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200402 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000403 {'args' : ('foo', 'bar'),
404 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000405 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200406 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000407 {'args' : ('foo', 'bar'),
408 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000409 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800410 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
411 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200412 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000413 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000414 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
415 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200416 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000417 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000418 'strerror' : 'strErrorStr',
419 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000420 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000421 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100422 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000423 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000424 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000425 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100426 'filename' : None, 'lineno' : None, 'offset' : None,
427 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000428 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100429 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000430 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000431 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100432 'offsetStr', 'textStr',
433 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000434 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100435 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
436 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000437 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100438 'textStr', 'endLinenoStr', 'endOffsetStr',
439 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000440 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000441 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100442 'textStr', 'endLinenoStr', 'endOffsetStr',
443 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000444 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100445 'filename' : None, 'lineno' : None, 'offset' : None,
446 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000447 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000448 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
449 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000450 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000451 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000452 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000454 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000455 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000456 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000457 'ordinal not in range'),
458 'encoding' : 'ascii', 'object' : b'\xff',
459 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000460 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
461 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000462 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000464 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000466 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000467 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000468 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000469 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100470 (NaiveException, ('foo',),
471 {'args': ('foo',), 'x': 'foo'}),
472 (SlottedNaiveException, ('foo',),
473 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000474 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000475 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200476 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000477 exceptionList.append(
478 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000479 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200480 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000481 'errno' : 1,
482 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000483 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000484 except NameError:
485 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000486
Guido van Rossumebe3e162007-05-17 18:20:34 +0000487 for exc, args, expected in exceptionList:
488 try:
489 e = exc(*args)
490 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000491 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100492 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000493 else:
494 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100495 if not type(e).__name__.endswith('NaiveException'):
496 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000497 # Verify no ref leaks in Exc_str()
498 s = str(e)
499 for checkArgName in expected:
500 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000501 self.assertEqual(repr(value),
502 repr(expected[checkArgName]),
503 '%r.%s == %r, expected %r' % (
504 e, checkArgName,
505 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000506
Guido van Rossumebe3e162007-05-17 18:20:34 +0000507 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000508 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000509 for protocol in range(p.HIGHEST_PROTOCOL + 1):
510 s = p.dumps(e, protocol)
511 new = p.loads(s)
512 for checkArgName in expected:
513 got = repr(getattr(new, checkArgName))
514 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000515 self.assertEqual(got, want,
516 'pickled "%r", attribute "%s' %
517 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000518
Collin Winter828f04a2007-08-31 00:04:24 +0000519 def testWithTraceback(self):
520 try:
521 raise IndexError(4)
522 except:
523 tb = sys.exc_info()[2]
524
525 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000526 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000527 self.assertEqual(e.__traceback__, tb)
528
529 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000530 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000531 self.assertEqual(e.__traceback__, tb)
532
533 class MyException(Exception):
534 pass
535
536 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000537 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000538 self.assertEqual(e.__traceback__, tb)
539
540 def testInvalidTraceback(self):
541 try:
542 Exception().__traceback__ = 5
543 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000544 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000545 else:
546 self.fail("No exception raised")
547
Georg Brandlab6f2f62009-03-31 04:16:10 +0000548 def testInvalidAttrs(self):
549 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
550 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
551 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
552 self.assertRaises(TypeError, delattr, Exception(), '__context__')
553
Collin Winter828f04a2007-08-31 00:04:24 +0000554 def testNoneClearsTracebackAttr(self):
555 try:
556 raise IndexError(4)
557 except:
558 tb = sys.exc_info()[2]
559
560 e = Exception()
561 e.__traceback__ = tb
562 e.__traceback__ = None
563 self.assertEqual(e.__traceback__, None)
564
565 def testChainingAttrs(self):
566 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000567 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700568 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000569
570 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000571 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700572 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000573
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200574 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000575 pass
576
577 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000578 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700579 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000580
581 def testChainingDescriptors(self):
582 try:
583 raise Exception()
584 except Exception as exc:
585 e = exc
586
587 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700588 self.assertIsNone(e.__cause__)
589 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000590
591 e.__context__ = NameError()
592 e.__cause__ = None
593 self.assertIsInstance(e.__context__, NameError)
594 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700595 self.assertTrue(e.__suppress_context__)
596 e.__suppress_context__ = False
597 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000598
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000599 def testKeywordArgs(self):
600 # test that builtin exception don't take keyword args,
601 # but user-defined subclasses can if they want
602 self.assertRaises(TypeError, BaseException, a=1)
603
604 class DerivedException(BaseException):
605 def __init__(self, fancy_arg):
606 BaseException.__init__(self)
607 self.fancy_arg = fancy_arg
608
609 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000610 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000611
Brett Cannon31f59292011-02-21 19:29:56 +0000612 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 def testInfiniteRecursion(self):
614 def f():
615 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400616 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
618 def g():
619 try:
620 return g()
621 except ValueError:
622 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400623 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000625 def test_str(self):
626 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000627 self.assertTrue(str(Exception))
628 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000629 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000630
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000631 def testExceptionCleanupNames(self):
632 # Make sure the local variable bound to the exception instance by
633 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000634 try:
635 raise Exception()
636 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000637 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000638 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000639 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000640
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000641 def testExceptionCleanupState(self):
642 # Make sure exception state is cleaned up as soon as the except
643 # block is left. See #2507
644
645 class MyException(Exception):
646 def __init__(self, obj):
647 self.obj = obj
648 class MyObj:
649 pass
650
651 def inner_raising_func():
652 # Create some references in exception value and traceback
653 local_ref = obj
654 raise MyException(obj)
655
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000656 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000657 obj = MyObj()
658 wr = weakref.ref(obj)
659 try:
660 inner_raising_func()
661 except MyException as e:
662 pass
663 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300664 gc_collect() # For PyPy or other GCs.
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000665 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300666 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000667
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000668 # Qualified "except" without "as"
669 obj = MyObj()
670 wr = weakref.ref(obj)
671 try:
672 inner_raising_func()
673 except MyException:
674 pass
675 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300676 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000677 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300678 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000679
680 # Bare "except"
681 obj = MyObj()
682 wr = weakref.ref(obj)
683 try:
684 inner_raising_func()
685 except:
686 pass
687 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300688 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000689 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300690 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000691
692 # "except" with premature block leave
693 obj = MyObj()
694 wr = weakref.ref(obj)
695 for i in [0]:
696 try:
697 inner_raising_func()
698 except:
699 break
700 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300701 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000702 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300703 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000704
705 # "except" block raising another exception
706 obj = MyObj()
707 wr = weakref.ref(obj)
708 try:
709 try:
710 inner_raising_func()
711 except:
712 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000713 except KeyError as e:
714 # We want to test that the except block above got rid of
715 # the exception raised in inner_raising_func(), but it
716 # also ends up in the __context__ of the KeyError, so we
717 # must clear the latter manually for our test to succeed.
718 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000719 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300720 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000721 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800722 # guarantee no ref cycles on CPython (don't gc_collect)
723 if check_impl_detail(cpython=False):
724 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300725 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000726
727 # Some complicated construct
728 obj = MyObj()
729 wr = weakref.ref(obj)
730 try:
731 inner_raising_func()
732 except MyException:
733 try:
734 try:
735 raise
736 finally:
737 raise
738 except MyException:
739 pass
740 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800741 if check_impl_detail(cpython=False):
742 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000743 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300744 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000745
746 # Inside an exception-silencing "with" block
747 class Context:
748 def __enter__(self):
749 return self
750 def __exit__ (self, exc_type, exc_value, exc_tb):
751 return True
752 obj = MyObj()
753 wr = weakref.ref(obj)
754 with Context():
755 inner_raising_func()
756 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800757 if check_impl_detail(cpython=False):
758 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000759 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300760 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000761
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000762 def test_exception_target_in_nested_scope(self):
763 # issue 4617: This used to raise a SyntaxError
764 # "can not delete variable 'e' referenced in nested scope"
765 def print_error():
766 e
767 try:
768 something
769 except Exception as e:
770 print_error()
771 # implicit "del e" here
772
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000773 def test_generator_leaking(self):
774 # Test that generator exception state doesn't leak into the calling
775 # frame
776 def yield_raise():
777 try:
778 raise KeyError("caught")
779 except KeyError:
780 yield sys.exc_info()[0]
781 yield sys.exc_info()[0]
782 yield sys.exc_info()[0]
783 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000784 self.assertEqual(next(g), KeyError)
785 self.assertEqual(sys.exc_info()[0], None)
786 self.assertEqual(next(g), KeyError)
787 self.assertEqual(sys.exc_info()[0], None)
788 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000789
790 # Same test, but inside an exception handler
791 try:
792 raise TypeError("foo")
793 except TypeError:
794 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000795 self.assertEqual(next(g), KeyError)
796 self.assertEqual(sys.exc_info()[0], TypeError)
797 self.assertEqual(next(g), KeyError)
798 self.assertEqual(sys.exc_info()[0], TypeError)
799 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000800 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000801 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000802
Benjamin Peterson83195c32011-07-03 13:44:00 -0500803 def test_generator_leaking2(self):
804 # See issue 12475.
805 def g():
806 yield
807 try:
808 raise RuntimeError
809 except RuntimeError:
810 it = g()
811 next(it)
812 try:
813 next(it)
814 except StopIteration:
815 pass
816 self.assertEqual(sys.exc_info(), (None, None, None))
817
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100818 def test_generator_leaking3(self):
819 # See issue #23353. When gen.throw() is called, the caller's
820 # exception state should be save and restored.
821 def g():
822 try:
823 yield
824 except ZeroDivisionError:
825 yield sys.exc_info()[1]
826 it = g()
827 next(it)
828 try:
829 1/0
830 except ZeroDivisionError as e:
831 self.assertIs(sys.exc_info()[1], e)
832 gen_exc = it.throw(e)
833 self.assertIs(sys.exc_info()[1], e)
834 self.assertIs(gen_exc, e)
835 self.assertEqual(sys.exc_info(), (None, None, None))
836
837 def test_generator_leaking4(self):
838 # See issue #23353. When an exception is raised by a generator,
839 # the caller's exception state should still be restored.
840 def g():
841 try:
842 1/0
843 except ZeroDivisionError:
844 yield sys.exc_info()[0]
845 raise
846 it = g()
847 try:
848 raise TypeError
849 except TypeError:
850 # The caller's exception state (TypeError) is temporarily
851 # saved in the generator.
852 tp = next(it)
853 self.assertIs(tp, ZeroDivisionError)
854 try:
855 next(it)
856 # We can't check it immediately, but while next() returns
857 # with an exception, it shouldn't have restored the old
858 # exception state (TypeError).
859 except ZeroDivisionError as e:
860 self.assertIs(sys.exc_info()[1], e)
861 # We used to find TypeError here.
862 self.assertEqual(sys.exc_info(), (None, None, None))
863
Benjamin Petersonac913412011-07-03 16:25:11 -0500864 def test_generator_doesnt_retain_old_exc(self):
865 def g():
866 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
867 yield
868 self.assertEqual(sys.exc_info(), (None, None, None))
869 it = g()
870 try:
871 raise RuntimeError
872 except RuntimeError:
873 next(it)
874 self.assertRaises(StopIteration, next, it)
875
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000876 def test_generator_finalizing_and_exc_info(self):
877 # See #7173
878 def simple_gen():
879 yield 1
880 def run_gen():
881 gen = simple_gen()
882 try:
883 raise RuntimeError
884 except RuntimeError:
885 return next(gen)
886 run_gen()
887 gc_collect()
888 self.assertEqual(sys.exc_info(), (None, None, None))
889
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200890 def _check_generator_cleanup_exc_state(self, testfunc):
891 # Issue #12791: exception state is cleaned up as soon as a generator
892 # is closed (reference cycles are broken).
893 class MyException(Exception):
894 def __init__(self, obj):
895 self.obj = obj
896 class MyObj:
897 pass
898
899 def raising_gen():
900 try:
901 raise MyException(obj)
902 except MyException:
903 yield
904
905 obj = MyObj()
906 wr = weakref.ref(obj)
907 g = raising_gen()
908 next(g)
909 testfunc(g)
910 g = obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300911 gc_collect() # For PyPy or other GCs.
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200912 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300913 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200914
915 def test_generator_throw_cleanup_exc_state(self):
916 def do_throw(g):
917 try:
918 g.throw(RuntimeError())
919 except RuntimeError:
920 pass
921 self._check_generator_cleanup_exc_state(do_throw)
922
923 def test_generator_close_cleanup_exc_state(self):
924 def do_close(g):
925 g.close()
926 self._check_generator_cleanup_exc_state(do_close)
927
928 def test_generator_del_cleanup_exc_state(self):
929 def do_del(g):
930 g = None
931 self._check_generator_cleanup_exc_state(do_del)
932
933 def test_generator_next_cleanup_exc_state(self):
934 def do_next(g):
935 try:
936 next(g)
937 except StopIteration:
938 pass
939 else:
940 self.fail("should have raised StopIteration")
941 self._check_generator_cleanup_exc_state(do_next)
942
943 def test_generator_send_cleanup_exc_state(self):
944 def do_send(g):
945 try:
946 g.send(None)
947 except StopIteration:
948 pass
949 else:
950 self.fail("should have raised StopIteration")
951 self._check_generator_cleanup_exc_state(do_send)
952
Benjamin Peterson27d63672008-06-15 20:09:12 +0000953 def test_3114(self):
954 # Bug #3114: in its destructor, MyObject retrieves a pointer to
955 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000956 class MyObject:
957 def __del__(self):
958 nonlocal e
959 e = sys.exc_info()
960 e = ()
961 try:
962 raise Exception(MyObject())
963 except:
964 pass
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300965 gc_collect() # For PyPy or other GCs.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000966 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000967
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700968 def test_raise_does_not_create_context_chain_cycle(self):
969 class A(Exception):
970 pass
971 class B(Exception):
972 pass
973 class C(Exception):
974 pass
975
976 # Create a context chain:
977 # C -> B -> A
978 # Then raise A in context of C.
979 try:
980 try:
981 raise A
982 except A as a_:
983 a = a_
984 try:
985 raise B
986 except B as b_:
987 b = b_
988 try:
989 raise C
990 except C as c_:
991 c = c_
992 self.assertIsInstance(a, A)
993 self.assertIsInstance(b, B)
994 self.assertIsInstance(c, C)
995 self.assertIsNone(a.__context__)
996 self.assertIs(b.__context__, a)
997 self.assertIs(c.__context__, b)
998 raise a
999 except A as e:
1000 exc = e
1001
1002 # Expect A -> C -> B, without cycle
1003 self.assertIs(exc, a)
1004 self.assertIs(a.__context__, c)
1005 self.assertIs(c.__context__, b)
1006 self.assertIsNone(b.__context__)
1007
1008 def test_no_hang_on_context_chain_cycle1(self):
1009 # See issue 25782. Cycle in context chain.
1010
1011 def cycle():
1012 try:
1013 raise ValueError(1)
1014 except ValueError as ex:
1015 ex.__context__ = ex
1016 raise TypeError(2)
1017
1018 try:
1019 cycle()
1020 except Exception as e:
1021 exc = e
1022
1023 self.assertIsInstance(exc, TypeError)
1024 self.assertIsInstance(exc.__context__, ValueError)
1025 self.assertIs(exc.__context__.__context__, exc.__context__)
1026
Miss Islington (bot)19604092021-08-16 02:01:14 -07001027 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001028 def test_no_hang_on_context_chain_cycle2(self):
1029 # See issue 25782. Cycle at head of context chain.
1030
1031 class A(Exception):
1032 pass
1033 class B(Exception):
1034 pass
1035 class C(Exception):
1036 pass
1037
1038 # Context cycle:
1039 # +-----------+
1040 # V |
1041 # C --> B --> A
1042 with self.assertRaises(C) as cm:
1043 try:
1044 raise A()
1045 except A as _a:
1046 a = _a
1047 try:
1048 raise B()
1049 except B as _b:
1050 b = _b
1051 try:
1052 raise C()
1053 except C as _c:
1054 c = _c
1055 a.__context__ = c
1056 raise c
1057
1058 self.assertIs(cm.exception, c)
1059 # Verify the expected context chain cycle
1060 self.assertIs(c.__context__, b)
1061 self.assertIs(b.__context__, a)
1062 self.assertIs(a.__context__, c)
1063
1064 def test_no_hang_on_context_chain_cycle3(self):
1065 # See issue 25782. Longer context chain with cycle.
1066
1067 class A(Exception):
1068 pass
1069 class B(Exception):
1070 pass
1071 class C(Exception):
1072 pass
1073 class D(Exception):
1074 pass
1075 class E(Exception):
1076 pass
1077
1078 # Context cycle:
1079 # +-----------+
1080 # V |
1081 # E --> D --> C --> B --> A
1082 with self.assertRaises(E) as cm:
1083 try:
1084 raise A()
1085 except A as _a:
1086 a = _a
1087 try:
1088 raise B()
1089 except B as _b:
1090 b = _b
1091 try:
1092 raise C()
1093 except C as _c:
1094 c = _c
1095 a.__context__ = c
1096 try:
1097 raise D()
1098 except D as _d:
1099 d = _d
1100 e = E()
1101 raise e
1102
1103 self.assertIs(cm.exception, e)
1104 # Verify the expected context chain cycle
1105 self.assertIs(e.__context__, d)
1106 self.assertIs(d.__context__, c)
1107 self.assertIs(c.__context__, b)
1108 self.assertIs(b.__context__, a)
1109 self.assertIs(a.__context__, c)
1110
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001111 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001112 # See issue 7309. This was a crasher.
1113
1114 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1115 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1116 u.end = 2
1117 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1118 u.end = 5
1119 u.reason = 0x345345345345345345
1120 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1121 u.encoding = 4000
1122 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1123 u.start = 1000
1124 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1125
1126 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1127 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1128 u.end = 2
1129 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1130 u.end = 5
1131 u.reason = 0x345345345345345345
1132 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1133 u.encoding = 4000
1134 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1135 u.start = 1000
1136 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1137
1138 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1139 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1140 u.end = 2
1141 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1142 u.end = 5
1143 u.reason = 0x345345345345345345
1144 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1145 u.start = 1000
1146 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001147
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001148 def test_unicode_errors_no_object(self):
1149 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001150 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001151 for klass in klasses:
1152 self.assertEqual(str(klass.__new__(klass)), "")
1153
Brett Cannon31f59292011-02-21 19:29:56 +00001154 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001155 def test_badisinstance(self):
1156 # Bug #2542: if issubclass(e, MyException) raises an exception,
1157 # it should be ignored
1158 class Meta(type):
1159 def __subclasscheck__(cls, subclass):
1160 raise ValueError()
1161 class MyException(Exception, metaclass=Meta):
1162 pass
1163
Martin Panter3263f682016-02-28 03:16:11 +00001164 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001165 try:
1166 raise KeyError()
1167 except MyException as e:
1168 self.fail("exception should not be a MyException")
1169 except KeyError:
1170 pass
1171 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001172 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001173 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001174 self.fail("Should have raised KeyError")
1175
1176 def g():
1177 try:
1178 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001179 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001180 return sys.exc_info()
1181 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001182 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001183 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001184
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001185
1186 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001187 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001188 # See bpo-33930
1189
1190 def foo():
1191 o = object()
1192 for x in range(1_000_000):
1193 # Create a big chain of method objects that will trigger
1194 # a deep chain of calls when they need to be destructed.
1195 o = o.__dir__
1196
1197 foo()
1198 support.gc_collect()
1199
xdegaye56d1f5c2017-10-26 15:09:06 +02001200 @cpython_only
1201 def test_recursion_normalizing_exception(self):
1202 # Issue #22898.
1203 # Test that a RecursionError is raised when tstate->recursion_depth is
1204 # equal to recursion_limit in PyErr_NormalizeException() and check
1205 # that a ResourceWarning is printed.
1206 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001207 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001208 # singleton was being used in that case, that held traceback data and
1209 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1210 # finalization of these locals.
1211 code = """if 1:
1212 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001213 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001214
1215 class MyException(Exception): pass
1216
1217 def setrecursionlimit(depth):
1218 while 1:
1219 try:
1220 sys.setrecursionlimit(depth)
1221 return depth
1222 except RecursionError:
1223 # sys.setrecursionlimit() raises a RecursionError if
1224 # the new recursion limit is too low (issue #25274).
1225 depth += 1
1226
1227 def recurse(cnt):
1228 cnt -= 1
1229 if cnt:
1230 recurse(cnt)
1231 else:
1232 generator.throw(MyException)
1233
1234 def gen():
1235 f = open(%a, mode='rb', buffering=0)
1236 yield
1237
1238 generator = gen()
1239 next(generator)
1240 recursionlimit = sys.getrecursionlimit()
1241 depth = get_recursion_depth()
1242 try:
1243 # Upon the last recursive invocation of recurse(),
1244 # tstate->recursion_depth is equal to (recursion_limit - 1)
1245 # and is equal to recursion_limit when _gen_throw() calls
1246 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001247 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001248 finally:
1249 sys.setrecursionlimit(recursionlimit)
1250 print('Done.')
1251 """ % __file__
1252 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1253 # Check that the program does not fail with SIGABRT.
1254 self.assertEqual(rc, 1)
1255 self.assertIn(b'RecursionError', err)
1256 self.assertIn(b'ResourceWarning', err)
1257 self.assertIn(b'Done.', out)
1258
1259 @cpython_only
1260 def test_recursion_normalizing_infinite_exception(self):
1261 # Issue #30697. Test that a RecursionError is raised when
1262 # PyErr_NormalizeException() maximum recursion depth has been
1263 # exceeded.
1264 code = """if 1:
1265 import _testcapi
1266 try:
1267 raise _testcapi.RecursingInfinitelyError
1268 finally:
1269 print('Done.')
1270 """
1271 rc, out, err = script_helper.assert_python_failure("-c", code)
1272 self.assertEqual(rc, 1)
1273 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1274 b'while normalizing an exception', err)
1275 self.assertIn(b'Done.', out)
1276
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001277
1278 def test_recursion_in_except_handler(self):
1279
1280 def set_relative_recursion_limit(n):
1281 depth = 1
1282 while True:
1283 try:
1284 sys.setrecursionlimit(depth)
1285 except RecursionError:
1286 depth += 1
1287 else:
1288 break
1289 sys.setrecursionlimit(depth+n)
1290
1291 def recurse_in_except():
1292 try:
1293 1/0
1294 except:
1295 recurse_in_except()
1296
1297 def recurse_after_except():
1298 try:
1299 1/0
1300 except:
1301 pass
1302 recurse_after_except()
1303
1304 def recurse_in_body_and_except():
1305 try:
1306 recurse_in_body_and_except()
1307 except:
1308 recurse_in_body_and_except()
1309
1310 recursionlimit = sys.getrecursionlimit()
1311 try:
1312 set_relative_recursion_limit(10)
1313 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1314 with self.subTest(func=func):
1315 try:
1316 func()
1317 except RecursionError:
1318 pass
1319 else:
1320 self.fail("Should have raised a RecursionError")
1321 finally:
1322 sys.setrecursionlimit(recursionlimit)
1323
1324
xdegaye56d1f5c2017-10-26 15:09:06 +02001325 @cpython_only
1326 def test_recursion_normalizing_with_no_memory(self):
1327 # Issue #30697. Test that in the abort that occurs when there is no
1328 # memory left and the size of the Python frames stack is greater than
1329 # the size of the list of preallocated MemoryError instances, the
1330 # Fatal Python error message mentions MemoryError.
1331 code = """if 1:
1332 import _testcapi
1333 class C(): pass
1334 def recurse(cnt):
1335 cnt -= 1
1336 if cnt:
1337 recurse(cnt)
1338 else:
1339 _testcapi.set_nomemory(0)
1340 C()
1341 recurse(16)
1342 """
1343 with SuppressCrashReport():
1344 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001345 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1346 b'Cannot recover from MemoryErrors while '
1347 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001348
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001349 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001350 def test_MemoryError(self):
1351 # PyErr_NoMemory always raises the same exception instance.
1352 # Check that the traceback is not doubled.
1353 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001354 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001355 def raiseMemError():
1356 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001357 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001358 except MemoryError as e:
1359 tb = e.__traceback__
1360 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001361 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001362 return traceback.format_tb(tb)
1363
1364 tb1 = raiseMemError()
1365 tb2 = raiseMemError()
1366 self.assertEqual(tb1, tb2)
1367
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001368 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001369 def test_exception_with_doc(self):
1370 import _testcapi
1371 doc2 = "This is a test docstring."
1372 doc4 = "This is another test docstring."
1373
1374 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1375 "error1")
1376
1377 # test basic usage of PyErr_NewException
1378 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1379 self.assertIs(type(error1), type)
1380 self.assertTrue(issubclass(error1, Exception))
1381 self.assertIsNone(error1.__doc__)
1382
1383 # test with given docstring
1384 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1385 self.assertEqual(error2.__doc__, doc2)
1386
1387 # test with explicit base (without docstring)
1388 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1389 base=error2)
1390 self.assertTrue(issubclass(error3, error2))
1391
1392 # test with explicit base tuple
1393 class C(object):
1394 pass
1395 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1396 (error3, C))
1397 self.assertTrue(issubclass(error4, error3))
1398 self.assertTrue(issubclass(error4, C))
1399 self.assertEqual(error4.__doc__, doc4)
1400
1401 # test with explicit dictionary
1402 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1403 error4, {'a': 1})
1404 self.assertTrue(issubclass(error5, error4))
1405 self.assertEqual(error5.a, 1)
1406 self.assertEqual(error5.__doc__, "")
1407
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001408 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001409 def test_memory_error_cleanup(self):
1410 # Issue #5437: preallocated MemoryError instances should not keep
1411 # traceback objects alive.
1412 from _testcapi import raise_memoryerror
1413 class C:
1414 pass
1415 wr = None
1416 def inner():
1417 nonlocal wr
1418 c = C()
1419 wr = weakref.ref(c)
1420 raise_memoryerror()
1421 # We cannot use assertRaises since it manually deletes the traceback
1422 try:
1423 inner()
1424 except MemoryError as e:
1425 self.assertNotEqual(wr(), None)
1426 else:
1427 self.fail("MemoryError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001428 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001429 self.assertEqual(wr(), None)
1430
Brett Cannon31f59292011-02-21 19:29:56 +00001431 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001432 def test_recursion_error_cleanup(self):
1433 # Same test as above, but with "recursion exceeded" errors
1434 class C:
1435 pass
1436 wr = None
1437 def inner():
1438 nonlocal wr
1439 c = C()
1440 wr = weakref.ref(c)
1441 inner()
1442 # We cannot use assertRaises since it manually deletes the traceback
1443 try:
1444 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001445 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001446 self.assertNotEqual(wr(), None)
1447 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001448 self.fail("RecursionError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001449 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001450 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001451
Antoine Pitroua7622852011-09-01 21:37:43 +02001452 def test_errno_ENOTDIR(self):
1453 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1454 with self.assertRaises(OSError) as cm:
1455 os.listdir(__file__)
1456 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1457
Martin Panter3263f682016-02-28 03:16:11 +00001458 def test_unraisable(self):
1459 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1460 class BrokenDel:
1461 def __del__(self):
1462 exc = ValueError("del is broken")
1463 # The following line is included in the traceback report:
1464 raise exc
1465
Victor Stinnere4d300e2019-05-22 23:44:02 +02001466 obj = BrokenDel()
1467 with support.catch_unraisable_exception() as cm:
1468 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001469
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001470 gc_collect() # For PyPy or other GCs.
Victor Stinnere4d300e2019-05-22 23:44:02 +02001471 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1472 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001473
1474 def test_unhandled(self):
1475 # Check for sensible reporting of unhandled exceptions
1476 for exc_type in (ValueError, BrokenStrException):
1477 with self.subTest(exc_type):
1478 try:
1479 exc = exc_type("test message")
1480 # The following line is included in the traceback report:
1481 raise exc
1482 except exc_type:
1483 with captured_stderr() as stderr:
1484 sys.__excepthook__(*sys.exc_info())
1485 report = stderr.getvalue()
1486 self.assertIn("test_exceptions.py", report)
1487 self.assertIn("raise exc", report)
1488 self.assertIn(exc_type.__name__, report)
1489 if exc_type is BrokenStrException:
1490 self.assertIn("<exception str() failed>", report)
1491 else:
1492 self.assertIn("test message", report)
1493 self.assertTrue(report.endswith("\n"))
1494
xdegaye66caacf2017-10-23 18:08:41 +02001495 @cpython_only
1496 def test_memory_error_in_PyErr_PrintEx(self):
1497 code = """if 1:
1498 import _testcapi
1499 class C(): pass
1500 _testcapi.set_nomemory(0, %d)
1501 C()
1502 """
1503
1504 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1505 # Span a large range of tests as the CPython code always evolves with
1506 # changes that add or remove memory allocations.
1507 for i in range(1, 20):
1508 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1509 self.assertIn(rc, (1, 120))
1510 self.assertIn(b'MemoryError', err)
1511
Mark Shannonae3087c2017-10-22 22:41:51 +01001512 def test_yield_in_nested_try_excepts(self):
1513 #Issue #25612
1514 class MainError(Exception):
1515 pass
1516
1517 class SubError(Exception):
1518 pass
1519
1520 def main():
1521 try:
1522 raise MainError()
1523 except MainError:
1524 try:
1525 yield
1526 except SubError:
1527 pass
1528 raise
1529
1530 coro = main()
1531 coro.send(None)
1532 with self.assertRaises(MainError):
1533 coro.throw(SubError())
1534
1535 def test_generator_doesnt_retain_old_exc2(self):
1536 #Issue 28884#msg282532
1537 def g():
1538 try:
1539 raise ValueError
1540 except ValueError:
1541 yield 1
1542 self.assertEqual(sys.exc_info(), (None, None, None))
1543 yield 2
1544
1545 gen = g()
1546
1547 try:
1548 raise IndexError
1549 except IndexError:
1550 self.assertEqual(next(gen), 1)
1551 self.assertEqual(next(gen), 2)
1552
1553 def test_raise_in_generator(self):
1554 #Issue 25612#msg304117
1555 def g():
1556 yield 1
1557 raise
1558 yield 2
1559
1560 with self.assertRaises(ZeroDivisionError):
1561 i = g()
1562 try:
1563 1/0
1564 except:
1565 next(i)
1566 next(i)
1567
Zackery Spytzce6a0702019-08-25 03:44:09 -06001568 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1569 def test_assert_shadowing(self):
1570 # Shadowing AssertionError would cause the assert statement to
1571 # misbehave.
1572 global AssertionError
1573 AssertionError = TypeError
1574 try:
1575 assert False, 'hello'
1576 except BaseException as e:
1577 del AssertionError
1578 self.assertIsInstance(e, AssertionError)
1579 self.assertEqual(str(e), 'hello')
1580 else:
1581 del AssertionError
1582 self.fail('Expected exception')
1583
Pablo Galindo9b648a92020-09-01 19:39:46 +01001584 def test_memory_error_subclasses(self):
1585 # bpo-41654: MemoryError instances use a freelist of objects that are
1586 # linked using the 'dict' attribute when they are inactive/dead.
1587 # Subclasses of MemoryError should not participate in the freelist
1588 # schema. This test creates a MemoryError object and keeps it alive
1589 # (therefore advancing the freelist) and then it creates and destroys a
1590 # subclass object. Finally, it checks that creating a new MemoryError
1591 # succeeds, proving that the freelist is not corrupted.
1592
1593 class TestException(MemoryError):
1594 pass
1595
1596 try:
1597 raise MemoryError
1598 except MemoryError as exc:
1599 inst = exc
1600
1601 try:
1602 raise TestException
1603 except Exception:
1604 pass
1605
1606 for _ in range(10):
1607 try:
1608 raise MemoryError
1609 except MemoryError as exc:
1610 pass
1611
1612 gc_collect()
1613
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001614global_for_suggestions = None
1615
1616class NameErrorTests(unittest.TestCase):
1617 def test_name_error_has_name(self):
1618 try:
1619 bluch
1620 except NameError as exc:
1621 self.assertEqual("bluch", exc.name)
1622
1623 def test_name_error_suggestions(self):
1624 def Substitution():
1625 noise = more_noise = a = bc = None
1626 blech = None
1627 print(bluch)
1628
1629 def Elimination():
1630 noise = more_noise = a = bc = None
1631 blch = None
1632 print(bluch)
1633
1634 def Addition():
1635 noise = more_noise = a = bc = None
1636 bluchin = None
1637 print(bluch)
1638
1639 def SubstitutionOverElimination():
1640 blach = None
1641 bluc = None
1642 print(bluch)
1643
1644 def SubstitutionOverAddition():
1645 blach = None
1646 bluchi = None
1647 print(bluch)
1648
1649 def EliminationOverAddition():
1650 blucha = None
1651 bluc = None
1652 print(bluch)
1653
Pablo Galindo7a041162021-04-19 23:35:53 +01001654 for func, suggestion in [(Substitution, "'blech'?"),
1655 (Elimination, "'blch'?"),
1656 (Addition, "'bluchin'?"),
1657 (EliminationOverAddition, "'blucha'?"),
1658 (SubstitutionOverElimination, "'blach'?"),
1659 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001660 err = None
1661 try:
1662 func()
1663 except NameError as exc:
1664 with support.captured_stderr() as err:
1665 sys.__excepthook__(*sys.exc_info())
1666 self.assertIn(suggestion, err.getvalue())
1667
1668 def test_name_error_suggestions_from_globals(self):
1669 def func():
1670 print(global_for_suggestio)
1671 try:
1672 func()
1673 except NameError as exc:
1674 with support.captured_stderr() as err:
1675 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001676 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001677
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001678 def test_name_error_suggestions_from_builtins(self):
1679 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001680 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001681 try:
1682 func()
1683 except NameError as exc:
1684 with support.captured_stderr() as err:
1685 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001686 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001687
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001688 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1689 def f():
1690 somethingverywronghehehehehehe = None
1691 print(somethingverywronghe)
1692
1693 try:
1694 f()
1695 except NameError as exc:
1696 with support.captured_stderr() as err:
1697 sys.__excepthook__(*sys.exc_info())
1698
1699 self.assertNotIn("somethingverywronghehe", err.getvalue())
1700
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001701 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1702 vvv = mom = w = id = pytho = None
1703
1704 with self.subTest(name="b"):
1705 try:
1706 b
1707 except NameError as exc:
1708 with support.captured_stderr() as err:
1709 sys.__excepthook__(*sys.exc_info())
1710 self.assertNotIn("you mean", err.getvalue())
1711 self.assertNotIn("vvv", err.getvalue())
1712 self.assertNotIn("mom", err.getvalue())
1713 self.assertNotIn("'id'", err.getvalue())
1714 self.assertNotIn("'w'", err.getvalue())
1715 self.assertNotIn("'pytho'", err.getvalue())
1716
1717 with self.subTest(name="v"):
1718 try:
1719 v
1720 except NameError as exc:
1721 with support.captured_stderr() as err:
1722 sys.__excepthook__(*sys.exc_info())
1723 self.assertNotIn("you mean", err.getvalue())
1724 self.assertNotIn("vvv", err.getvalue())
1725 self.assertNotIn("mom", err.getvalue())
1726 self.assertNotIn("'id'", err.getvalue())
1727 self.assertNotIn("'w'", err.getvalue())
1728 self.assertNotIn("'pytho'", err.getvalue())
1729
1730 with self.subTest(name="m"):
1731 try:
1732 m
1733 except NameError as exc:
1734 with support.captured_stderr() as err:
1735 sys.__excepthook__(*sys.exc_info())
1736 self.assertNotIn("you mean", err.getvalue())
1737 self.assertNotIn("vvv", err.getvalue())
1738 self.assertNotIn("mom", err.getvalue())
1739 self.assertNotIn("'id'", err.getvalue())
1740 self.assertNotIn("'w'", err.getvalue())
1741 self.assertNotIn("'pytho'", err.getvalue())
1742
1743 with self.subTest(name="py"):
1744 try:
1745 py
1746 except NameError as exc:
1747 with support.captured_stderr() as err:
1748 sys.__excepthook__(*sys.exc_info())
1749 self.assertNotIn("you mean", err.getvalue())
1750 self.assertNotIn("vvv", err.getvalue())
1751 self.assertNotIn("mom", err.getvalue())
1752 self.assertNotIn("'id'", err.getvalue())
1753 self.assertNotIn("'w'", err.getvalue())
1754 self.assertNotIn("'pytho'", err.getvalue())
1755
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001756 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001757 def f():
1758 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001759 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1760 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1761 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1762 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1763 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1764 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1765 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1766 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1767 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1768 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1769 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1770 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1771 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1772 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1773 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1774 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1775 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1776 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1777 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1778 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1779 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1780 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1781 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1782 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1783 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1784 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1785 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1786 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1787 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1788 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1789 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1790 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1791 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1792 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1793 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1794 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1795 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1796 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1797 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1798 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1799 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1800 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1801 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1802 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1803 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1804 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1805 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1806 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1807 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1808 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1809 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1810 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1811 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1812 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1813 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1814 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1815 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1816 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1817 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1818 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1819 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1820 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1821 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1822 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1823 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1824 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1825 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1826 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1827 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1828 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1829 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1830 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1831 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1832 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1833 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1834 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1835 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1836 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1837 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1838 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1839 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001840 print(a0)
1841
1842 try:
1843 f()
1844 except NameError as exc:
1845 with support.captured_stderr() as err:
1846 sys.__excepthook__(*sys.exc_info())
1847
Miss Islington (bot)d55bf812021-10-07 05:11:38 -07001848 self.assertNotRegex(err.getvalue(), r"NameError.*a1")
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001849
1850 def test_name_error_with_custom_exceptions(self):
1851 def f():
1852 blech = None
1853 raise NameError()
1854
1855 try:
1856 f()
1857 except NameError as exc:
1858 with support.captured_stderr() as err:
1859 sys.__excepthook__(*sys.exc_info())
1860
1861 self.assertNotIn("blech", err.getvalue())
1862
1863 def f():
1864 blech = None
1865 raise NameError
1866
1867 try:
1868 f()
1869 except NameError as exc:
1870 with support.captured_stderr() as err:
1871 sys.__excepthook__(*sys.exc_info())
1872
1873 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001874
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001875 def test_unbound_local_error_doesn_not_match(self):
1876 def foo():
1877 something = 3
1878 print(somethong)
1879 somethong = 3
1880
1881 try:
1882 foo()
1883 except UnboundLocalError as exc:
1884 with support.captured_stderr() as err:
1885 sys.__excepthook__(*sys.exc_info())
1886
1887 self.assertNotIn("something", err.getvalue())
1888
Łukasz Langa8eabe602021-11-18 01:28:04 +01001889 def test_issue45826(self):
1890 # regression test for bpo-45826
1891 def f():
1892 with self.assertRaisesRegex(NameError, 'aaa'):
1893 aab
1894
1895 try:
1896 f()
1897 except self.failureException:
1898 with support.captured_stderr() as err:
1899 sys.__excepthook__(*sys.exc_info())
1900
1901 self.assertIn("aab", err.getvalue())
1902
1903 def test_issue45826_focused(self):
1904 def f():
1905 try:
1906 nonsense
1907 except BaseException as E:
1908 E.with_traceback(None)
1909 raise ZeroDivisionError()
1910
1911 try:
1912 f()
1913 except ZeroDivisionError:
1914 with support.captured_stderr() as err:
1915 sys.__excepthook__(*sys.exc_info())
1916
1917 self.assertIn("nonsense", err.getvalue())
1918 self.assertIn("ZeroDivisionError", err.getvalue())
1919
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001920
Pablo Galindo37494b42021-04-14 02:36:07 +01001921class AttributeErrorTests(unittest.TestCase):
1922 def test_attributes(self):
1923 # Setting 'attr' should not be a problem.
1924 exc = AttributeError('Ouch!')
1925 self.assertIsNone(exc.name)
1926 self.assertIsNone(exc.obj)
1927
1928 sentinel = object()
1929 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1930 self.assertEqual(exc.name, 'carry')
1931 self.assertIs(exc.obj, sentinel)
1932
1933 def test_getattr_has_name_and_obj(self):
1934 class A:
1935 blech = None
1936
1937 obj = A()
1938 try:
1939 obj.bluch
1940 except AttributeError as exc:
1941 self.assertEqual("bluch", exc.name)
1942 self.assertEqual(obj, exc.obj)
1943
1944 def test_getattr_has_name_and_obj_for_method(self):
1945 class A:
1946 def blech(self):
1947 return
1948
1949 obj = A()
1950 try:
1951 obj.bluch()
1952 except AttributeError as exc:
1953 self.assertEqual("bluch", exc.name)
1954 self.assertEqual(obj, exc.obj)
1955
1956 def test_getattr_suggestions(self):
1957 class Substitution:
1958 noise = more_noise = a = bc = None
1959 blech = None
1960
1961 class Elimination:
1962 noise = more_noise = a = bc = None
1963 blch = None
1964
1965 class Addition:
1966 noise = more_noise = a = bc = None
1967 bluchin = None
1968
1969 class SubstitutionOverElimination:
1970 blach = None
1971 bluc = None
1972
1973 class SubstitutionOverAddition:
1974 blach = None
1975 bluchi = None
1976
1977 class EliminationOverAddition:
1978 blucha = None
1979 bluc = None
1980
Pablo Galindo7a041162021-04-19 23:35:53 +01001981 for cls, suggestion in [(Substitution, "'blech'?"),
1982 (Elimination, "'blch'?"),
1983 (Addition, "'bluchin'?"),
1984 (EliminationOverAddition, "'bluc'?"),
1985 (SubstitutionOverElimination, "'blach'?"),
1986 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001987 try:
1988 cls().bluch
1989 except AttributeError as exc:
1990 with support.captured_stderr() as err:
1991 sys.__excepthook__(*sys.exc_info())
1992
1993 self.assertIn(suggestion, err.getvalue())
1994
1995 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1996 class A:
1997 blech = None
1998
1999 try:
2000 A().somethingverywrong
2001 except AttributeError as exc:
2002 with support.captured_stderr() as err:
2003 sys.__excepthook__(*sys.exc_info())
2004
2005 self.assertNotIn("blech", err.getvalue())
2006
Dennis Sweeney284c52d2021-04-26 20:22:27 -04002007 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
2008 class MyClass:
2009 vvv = mom = w = id = pytho = None
2010
2011 with self.subTest(name="b"):
2012 try:
2013 MyClass.b
2014 except AttributeError as exc:
2015 with support.captured_stderr() as err:
2016 sys.__excepthook__(*sys.exc_info())
2017 self.assertNotIn("you mean", err.getvalue())
2018 self.assertNotIn("vvv", err.getvalue())
2019 self.assertNotIn("mom", err.getvalue())
2020 self.assertNotIn("'id'", err.getvalue())
2021 self.assertNotIn("'w'", err.getvalue())
2022 self.assertNotIn("'pytho'", err.getvalue())
2023
2024 with self.subTest(name="v"):
2025 try:
2026 MyClass.v
2027 except AttributeError as exc:
2028 with support.captured_stderr() as err:
2029 sys.__excepthook__(*sys.exc_info())
2030 self.assertNotIn("you mean", err.getvalue())
2031 self.assertNotIn("vvv", err.getvalue())
2032 self.assertNotIn("mom", err.getvalue())
2033 self.assertNotIn("'id'", err.getvalue())
2034 self.assertNotIn("'w'", err.getvalue())
2035 self.assertNotIn("'pytho'", err.getvalue())
2036
2037 with self.subTest(name="m"):
2038 try:
2039 MyClass.m
2040 except AttributeError as exc:
2041 with support.captured_stderr() as err:
2042 sys.__excepthook__(*sys.exc_info())
2043 self.assertNotIn("you mean", err.getvalue())
2044 self.assertNotIn("vvv", err.getvalue())
2045 self.assertNotIn("mom", err.getvalue())
2046 self.assertNotIn("'id'", err.getvalue())
2047 self.assertNotIn("'w'", err.getvalue())
2048 self.assertNotIn("'pytho'", err.getvalue())
2049
2050 with self.subTest(name="py"):
2051 try:
2052 MyClass.py
2053 except AttributeError as exc:
2054 with support.captured_stderr() as err:
2055 sys.__excepthook__(*sys.exc_info())
2056 self.assertNotIn("you mean", err.getvalue())
2057 self.assertNotIn("vvv", err.getvalue())
2058 self.assertNotIn("mom", err.getvalue())
2059 self.assertNotIn("'id'", err.getvalue())
2060 self.assertNotIn("'w'", err.getvalue())
2061 self.assertNotIn("'pytho'", err.getvalue())
2062
2063
Pablo Galindo37494b42021-04-14 02:36:07 +01002064 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2065 class A:
2066 blech = None
2067 # A class with a very big __dict__ will not be consider
2068 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002069 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002070 setattr(A, f"index_{index}", None)
2071
2072 try:
2073 A().bluch
2074 except AttributeError as exc:
2075 with support.captured_stderr() as err:
2076 sys.__excepthook__(*sys.exc_info())
2077
2078 self.assertNotIn("blech", err.getvalue())
2079
2080 def test_getattr_suggestions_no_args(self):
2081 class A:
2082 blech = None
2083 def __getattr__(self, attr):
2084 raise AttributeError()
2085
2086 try:
2087 A().bluch
2088 except AttributeError as exc:
2089 with support.captured_stderr() as err:
2090 sys.__excepthook__(*sys.exc_info())
2091
2092 self.assertIn("blech", err.getvalue())
2093
2094 class A:
2095 blech = None
2096 def __getattr__(self, attr):
2097 raise AttributeError
2098
2099 try:
2100 A().bluch
2101 except AttributeError as exc:
2102 with support.captured_stderr() as err:
2103 sys.__excepthook__(*sys.exc_info())
2104
2105 self.assertIn("blech", err.getvalue())
2106
2107 def test_getattr_suggestions_invalid_args(self):
2108 class NonStringifyClass:
2109 __str__ = None
2110 __repr__ = None
2111
2112 class A:
2113 blech = None
2114 def __getattr__(self, attr):
2115 raise AttributeError(NonStringifyClass())
2116
2117 class B:
2118 blech = None
2119 def __getattr__(self, attr):
2120 raise AttributeError("Error", 23)
2121
2122 class C:
2123 blech = None
2124 def __getattr__(self, attr):
2125 raise AttributeError(23)
2126
2127 for cls in [A, B, C]:
2128 try:
2129 cls().bluch
2130 except AttributeError as exc:
2131 with support.captured_stderr() as err:
2132 sys.__excepthook__(*sys.exc_info())
2133
2134 self.assertIn("blech", err.getvalue())
2135
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002136 def test_getattr_suggestions_for_same_name(self):
2137 class A:
2138 def __dir__(self):
2139 return ['blech']
2140 try:
2141 A().blech
2142 except AttributeError as exc:
2143 with support.captured_stderr() as err:
2144 sys.__excepthook__(*sys.exc_info())
2145
2146 self.assertNotIn("Did you mean", err.getvalue())
2147
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002148 def test_attribute_error_with_failing_dict(self):
2149 class T:
2150 bluch = 1
2151 def __dir__(self):
2152 raise AttributeError("oh no!")
2153
2154 try:
2155 T().blich
2156 except AttributeError as exc:
2157 with support.captured_stderr() as err:
2158 sys.__excepthook__(*sys.exc_info())
2159
2160 self.assertNotIn("blech", err.getvalue())
2161 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002162
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002163 def test_attribute_error_with_bad_name(self):
2164 try:
2165 raise AttributeError(name=12, obj=23)
2166 except AttributeError as exc:
2167 with support.captured_stderr() as err:
2168 sys.__excepthook__(*sys.exc_info())
2169
2170 self.assertNotIn("?", err.getvalue())
2171
2172
Brett Cannon79ec55e2012-04-12 20:24:54 -04002173class ImportErrorTests(unittest.TestCase):
2174
2175 def test_attributes(self):
2176 # Setting 'name' and 'path' should not be a problem.
2177 exc = ImportError('test')
2178 self.assertIsNone(exc.name)
2179 self.assertIsNone(exc.path)
2180
2181 exc = ImportError('test', name='somemodule')
2182 self.assertEqual(exc.name, 'somemodule')
2183 self.assertIsNone(exc.path)
2184
2185 exc = ImportError('test', path='somepath')
2186 self.assertEqual(exc.path, 'somepath')
2187 self.assertIsNone(exc.name)
2188
2189 exc = ImportError('test', path='somepath', name='somename')
2190 self.assertEqual(exc.name, 'somename')
2191 self.assertEqual(exc.path, 'somepath')
2192
Michael Seifert64c8f702017-04-09 09:47:12 +02002193 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002194 with self.assertRaisesRegex(TypeError, msg):
2195 ImportError('test', invalid='keyword')
2196
2197 with self.assertRaisesRegex(TypeError, msg):
2198 ImportError('test', name='name', invalid='keyword')
2199
2200 with self.assertRaisesRegex(TypeError, msg):
2201 ImportError('test', path='path', invalid='keyword')
2202
2203 with self.assertRaisesRegex(TypeError, msg):
2204 ImportError(invalid='keyword')
2205
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002206 with self.assertRaisesRegex(TypeError, msg):
2207 ImportError('test', invalid='keyword', another=True)
2208
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002209 def test_reset_attributes(self):
2210 exc = ImportError('test', name='name', path='path')
2211 self.assertEqual(exc.args, ('test',))
2212 self.assertEqual(exc.msg, 'test')
2213 self.assertEqual(exc.name, 'name')
2214 self.assertEqual(exc.path, 'path')
2215
2216 # Reset not specified attributes
2217 exc.__init__()
2218 self.assertEqual(exc.args, ())
2219 self.assertEqual(exc.msg, None)
2220 self.assertEqual(exc.name, None)
2221 self.assertEqual(exc.path, None)
2222
Brett Cannon07c6e712012-08-24 13:05:09 -04002223 def test_non_str_argument(self):
2224 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002225 with check_warnings(('', BytesWarning), quiet=True):
2226 arg = b'abc'
2227 exc = ImportError(arg)
2228 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002229
Serhiy Storchakab7853962017-04-08 09:55:07 +03002230 def test_copy_pickle(self):
2231 for kwargs in (dict(),
2232 dict(name='somename'),
2233 dict(path='somepath'),
2234 dict(name='somename', path='somepath')):
2235 orig = ImportError('test', **kwargs)
2236 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2237 exc = pickle.loads(pickle.dumps(orig, proto))
2238 self.assertEqual(exc.args, ('test',))
2239 self.assertEqual(exc.msg, 'test')
2240 self.assertEqual(exc.name, orig.name)
2241 self.assertEqual(exc.path, orig.path)
2242 for c in copy.copy, copy.deepcopy:
2243 exc = c(orig)
2244 self.assertEqual(exc.args, ('test',))
2245 self.assertEqual(exc.msg, 'test')
2246 self.assertEqual(exc.name, orig.name)
2247 self.assertEqual(exc.path, orig.path)
2248
Pablo Galindoa77aac42021-04-23 14:27:05 +01002249class SyntaxErrorTests(unittest.TestCase):
2250 def test_range_of_offsets(self):
2251 cases = [
2252 # Basic range from 2->7
2253 (("bad.py", 1, 2, "abcdefg", 1, 7),
2254 dedent(
2255 """
2256 File "bad.py", line 1
2257 abcdefg
2258 ^^^^^
2259 SyntaxError: bad bad
2260 """)),
2261 # end_offset = start_offset + 1
2262 (("bad.py", 1, 2, "abcdefg", 1, 3),
2263 dedent(
2264 """
2265 File "bad.py", line 1
2266 abcdefg
2267 ^
2268 SyntaxError: bad bad
2269 """)),
2270 # Negative end offset
2271 (("bad.py", 1, 2, "abcdefg", 1, -2),
2272 dedent(
2273 """
2274 File "bad.py", line 1
2275 abcdefg
2276 ^
2277 SyntaxError: bad bad
2278 """)),
2279 # end offset before starting offset
2280 (("bad.py", 1, 4, "abcdefg", 1, 2),
2281 dedent(
2282 """
2283 File "bad.py", line 1
2284 abcdefg
2285 ^
2286 SyntaxError: bad bad
2287 """)),
2288 # Both offsets negative
2289 (("bad.py", 1, -4, "abcdefg", 1, -2),
2290 dedent(
2291 """
2292 File "bad.py", line 1
2293 abcdefg
2294 SyntaxError: bad bad
2295 """)),
2296 # Both offsets negative and the end more negative
2297 (("bad.py", 1, -4, "abcdefg", 1, -5),
2298 dedent(
2299 """
2300 File "bad.py", line 1
2301 abcdefg
2302 SyntaxError: bad bad
2303 """)),
2304 # Both offsets 0
2305 (("bad.py", 1, 0, "abcdefg", 1, 0),
2306 dedent(
2307 """
2308 File "bad.py", line 1
2309 abcdefg
2310 SyntaxError: bad bad
2311 """)),
2312 # Start offset 0 and end offset not 0
2313 (("bad.py", 1, 0, "abcdefg", 1, 5),
2314 dedent(
2315 """
2316 File "bad.py", line 1
2317 abcdefg
2318 SyntaxError: bad bad
2319 """)),
Christian Clausscfca4a62021-10-07 17:49:47 +02002320 # End offset pass the source length
Pablo Galindoa77aac42021-04-23 14:27:05 +01002321 (("bad.py", 1, 2, "abcdefg", 1, 100),
2322 dedent(
2323 """
2324 File "bad.py", line 1
2325 abcdefg
2326 ^^^^^^
2327 SyntaxError: bad bad
2328 """)),
2329 ]
2330 for args, expected in cases:
2331 with self.subTest(args=args):
2332 try:
2333 raise SyntaxError("bad bad", args)
2334 except SyntaxError as exc:
2335 with support.captured_stderr() as err:
2336 sys.__excepthook__(*sys.exc_info())
Miss Islington (bot)c800e392021-09-21 15:38:59 -07002337 self.assertIn(expected, err.getvalue())
Pablo Galindoa77aac42021-04-23 14:27:05 +01002338 the_exception = exc
2339
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002340 def test_encodings(self):
2341 source = (
2342 '# -*- coding: cp437 -*-\n'
2343 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2344 )
2345 try:
2346 with open(TESTFN, 'w', encoding='cp437') as testfile:
2347 testfile.write(source)
2348 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2349 err = err.decode('utf-8').splitlines()
2350
2351 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2352 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2353 finally:
2354 unlink(TESTFN)
2355
Łukasz Langa904af3d2021-11-20 16:34:56 +01002356 # Check backwards tokenizer errors
2357 source = '# -*- coding: ascii -*-\n\n(\n'
2358 try:
2359 with open(TESTFN, 'w', encoding='ascii') as testfile:
2360 testfile.write(source)
2361 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2362 err = err.decode('utf-8').splitlines()
2363
2364 self.assertEqual(err[-3], ' (')
2365 self.assertEqual(err[-2], ' ^')
2366 finally:
2367 unlink(TESTFN)
2368
Pablo Galindoa77aac42021-04-23 14:27:05 +01002369 def test_attributes_new_constructor(self):
2370 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2371 the_exception = SyntaxError("bad bad", args)
2372 filename, lineno, offset, error, end_lineno, end_offset = args
2373 self.assertEqual(filename, the_exception.filename)
2374 self.assertEqual(lineno, the_exception.lineno)
2375 self.assertEqual(end_lineno, the_exception.end_lineno)
2376 self.assertEqual(offset, the_exception.offset)
2377 self.assertEqual(end_offset, the_exception.end_offset)
2378 self.assertEqual(error, the_exception.text)
2379 self.assertEqual("bad bad", the_exception.msg)
2380
2381 def test_attributes_old_constructor(self):
2382 args = ("bad.py", 1, 2, "abcdefg")
2383 the_exception = SyntaxError("bad bad", args)
2384 filename, lineno, offset, error = args
2385 self.assertEqual(filename, the_exception.filename)
2386 self.assertEqual(lineno, the_exception.lineno)
2387 self.assertEqual(None, the_exception.end_lineno)
2388 self.assertEqual(offset, the_exception.offset)
2389 self.assertEqual(None, the_exception.end_offset)
2390 self.assertEqual(error, the_exception.text)
2391 self.assertEqual("bad bad", the_exception.msg)
2392
2393 def test_incorrect_constructor(self):
2394 args = ("bad.py", 1, 2)
2395 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2396
2397 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2398 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2399
2400 args = ("bad.py", 1, 2, "abcdefg", 1)
2401 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2402
Brett Cannon79ec55e2012-04-12 20:24:54 -04002403
Mark Shannonbf353f32020-12-17 13:55:28 +00002404class PEP626Tests(unittest.TestCase):
2405
Mark Shannon0b6b2862021-06-24 13:09:14 +01002406 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002407 try:
2408 f()
2409 except Exception as ex:
2410 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002411 else:
2412 self.fail("No exception raised")
2413 lines = []
2414 t = t.tb_next # Skip this function
2415 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002416 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002417 lines.append(
2418 None if frame.f_lineno is None else
2419 frame.f_lineno-frame.f_code.co_firstlineno
2420 )
2421 t = t.tb_next
2422 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002423
2424 def test_lineno_after_raise_simple(self):
2425 def simple():
2426 1/0
2427 pass
2428 self.lineno_after_raise(simple, 1)
2429
2430 def test_lineno_after_raise_in_except(self):
2431 def in_except():
2432 try:
2433 1/0
2434 except:
2435 1/0
2436 pass
2437 self.lineno_after_raise(in_except, 4)
2438
2439 def test_lineno_after_other_except(self):
2440 def other_except():
2441 try:
2442 1/0
2443 except TypeError as ex:
2444 pass
2445 self.lineno_after_raise(other_except, 3)
2446
2447 def test_lineno_in_named_except(self):
2448 def in_named_except():
2449 try:
2450 1/0
2451 except Exception as ex:
2452 1/0
2453 pass
2454 self.lineno_after_raise(in_named_except, 4)
2455
2456 def test_lineno_in_try(self):
2457 def in_try():
2458 try:
2459 1/0
2460 finally:
2461 pass
2462 self.lineno_after_raise(in_try, 4)
2463
2464 def test_lineno_in_finally_normal(self):
2465 def in_finally_normal():
2466 try:
2467 pass
2468 finally:
2469 1/0
2470 pass
2471 self.lineno_after_raise(in_finally_normal, 4)
2472
2473 def test_lineno_in_finally_except(self):
2474 def in_finally_except():
2475 try:
2476 1/0
2477 finally:
2478 1/0
2479 pass
2480 self.lineno_after_raise(in_finally_except, 4)
2481
2482 def test_lineno_after_with(self):
2483 class Noop:
2484 def __enter__(self):
2485 return self
2486 def __exit__(self, *args):
2487 pass
2488 def after_with():
2489 with Noop():
2490 1/0
2491 pass
2492 self.lineno_after_raise(after_with, 2)
2493
Mark Shannon088a15c2021-04-29 19:28:50 +01002494 def test_missing_lineno_shows_as_none(self):
2495 def f():
2496 1/0
2497 self.lineno_after_raise(f, 1)
2498 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2499 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002500
Mark Shannon0b6b2862021-06-24 13:09:14 +01002501 def test_lineno_after_raise_in_with_exit(self):
2502 class ExitFails:
2503 def __enter__(self):
2504 return self
2505 def __exit__(self, *args):
2506 raise ValueError
2507
2508 def after_with():
2509 with ExitFails():
2510 1/0
2511 self.lineno_after_raise(after_with, 1, 1)
2512
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002513if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002514 unittest.main()