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