Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1 | # Python test set -- part 5, built-in exceptions |
| 2 | |
Serhiy Storchaka | b785396 | 2017-04-08 09:55:07 +0300 | [diff] [blame] | 3 | import copy |
Pablo Galindo | 9b648a9 | 2020-09-01 19:39:46 +0100 | [diff] [blame] | 4 | import gc |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 5 | import os |
| 6 | import sys |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 7 | import unittest |
Guido van Rossum | bf12cdb | 2006-08-17 20:24:18 +0000 | [diff] [blame] | 8 | import pickle |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 9 | import weakref |
Antoine Pitrou | a762285 | 2011-09-01 21:37:43 +0200 | [diff] [blame] | 10 | import errno |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 11 | from textwrap import dedent |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 12 | |
Hai Shi | 4660597 | 2020-08-04 00:49:18 +0800 | [diff] [blame] | 13 | from test.support import (captured_stderr, check_impl_detail, |
| 14 | cpython_only, gc_collect, |
| 15 | no_tracing, script_helper, |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 16 | SuppressCrashReport) |
Hai Shi | 4660597 | 2020-08-04 00:49:18 +0800 | [diff] [blame] | 17 | from test.support.import_helper import import_module |
| 18 | from test.support.os_helper import TESTFN, unlink |
| 19 | from test.support.warnings_helper import check_warnings |
Victor Stinner | e4d300e | 2019-05-22 23:44:02 +0200 | [diff] [blame] | 20 | from test import support |
| 21 | |
| 22 | |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 23 | class NaiveException(Exception): |
| 24 | def __init__(self, x): |
| 25 | self.x = x |
| 26 | |
| 27 | class SlottedNaiveException(Exception): |
| 28 | __slots__ = ('x',) |
| 29 | def __init__(self, x): |
| 30 | self.x = x |
| 31 | |
Martin Panter | 3263f68 | 2016-02-28 03:16:11 +0000 | [diff] [blame] | 32 | class BrokenStrException(Exception): |
| 33 | def __str__(self): |
| 34 | raise Exception("str() is broken") |
| 35 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 36 | # XXX This is not really enough, each *operation* should be tested! |
| 37 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 38 | class ExceptionTests(unittest.TestCase): |
Barry Warsaw | b9c1d3d | 2001-08-13 23:07:00 +0000 | [diff] [blame] | 39 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 40 | def raise_catch(self, exc, excname): |
Pablo Galindo | af8e5f8 | 2020-05-17 01:22:00 +0100 | [diff] [blame] | 41 | 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 Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 52 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 53 | def testRaising(self): |
| 54 | self.raise_catch(AttributeError, "AttributeError") |
| 55 | self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 56 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 57 | self.raise_catch(EOFError, "EOFError") |
Inada Naoki | 8bbfeb3 | 2021-04-02 12:53:46 +0900 | [diff] [blame] | 58 | fp = open(TESTFN, 'w', encoding="utf-8") |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 59 | fp.close() |
Inada Naoki | 8bbfeb3 | 2021-04-02 12:53:46 +0900 | [diff] [blame] | 60 | fp = open(TESTFN, 'r', encoding="utf-8") |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 61 | savestdin = sys.stdin |
| 62 | try: |
| 63 | try: |
| 64 | import marshal |
Antoine Pitrou | 4a90ef0 | 2012-03-03 02:35:32 +0100 | [diff] [blame] | 65 | marshal.loads(b'') |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 66 | except EOFError: |
| 67 | pass |
| 68 | finally: |
| 69 | sys.stdin = savestdin |
| 70 | fp.close() |
| 71 | unlink(TESTFN) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 72 | |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 73 | self.raise_catch(OSError, "OSError") |
| 74 | self.assertRaises(OSError, open, 'this file does not exist', 'r') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 75 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 76 | self.raise_catch(ImportError, "ImportError") |
| 77 | self.assertRaises(ImportError, __import__, "undefined_module") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 78 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 79 | self.raise_catch(IndexError, "IndexError") |
| 80 | x = [] |
| 81 | self.assertRaises(IndexError, x.__getitem__, 10) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 82 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 83 | self.raise_catch(KeyError, "KeyError") |
| 84 | x = {} |
| 85 | self.assertRaises(KeyError, x.__getitem__, 'key') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 86 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 87 | self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 88 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 89 | self.raise_catch(MemoryError, "MemoryError") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 90 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 91 | self.raise_catch(NameError, "NameError") |
| 92 | try: x = undefined_variable |
| 93 | except NameError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 94 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 95 | 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 Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 99 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 100 | self.raise_catch(RuntimeError, "RuntimeError") |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 101 | self.raise_catch(RecursionError, "RecursionError") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 102 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 103 | self.raise_catch(SyntaxError, "SyntaxError") |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 104 | try: exec('/\n') |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 105 | except SyntaxError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 106 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 107 | self.raise_catch(IndentationError, "IndentationError") |
Fred Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 108 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 109 | self.raise_catch(TabError, "TabError") |
Georg Brandl | e1b5ac6 | 2008-06-04 13:06:58 +0000 | [diff] [blame] | 110 | 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 Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 114 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 115 | self.raise_catch(SystemError, "SystemError") |
Fred Drake | 72e48bd | 2000-09-08 16:32:34 +0000 | [diff] [blame] | 116 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 117 | self.raise_catch(SystemExit, "SystemExit") |
| 118 | self.assertRaises(SystemExit, sys.exit, 0) |
Fred Drake | 85f3639 | 2000-07-11 17:53:00 +0000 | [diff] [blame] | 119 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 120 | self.raise_catch(TypeError, "TypeError") |
| 121 | try: [] + () |
| 122 | except TypeError: pass |
Fred Drake | 85f3639 | 2000-07-11 17:53:00 +0000 | [diff] [blame] | 123 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 124 | self.raise_catch(ValueError, "ValueError") |
Guido van Rossum | e63bae6 | 2007-07-17 00:34:25 +0000 | [diff] [blame] | 125 | self.assertRaises(ValueError, chr, 17<<16) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 126 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 127 | self.raise_catch(ZeroDivisionError, "ZeroDivisionError") |
| 128 | try: x = 1/0 |
| 129 | except ZeroDivisionError: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 130 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 131 | self.raise_catch(Exception, "Exception") |
| 132 | try: x = 1/0 |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 133 | except Exception as e: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 134 | |
Yury Selivanov | ccc897f | 2015-07-03 01:16:04 -0400 | [diff] [blame] | 135 | self.raise_catch(StopAsyncIteration, "StopAsyncIteration") |
| 136 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 137 | def testSyntaxErrorMessage(self): |
| 138 | # make sure the right exception message is raised for each of |
| 139 | # these code fragments |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 140 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 141 | def ckmsg(src, msg): |
Pablo Galindo | af8e5f8 | 2020-05-17 01:22:00 +0100 | [diff] [blame] | 142 | 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 Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 150 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 151 | s = '''if 1: |
| 152 | try: |
| 153 | continue |
| 154 | except: |
| 155 | pass''' |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 156 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 157 | ckmsg(s, "'continue' not properly in loop") |
| 158 | ckmsg("continue\n", "'continue' not properly in loop") |
Thomas Wouters | 303de6a | 2006-04-20 22:42:37 +0000 | [diff] [blame] | 159 | |
Martijn Pieters | 772d809 | 2017-08-22 21:16:23 +0100 | [diff] [blame] | 160 | def testSyntaxErrorMissingParens(self): |
| 161 | def ckmsg(src, msg, exception=SyntaxError): |
| 162 | try: |
| 163 | compile(src, '<fragment>', 'exec') |
| 164 | except exception as e: |
| 165 | if e.msg != msg: |
| 166 | self.fail("expected %s, got %s" % (msg, e.msg)) |
| 167 | else: |
| 168 | self.fail("failed to get expected SyntaxError") |
| 169 | |
| 170 | s = '''print "old style"''' |
| 171 | ckmsg(s, "Missing parentheses in call to 'print'. " |
| 172 | "Did you mean print(\"old style\")?") |
| 173 | |
| 174 | s = '''print "old style",''' |
| 175 | ckmsg(s, "Missing parentheses in call to 'print'. " |
| 176 | "Did you mean print(\"old style\", end=\" \")?") |
| 177 | |
| 178 | s = '''exec "old style"''' |
| 179 | ckmsg(s, "Missing parentheses in call to 'exec'") |
| 180 | |
| 181 | # should not apply to subclasses, see issue #31161 |
| 182 | s = '''if True:\nprint "No indent"''' |
Pablo Galindo | 56c95df | 2021-04-21 15:28:21 +0100 | [diff] [blame] | 183 | ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError) |
Martijn Pieters | 772d809 | 2017-08-22 21:16:23 +0100 | [diff] [blame] | 184 | |
| 185 | s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' |
| 186 | ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) |
| 187 | |
Batuhan Taskaya | 76c1b4d | 2020-05-01 16:13:43 +0300 | [diff] [blame] | 188 | def check(self, src, lineno, offset, encoding='utf-8'): |
Pablo Galindo | af8e5f8 | 2020-05-17 01:22:00 +0100 | [diff] [blame] | 189 | with self.subTest(source=src, lineno=lineno, offset=offset): |
| 190 | with self.assertRaises(SyntaxError) as cm: |
| 191 | compile(src, '<fragment>', 'exec') |
| 192 | self.assertEqual(cm.exception.lineno, lineno) |
| 193 | self.assertEqual(cm.exception.offset, offset) |
| 194 | if cm.exception.text is not None: |
| 195 | if not isinstance(src, str): |
| 196 | src = src.decode(encoding, 'replace') |
| 197 | line = src.split('\n')[lineno-1] |
| 198 | self.assertIn(line, cm.exception.text) |
Serhiy Storchaka | 65fd059 | 2014-01-21 22:26:52 +0200 | [diff] [blame] | 199 | |
Batuhan Taskaya | 76c1b4d | 2020-05-01 16:13:43 +0300 | [diff] [blame] | 200 | def testSyntaxErrorOffset(self): |
| 201 | check = self.check |
Serhiy Storchaka | 65fd059 | 2014-01-21 22:26:52 +0200 | [diff] [blame] | 202 | check('def fact(x):\n\treturn x!\n', 2, 10) |
| 203 | check('1 +\n', 1, 4) |
| 204 | check('def spam():\n print(1)\n print(2)', 3, 10) |
| 205 | check('Python = "Python" +', 1, 20) |
| 206 | check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) |
Serhiy Storchaka | 0cc6b5e | 2020-02-12 12:17:00 +0200 | [diff] [blame] | 207 | check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +', |
| 208 | 2, 19, encoding='cp1251') |
| 209 | check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18) |
Batuhan Taskaya | a698d52 | 2021-01-21 00:38:47 +0300 | [diff] [blame] | 210 | check('x = "a', 1, 5) |
Ammar Askar | 025eb98 | 2018-09-24 17:12:49 -0400 | [diff] [blame] | 211 | check('lambda x: x = 2', 1, 1) |
Lysandros Nikolaou | 15acc4e | 2020-10-27 20:54:20 +0200 | [diff] [blame] | 212 | check('f{a + b + c}', 1, 2) |
Lysandros Nikolaou | e5fe509 | 2021-01-14 23:36:30 +0200 | [diff] [blame] | 213 | check('[file for str(file) in []\n])', 1, 11) |
| 214 | check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5) |
| 215 | check('[file for\n str(file) in []]', 2, 2) |
Ammar Askar | 025eb98 | 2018-09-24 17:12:49 -0400 | [diff] [blame] | 216 | |
| 217 | # Errors thrown by compile.c |
| 218 | check('class foo:return 1', 1, 11) |
| 219 | check('def f():\n continue', 2, 3) |
| 220 | check('def f():\n break', 2, 3) |
| 221 | check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 2, 3) |
| 222 | |
| 223 | # Errors thrown by tokenizer.c |
| 224 | check('(0x+1)', 1, 3) |
| 225 | check('x = 0xI', 1, 6) |
| 226 | check('0010 + 2', 1, 4) |
| 227 | check('x = 32e-+4', 1, 8) |
| 228 | check('x = 0o9', 1, 6) |
Serhiy Storchaka | 0cc6b5e | 2020-02-12 12:17:00 +0200 | [diff] [blame] | 229 | check('\u03b1 = 0xI', 1, 6) |
| 230 | check(b'\xce\xb1 = 0xI', 1, 6) |
| 231 | check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6, |
| 232 | encoding='iso8859-7') |
Pablo Galindo | 11a7f15 | 2020-04-21 01:53:04 +0100 | [diff] [blame] | 233 | check(b"""if 1: |
| 234 | def foo(): |
| 235 | ''' |
| 236 | |
| 237 | def bar(): |
| 238 | pass |
| 239 | |
| 240 | def baz(): |
| 241 | '''quux''' |
Batuhan Taskaya | a698d52 | 2021-01-21 00:38:47 +0300 | [diff] [blame] | 242 | """, 9, 24) |
Pablo Galindo | bcc3036 | 2020-05-14 21:11:48 +0100 | [diff] [blame] | 243 | check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4) |
| 244 | check("(1+)", 1, 4) |
Ammar Askar | 025eb98 | 2018-09-24 17:12:49 -0400 | [diff] [blame] | 245 | |
| 246 | # Errors thrown by symtable.c |
Serhiy Storchaka | b619b09 | 2018-11-27 09:40:29 +0200 | [diff] [blame] | 247 | check('x = [(yield i) for i in range(3)]', 1, 5) |
Ammar Askar | 025eb98 | 2018-09-24 17:12:49 -0400 | [diff] [blame] | 248 | check('def f():\n from _ import *', 1, 1) |
| 249 | check('def f(x, x):\n pass', 1, 1) |
| 250 | check('def f(x):\n nonlocal x', 2, 3) |
| 251 | check('def f(x):\n x = 1\n global x', 3, 3) |
| 252 | check('nonlocal x', 1, 1) |
| 253 | check('def f():\n global x\n nonlocal x', 2, 3) |
| 254 | |
Ammar Askar | 025eb98 | 2018-09-24 17:12:49 -0400 | [diff] [blame] | 255 | # Errors thrown by future.c |
| 256 | check('from __future__ import doesnt_exist', 1, 1) |
| 257 | check('from __future__ import braces', 1, 1) |
| 258 | check('x=1\nfrom __future__ import division', 2, 1) |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 259 | check('foo(1=2)', 1, 5) |
Lysandros Nikolaou | a15c9b3 | 2020-05-13 22:36:27 +0300 | [diff] [blame] | 260 | check('def f():\n x, y: int', 2, 3) |
| 261 | check('[*x for x in xs]', 1, 2) |
| 262 | check('foo(x for x in range(10), 100)', 1, 5) |
Lysandros Nikolaou | 01ece63 | 2020-06-19 02:10:43 +0300 | [diff] [blame] | 263 | check('for 1 in []: pass', 1, 5) |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 264 | check('(yield i) = 2', 1, 2) |
| 265 | check('def f(*):\n pass', 1, 7) |
Serhiy Storchaka | 65fd059 | 2014-01-21 22:26:52 +0200 | [diff] [blame] | 266 | |
Benjamin Peterson | 17e0bbc | 2010-06-28 15:39:55 +0000 | [diff] [blame] | 267 | @cpython_only |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 268 | def testSettingException(self): |
| 269 | # test that setting an exception at the C level works even if the |
| 270 | # exception object can't be constructed. |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 271 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 272 | class BadException(Exception): |
| 273 | def __init__(self_): |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 274 | raise RuntimeError("can't instantiate BadException") |
Finn Bock | aa3dc45 | 2001-12-08 10:15:48 +0000 | [diff] [blame] | 275 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 276 | class InvalidException: |
| 277 | pass |
Thomas Wouters | 303de6a | 2006-04-20 22:42:37 +0000 | [diff] [blame] | 278 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 279 | def test_capi1(): |
| 280 | import _testcapi |
| 281 | try: |
| 282 | _testcapi.raise_exception(BadException, 1) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 283 | except TypeError as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 284 | exc, err, tb = sys.exc_info() |
| 285 | co = tb.tb_frame.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 286 | self.assertEqual(co.co_name, "test_capi1") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 287 | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 288 | else: |
| 289 | self.fail("Expected exception") |
Jeremy Hylton | ede049b | 2001-09-26 20:01:13 +0000 | [diff] [blame] | 290 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 291 | def test_capi2(): |
| 292 | import _testcapi |
| 293 | try: |
| 294 | _testcapi.raise_exception(BadException, 0) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 295 | except RuntimeError as err: |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 296 | exc, err, tb = sys.exc_info() |
| 297 | co = tb.tb_frame.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 298 | self.assertEqual(co.co_name, "__init__") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 299 | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 300 | co2 = tb.tb_frame.f_back.f_code |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 301 | self.assertEqual(co2.co_name, "test_capi2") |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 302 | else: |
| 303 | self.fail("Expected exception") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 304 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 305 | def test_capi3(): |
| 306 | import _testcapi |
| 307 | self.assertRaises(SystemError, _testcapi.raise_exception, |
| 308 | InvalidException, 1) |
| 309 | |
| 310 | if not sys.platform.startswith('java'): |
| 311 | test_capi1() |
| 312 | test_capi2() |
| 313 | test_capi3() |
| 314 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 315 | def test_WindowsError(self): |
| 316 | try: |
| 317 | WindowsError |
| 318 | except NameError: |
| 319 | pass |
| 320 | else: |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 321 | self.assertIs(WindowsError, OSError) |
| 322 | self.assertEqual(str(OSError(1001)), "1001") |
| 323 | self.assertEqual(str(OSError(1001, "message")), |
| 324 | "[Errno 1001] message") |
| 325 | # POSIX errno (9 aka EBADF) is untranslated |
| 326 | w = OSError(9, 'foo', 'bar') |
| 327 | self.assertEqual(w.errno, 9) |
| 328 | self.assertEqual(w.winerror, None) |
| 329 | self.assertEqual(str(w), "[Errno 9] foo: 'bar'") |
| 330 | # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) |
| 331 | w = OSError(0, 'foo', 'bar', 3) |
| 332 | self.assertEqual(w.errno, 2) |
| 333 | self.assertEqual(w.winerror, 3) |
| 334 | self.assertEqual(w.strerror, 'foo') |
| 335 | self.assertEqual(w.filename, 'bar') |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 336 | self.assertEqual(w.filename2, None) |
Richard Oudkerk | 3014771 | 2012-08-28 19:33:26 +0100 | [diff] [blame] | 337 | self.assertEqual(str(w), "[WinError 3] foo: 'bar'") |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 338 | # Unknown win error becomes EINVAL (22) |
| 339 | w = OSError(0, 'foo', None, 1001) |
| 340 | self.assertEqual(w.errno, 22) |
| 341 | self.assertEqual(w.winerror, 1001) |
| 342 | self.assertEqual(w.strerror, 'foo') |
| 343 | self.assertEqual(w.filename, None) |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 344 | self.assertEqual(w.filename2, None) |
Richard Oudkerk | 3014771 | 2012-08-28 19:33:26 +0100 | [diff] [blame] | 345 | self.assertEqual(str(w), "[WinError 1001] foo") |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 346 | # Non-numeric "errno" |
| 347 | w = OSError('bar', 'foo') |
| 348 | self.assertEqual(w.errno, 'bar') |
| 349 | self.assertEqual(w.winerror, None) |
| 350 | self.assertEqual(w.strerror, 'foo') |
| 351 | self.assertEqual(w.filename, None) |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 352 | self.assertEqual(w.filename2, None) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 353 | |
Victor Stinner | d223fa6 | 2015-04-02 14:17:38 +0200 | [diff] [blame] | 354 | @unittest.skipUnless(sys.platform == 'win32', |
| 355 | 'test specific to Windows') |
Serhiy Storchaka | f41f8f9 | 2015-04-02 09:47:27 +0300 | [diff] [blame] | 356 | def test_windows_message(self): |
| 357 | """Should fill in unknown error code in Windows error message""" |
Victor Stinner | d223fa6 | 2015-04-02 14:17:38 +0200 | [diff] [blame] | 358 | ctypes = import_module('ctypes') |
| 359 | # this error code has no message, Python formats it as hexadecimal |
| 360 | code = 3765269347 |
| 361 | with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): |
| 362 | ctypes.pythonapi.PyErr_SetFromWindowsErr(code) |
Serhiy Storchaka | f41f8f9 | 2015-04-02 09:47:27 +0300 | [diff] [blame] | 363 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 364 | def testAttributes(self): |
| 365 | # test that exception attributes are happy |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 366 | |
| 367 | exceptionList = [ |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 368 | (BaseException, (), {'args' : ()}), |
| 369 | (BaseException, (1, ), {'args' : (1,)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 370 | (BaseException, ('foo',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 371 | {'args' : ('foo',)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 372 | (BaseException, ('foo', 1), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 373 | {'args' : ('foo', 1)}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 374 | (SystemExit, ('foo',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 375 | {'args' : ('foo',), 'code' : 'foo'}), |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 376 | (OSError, ('foo',), |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 377 | {'args' : ('foo',), 'filename' : None, 'filename2' : None, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 378 | 'errno' : None, 'strerror' : None}), |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 379 | (OSError, ('foo', 'bar'), |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 380 | {'args' : ('foo', 'bar'), |
| 381 | 'filename' : None, 'filename2' : None, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 382 | 'errno' : 'foo', 'strerror' : 'bar'}), |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 383 | (OSError, ('foo', 'bar', 'baz'), |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 384 | {'args' : ('foo', 'bar'), |
| 385 | 'filename' : 'baz', 'filename2' : None, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 386 | 'errno' : 'foo', 'strerror' : 'bar'}), |
Larry Hastings | b082731 | 2014-02-09 22:05:19 -0800 | [diff] [blame] | 387 | (OSError, ('foo', 'bar', 'baz', None, 'quux'), |
| 388 | {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 389 | (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 390 | {'args' : ('errnoStr', 'strErrorStr'), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 391 | 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', |
| 392 | 'filename' : 'filenameStr'}), |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 393 | (OSError, (1, 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 394 | {'args' : (1, 'strErrorStr'), 'errno' : 1, |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 395 | 'strerror' : 'strErrorStr', |
| 396 | 'filename' : 'filenameStr', 'filename2' : None}), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 397 | (SyntaxError, (), {'msg' : None, 'text' : None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 398 | 'filename' : None, 'lineno' : None, 'offset' : None, |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 399 | 'end_offset': None, 'print_file_and_line' : None}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 400 | (SyntaxError, ('msgStr',), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 401 | {'args' : ('msgStr',), 'text' : None, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 402 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 403 | 'filename' : None, 'lineno' : None, 'offset' : None, |
| 404 | 'end_offset': None}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 405 | (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 406 | 'textStr', 'endLinenoStr', 'endOffsetStr')), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 407 | {'offset' : 'offsetStr', 'text' : 'textStr', |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 408 | 'args' : ('msgStr', ('filenameStr', 'linenoStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 409 | 'offsetStr', 'textStr', |
| 410 | 'endLinenoStr', 'endOffsetStr')), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 411 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 412 | 'filename' : 'filenameStr', 'lineno' : 'linenoStr', |
| 413 | 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 414 | (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 415 | 'textStr', 'endLinenoStr', 'endOffsetStr', |
| 416 | 'print_file_and_lineStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 417 | {'text' : None, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 418 | 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 419 | 'textStr', 'endLinenoStr', 'endOffsetStr', |
| 420 | 'print_file_and_lineStr'), |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 421 | 'print_file_and_line' : None, 'msg' : 'msgStr', |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 422 | 'filename' : None, 'lineno' : None, 'offset' : None, |
| 423 | 'end_lineno': None, 'end_offset': None}), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 424 | (UnicodeError, (), {'args' : (),}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 425 | (UnicodeEncodeError, ('ascii', 'a', 0, 1, |
| 426 | 'ordinal not in range'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 427 | {'args' : ('ascii', 'a', 0, 1, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 428 | 'ordinal not in range'), |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 429 | 'encoding' : 'ascii', 'object' : 'a', |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 430 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 431 | (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 432 | 'ordinal not in range'), |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 433 | {'args' : ('ascii', bytearray(b'\xff'), 0, 1, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 434 | 'ordinal not in range'), |
| 435 | 'encoding' : 'ascii', 'object' : b'\xff', |
| 436 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 437 | (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, |
| 438 | 'ordinal not in range'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 439 | {'args' : ('ascii', b'\xff', 0, 1, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 440 | 'ordinal not in range'), |
Guido van Rossum | b8142c3 | 2007-05-08 17:49:10 +0000 | [diff] [blame] | 441 | 'encoding' : 'ascii', 'object' : b'\xff', |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 442 | 'start' : 0, 'reason' : 'ordinal not in range'}), |
Walter Dörwald | eceb0fb | 2007-05-24 17:49:56 +0000 | [diff] [blame] | 443 | (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 444 | {'args' : ('\u3042', 0, 1, 'ouch'), |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 445 | 'object' : '\u3042', 'reason' : 'ouch', |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 446 | 'start' : 0, 'end' : 1}), |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 447 | (NaiveException, ('foo',), |
| 448 | {'args': ('foo',), 'x': 'foo'}), |
| 449 | (SlottedNaiveException, ('foo',), |
| 450 | {'args': ('foo',), 'x': 'foo'}), |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 451 | ] |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 452 | try: |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 453 | # More tests are in test_WindowsError |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 454 | exceptionList.append( |
| 455 | (WindowsError, (1, 'strErrorStr', 'filenameStr'), |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 456 | {'args' : (1, 'strErrorStr'), |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 457 | 'strerror' : 'strErrorStr', 'winerror' : None, |
Martin Panter | 5487c13 | 2015-10-26 11:05:42 +0000 | [diff] [blame] | 458 | 'errno' : 1, |
| 459 | 'filename' : 'filenameStr', 'filename2' : None}) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 460 | ) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 461 | except NameError: |
| 462 | pass |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 463 | |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 464 | for exc, args, expected in exceptionList: |
| 465 | try: |
| 466 | e = exc(*args) |
| 467 | except: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 468 | print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr) |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 469 | # raise |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 470 | else: |
| 471 | # Verify module name |
Richard Oudkerk | 5562d9d | 2012-07-28 17:45:28 +0100 | [diff] [blame] | 472 | if not type(e).__name__.endswith('NaiveException'): |
| 473 | self.assertEqual(type(e).__module__, 'builtins') |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 474 | # Verify no ref leaks in Exc_str() |
| 475 | s = str(e) |
| 476 | for checkArgName in expected: |
| 477 | value = getattr(e, checkArgName) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 478 | self.assertEqual(repr(value), |
| 479 | repr(expected[checkArgName]), |
| 480 | '%r.%s == %r, expected %r' % ( |
| 481 | e, checkArgName, |
| 482 | value, expected[checkArgName])) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 483 | |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 484 | # test for pickling support |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 485 | for p in [pickle]: |
Guido van Rossum | ebe3e16 | 2007-05-17 18:20:34 +0000 | [diff] [blame] | 486 | for protocol in range(p.HIGHEST_PROTOCOL + 1): |
| 487 | s = p.dumps(e, protocol) |
| 488 | new = p.loads(s) |
| 489 | for checkArgName in expected: |
| 490 | got = repr(getattr(new, checkArgName)) |
| 491 | want = repr(expected[checkArgName]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 492 | self.assertEqual(got, want, |
| 493 | 'pickled "%r", attribute "%s' % |
| 494 | (e, checkArgName)) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 495 | |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 496 | def testWithTraceback(self): |
| 497 | try: |
| 498 | raise IndexError(4) |
| 499 | except: |
| 500 | tb = sys.exc_info()[2] |
| 501 | |
| 502 | e = BaseException().with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 503 | self.assertIsInstance(e, BaseException) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 504 | self.assertEqual(e.__traceback__, tb) |
| 505 | |
| 506 | e = IndexError(5).with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 507 | self.assertIsInstance(e, IndexError) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 508 | self.assertEqual(e.__traceback__, tb) |
| 509 | |
| 510 | class MyException(Exception): |
| 511 | pass |
| 512 | |
| 513 | e = MyException().with_traceback(tb) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 514 | self.assertIsInstance(e, MyException) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 515 | self.assertEqual(e.__traceback__, tb) |
| 516 | |
| 517 | def testInvalidTraceback(self): |
| 518 | try: |
| 519 | Exception().__traceback__ = 5 |
| 520 | except TypeError as e: |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 521 | self.assertIn("__traceback__ must be a traceback", str(e)) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 522 | else: |
| 523 | self.fail("No exception raised") |
| 524 | |
Georg Brandl | ab6f2f6 | 2009-03-31 04:16:10 +0000 | [diff] [blame] | 525 | def testInvalidAttrs(self): |
| 526 | self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1) |
| 527 | self.assertRaises(TypeError, delattr, Exception(), '__cause__') |
| 528 | self.assertRaises(TypeError, setattr, Exception(), '__context__', 1) |
| 529 | self.assertRaises(TypeError, delattr, Exception(), '__context__') |
| 530 | |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 531 | def testNoneClearsTracebackAttr(self): |
| 532 | try: |
| 533 | raise IndexError(4) |
| 534 | except: |
| 535 | tb = sys.exc_info()[2] |
| 536 | |
| 537 | e = Exception() |
| 538 | e.__traceback__ = tb |
| 539 | e.__traceback__ = None |
| 540 | self.assertEqual(e.__traceback__, None) |
| 541 | |
| 542 | def testChainingAttrs(self): |
| 543 | e = Exception() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 544 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 545 | self.assertIsNone(e.__cause__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 546 | |
| 547 | e = TypeError() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 548 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 549 | self.assertIsNone(e.__cause__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 550 | |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 551 | class MyException(OSError): |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 552 | pass |
| 553 | |
| 554 | e = MyException() |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 555 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 556 | self.assertIsNone(e.__cause__) |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 557 | |
| 558 | def testChainingDescriptors(self): |
| 559 | try: |
| 560 | raise Exception() |
| 561 | except Exception as exc: |
| 562 | e = exc |
| 563 | |
| 564 | self.assertIsNone(e.__context__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 565 | self.assertIsNone(e.__cause__) |
| 566 | self.assertFalse(e.__suppress_context__) |
Nick Coghlan | ab7bf21 | 2012-02-26 17:49:52 +1000 | [diff] [blame] | 567 | |
| 568 | e.__context__ = NameError() |
| 569 | e.__cause__ = None |
| 570 | self.assertIsInstance(e.__context__, NameError) |
| 571 | self.assertIsNone(e.__cause__) |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 572 | self.assertTrue(e.__suppress_context__) |
| 573 | e.__suppress_context__ = False |
| 574 | self.assertFalse(e.__suppress_context__) |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 575 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 576 | def testKeywordArgs(self): |
| 577 | # test that builtin exception don't take keyword args, |
| 578 | # but user-defined subclasses can if they want |
| 579 | self.assertRaises(TypeError, BaseException, a=1) |
| 580 | |
| 581 | class DerivedException(BaseException): |
| 582 | def __init__(self, fancy_arg): |
| 583 | BaseException.__init__(self) |
| 584 | self.fancy_arg = fancy_arg |
| 585 | |
| 586 | x = DerivedException(fancy_arg=42) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 587 | self.assertEqual(x.fancy_arg, 42) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 588 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 589 | @no_tracing |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 590 | def testInfiniteRecursion(self): |
| 591 | def f(): |
| 592 | return f() |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 593 | self.assertRaises(RecursionError, f) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 594 | |
| 595 | def g(): |
| 596 | try: |
| 597 | return g() |
| 598 | except ValueError: |
| 599 | return -1 |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 600 | self.assertRaises(RecursionError, g) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 601 | |
Ezio Melotti | 2f5a78c | 2009-12-24 22:54:06 +0000 | [diff] [blame] | 602 | def test_str(self): |
| 603 | # Make sure both instances and classes have a str representation. |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 604 | self.assertTrue(str(Exception)) |
| 605 | self.assertTrue(str(Exception('a'))) |
Ezio Melotti | 2f5a78c | 2009-12-24 22:54:06 +0000 | [diff] [blame] | 606 | self.assertTrue(str(Exception('a', 'b'))) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 607 | |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 608 | def testExceptionCleanupNames(self): |
| 609 | # Make sure the local variable bound to the exception instance by |
| 610 | # an "except" statement is only visible inside the except block. |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 611 | try: |
| 612 | raise Exception() |
| 613 | except Exception as e: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 614 | self.assertTrue(e) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 615 | del e |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 616 | self.assertNotIn('e', locals()) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 617 | |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 618 | def testExceptionCleanupState(self): |
| 619 | # Make sure exception state is cleaned up as soon as the except |
| 620 | # block is left. See #2507 |
| 621 | |
| 622 | class MyException(Exception): |
| 623 | def __init__(self, obj): |
| 624 | self.obj = obj |
| 625 | class MyObj: |
| 626 | pass |
| 627 | |
| 628 | def inner_raising_func(): |
| 629 | # Create some references in exception value and traceback |
| 630 | local_ref = obj |
| 631 | raise MyException(obj) |
| 632 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 633 | # Qualified "except" with "as" |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 634 | obj = MyObj() |
| 635 | wr = weakref.ref(obj) |
| 636 | try: |
| 637 | inner_raising_func() |
| 638 | except MyException as e: |
| 639 | pass |
| 640 | obj = None |
| 641 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 642 | self.assertIsNone(obj) |
Barry Warsaw | 8d109cb | 2008-05-08 04:26:35 +0000 | [diff] [blame] | 643 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 644 | # Qualified "except" without "as" |
| 645 | obj = MyObj() |
| 646 | wr = weakref.ref(obj) |
| 647 | try: |
| 648 | inner_raising_func() |
| 649 | except MyException: |
| 650 | pass |
| 651 | obj = None |
| 652 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 653 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 654 | |
| 655 | # Bare "except" |
| 656 | obj = MyObj() |
| 657 | wr = weakref.ref(obj) |
| 658 | try: |
| 659 | inner_raising_func() |
| 660 | except: |
| 661 | pass |
| 662 | obj = None |
| 663 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 664 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 665 | |
| 666 | # "except" with premature block leave |
| 667 | obj = MyObj() |
| 668 | wr = weakref.ref(obj) |
| 669 | for i in [0]: |
| 670 | try: |
| 671 | inner_raising_func() |
| 672 | except: |
| 673 | break |
| 674 | obj = None |
| 675 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 676 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 677 | |
| 678 | # "except" block raising another exception |
| 679 | obj = MyObj() |
| 680 | wr = weakref.ref(obj) |
| 681 | try: |
| 682 | try: |
| 683 | inner_raising_func() |
| 684 | except: |
| 685 | raise KeyError |
Guido van Rossum | b4fb6e4 | 2008-06-14 20:20:24 +0000 | [diff] [blame] | 686 | except KeyError as e: |
| 687 | # We want to test that the except block above got rid of |
| 688 | # the exception raised in inner_raising_func(), but it |
| 689 | # also ends up in the __context__ of the KeyError, so we |
| 690 | # must clear the latter manually for our test to succeed. |
| 691 | e.__context__ = None |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 692 | obj = None |
| 693 | obj = wr() |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 694 | # guarantee no ref cycles on CPython (don't gc_collect) |
| 695 | if check_impl_detail(cpython=False): |
| 696 | gc_collect() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 697 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 698 | |
| 699 | # Some complicated construct |
| 700 | obj = MyObj() |
| 701 | wr = weakref.ref(obj) |
| 702 | try: |
| 703 | inner_raising_func() |
| 704 | except MyException: |
| 705 | try: |
| 706 | try: |
| 707 | raise |
| 708 | finally: |
| 709 | raise |
| 710 | except MyException: |
| 711 | pass |
| 712 | obj = None |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 713 | if check_impl_detail(cpython=False): |
| 714 | gc_collect() |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 715 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 716 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 717 | |
| 718 | # Inside an exception-silencing "with" block |
| 719 | class Context: |
| 720 | def __enter__(self): |
| 721 | return self |
| 722 | def __exit__ (self, exc_type, exc_value, exc_tb): |
| 723 | return True |
| 724 | obj = MyObj() |
| 725 | wr = weakref.ref(obj) |
| 726 | with Context(): |
| 727 | inner_raising_func() |
| 728 | obj = None |
Philip Jenvey | b37ac8e | 2012-11-14 14:37:24 -0800 | [diff] [blame] | 729 | if check_impl_detail(cpython=False): |
| 730 | gc_collect() |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 731 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 732 | self.assertIsNone(obj) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 733 | |
Amaury Forgeot d'Arc | ba117ef | 2010-09-10 21:39:53 +0000 | [diff] [blame] | 734 | def test_exception_target_in_nested_scope(self): |
| 735 | # issue 4617: This used to raise a SyntaxError |
| 736 | # "can not delete variable 'e' referenced in nested scope" |
| 737 | def print_error(): |
| 738 | e |
| 739 | try: |
| 740 | something |
| 741 | except Exception as e: |
| 742 | print_error() |
| 743 | # implicit "del e" here |
| 744 | |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 745 | def test_generator_leaking(self): |
| 746 | # Test that generator exception state doesn't leak into the calling |
| 747 | # frame |
| 748 | def yield_raise(): |
| 749 | try: |
| 750 | raise KeyError("caught") |
| 751 | except KeyError: |
| 752 | yield sys.exc_info()[0] |
| 753 | yield sys.exc_info()[0] |
| 754 | yield sys.exc_info()[0] |
| 755 | g = yield_raise() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 756 | self.assertEqual(next(g), KeyError) |
| 757 | self.assertEqual(sys.exc_info()[0], None) |
| 758 | self.assertEqual(next(g), KeyError) |
| 759 | self.assertEqual(sys.exc_info()[0], None) |
| 760 | self.assertEqual(next(g), None) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 761 | |
| 762 | # Same test, but inside an exception handler |
| 763 | try: |
| 764 | raise TypeError("foo") |
| 765 | except TypeError: |
| 766 | g = yield_raise() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 767 | self.assertEqual(next(g), KeyError) |
| 768 | self.assertEqual(sys.exc_info()[0], TypeError) |
| 769 | self.assertEqual(next(g), KeyError) |
| 770 | self.assertEqual(sys.exc_info()[0], TypeError) |
| 771 | self.assertEqual(next(g), TypeError) |
Benjamin Peterson | eec3d71 | 2008-06-11 15:59:43 +0000 | [diff] [blame] | 772 | del g |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 773 | self.assertEqual(sys.exc_info()[0], TypeError) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 774 | |
Benjamin Peterson | 83195c3 | 2011-07-03 13:44:00 -0500 | [diff] [blame] | 775 | def test_generator_leaking2(self): |
| 776 | # See issue 12475. |
| 777 | def g(): |
| 778 | yield |
| 779 | try: |
| 780 | raise RuntimeError |
| 781 | except RuntimeError: |
| 782 | it = g() |
| 783 | next(it) |
| 784 | try: |
| 785 | next(it) |
| 786 | except StopIteration: |
| 787 | pass |
| 788 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 789 | |
Antoine Pitrou | c4c19b3 | 2015-03-18 22:22:46 +0100 | [diff] [blame] | 790 | def test_generator_leaking3(self): |
| 791 | # See issue #23353. When gen.throw() is called, the caller's |
| 792 | # exception state should be save and restored. |
| 793 | def g(): |
| 794 | try: |
| 795 | yield |
| 796 | except ZeroDivisionError: |
| 797 | yield sys.exc_info()[1] |
| 798 | it = g() |
| 799 | next(it) |
| 800 | try: |
| 801 | 1/0 |
| 802 | except ZeroDivisionError as e: |
| 803 | self.assertIs(sys.exc_info()[1], e) |
| 804 | gen_exc = it.throw(e) |
| 805 | self.assertIs(sys.exc_info()[1], e) |
| 806 | self.assertIs(gen_exc, e) |
| 807 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 808 | |
| 809 | def test_generator_leaking4(self): |
| 810 | # See issue #23353. When an exception is raised by a generator, |
| 811 | # the caller's exception state should still be restored. |
| 812 | def g(): |
| 813 | try: |
| 814 | 1/0 |
| 815 | except ZeroDivisionError: |
| 816 | yield sys.exc_info()[0] |
| 817 | raise |
| 818 | it = g() |
| 819 | try: |
| 820 | raise TypeError |
| 821 | except TypeError: |
| 822 | # The caller's exception state (TypeError) is temporarily |
| 823 | # saved in the generator. |
| 824 | tp = next(it) |
| 825 | self.assertIs(tp, ZeroDivisionError) |
| 826 | try: |
| 827 | next(it) |
| 828 | # We can't check it immediately, but while next() returns |
| 829 | # with an exception, it shouldn't have restored the old |
| 830 | # exception state (TypeError). |
| 831 | except ZeroDivisionError as e: |
| 832 | self.assertIs(sys.exc_info()[1], e) |
| 833 | # We used to find TypeError here. |
| 834 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 835 | |
Benjamin Peterson | ac91341 | 2011-07-03 16:25:11 -0500 | [diff] [blame] | 836 | def test_generator_doesnt_retain_old_exc(self): |
| 837 | def g(): |
| 838 | self.assertIsInstance(sys.exc_info()[1], RuntimeError) |
| 839 | yield |
| 840 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 841 | it = g() |
| 842 | try: |
| 843 | raise RuntimeError |
| 844 | except RuntimeError: |
| 845 | next(it) |
| 846 | self.assertRaises(StopIteration, next, it) |
| 847 | |
Benjamin Peterson | ae5f2f4 | 2010-03-07 17:10:51 +0000 | [diff] [blame] | 848 | def test_generator_finalizing_and_exc_info(self): |
| 849 | # See #7173 |
| 850 | def simple_gen(): |
| 851 | yield 1 |
| 852 | def run_gen(): |
| 853 | gen = simple_gen() |
| 854 | try: |
| 855 | raise RuntimeError |
| 856 | except RuntimeError: |
| 857 | return next(gen) |
| 858 | run_gen() |
| 859 | gc_collect() |
| 860 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 861 | |
Antoine Pitrou | a370fcf | 2011-08-20 14:15:03 +0200 | [diff] [blame] | 862 | def _check_generator_cleanup_exc_state(self, testfunc): |
| 863 | # Issue #12791: exception state is cleaned up as soon as a generator |
| 864 | # is closed (reference cycles are broken). |
| 865 | class MyException(Exception): |
| 866 | def __init__(self, obj): |
| 867 | self.obj = obj |
| 868 | class MyObj: |
| 869 | pass |
| 870 | |
| 871 | def raising_gen(): |
| 872 | try: |
| 873 | raise MyException(obj) |
| 874 | except MyException: |
| 875 | yield |
| 876 | |
| 877 | obj = MyObj() |
| 878 | wr = weakref.ref(obj) |
| 879 | g = raising_gen() |
| 880 | next(g) |
| 881 | testfunc(g) |
| 882 | g = obj = None |
| 883 | obj = wr() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 884 | self.assertIsNone(obj) |
Antoine Pitrou | a370fcf | 2011-08-20 14:15:03 +0200 | [diff] [blame] | 885 | |
| 886 | def test_generator_throw_cleanup_exc_state(self): |
| 887 | def do_throw(g): |
| 888 | try: |
| 889 | g.throw(RuntimeError()) |
| 890 | except RuntimeError: |
| 891 | pass |
| 892 | self._check_generator_cleanup_exc_state(do_throw) |
| 893 | |
| 894 | def test_generator_close_cleanup_exc_state(self): |
| 895 | def do_close(g): |
| 896 | g.close() |
| 897 | self._check_generator_cleanup_exc_state(do_close) |
| 898 | |
| 899 | def test_generator_del_cleanup_exc_state(self): |
| 900 | def do_del(g): |
| 901 | g = None |
| 902 | self._check_generator_cleanup_exc_state(do_del) |
| 903 | |
| 904 | def test_generator_next_cleanup_exc_state(self): |
| 905 | def do_next(g): |
| 906 | try: |
| 907 | next(g) |
| 908 | except StopIteration: |
| 909 | pass |
| 910 | else: |
| 911 | self.fail("should have raised StopIteration") |
| 912 | self._check_generator_cleanup_exc_state(do_next) |
| 913 | |
| 914 | def test_generator_send_cleanup_exc_state(self): |
| 915 | def do_send(g): |
| 916 | try: |
| 917 | g.send(None) |
| 918 | except StopIteration: |
| 919 | pass |
| 920 | else: |
| 921 | self.fail("should have raised StopIteration") |
| 922 | self._check_generator_cleanup_exc_state(do_send) |
| 923 | |
Benjamin Peterson | 27d6367 | 2008-06-15 20:09:12 +0000 | [diff] [blame] | 924 | def test_3114(self): |
| 925 | # Bug #3114: in its destructor, MyObject retrieves a pointer to |
| 926 | # obsolete and/or deallocated objects. |
Benjamin Peterson | 979f311 | 2008-06-15 00:05:44 +0000 | [diff] [blame] | 927 | class MyObject: |
| 928 | def __del__(self): |
| 929 | nonlocal e |
| 930 | e = sys.exc_info() |
| 931 | e = () |
| 932 | try: |
| 933 | raise Exception(MyObject()) |
| 934 | except: |
| 935 | pass |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 936 | self.assertEqual(e, (None, None, None)) |
Benjamin Peterson | 979f311 | 2008-06-15 00:05:44 +0000 | [diff] [blame] | 937 | |
Benjamin Peterson | 24dfb05 | 2014-04-02 12:05:35 -0400 | [diff] [blame] | 938 | def test_unicode_change_attributes(self): |
Eric Smith | 0facd77 | 2010-02-24 15:42:29 +0000 | [diff] [blame] | 939 | # See issue 7309. This was a crasher. |
| 940 | |
| 941 | u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') |
| 942 | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") |
| 943 | u.end = 2 |
| 944 | self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") |
| 945 | u.end = 5 |
| 946 | u.reason = 0x345345345345345345 |
| 947 | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") |
| 948 | u.encoding = 4000 |
| 949 | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") |
| 950 | u.start = 1000 |
| 951 | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") |
| 952 | |
| 953 | u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') |
| 954 | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") |
| 955 | u.end = 2 |
| 956 | self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") |
| 957 | u.end = 5 |
| 958 | u.reason = 0x345345345345345345 |
| 959 | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 960 | u.encoding = 4000 |
| 961 | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 962 | u.start = 1000 |
| 963 | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") |
| 964 | |
| 965 | u = UnicodeTranslateError('xxxx', 1, 5, 'foo') |
| 966 | self.assertEqual(str(u), "can't translate characters in position 1-4: foo") |
| 967 | u.end = 2 |
| 968 | self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") |
| 969 | u.end = 5 |
| 970 | u.reason = 0x345345345345345345 |
| 971 | self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") |
| 972 | u.start = 1000 |
| 973 | self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") |
Benjamin Peterson | 6e7740c | 2008-08-20 23:23:34 +0000 | [diff] [blame] | 974 | |
Benjamin Peterson | 9b09ba1 | 2014-04-02 12:15:06 -0400 | [diff] [blame] | 975 | def test_unicode_errors_no_object(self): |
| 976 | # See issue #21134. |
Benjamin Peterson | e331121 | 2014-04-02 15:51:38 -0400 | [diff] [blame] | 977 | klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError |
Benjamin Peterson | 9b09ba1 | 2014-04-02 12:15:06 -0400 | [diff] [blame] | 978 | for klass in klasses: |
| 979 | self.assertEqual(str(klass.__new__(klass)), "") |
| 980 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 981 | @no_tracing |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 982 | def test_badisinstance(self): |
| 983 | # Bug #2542: if issubclass(e, MyException) raises an exception, |
| 984 | # it should be ignored |
| 985 | class Meta(type): |
| 986 | def __subclasscheck__(cls, subclass): |
| 987 | raise ValueError() |
| 988 | class MyException(Exception, metaclass=Meta): |
| 989 | pass |
| 990 | |
Martin Panter | 3263f68 | 2016-02-28 03:16:11 +0000 | [diff] [blame] | 991 | with captured_stderr() as stderr: |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 992 | try: |
| 993 | raise KeyError() |
| 994 | except MyException as e: |
| 995 | self.fail("exception should not be a MyException") |
| 996 | except KeyError: |
| 997 | pass |
| 998 | except: |
Antoine Pitrou | ec569b7 | 2008-08-26 22:40:48 +0000 | [diff] [blame] | 999 | self.fail("Should have raised KeyError") |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 1000 | else: |
Antoine Pitrou | ec569b7 | 2008-08-26 22:40:48 +0000 | [diff] [blame] | 1001 | self.fail("Should have raised KeyError") |
| 1002 | |
| 1003 | def g(): |
| 1004 | try: |
| 1005 | return g() |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 1006 | except RecursionError: |
Antoine Pitrou | ec569b7 | 2008-08-26 22:40:48 +0000 | [diff] [blame] | 1007 | return sys.exc_info() |
| 1008 | e, v, tb = g() |
Serhiy Storchaka | f15c4d3 | 2017-03-30 18:05:08 +0300 | [diff] [blame] | 1009 | self.assertIsInstance(v, RecursionError, type(v)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1010 | self.assertIn("maximum recursion depth exceeded", str(v)) |
Benjamin Peterson | 69c88f7 | 2008-07-31 01:47:08 +0000 | [diff] [blame] | 1011 | |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 1012 | @cpython_only |
| 1013 | def test_recursion_normalizing_exception(self): |
| 1014 | # Issue #22898. |
| 1015 | # Test that a RecursionError is raised when tstate->recursion_depth is |
| 1016 | # equal to recursion_limit in PyErr_NormalizeException() and check |
| 1017 | # that a ResourceWarning is printed. |
| 1018 | # Prior to #22898, the recursivity of PyErr_NormalizeException() was |
luzpaz | a5293b4 | 2017-11-05 07:37:50 -0600 | [diff] [blame] | 1019 | # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 1020 | # singleton was being used in that case, that held traceback data and |
| 1021 | # locals indefinitely and would cause a segfault in _PyExc_Fini() upon |
| 1022 | # finalization of these locals. |
| 1023 | code = """if 1: |
| 1024 | import sys |
Victor Stinner | 3f2f4fe | 2020-03-13 13:07:31 +0100 | [diff] [blame] | 1025 | from _testinternalcapi import get_recursion_depth |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 1026 | |
| 1027 | class MyException(Exception): pass |
| 1028 | |
| 1029 | def setrecursionlimit(depth): |
| 1030 | while 1: |
| 1031 | try: |
| 1032 | sys.setrecursionlimit(depth) |
| 1033 | return depth |
| 1034 | except RecursionError: |
| 1035 | # sys.setrecursionlimit() raises a RecursionError if |
| 1036 | # the new recursion limit is too low (issue #25274). |
| 1037 | depth += 1 |
| 1038 | |
| 1039 | def recurse(cnt): |
| 1040 | cnt -= 1 |
| 1041 | if cnt: |
| 1042 | recurse(cnt) |
| 1043 | else: |
| 1044 | generator.throw(MyException) |
| 1045 | |
| 1046 | def gen(): |
| 1047 | f = open(%a, mode='rb', buffering=0) |
| 1048 | yield |
| 1049 | |
| 1050 | generator = gen() |
| 1051 | next(generator) |
| 1052 | recursionlimit = sys.getrecursionlimit() |
| 1053 | depth = get_recursion_depth() |
| 1054 | try: |
| 1055 | # Upon the last recursive invocation of recurse(), |
| 1056 | # tstate->recursion_depth is equal to (recursion_limit - 1) |
| 1057 | # and is equal to recursion_limit when _gen_throw() calls |
| 1058 | # PyErr_NormalizeException(). |
Mark Shannon | 4e7a69b | 2020-12-02 13:30:55 +0000 | [diff] [blame] | 1059 | recurse(setrecursionlimit(depth + 2) - depth) |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 1060 | finally: |
| 1061 | sys.setrecursionlimit(recursionlimit) |
| 1062 | print('Done.') |
| 1063 | """ % __file__ |
| 1064 | rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code) |
| 1065 | # Check that the program does not fail with SIGABRT. |
| 1066 | self.assertEqual(rc, 1) |
| 1067 | self.assertIn(b'RecursionError', err) |
| 1068 | self.assertIn(b'ResourceWarning', err) |
| 1069 | self.assertIn(b'Done.', out) |
| 1070 | |
| 1071 | @cpython_only |
| 1072 | def test_recursion_normalizing_infinite_exception(self): |
| 1073 | # Issue #30697. Test that a RecursionError is raised when |
| 1074 | # PyErr_NormalizeException() maximum recursion depth has been |
| 1075 | # exceeded. |
| 1076 | code = """if 1: |
| 1077 | import _testcapi |
| 1078 | try: |
| 1079 | raise _testcapi.RecursingInfinitelyError |
| 1080 | finally: |
| 1081 | print('Done.') |
| 1082 | """ |
| 1083 | rc, out, err = script_helper.assert_python_failure("-c", code) |
| 1084 | self.assertEqual(rc, 1) |
| 1085 | self.assertIn(b'RecursionError: maximum recursion depth exceeded ' |
| 1086 | b'while normalizing an exception', err) |
| 1087 | self.assertIn(b'Done.', out) |
| 1088 | |
Mark Shannon | 4e7a69b | 2020-12-02 13:30:55 +0000 | [diff] [blame] | 1089 | |
| 1090 | def test_recursion_in_except_handler(self): |
| 1091 | |
| 1092 | def set_relative_recursion_limit(n): |
| 1093 | depth = 1 |
| 1094 | while True: |
| 1095 | try: |
| 1096 | sys.setrecursionlimit(depth) |
| 1097 | except RecursionError: |
| 1098 | depth += 1 |
| 1099 | else: |
| 1100 | break |
| 1101 | sys.setrecursionlimit(depth+n) |
| 1102 | |
| 1103 | def recurse_in_except(): |
| 1104 | try: |
| 1105 | 1/0 |
| 1106 | except: |
| 1107 | recurse_in_except() |
| 1108 | |
| 1109 | def recurse_after_except(): |
| 1110 | try: |
| 1111 | 1/0 |
| 1112 | except: |
| 1113 | pass |
| 1114 | recurse_after_except() |
| 1115 | |
| 1116 | def recurse_in_body_and_except(): |
| 1117 | try: |
| 1118 | recurse_in_body_and_except() |
| 1119 | except: |
| 1120 | recurse_in_body_and_except() |
| 1121 | |
| 1122 | recursionlimit = sys.getrecursionlimit() |
| 1123 | try: |
| 1124 | set_relative_recursion_limit(10) |
| 1125 | for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except): |
| 1126 | with self.subTest(func=func): |
| 1127 | try: |
| 1128 | func() |
| 1129 | except RecursionError: |
| 1130 | pass |
| 1131 | else: |
| 1132 | self.fail("Should have raised a RecursionError") |
| 1133 | finally: |
| 1134 | sys.setrecursionlimit(recursionlimit) |
| 1135 | |
| 1136 | |
xdegaye | 56d1f5c | 2017-10-26 15:09:06 +0200 | [diff] [blame] | 1137 | @cpython_only |
| 1138 | def test_recursion_normalizing_with_no_memory(self): |
| 1139 | # Issue #30697. Test that in the abort that occurs when there is no |
| 1140 | # memory left and the size of the Python frames stack is greater than |
| 1141 | # the size of the list of preallocated MemoryError instances, the |
| 1142 | # Fatal Python error message mentions MemoryError. |
| 1143 | code = """if 1: |
| 1144 | import _testcapi |
| 1145 | class C(): pass |
| 1146 | def recurse(cnt): |
| 1147 | cnt -= 1 |
| 1148 | if cnt: |
| 1149 | recurse(cnt) |
| 1150 | else: |
| 1151 | _testcapi.set_nomemory(0) |
| 1152 | C() |
| 1153 | recurse(16) |
| 1154 | """ |
| 1155 | with SuppressCrashReport(): |
| 1156 | rc, out, err = script_helper.assert_python_failure("-c", code) |
Victor Stinner | 9e5d30c | 2020-03-07 00:54:20 +0100 | [diff] [blame] | 1157 | self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: ' |
| 1158 | b'Cannot recover from MemoryErrors while ' |
| 1159 | b'normalizing exceptions.', err) |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 1160 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 1161 | @cpython_only |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 1162 | def test_MemoryError(self): |
| 1163 | # PyErr_NoMemory always raises the same exception instance. |
| 1164 | # Check that the traceback is not doubled. |
| 1165 | import traceback |
Benjamin Peterson | 0067bd6 | 2008-08-16 16:11:03 +0000 | [diff] [blame] | 1166 | from _testcapi import raise_memoryerror |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 1167 | def raiseMemError(): |
| 1168 | try: |
Benjamin Peterson | 0067bd6 | 2008-08-16 16:11:03 +0000 | [diff] [blame] | 1169 | raise_memoryerror() |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 1170 | except MemoryError as e: |
| 1171 | tb = e.__traceback__ |
| 1172 | else: |
Mark Shannon | 4e7a69b | 2020-12-02 13:30:55 +0000 | [diff] [blame] | 1173 | self.fail("Should have raised a MemoryError") |
Amaury Forgeot d'Arc | e19cadb | 2008-07-31 22:56:02 +0000 | [diff] [blame] | 1174 | return traceback.format_tb(tb) |
| 1175 | |
| 1176 | tb1 = raiseMemError() |
| 1177 | tb2 = raiseMemError() |
| 1178 | self.assertEqual(tb1, tb2) |
| 1179 | |
Benjamin Peterson | 17e0bbc | 2010-06-28 15:39:55 +0000 | [diff] [blame] | 1180 | @cpython_only |
Georg Brandl | 1e28a27 | 2009-12-28 08:41:01 +0000 | [diff] [blame] | 1181 | def test_exception_with_doc(self): |
| 1182 | import _testcapi |
| 1183 | doc2 = "This is a test docstring." |
| 1184 | doc4 = "This is another test docstring." |
| 1185 | |
| 1186 | self.assertRaises(SystemError, _testcapi.make_exception_with_doc, |
| 1187 | "error1") |
| 1188 | |
| 1189 | # test basic usage of PyErr_NewException |
| 1190 | error1 = _testcapi.make_exception_with_doc("_testcapi.error1") |
| 1191 | self.assertIs(type(error1), type) |
| 1192 | self.assertTrue(issubclass(error1, Exception)) |
| 1193 | self.assertIsNone(error1.__doc__) |
| 1194 | |
| 1195 | # test with given docstring |
| 1196 | error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) |
| 1197 | self.assertEqual(error2.__doc__, doc2) |
| 1198 | |
| 1199 | # test with explicit base (without docstring) |
| 1200 | error3 = _testcapi.make_exception_with_doc("_testcapi.error3", |
| 1201 | base=error2) |
| 1202 | self.assertTrue(issubclass(error3, error2)) |
| 1203 | |
| 1204 | # test with explicit base tuple |
| 1205 | class C(object): |
| 1206 | pass |
| 1207 | error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, |
| 1208 | (error3, C)) |
| 1209 | self.assertTrue(issubclass(error4, error3)) |
| 1210 | self.assertTrue(issubclass(error4, C)) |
| 1211 | self.assertEqual(error4.__doc__, doc4) |
| 1212 | |
| 1213 | # test with explicit dictionary |
| 1214 | error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", |
| 1215 | error4, {'a': 1}) |
| 1216 | self.assertTrue(issubclass(error5, error4)) |
| 1217 | self.assertEqual(error5.a, 1) |
| 1218 | self.assertEqual(error5.__doc__, "") |
| 1219 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 1220 | @cpython_only |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 1221 | def test_memory_error_cleanup(self): |
| 1222 | # Issue #5437: preallocated MemoryError instances should not keep |
| 1223 | # traceback objects alive. |
| 1224 | from _testcapi import raise_memoryerror |
| 1225 | class C: |
| 1226 | pass |
| 1227 | wr = None |
| 1228 | def inner(): |
| 1229 | nonlocal wr |
| 1230 | c = C() |
| 1231 | wr = weakref.ref(c) |
| 1232 | raise_memoryerror() |
| 1233 | # We cannot use assertRaises since it manually deletes the traceback |
| 1234 | try: |
| 1235 | inner() |
| 1236 | except MemoryError as e: |
| 1237 | self.assertNotEqual(wr(), None) |
| 1238 | else: |
| 1239 | self.fail("MemoryError not raised") |
| 1240 | self.assertEqual(wr(), None) |
| 1241 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 1242 | @no_tracing |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 1243 | def test_recursion_error_cleanup(self): |
| 1244 | # Same test as above, but with "recursion exceeded" errors |
| 1245 | class C: |
| 1246 | pass |
| 1247 | wr = None |
| 1248 | def inner(): |
| 1249 | nonlocal wr |
| 1250 | c = C() |
| 1251 | wr = weakref.ref(c) |
| 1252 | inner() |
| 1253 | # We cannot use assertRaises since it manually deletes the traceback |
| 1254 | try: |
| 1255 | inner() |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 1256 | except RecursionError as e: |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 1257 | self.assertNotEqual(wr(), None) |
| 1258 | else: |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 1259 | self.fail("RecursionError not raised") |
Antoine Pitrou | 07e20ef | 2010-10-28 22:56:58 +0000 | [diff] [blame] | 1260 | self.assertEqual(wr(), None) |
Georg Brandl | 1e28a27 | 2009-12-28 08:41:01 +0000 | [diff] [blame] | 1261 | |
Antoine Pitrou | a762285 | 2011-09-01 21:37:43 +0200 | [diff] [blame] | 1262 | def test_errno_ENOTDIR(self): |
| 1263 | # Issue #12802: "not a directory" errors are ENOTDIR even on Windows |
| 1264 | with self.assertRaises(OSError) as cm: |
| 1265 | os.listdir(__file__) |
| 1266 | self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) |
| 1267 | |
Martin Panter | 3263f68 | 2016-02-28 03:16:11 +0000 | [diff] [blame] | 1268 | def test_unraisable(self): |
| 1269 | # Issue #22836: PyErr_WriteUnraisable() should give sensible reports |
| 1270 | class BrokenDel: |
| 1271 | def __del__(self): |
| 1272 | exc = ValueError("del is broken") |
| 1273 | # The following line is included in the traceback report: |
| 1274 | raise exc |
| 1275 | |
Victor Stinner | e4d300e | 2019-05-22 23:44:02 +0200 | [diff] [blame] | 1276 | obj = BrokenDel() |
| 1277 | with support.catch_unraisable_exception() as cm: |
| 1278 | del obj |
Martin Panter | 3263f68 | 2016-02-28 03:16:11 +0000 | [diff] [blame] | 1279 | |
Victor Stinner | e4d300e | 2019-05-22 23:44:02 +0200 | [diff] [blame] | 1280 | self.assertEqual(cm.unraisable.object, BrokenDel.__del__) |
| 1281 | self.assertIsNotNone(cm.unraisable.exc_traceback) |
Martin Panter | 3263f68 | 2016-02-28 03:16:11 +0000 | [diff] [blame] | 1282 | |
| 1283 | def test_unhandled(self): |
| 1284 | # Check for sensible reporting of unhandled exceptions |
| 1285 | for exc_type in (ValueError, BrokenStrException): |
| 1286 | with self.subTest(exc_type): |
| 1287 | try: |
| 1288 | exc = exc_type("test message") |
| 1289 | # The following line is included in the traceback report: |
| 1290 | raise exc |
| 1291 | except exc_type: |
| 1292 | with captured_stderr() as stderr: |
| 1293 | sys.__excepthook__(*sys.exc_info()) |
| 1294 | report = stderr.getvalue() |
| 1295 | self.assertIn("test_exceptions.py", report) |
| 1296 | self.assertIn("raise exc", report) |
| 1297 | self.assertIn(exc_type.__name__, report) |
| 1298 | if exc_type is BrokenStrException: |
| 1299 | self.assertIn("<exception str() failed>", report) |
| 1300 | else: |
| 1301 | self.assertIn("test message", report) |
| 1302 | self.assertTrue(report.endswith("\n")) |
| 1303 | |
xdegaye | 66caacf | 2017-10-23 18:08:41 +0200 | [diff] [blame] | 1304 | @cpython_only |
| 1305 | def test_memory_error_in_PyErr_PrintEx(self): |
| 1306 | code = """if 1: |
| 1307 | import _testcapi |
| 1308 | class C(): pass |
| 1309 | _testcapi.set_nomemory(0, %d) |
| 1310 | C() |
| 1311 | """ |
| 1312 | |
| 1313 | # Issue #30817: Abort in PyErr_PrintEx() when no memory. |
| 1314 | # Span a large range of tests as the CPython code always evolves with |
| 1315 | # changes that add or remove memory allocations. |
| 1316 | for i in range(1, 20): |
| 1317 | rc, out, err = script_helper.assert_python_failure("-c", code % i) |
| 1318 | self.assertIn(rc, (1, 120)) |
| 1319 | self.assertIn(b'MemoryError', err) |
| 1320 | |
Mark Shannon | ae3087c | 2017-10-22 22:41:51 +0100 | [diff] [blame] | 1321 | def test_yield_in_nested_try_excepts(self): |
| 1322 | #Issue #25612 |
| 1323 | class MainError(Exception): |
| 1324 | pass |
| 1325 | |
| 1326 | class SubError(Exception): |
| 1327 | pass |
| 1328 | |
| 1329 | def main(): |
| 1330 | try: |
| 1331 | raise MainError() |
| 1332 | except MainError: |
| 1333 | try: |
| 1334 | yield |
| 1335 | except SubError: |
| 1336 | pass |
| 1337 | raise |
| 1338 | |
| 1339 | coro = main() |
| 1340 | coro.send(None) |
| 1341 | with self.assertRaises(MainError): |
| 1342 | coro.throw(SubError()) |
| 1343 | |
| 1344 | def test_generator_doesnt_retain_old_exc2(self): |
| 1345 | #Issue 28884#msg282532 |
| 1346 | def g(): |
| 1347 | try: |
| 1348 | raise ValueError |
| 1349 | except ValueError: |
| 1350 | yield 1 |
| 1351 | self.assertEqual(sys.exc_info(), (None, None, None)) |
| 1352 | yield 2 |
| 1353 | |
| 1354 | gen = g() |
| 1355 | |
| 1356 | try: |
| 1357 | raise IndexError |
| 1358 | except IndexError: |
| 1359 | self.assertEqual(next(gen), 1) |
| 1360 | self.assertEqual(next(gen), 2) |
| 1361 | |
| 1362 | def test_raise_in_generator(self): |
| 1363 | #Issue 25612#msg304117 |
| 1364 | def g(): |
| 1365 | yield 1 |
| 1366 | raise |
| 1367 | yield 2 |
| 1368 | |
| 1369 | with self.assertRaises(ZeroDivisionError): |
| 1370 | i = g() |
| 1371 | try: |
| 1372 | 1/0 |
| 1373 | except: |
| 1374 | next(i) |
| 1375 | next(i) |
| 1376 | |
Zackery Spytz | ce6a070 | 2019-08-25 03:44:09 -0600 | [diff] [blame] | 1377 | @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") |
| 1378 | def test_assert_shadowing(self): |
| 1379 | # Shadowing AssertionError would cause the assert statement to |
| 1380 | # misbehave. |
| 1381 | global AssertionError |
| 1382 | AssertionError = TypeError |
| 1383 | try: |
| 1384 | assert False, 'hello' |
| 1385 | except BaseException as e: |
| 1386 | del AssertionError |
| 1387 | self.assertIsInstance(e, AssertionError) |
| 1388 | self.assertEqual(str(e), 'hello') |
| 1389 | else: |
| 1390 | del AssertionError |
| 1391 | self.fail('Expected exception') |
| 1392 | |
Pablo Galindo | 9b648a9 | 2020-09-01 19:39:46 +0100 | [diff] [blame] | 1393 | def test_memory_error_subclasses(self): |
| 1394 | # bpo-41654: MemoryError instances use a freelist of objects that are |
| 1395 | # linked using the 'dict' attribute when they are inactive/dead. |
| 1396 | # Subclasses of MemoryError should not participate in the freelist |
| 1397 | # schema. This test creates a MemoryError object and keeps it alive |
| 1398 | # (therefore advancing the freelist) and then it creates and destroys a |
| 1399 | # subclass object. Finally, it checks that creating a new MemoryError |
| 1400 | # succeeds, proving that the freelist is not corrupted. |
| 1401 | |
| 1402 | class TestException(MemoryError): |
| 1403 | pass |
| 1404 | |
| 1405 | try: |
| 1406 | raise MemoryError |
| 1407 | except MemoryError as exc: |
| 1408 | inst = exc |
| 1409 | |
| 1410 | try: |
| 1411 | raise TestException |
| 1412 | except Exception: |
| 1413 | pass |
| 1414 | |
| 1415 | for _ in range(10): |
| 1416 | try: |
| 1417 | raise MemoryError |
| 1418 | except MemoryError as exc: |
| 1419 | pass |
| 1420 | |
| 1421 | gc_collect() |
| 1422 | |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1423 | global_for_suggestions = None |
| 1424 | |
| 1425 | class NameErrorTests(unittest.TestCase): |
| 1426 | def test_name_error_has_name(self): |
| 1427 | try: |
| 1428 | bluch |
| 1429 | except NameError as exc: |
| 1430 | self.assertEqual("bluch", exc.name) |
| 1431 | |
| 1432 | def test_name_error_suggestions(self): |
| 1433 | def Substitution(): |
| 1434 | noise = more_noise = a = bc = None |
| 1435 | blech = None |
| 1436 | print(bluch) |
| 1437 | |
| 1438 | def Elimination(): |
| 1439 | noise = more_noise = a = bc = None |
| 1440 | blch = None |
| 1441 | print(bluch) |
| 1442 | |
| 1443 | def Addition(): |
| 1444 | noise = more_noise = a = bc = None |
| 1445 | bluchin = None |
| 1446 | print(bluch) |
| 1447 | |
| 1448 | def SubstitutionOverElimination(): |
| 1449 | blach = None |
| 1450 | bluc = None |
| 1451 | print(bluch) |
| 1452 | |
| 1453 | def SubstitutionOverAddition(): |
| 1454 | blach = None |
| 1455 | bluchi = None |
| 1456 | print(bluch) |
| 1457 | |
| 1458 | def EliminationOverAddition(): |
| 1459 | blucha = None |
| 1460 | bluc = None |
| 1461 | print(bluch) |
| 1462 | |
Pablo Galindo | 7a04116 | 2021-04-19 23:35:53 +0100 | [diff] [blame] | 1463 | for func, suggestion in [(Substitution, "'blech'?"), |
| 1464 | (Elimination, "'blch'?"), |
| 1465 | (Addition, "'bluchin'?"), |
| 1466 | (EliminationOverAddition, "'blucha'?"), |
| 1467 | (SubstitutionOverElimination, "'blach'?"), |
| 1468 | (SubstitutionOverAddition, "'blach'?")]: |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1469 | err = None |
| 1470 | try: |
| 1471 | func() |
| 1472 | except NameError as exc: |
| 1473 | with support.captured_stderr() as err: |
| 1474 | sys.__excepthook__(*sys.exc_info()) |
| 1475 | self.assertIn(suggestion, err.getvalue()) |
| 1476 | |
| 1477 | def test_name_error_suggestions_from_globals(self): |
| 1478 | def func(): |
| 1479 | print(global_for_suggestio) |
| 1480 | try: |
| 1481 | func() |
| 1482 | except NameError as exc: |
| 1483 | with support.captured_stderr() as err: |
| 1484 | sys.__excepthook__(*sys.exc_info()) |
Pablo Galindo | 7a04116 | 2021-04-19 23:35:53 +0100 | [diff] [blame] | 1485 | self.assertIn("'global_for_suggestions'?", err.getvalue()) |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1486 | |
Pablo Galindo | 3ab4bea | 2021-04-17 22:26:54 +0100 | [diff] [blame] | 1487 | def test_name_error_suggestions_from_builtins(self): |
| 1488 | def func(): |
Dennis Sweeney | 80a2a4e | 2021-05-03 11:47:27 -0400 | [diff] [blame^] | 1489 | print(ZeroDivisionErrrrr) |
Pablo Galindo | 3ab4bea | 2021-04-17 22:26:54 +0100 | [diff] [blame] | 1490 | try: |
| 1491 | func() |
| 1492 | except NameError as exc: |
| 1493 | with support.captured_stderr() as err: |
| 1494 | sys.__excepthook__(*sys.exc_info()) |
Dennis Sweeney | 80a2a4e | 2021-05-03 11:47:27 -0400 | [diff] [blame^] | 1495 | self.assertIn("'ZeroDivisionError'?", err.getvalue()) |
Pablo Galindo | 3ab4bea | 2021-04-17 22:26:54 +0100 | [diff] [blame] | 1496 | |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1497 | def test_name_error_suggestions_do_not_trigger_for_long_names(self): |
| 1498 | def f(): |
| 1499 | somethingverywronghehehehehehe = None |
| 1500 | print(somethingverywronghe) |
| 1501 | |
| 1502 | try: |
| 1503 | f() |
| 1504 | except NameError as exc: |
| 1505 | with support.captured_stderr() as err: |
| 1506 | sys.__excepthook__(*sys.exc_info()) |
| 1507 | |
| 1508 | self.assertNotIn("somethingverywronghehe", err.getvalue()) |
| 1509 | |
Dennis Sweeney | 284c52d | 2021-04-26 20:22:27 -0400 | [diff] [blame] | 1510 | def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self): |
| 1511 | vvv = mom = w = id = pytho = None |
| 1512 | |
| 1513 | with self.subTest(name="b"): |
| 1514 | try: |
| 1515 | b |
| 1516 | except NameError as exc: |
| 1517 | with support.captured_stderr() as err: |
| 1518 | sys.__excepthook__(*sys.exc_info()) |
| 1519 | self.assertNotIn("you mean", err.getvalue()) |
| 1520 | self.assertNotIn("vvv", err.getvalue()) |
| 1521 | self.assertNotIn("mom", err.getvalue()) |
| 1522 | self.assertNotIn("'id'", err.getvalue()) |
| 1523 | self.assertNotIn("'w'", err.getvalue()) |
| 1524 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1525 | |
| 1526 | with self.subTest(name="v"): |
| 1527 | try: |
| 1528 | v |
| 1529 | except NameError as exc: |
| 1530 | with support.captured_stderr() as err: |
| 1531 | sys.__excepthook__(*sys.exc_info()) |
| 1532 | self.assertNotIn("you mean", err.getvalue()) |
| 1533 | self.assertNotIn("vvv", err.getvalue()) |
| 1534 | self.assertNotIn("mom", err.getvalue()) |
| 1535 | self.assertNotIn("'id'", err.getvalue()) |
| 1536 | self.assertNotIn("'w'", err.getvalue()) |
| 1537 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1538 | |
| 1539 | with self.subTest(name="m"): |
| 1540 | try: |
| 1541 | m |
| 1542 | except NameError as exc: |
| 1543 | with support.captured_stderr() as err: |
| 1544 | sys.__excepthook__(*sys.exc_info()) |
| 1545 | self.assertNotIn("you mean", err.getvalue()) |
| 1546 | self.assertNotIn("vvv", err.getvalue()) |
| 1547 | self.assertNotIn("mom", err.getvalue()) |
| 1548 | self.assertNotIn("'id'", err.getvalue()) |
| 1549 | self.assertNotIn("'w'", err.getvalue()) |
| 1550 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1551 | |
| 1552 | with self.subTest(name="py"): |
| 1553 | try: |
| 1554 | py |
| 1555 | except NameError as exc: |
| 1556 | with support.captured_stderr() as err: |
| 1557 | sys.__excepthook__(*sys.exc_info()) |
| 1558 | self.assertNotIn("you mean", err.getvalue()) |
| 1559 | self.assertNotIn("vvv", err.getvalue()) |
| 1560 | self.assertNotIn("mom", err.getvalue()) |
| 1561 | self.assertNotIn("'id'", err.getvalue()) |
| 1562 | self.assertNotIn("'w'", err.getvalue()) |
| 1563 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1564 | |
Pablo Galindo | 3ab4bea | 2021-04-17 22:26:54 +0100 | [diff] [blame] | 1565 | def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self): |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1566 | def f(): |
| 1567 | # Mutating locals() is unreliable, so we need to do it by hand |
Dennis Sweeney | 80a2a4e | 2021-05-03 11:47:27 -0400 | [diff] [blame^] | 1568 | a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \ |
| 1569 | a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \ |
| 1570 | a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \ |
| 1571 | a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \ |
| 1572 | a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \ |
| 1573 | a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \ |
| 1574 | a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \ |
| 1575 | a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \ |
| 1576 | a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \ |
| 1577 | a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \ |
| 1578 | a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \ |
| 1579 | a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \ |
| 1580 | a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \ |
| 1581 | a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \ |
| 1582 | a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \ |
| 1583 | a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \ |
| 1584 | a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \ |
| 1585 | a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \ |
| 1586 | a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \ |
| 1587 | a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \ |
| 1588 | a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \ |
| 1589 | a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \ |
| 1590 | a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \ |
| 1591 | a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \ |
| 1592 | a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \ |
| 1593 | a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \ |
| 1594 | a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \ |
| 1595 | a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \ |
| 1596 | a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \ |
| 1597 | a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \ |
| 1598 | a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \ |
| 1599 | a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \ |
| 1600 | a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \ |
| 1601 | a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \ |
| 1602 | a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \ |
| 1603 | a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \ |
| 1604 | a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \ |
| 1605 | a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \ |
| 1606 | a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \ |
| 1607 | a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \ |
| 1608 | a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \ |
| 1609 | a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \ |
| 1610 | a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \ |
| 1611 | a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \ |
| 1612 | a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \ |
| 1613 | a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \ |
| 1614 | a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \ |
| 1615 | a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \ |
| 1616 | a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \ |
| 1617 | a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \ |
| 1618 | a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \ |
| 1619 | a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \ |
| 1620 | a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \ |
| 1621 | a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \ |
| 1622 | a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \ |
| 1623 | a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \ |
| 1624 | a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \ |
| 1625 | a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \ |
| 1626 | a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \ |
| 1627 | a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \ |
| 1628 | a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \ |
| 1629 | a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \ |
| 1630 | a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \ |
| 1631 | a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \ |
| 1632 | a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \ |
| 1633 | a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \ |
| 1634 | a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \ |
| 1635 | a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \ |
| 1636 | a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \ |
| 1637 | a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \ |
| 1638 | a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \ |
| 1639 | a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \ |
| 1640 | a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \ |
| 1641 | a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \ |
| 1642 | a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \ |
| 1643 | a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \ |
| 1644 | a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \ |
| 1645 | a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \ |
| 1646 | a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \ |
| 1647 | a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \ |
| 1648 | = None |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1649 | print(a0) |
| 1650 | |
| 1651 | try: |
| 1652 | f() |
| 1653 | except NameError as exc: |
| 1654 | with support.captured_stderr() as err: |
| 1655 | sys.__excepthook__(*sys.exc_info()) |
| 1656 | |
Pablo Galindo | 3ab4bea | 2021-04-17 22:26:54 +0100 | [diff] [blame] | 1657 | self.assertNotIn("a1", err.getvalue()) |
Pablo Galindo | 5bf8bf2 | 2021-04-14 15:10:33 +0100 | [diff] [blame] | 1658 | |
| 1659 | def test_name_error_with_custom_exceptions(self): |
| 1660 | def f(): |
| 1661 | blech = None |
| 1662 | raise NameError() |
| 1663 | |
| 1664 | try: |
| 1665 | f() |
| 1666 | except NameError as exc: |
| 1667 | with support.captured_stderr() as err: |
| 1668 | sys.__excepthook__(*sys.exc_info()) |
| 1669 | |
| 1670 | self.assertNotIn("blech", err.getvalue()) |
| 1671 | |
| 1672 | def f(): |
| 1673 | blech = None |
| 1674 | raise NameError |
| 1675 | |
| 1676 | try: |
| 1677 | f() |
| 1678 | except NameError as exc: |
| 1679 | with support.captured_stderr() as err: |
| 1680 | sys.__excepthook__(*sys.exc_info()) |
| 1681 | |
| 1682 | self.assertNotIn("blech", err.getvalue()) |
Antoine Pitrou | a762285 | 2011-09-01 21:37:43 +0200 | [diff] [blame] | 1683 | |
Pablo Galindo | 0ad81d4 | 2021-04-16 17:12:03 +0100 | [diff] [blame] | 1684 | def test_unbound_local_error_doesn_not_match(self): |
| 1685 | def foo(): |
| 1686 | something = 3 |
| 1687 | print(somethong) |
| 1688 | somethong = 3 |
| 1689 | |
| 1690 | try: |
| 1691 | foo() |
| 1692 | except UnboundLocalError as exc: |
| 1693 | with support.captured_stderr() as err: |
| 1694 | sys.__excepthook__(*sys.exc_info()) |
| 1695 | |
| 1696 | self.assertNotIn("something", err.getvalue()) |
| 1697 | |
| 1698 | |
Pablo Galindo | 37494b4 | 2021-04-14 02:36:07 +0100 | [diff] [blame] | 1699 | class AttributeErrorTests(unittest.TestCase): |
| 1700 | def test_attributes(self): |
| 1701 | # Setting 'attr' should not be a problem. |
| 1702 | exc = AttributeError('Ouch!') |
| 1703 | self.assertIsNone(exc.name) |
| 1704 | self.assertIsNone(exc.obj) |
| 1705 | |
| 1706 | sentinel = object() |
| 1707 | exc = AttributeError('Ouch', name='carry', obj=sentinel) |
| 1708 | self.assertEqual(exc.name, 'carry') |
| 1709 | self.assertIs(exc.obj, sentinel) |
| 1710 | |
| 1711 | def test_getattr_has_name_and_obj(self): |
| 1712 | class A: |
| 1713 | blech = None |
| 1714 | |
| 1715 | obj = A() |
| 1716 | try: |
| 1717 | obj.bluch |
| 1718 | except AttributeError as exc: |
| 1719 | self.assertEqual("bluch", exc.name) |
| 1720 | self.assertEqual(obj, exc.obj) |
| 1721 | |
| 1722 | def test_getattr_has_name_and_obj_for_method(self): |
| 1723 | class A: |
| 1724 | def blech(self): |
| 1725 | return |
| 1726 | |
| 1727 | obj = A() |
| 1728 | try: |
| 1729 | obj.bluch() |
| 1730 | except AttributeError as exc: |
| 1731 | self.assertEqual("bluch", exc.name) |
| 1732 | self.assertEqual(obj, exc.obj) |
| 1733 | |
| 1734 | def test_getattr_suggestions(self): |
| 1735 | class Substitution: |
| 1736 | noise = more_noise = a = bc = None |
| 1737 | blech = None |
| 1738 | |
| 1739 | class Elimination: |
| 1740 | noise = more_noise = a = bc = None |
| 1741 | blch = None |
| 1742 | |
| 1743 | class Addition: |
| 1744 | noise = more_noise = a = bc = None |
| 1745 | bluchin = None |
| 1746 | |
| 1747 | class SubstitutionOverElimination: |
| 1748 | blach = None |
| 1749 | bluc = None |
| 1750 | |
| 1751 | class SubstitutionOverAddition: |
| 1752 | blach = None |
| 1753 | bluchi = None |
| 1754 | |
| 1755 | class EliminationOverAddition: |
| 1756 | blucha = None |
| 1757 | bluc = None |
| 1758 | |
Pablo Galindo | 7a04116 | 2021-04-19 23:35:53 +0100 | [diff] [blame] | 1759 | for cls, suggestion in [(Substitution, "'blech'?"), |
| 1760 | (Elimination, "'blch'?"), |
| 1761 | (Addition, "'bluchin'?"), |
| 1762 | (EliminationOverAddition, "'bluc'?"), |
| 1763 | (SubstitutionOverElimination, "'blach'?"), |
| 1764 | (SubstitutionOverAddition, "'blach'?")]: |
Pablo Galindo | 37494b4 | 2021-04-14 02:36:07 +0100 | [diff] [blame] | 1765 | try: |
| 1766 | cls().bluch |
| 1767 | except AttributeError as exc: |
| 1768 | with support.captured_stderr() as err: |
| 1769 | sys.__excepthook__(*sys.exc_info()) |
| 1770 | |
| 1771 | self.assertIn(suggestion, err.getvalue()) |
| 1772 | |
| 1773 | def test_getattr_suggestions_do_not_trigger_for_long_attributes(self): |
| 1774 | class A: |
| 1775 | blech = None |
| 1776 | |
| 1777 | try: |
| 1778 | A().somethingverywrong |
| 1779 | except AttributeError as exc: |
| 1780 | with support.captured_stderr() as err: |
| 1781 | sys.__excepthook__(*sys.exc_info()) |
| 1782 | |
| 1783 | self.assertNotIn("blech", err.getvalue()) |
| 1784 | |
Dennis Sweeney | 284c52d | 2021-04-26 20:22:27 -0400 | [diff] [blame] | 1785 | def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self): |
| 1786 | class MyClass: |
| 1787 | vvv = mom = w = id = pytho = None |
| 1788 | |
| 1789 | with self.subTest(name="b"): |
| 1790 | try: |
| 1791 | MyClass.b |
| 1792 | except AttributeError as exc: |
| 1793 | with support.captured_stderr() as err: |
| 1794 | sys.__excepthook__(*sys.exc_info()) |
| 1795 | self.assertNotIn("you mean", err.getvalue()) |
| 1796 | self.assertNotIn("vvv", err.getvalue()) |
| 1797 | self.assertNotIn("mom", err.getvalue()) |
| 1798 | self.assertNotIn("'id'", err.getvalue()) |
| 1799 | self.assertNotIn("'w'", err.getvalue()) |
| 1800 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1801 | |
| 1802 | with self.subTest(name="v"): |
| 1803 | try: |
| 1804 | MyClass.v |
| 1805 | except AttributeError as exc: |
| 1806 | with support.captured_stderr() as err: |
| 1807 | sys.__excepthook__(*sys.exc_info()) |
| 1808 | self.assertNotIn("you mean", err.getvalue()) |
| 1809 | self.assertNotIn("vvv", err.getvalue()) |
| 1810 | self.assertNotIn("mom", err.getvalue()) |
| 1811 | self.assertNotIn("'id'", err.getvalue()) |
| 1812 | self.assertNotIn("'w'", err.getvalue()) |
| 1813 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1814 | |
| 1815 | with self.subTest(name="m"): |
| 1816 | try: |
| 1817 | MyClass.m |
| 1818 | except AttributeError as exc: |
| 1819 | with support.captured_stderr() as err: |
| 1820 | sys.__excepthook__(*sys.exc_info()) |
| 1821 | self.assertNotIn("you mean", err.getvalue()) |
| 1822 | self.assertNotIn("vvv", err.getvalue()) |
| 1823 | self.assertNotIn("mom", err.getvalue()) |
| 1824 | self.assertNotIn("'id'", err.getvalue()) |
| 1825 | self.assertNotIn("'w'", err.getvalue()) |
| 1826 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1827 | |
| 1828 | with self.subTest(name="py"): |
| 1829 | try: |
| 1830 | MyClass.py |
| 1831 | except AttributeError as exc: |
| 1832 | with support.captured_stderr() as err: |
| 1833 | sys.__excepthook__(*sys.exc_info()) |
| 1834 | self.assertNotIn("you mean", err.getvalue()) |
| 1835 | self.assertNotIn("vvv", err.getvalue()) |
| 1836 | self.assertNotIn("mom", err.getvalue()) |
| 1837 | self.assertNotIn("'id'", err.getvalue()) |
| 1838 | self.assertNotIn("'w'", err.getvalue()) |
| 1839 | self.assertNotIn("'pytho'", err.getvalue()) |
| 1840 | |
| 1841 | |
Pablo Galindo | 37494b4 | 2021-04-14 02:36:07 +0100 | [diff] [blame] | 1842 | def test_getattr_suggestions_do_not_trigger_for_big_dicts(self): |
| 1843 | class A: |
| 1844 | blech = None |
| 1845 | # A class with a very big __dict__ will not be consider |
| 1846 | # for suggestions. |
Dennis Sweeney | 80a2a4e | 2021-05-03 11:47:27 -0400 | [diff] [blame^] | 1847 | for index in range(2000): |
Pablo Galindo | 37494b4 | 2021-04-14 02:36:07 +0100 | [diff] [blame] | 1848 | setattr(A, f"index_{index}", None) |
| 1849 | |
| 1850 | try: |
| 1851 | A().bluch |
| 1852 | except AttributeError as exc: |
| 1853 | with support.captured_stderr() as err: |
| 1854 | sys.__excepthook__(*sys.exc_info()) |
| 1855 | |
| 1856 | self.assertNotIn("blech", err.getvalue()) |
| 1857 | |
| 1858 | def test_getattr_suggestions_no_args(self): |
| 1859 | class A: |
| 1860 | blech = None |
| 1861 | def __getattr__(self, attr): |
| 1862 | raise AttributeError() |
| 1863 | |
| 1864 | try: |
| 1865 | A().bluch |
| 1866 | except AttributeError as exc: |
| 1867 | with support.captured_stderr() as err: |
| 1868 | sys.__excepthook__(*sys.exc_info()) |
| 1869 | |
| 1870 | self.assertIn("blech", err.getvalue()) |
| 1871 | |
| 1872 | class A: |
| 1873 | blech = None |
| 1874 | def __getattr__(self, attr): |
| 1875 | raise AttributeError |
| 1876 | |
| 1877 | try: |
| 1878 | A().bluch |
| 1879 | except AttributeError as exc: |
| 1880 | with support.captured_stderr() as err: |
| 1881 | sys.__excepthook__(*sys.exc_info()) |
| 1882 | |
| 1883 | self.assertIn("blech", err.getvalue()) |
| 1884 | |
| 1885 | def test_getattr_suggestions_invalid_args(self): |
| 1886 | class NonStringifyClass: |
| 1887 | __str__ = None |
| 1888 | __repr__ = None |
| 1889 | |
| 1890 | class A: |
| 1891 | blech = None |
| 1892 | def __getattr__(self, attr): |
| 1893 | raise AttributeError(NonStringifyClass()) |
| 1894 | |
| 1895 | class B: |
| 1896 | blech = None |
| 1897 | def __getattr__(self, attr): |
| 1898 | raise AttributeError("Error", 23) |
| 1899 | |
| 1900 | class C: |
| 1901 | blech = None |
| 1902 | def __getattr__(self, attr): |
| 1903 | raise AttributeError(23) |
| 1904 | |
| 1905 | for cls in [A, B, C]: |
| 1906 | try: |
| 1907 | cls().bluch |
| 1908 | except AttributeError as exc: |
| 1909 | with support.captured_stderr() as err: |
| 1910 | sys.__excepthook__(*sys.exc_info()) |
| 1911 | |
| 1912 | self.assertIn("blech", err.getvalue()) |
| 1913 | |
Pablo Galindo | e07f4ab | 2021-04-14 18:58:28 +0100 | [diff] [blame] | 1914 | def test_attribute_error_with_failing_dict(self): |
| 1915 | class T: |
| 1916 | bluch = 1 |
| 1917 | def __dir__(self): |
| 1918 | raise AttributeError("oh no!") |
| 1919 | |
| 1920 | try: |
| 1921 | T().blich |
| 1922 | except AttributeError as exc: |
| 1923 | with support.captured_stderr() as err: |
| 1924 | sys.__excepthook__(*sys.exc_info()) |
| 1925 | |
| 1926 | self.assertNotIn("blech", err.getvalue()) |
| 1927 | self.assertNotIn("oh no!", err.getvalue()) |
Pablo Galindo | 37494b4 | 2021-04-14 02:36:07 +0100 | [diff] [blame] | 1928 | |
Pablo Galindo | 0b1c169 | 2021-04-17 23:28:45 +0100 | [diff] [blame] | 1929 | def test_attribute_error_with_bad_name(self): |
| 1930 | try: |
| 1931 | raise AttributeError(name=12, obj=23) |
| 1932 | except AttributeError as exc: |
| 1933 | with support.captured_stderr() as err: |
| 1934 | sys.__excepthook__(*sys.exc_info()) |
| 1935 | |
| 1936 | self.assertNotIn("?", err.getvalue()) |
| 1937 | |
| 1938 | |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 1939 | class ImportErrorTests(unittest.TestCase): |
| 1940 | |
| 1941 | def test_attributes(self): |
| 1942 | # Setting 'name' and 'path' should not be a problem. |
| 1943 | exc = ImportError('test') |
| 1944 | self.assertIsNone(exc.name) |
| 1945 | self.assertIsNone(exc.path) |
| 1946 | |
| 1947 | exc = ImportError('test', name='somemodule') |
| 1948 | self.assertEqual(exc.name, 'somemodule') |
| 1949 | self.assertIsNone(exc.path) |
| 1950 | |
| 1951 | exc = ImportError('test', path='somepath') |
| 1952 | self.assertEqual(exc.path, 'somepath') |
| 1953 | self.assertIsNone(exc.name) |
| 1954 | |
| 1955 | exc = ImportError('test', path='somepath', name='somename') |
| 1956 | self.assertEqual(exc.name, 'somename') |
| 1957 | self.assertEqual(exc.path, 'somepath') |
| 1958 | |
Michael Seifert | 64c8f70 | 2017-04-09 09:47:12 +0200 | [diff] [blame] | 1959 | msg = "'invalid' is an invalid keyword argument for ImportError" |
Serhiy Storchaka | 47dee11 | 2016-09-27 20:45:35 +0300 | [diff] [blame] | 1960 | with self.assertRaisesRegex(TypeError, msg): |
| 1961 | ImportError('test', invalid='keyword') |
| 1962 | |
| 1963 | with self.assertRaisesRegex(TypeError, msg): |
| 1964 | ImportError('test', name='name', invalid='keyword') |
| 1965 | |
| 1966 | with self.assertRaisesRegex(TypeError, msg): |
| 1967 | ImportError('test', path='path', invalid='keyword') |
| 1968 | |
| 1969 | with self.assertRaisesRegex(TypeError, msg): |
| 1970 | ImportError(invalid='keyword') |
| 1971 | |
Serhiy Storchaka | 47dee11 | 2016-09-27 20:45:35 +0300 | [diff] [blame] | 1972 | with self.assertRaisesRegex(TypeError, msg): |
| 1973 | ImportError('test', invalid='keyword', another=True) |
| 1974 | |
Serhiy Storchaka | e9e4448 | 2016-09-28 07:53:32 +0300 | [diff] [blame] | 1975 | def test_reset_attributes(self): |
| 1976 | exc = ImportError('test', name='name', path='path') |
| 1977 | self.assertEqual(exc.args, ('test',)) |
| 1978 | self.assertEqual(exc.msg, 'test') |
| 1979 | self.assertEqual(exc.name, 'name') |
| 1980 | self.assertEqual(exc.path, 'path') |
| 1981 | |
| 1982 | # Reset not specified attributes |
| 1983 | exc.__init__() |
| 1984 | self.assertEqual(exc.args, ()) |
| 1985 | self.assertEqual(exc.msg, None) |
| 1986 | self.assertEqual(exc.name, None) |
| 1987 | self.assertEqual(exc.path, None) |
| 1988 | |
Brett Cannon | 07c6e71 | 2012-08-24 13:05:09 -0400 | [diff] [blame] | 1989 | def test_non_str_argument(self): |
| 1990 | # Issue #15778 |
Nadeem Vawda | 6d70870 | 2012-10-14 01:42:32 +0200 | [diff] [blame] | 1991 | with check_warnings(('', BytesWarning), quiet=True): |
| 1992 | arg = b'abc' |
| 1993 | exc = ImportError(arg) |
| 1994 | self.assertEqual(str(arg), str(exc)) |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 1995 | |
Serhiy Storchaka | b785396 | 2017-04-08 09:55:07 +0300 | [diff] [blame] | 1996 | def test_copy_pickle(self): |
| 1997 | for kwargs in (dict(), |
| 1998 | dict(name='somename'), |
| 1999 | dict(path='somepath'), |
| 2000 | dict(name='somename', path='somepath')): |
| 2001 | orig = ImportError('test', **kwargs) |
| 2002 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 2003 | exc = pickle.loads(pickle.dumps(orig, proto)) |
| 2004 | self.assertEqual(exc.args, ('test',)) |
| 2005 | self.assertEqual(exc.msg, 'test') |
| 2006 | self.assertEqual(exc.name, orig.name) |
| 2007 | self.assertEqual(exc.path, orig.path) |
| 2008 | for c in copy.copy, copy.deepcopy: |
| 2009 | exc = c(orig) |
| 2010 | self.assertEqual(exc.args, ('test',)) |
| 2011 | self.assertEqual(exc.msg, 'test') |
| 2012 | self.assertEqual(exc.name, orig.name) |
| 2013 | self.assertEqual(exc.path, orig.path) |
| 2014 | |
Pablo Galindo | a77aac4 | 2021-04-23 14:27:05 +0100 | [diff] [blame] | 2015 | class SyntaxErrorTests(unittest.TestCase): |
| 2016 | def test_range_of_offsets(self): |
| 2017 | cases = [ |
| 2018 | # Basic range from 2->7 |
| 2019 | (("bad.py", 1, 2, "abcdefg", 1, 7), |
| 2020 | dedent( |
| 2021 | """ |
| 2022 | File "bad.py", line 1 |
| 2023 | abcdefg |
| 2024 | ^^^^^ |
| 2025 | SyntaxError: bad bad |
| 2026 | """)), |
| 2027 | # end_offset = start_offset + 1 |
| 2028 | (("bad.py", 1, 2, "abcdefg", 1, 3), |
| 2029 | dedent( |
| 2030 | """ |
| 2031 | File "bad.py", line 1 |
| 2032 | abcdefg |
| 2033 | ^ |
| 2034 | SyntaxError: bad bad |
| 2035 | """)), |
| 2036 | # Negative end offset |
| 2037 | (("bad.py", 1, 2, "abcdefg", 1, -2), |
| 2038 | dedent( |
| 2039 | """ |
| 2040 | File "bad.py", line 1 |
| 2041 | abcdefg |
| 2042 | ^ |
| 2043 | SyntaxError: bad bad |
| 2044 | """)), |
| 2045 | # end offset before starting offset |
| 2046 | (("bad.py", 1, 4, "abcdefg", 1, 2), |
| 2047 | dedent( |
| 2048 | """ |
| 2049 | File "bad.py", line 1 |
| 2050 | abcdefg |
| 2051 | ^ |
| 2052 | SyntaxError: bad bad |
| 2053 | """)), |
| 2054 | # Both offsets negative |
| 2055 | (("bad.py", 1, -4, "abcdefg", 1, -2), |
| 2056 | dedent( |
| 2057 | """ |
| 2058 | File "bad.py", line 1 |
| 2059 | abcdefg |
| 2060 | SyntaxError: bad bad |
| 2061 | """)), |
| 2062 | # Both offsets negative and the end more negative |
| 2063 | (("bad.py", 1, -4, "abcdefg", 1, -5), |
| 2064 | dedent( |
| 2065 | """ |
| 2066 | File "bad.py", line 1 |
| 2067 | abcdefg |
| 2068 | SyntaxError: bad bad |
| 2069 | """)), |
| 2070 | # Both offsets 0 |
| 2071 | (("bad.py", 1, 0, "abcdefg", 1, 0), |
| 2072 | dedent( |
| 2073 | """ |
| 2074 | File "bad.py", line 1 |
| 2075 | abcdefg |
| 2076 | SyntaxError: bad bad |
| 2077 | """)), |
| 2078 | # Start offset 0 and end offset not 0 |
| 2079 | (("bad.py", 1, 0, "abcdefg", 1, 5), |
| 2080 | dedent( |
| 2081 | """ |
| 2082 | File "bad.py", line 1 |
| 2083 | abcdefg |
| 2084 | SyntaxError: bad bad |
| 2085 | """)), |
| 2086 | # End offset pass the source lenght |
| 2087 | (("bad.py", 1, 2, "abcdefg", 1, 100), |
| 2088 | dedent( |
| 2089 | """ |
| 2090 | File "bad.py", line 1 |
| 2091 | abcdefg |
| 2092 | ^^^^^^ |
| 2093 | SyntaxError: bad bad |
| 2094 | """)), |
| 2095 | ] |
| 2096 | for args, expected in cases: |
| 2097 | with self.subTest(args=args): |
| 2098 | try: |
| 2099 | raise SyntaxError("bad bad", args) |
| 2100 | except SyntaxError as exc: |
| 2101 | with support.captured_stderr() as err: |
| 2102 | sys.__excepthook__(*sys.exc_info()) |
| 2103 | the_exception = exc |
| 2104 | |
| 2105 | def test_attributes_new_constructor(self): |
| 2106 | args = ("bad.py", 1, 2, "abcdefg", 1, 100) |
| 2107 | the_exception = SyntaxError("bad bad", args) |
| 2108 | filename, lineno, offset, error, end_lineno, end_offset = args |
| 2109 | self.assertEqual(filename, the_exception.filename) |
| 2110 | self.assertEqual(lineno, the_exception.lineno) |
| 2111 | self.assertEqual(end_lineno, the_exception.end_lineno) |
| 2112 | self.assertEqual(offset, the_exception.offset) |
| 2113 | self.assertEqual(end_offset, the_exception.end_offset) |
| 2114 | self.assertEqual(error, the_exception.text) |
| 2115 | self.assertEqual("bad bad", the_exception.msg) |
| 2116 | |
| 2117 | def test_attributes_old_constructor(self): |
| 2118 | args = ("bad.py", 1, 2, "abcdefg") |
| 2119 | the_exception = SyntaxError("bad bad", args) |
| 2120 | filename, lineno, offset, error = args |
| 2121 | self.assertEqual(filename, the_exception.filename) |
| 2122 | self.assertEqual(lineno, the_exception.lineno) |
| 2123 | self.assertEqual(None, the_exception.end_lineno) |
| 2124 | self.assertEqual(offset, the_exception.offset) |
| 2125 | self.assertEqual(None, the_exception.end_offset) |
| 2126 | self.assertEqual(error, the_exception.text) |
| 2127 | self.assertEqual("bad bad", the_exception.msg) |
| 2128 | |
| 2129 | def test_incorrect_constructor(self): |
| 2130 | args = ("bad.py", 1, 2) |
| 2131 | self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2132 | |
| 2133 | args = ("bad.py", 1, 2, 4, 5, 6, 7) |
| 2134 | self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2135 | |
| 2136 | args = ("bad.py", 1, 2, "abcdefg", 1) |
| 2137 | self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2138 | |
Brett Cannon | 79ec55e | 2012-04-12 20:24:54 -0400 | [diff] [blame] | 2139 | |
Mark Shannon | bf353f3 | 2020-12-17 13:55:28 +0000 | [diff] [blame] | 2140 | class PEP626Tests(unittest.TestCase): |
| 2141 | |
| 2142 | def lineno_after_raise(self, f, line): |
| 2143 | try: |
| 2144 | f() |
| 2145 | except Exception as ex: |
| 2146 | t = ex.__traceback__ |
| 2147 | while t.tb_next: |
| 2148 | t = t.tb_next |
| 2149 | frame = t.tb_frame |
Mark Shannon | 088a15c | 2021-04-29 19:28:50 +0100 | [diff] [blame] | 2150 | if line is None: |
| 2151 | self.assertEqual(frame.f_lineno, line) |
| 2152 | else: |
| 2153 | self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line) |
Mark Shannon | bf353f3 | 2020-12-17 13:55:28 +0000 | [diff] [blame] | 2154 | |
| 2155 | def test_lineno_after_raise_simple(self): |
| 2156 | def simple(): |
| 2157 | 1/0 |
| 2158 | pass |
| 2159 | self.lineno_after_raise(simple, 1) |
| 2160 | |
| 2161 | def test_lineno_after_raise_in_except(self): |
| 2162 | def in_except(): |
| 2163 | try: |
| 2164 | 1/0 |
| 2165 | except: |
| 2166 | 1/0 |
| 2167 | pass |
| 2168 | self.lineno_after_raise(in_except, 4) |
| 2169 | |
| 2170 | def test_lineno_after_other_except(self): |
| 2171 | def other_except(): |
| 2172 | try: |
| 2173 | 1/0 |
| 2174 | except TypeError as ex: |
| 2175 | pass |
| 2176 | self.lineno_after_raise(other_except, 3) |
| 2177 | |
| 2178 | def test_lineno_in_named_except(self): |
| 2179 | def in_named_except(): |
| 2180 | try: |
| 2181 | 1/0 |
| 2182 | except Exception as ex: |
| 2183 | 1/0 |
| 2184 | pass |
| 2185 | self.lineno_after_raise(in_named_except, 4) |
| 2186 | |
| 2187 | def test_lineno_in_try(self): |
| 2188 | def in_try(): |
| 2189 | try: |
| 2190 | 1/0 |
| 2191 | finally: |
| 2192 | pass |
| 2193 | self.lineno_after_raise(in_try, 4) |
| 2194 | |
| 2195 | def test_lineno_in_finally_normal(self): |
| 2196 | def in_finally_normal(): |
| 2197 | try: |
| 2198 | pass |
| 2199 | finally: |
| 2200 | 1/0 |
| 2201 | pass |
| 2202 | self.lineno_after_raise(in_finally_normal, 4) |
| 2203 | |
| 2204 | def test_lineno_in_finally_except(self): |
| 2205 | def in_finally_except(): |
| 2206 | try: |
| 2207 | 1/0 |
| 2208 | finally: |
| 2209 | 1/0 |
| 2210 | pass |
| 2211 | self.lineno_after_raise(in_finally_except, 4) |
| 2212 | |
| 2213 | def test_lineno_after_with(self): |
| 2214 | class Noop: |
| 2215 | def __enter__(self): |
| 2216 | return self |
| 2217 | def __exit__(self, *args): |
| 2218 | pass |
| 2219 | def after_with(): |
| 2220 | with Noop(): |
| 2221 | 1/0 |
| 2222 | pass |
| 2223 | self.lineno_after_raise(after_with, 2) |
| 2224 | |
Mark Shannon | 088a15c | 2021-04-29 19:28:50 +0100 | [diff] [blame] | 2225 | def test_missing_lineno_shows_as_none(self): |
| 2226 | def f(): |
| 2227 | 1/0 |
| 2228 | self.lineno_after_raise(f, 1) |
| 2229 | f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80') |
| 2230 | self.lineno_after_raise(f, None) |
Mark Shannon | bf353f3 | 2020-12-17 13:55:28 +0000 | [diff] [blame] | 2231 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 2232 | if __name__ == '__main__': |
Guido van Rossum | b8142c3 | 2007-05-08 17:49:10 +0000 | [diff] [blame] | 2233 | unittest.main() |