Debian Codegraph @

Lib/test/test_capi/test_exceptions.py

raw
1 import errno
2 import os
3 import re
4 import sys
5 import unittest
6 import textwrap
7
8 from test import support
9 from test.support import import_helper
10 from test.support.os_helper import TESTFN, TESTFN_UNDECODABLE
11 from test.support.script_helper import assert_python_failure, assert_python_ok
12 from test.support.testcase import ExceptionIsLikeMixin
13
14 from .test_misc import decode_stderr
15
16 # Skip this test if the _testcapi module isn't available.
17 _testcapi = import_helper.import_module('_testcapi')
18
19 NULL = None
20
21 class CustomError(Exception):
22 pass
23
24
25 class Test_Exceptions(unittest.TestCase):
26
27 def test_exception(self):
28 raised_exception = ValueError("5")
29 new_exc = TypeError("TEST")
30 try:
31 raise raised_exception
32 except ValueError as e:
33 orig_sys_exception = sys.exception()
34 orig_exception = _testcapi.set_exception(new_exc)
35 new_sys_exception = sys.exception()
36 new_exception = _testcapi.set_exception(orig_exception)
37 reset_sys_exception = sys.exception()
38
39 self.assertEqual(orig_exception, e)
40
41 self.assertEqual(orig_exception, raised_exception)
42 self.assertEqual(orig_sys_exception, orig_exception)
43 self.assertEqual(reset_sys_exception, orig_exception)
44 self.assertEqual(new_exception, new_exc)
45 self.assertEqual(new_sys_exception, new_exception)
46 else:
47 self.fail("Exception not raised")
48
49 def test_exc_info(self):
50 raised_exception = ValueError("5")
51 new_exc = TypeError("TEST")
52 try:
53 raise raised_exception
54 except ValueError as e:
55 tb = e.__traceback__
56 orig_sys_exc_info = sys.exc_info()
57 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
58 new_sys_exc_info = sys.exc_info()
59 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
60 reset_sys_exc_info = sys.exc_info()
61
62 self.assertEqual(orig_exc_info[1], e)
63
64 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
65 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
66 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
67 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
68 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
69 else:
70 self.assertTrue(False)
71
72 def test_warn_with_stacklevel(self):
73 code = textwrap.dedent('''\
74 import _testcapi
75
76 def foo():
77 _testcapi.function_set_warning()
78
79 foo() # line 6
80
81
82 foo() # line 9
83 ''')
84 proc = assert_python_ok("-c", code)
85 warnings = proc.err.splitlines()
86 self.assertEqual(warnings, [
87 b'<string>:6: RuntimeWarning: Testing PyErr_WarnEx',
88 b'<string>:9: RuntimeWarning: Testing PyErr_WarnEx',
89 ])
90
91 def test_warn_during_finalization(self):
92 code = textwrap.dedent('''\
93 import _testcapi
94
95 class Foo:
96 def foo(self):
97 _testcapi.function_set_warning()
98 def __del__(self):
99 self.foo()
100
101 ref = Foo()
102 ''')
103 proc = assert_python_ok("-c", code)
104 warnings = proc.err.splitlines()
105 # Due to the finalization of the interpreter, the source will be ommited
106 # because the ``warnings`` module cannot be imported at this time
107 self.assertEqual(warnings, [
108 b'<string>:7: RuntimeWarning: Testing PyErr_WarnEx',
109 ])
110
111
112 class Test_FatalError(unittest.TestCase):
113
114 def check_fatal_error(self, code, expected, not_expected=()):
115 with support.SuppressCrashReport():
116 rc, out, err = assert_python_failure('-sSI', '-c', code)
117
118 err = decode_stderr(err)
119 self.assertIn('Fatal Python error: _testcapi_fatal_error_impl: MESSAGE\n',
120 err)
121
122 match = re.search(r'^Extension modules:(.*) \(total: ([0-9]+)\)$',
123 err, re.MULTILINE)
124 if not match:
125 self.fail(f"Cannot find 'Extension modules:' in {err!r}")
126 modules = set(match.group(1).strip().split(', '))
127 total = int(match.group(2))
128
129 for name in expected:
130 self.assertIn(name, modules)
131 for name in not_expected:
132 self.assertNotIn(name, modules)
133 self.assertEqual(len(modules), total)
134
135 @support.requires_subprocess()
136 def test_fatal_error(self):
137 # By default, stdlib extension modules are ignored,
138 # but not test modules.
139 expected = ('_testcapi',)
140 not_expected = ('sys',)
141 code = 'import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")'
142 self.check_fatal_error(code, expected, not_expected)
143
144 # Mark _testcapi as stdlib module, but not sys
145 expected = ('sys',)
146 not_expected = ('_testcapi',)
147 code = """if True:
148 import _testcapi, sys
149 sys.stdlib_module_names = frozenset({"_testcapi"})
150 _testcapi.fatal_error(b"MESSAGE")
151 """
152 self.check_fatal_error(code, expected)
153
154
155 class Test_ErrSetAndRestore(unittest.TestCase):
156
157 def test_err_set_raised(self):
158 with self.assertRaises(ValueError):
159 _testcapi.err_set_raised(ValueError())
160 v = ValueError()
161 try:
162 _testcapi.err_set_raised(v)
163 except ValueError as ex:
164 self.assertIs(v, ex)
165
166 def test_err_restore(self):
167 with self.assertRaises(ValueError):
168 _testcapi.err_restore(ValueError)
169 with self.assertRaises(ValueError):
170 _testcapi.err_restore(ValueError, 1)
171 with self.assertRaises(ValueError):
172 _testcapi.err_restore(ValueError, 1, None)
173 with self.assertRaises(ValueError):
174 _testcapi.err_restore(ValueError, ValueError())
175 try:
176 _testcapi.err_restore(KeyError, "hi")
177 except KeyError as k:
178 self.assertEqual("hi", k.args[0])
179 try:
180 1/0
181 except Exception as e:
182 tb = e.__traceback__
183 with self.assertRaises(ValueError):
184 _testcapi.err_restore(ValueError, 1, tb)
185 with self.assertRaises(TypeError):
186 _testcapi.err_restore(ValueError, 1, 0)
187 try:
188 _testcapi.err_restore(ValueError, 1, tb)
189 except ValueError as v:
190 self.assertEqual(1, v.args[0])
191 self.assertIs(tb, v.__traceback__.tb_next)
192
193 def test_set_object(self):
194
195 # new exception as obj is not an exception
196 with self.assertRaises(ValueError) as e:
197 _testcapi.exc_set_object(ValueError, 42)
198 self.assertEqual(e.exception.args, (42,))
199
200 # wraps the exception because unrelated types
201 with self.assertRaises(ValueError) as e:
202 _testcapi.exc_set_object(ValueError, TypeError(1,2,3))
203 wrapped = e.exception.args[0]
204 self.assertIsInstance(wrapped, TypeError)
205 self.assertEqual(wrapped.args, (1, 2, 3))
206
207 # is superclass, so does not wrap
208 with self.assertRaises(PermissionError) as e:
209 _testcapi.exc_set_object(OSError, PermissionError(24))
210 self.assertEqual(e.exception.args, (24,))
211
212 class Meta(type):
213 def __subclasscheck__(cls, sub):
214 1/0
215
216 class Broken(Exception, metaclass=Meta):
217 pass
218
219 with self.assertRaises(ZeroDivisionError) as e:
220 _testcapi.exc_set_object(Broken, Broken())
221
222 def test_set_object_and_fetch(self):
223 class Broken(Exception):
224 def __init__(self, *arg):
225 raise ValueError("Broken __init__")
226
227 exc = _testcapi.exc_set_object_fetch(Broken, 'abcd')
228 self.assertIsInstance(exc, ValueError)
229 self.assertEqual(exc.__notes__[0],
230 "Normalization failed: type=Broken args='abcd'")
231
232 class BadArg:
233 def __repr__(self):
234 raise TypeError('Broken arg type')
235
236 exc = _testcapi.exc_set_object_fetch(Broken, BadArg())
237 self.assertIsInstance(exc, ValueError)
238 self.assertEqual(exc.__notes__[0],
239 'Normalization failed: type=Broken args=<unknown>')
240
241 def test_set_string(self):
242 """Test PyErr_SetString()"""
243 setstring = _testcapi.err_setstring
244 with self.assertRaises(ZeroDivisionError) as e:
245 setstring(ZeroDivisionError, b'error')
246 self.assertEqual(e.exception.args, ('error',))
247 with self.assertRaises(ZeroDivisionError) as e:
248 setstring(ZeroDivisionError, 'помилка'.encode())
249 self.assertEqual(e.exception.args, ('помилка',))
250
251 with self.assertRaises(UnicodeDecodeError):
252 setstring(ZeroDivisionError, b'\xff')
253 self.assertRaises(SystemError, setstring, list, b'error')
254 # CRASHES setstring(ZeroDivisionError, NULL)
255 # CRASHES setstring(NULL, b'error')
256
257 def test_format(self):
258 """Test PyErr_Format()"""
259 import_helper.import_module('ctypes')
260 from ctypes import pythonapi, py_object, c_char_p, c_int
261 name = "PyErr_Format"
262 PyErr_Format = getattr(pythonapi, name)
263 PyErr_Format.argtypes = (py_object, c_char_p,)
264 PyErr_Format.restype = py_object
265 with self.assertRaises(ZeroDivisionError) as e:
266 PyErr_Format(ZeroDivisionError, b'%s %d', b'error', c_int(42))
267 self.assertEqual(e.exception.args, ('error 42',))
268 with self.assertRaises(ZeroDivisionError) as e:
269 PyErr_Format(ZeroDivisionError, b'%s', 'помилка'.encode())
270 self.assertEqual(e.exception.args, ('помилка',))
271
272 with self.assertRaisesRegex(OverflowError, 'not in range'):
273 PyErr_Format(ZeroDivisionError, b'%c', c_int(-1))
274 with self.assertRaisesRegex(ValueError, 'format string'):
275 PyErr_Format(ZeroDivisionError, b'\xff')
276 self.assertRaises(SystemError, PyErr_Format, list, b'error')
277 # CRASHES PyErr_Format(ZeroDivisionError, NULL)
278 # CRASHES PyErr_Format(py_object(), b'error')
279
280 def test_setfromerrnowithfilename(self):
281 """Test PyErr_SetFromErrnoWithFilename()"""
282 setfromerrnowithfilename = _testcapi.err_setfromerrnowithfilename
283 ENOENT = errno.ENOENT
284 with self.assertRaises(FileNotFoundError) as e:
285 setfromerrnowithfilename(ENOENT, OSError, b'file')
286 self.assertEqual(e.exception.args,
287 (ENOENT, 'No such file or directory'))
288 self.assertEqual(e.exception.errno, ENOENT)
289 self.assertEqual(e.exception.filename, 'file')
290
291 with self.assertRaises(FileNotFoundError) as e:
292 setfromerrnowithfilename(ENOENT, OSError, os.fsencode(TESTFN))
293 self.assertEqual(e.exception.filename, TESTFN)
294
295 if TESTFN_UNDECODABLE:
296 with self.assertRaises(FileNotFoundError) as e:
297 setfromerrnowithfilename(ENOENT, OSError, TESTFN_UNDECODABLE)
298 self.assertEqual(e.exception.filename,
299 os.fsdecode(TESTFN_UNDECODABLE))
300
301 with self.assertRaises(FileNotFoundError) as e:
302 setfromerrnowithfilename(ENOENT, OSError, NULL)
303 self.assertIsNone(e.exception.filename)
304
305 with self.assertRaises(OSError) as e:
306 setfromerrnowithfilename(0, OSError, b'file')
307 self.assertEqual(e.exception.args, (0, 'Error'))
308 self.assertEqual(e.exception.errno, 0)
309 self.assertEqual(e.exception.filename, 'file')
310
311 with self.assertRaises(ZeroDivisionError) as e:
312 setfromerrnowithfilename(ENOENT, ZeroDivisionError, b'file')
313 self.assertEqual(e.exception.args,
314 (ENOENT, 'No such file or directory', 'file'))
315 # CRASHES setfromerrnowithfilename(ENOENT, NULL, b'error')
316
317 def test_err_writeunraisable(self):
318 # Test PyErr_WriteUnraisable()
319 writeunraisable = _testcapi.err_writeunraisable
320 firstline = self.test_err_writeunraisable.__code__.co_firstlineno
321
322 with support.catch_unraisable_exception() as cm:
323 writeunraisable(CustomError('oops!'), hex)
324 self.assertEqual(cm.unraisable.exc_type, CustomError)
325 self.assertEqual(str(cm.unraisable.exc_value), 'oops!')
326 self.assertEqual(cm.unraisable.exc_traceback.tb_lineno,
327 firstline + 6)
328 self.assertIsNone(cm.unraisable.err_msg)
329 self.assertEqual(cm.unraisable.object, hex)
330
331 with support.catch_unraisable_exception() as cm:
332 writeunraisable(CustomError('oops!'), NULL)
333 self.assertEqual(cm.unraisable.exc_type, CustomError)
334 self.assertEqual(str(cm.unraisable.exc_value), 'oops!')
335 self.assertEqual(cm.unraisable.exc_traceback.tb_lineno,
336 firstline + 15)
337 self.assertIsNone(cm.unraisable.err_msg)
338 self.assertIsNone(cm.unraisable.object)
339
340 with (support.swap_attr(sys, 'unraisablehook', None),
341 support.captured_stderr() as stderr):
342 writeunraisable(CustomError('oops!'), hex)
343 lines = stderr.getvalue().splitlines()
344 self.assertEqual(lines[0], f'Exception ignored in: {hex!r}')
345 self.assertEqual(lines[1], 'Traceback (most recent call last):')
346 self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!')
347
348 with (support.swap_attr(sys, 'unraisablehook', None),
349 support.captured_stderr() as stderr):
350 writeunraisable(CustomError('oops!'), NULL)
351 lines = stderr.getvalue().splitlines()
352 self.assertEqual(lines[0], 'Traceback (most recent call last):')
353 self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!')
354
355 # CRASHES writeunraisable(NULL, hex)
356 # CRASHES writeunraisable(NULL, NULL)
357
358 def test_err_formatunraisable(self):
359 # Test PyErr_FormatUnraisable()
360 formatunraisable = _testcapi.err_formatunraisable
361 firstline = self.test_err_formatunraisable.__code__.co_firstlineno
362
363 with support.catch_unraisable_exception() as cm:
364 formatunraisable(CustomError('oops!'), b'Error in %R', [])
365 self.assertEqual(cm.unraisable.exc_type, CustomError)
366 self.assertEqual(str(cm.unraisable.exc_value), 'oops!')
367 self.assertEqual(cm.unraisable.exc_traceback.tb_lineno,
368 firstline + 6)
369 self.assertEqual(cm.unraisable.err_msg, 'Error in []')
370 self.assertIsNone(cm.unraisable.object)
371
372 with support.catch_unraisable_exception() as cm:
373 formatunraisable(CustomError('oops!'), b'undecodable \xff')
374 self.assertEqual(cm.unraisable.exc_type, CustomError)
375 self.assertEqual(str(cm.unraisable.exc_value), 'oops!')
376 self.assertEqual(cm.unraisable.exc_traceback.tb_lineno,
377 firstline + 15)
378 self.assertIsNone(cm.unraisable.err_msg)
379 self.assertIsNone(cm.unraisable.object)
380
381 with support.catch_unraisable_exception() as cm:
382 formatunraisable(CustomError('oops!'), NULL)
383 self.assertEqual(cm.unraisable.exc_type, CustomError)
384 self.assertEqual(str(cm.unraisable.exc_value), 'oops!')
385 self.assertEqual(cm.unraisable.exc_traceback.tb_lineno,
386 firstline + 24)
387 self.assertIsNone(cm.unraisable.err_msg)
388 self.assertIsNone(cm.unraisable.object)
389
390 with (support.swap_attr(sys, 'unraisablehook', None),
391 support.captured_stderr() as stderr):
392 formatunraisable(CustomError('oops!'), b'Error in %R', [])
393 lines = stderr.getvalue().splitlines()
394 self.assertEqual(lines[0], f'Error in []:')
395 self.assertEqual(lines[1], 'Traceback (most recent call last):')
396 self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!')
397
398 with (support.swap_attr(sys, 'unraisablehook', None),
399 support.captured_stderr() as stderr):
400 formatunraisable(CustomError('oops!'), b'undecodable \xff')
401 lines = stderr.getvalue().splitlines()
402 self.assertEqual(lines[0], 'Traceback (most recent call last):')
403 self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!')
404
405 with (support.swap_attr(sys, 'unraisablehook', None),
406 support.captured_stderr() as stderr):
407 formatunraisable(CustomError('oops!'), NULL)
408 lines = stderr.getvalue().splitlines()
409 self.assertEqual(lines[0], 'Traceback (most recent call last):')
410 self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!')
411
412 # CRASHES formatunraisable(NULL, b'Error in %R', [])
413 # CRASHES formatunraisable(NULL, NULL)
414
415
416 class Test_PyUnstable_Exc_PrepReraiseStar(ExceptionIsLikeMixin, unittest.TestCase):
417
418 def setUp(self):
419 super().setUp()
420 try:
421 raise ExceptionGroup("eg", [TypeError('bad type'), ValueError(42)])
422 except ExceptionGroup as e:
423 self.orig = e
424
425 def test_invalid_args(self):
426 with self.assertRaisesRegex(TypeError, "orig must be an exception"):
427 _testcapi.unstable_exc_prep_reraise_star(42, [None])
428
429 with self.assertRaisesRegex(TypeError, "excs must be a list"):
430 _testcapi.unstable_exc_prep_reraise_star(self.orig, 42)
431
432 with self.assertRaisesRegex(TypeError, "not an exception"):
433 _testcapi.unstable_exc_prep_reraise_star(self.orig, [TypeError(42), 42])
434
435 with self.assertRaisesRegex(ValueError, "orig must be a raised exception"):
436 _testcapi.unstable_exc_prep_reraise_star(ValueError(42), [TypeError(42)])
437
438 with self.assertRaisesRegex(ValueError, "orig must be a raised exception"):
439 _testcapi.unstable_exc_prep_reraise_star(ExceptionGroup("eg", [ValueError(42)]),
440 [TypeError(42)])
441
442
443 def test_nothing_to_reraise(self):
444 self.assertEqual(
445 _testcapi.unstable_exc_prep_reraise_star(self.orig, [None]), None)
446
447 try:
448 raise ValueError(42)
449 except ValueError as e:
450 orig = e
451 self.assertEqual(
452 _testcapi.unstable_exc_prep_reraise_star(orig, [None]), None)
453
454 def test_reraise_orig(self):
455 orig = self.orig
456 res = _testcapi.unstable_exc_prep_reraise_star(orig, [orig])
457 self.assertExceptionIsLike(res, orig)
458
459 def test_raise_orig_parts(self):
460 orig = self.orig
461 match, rest = orig.split(TypeError)
462
463 test_cases = [
464 ([match, rest], orig),
465 ([rest, match], orig),
466 ([match], match),
467 ([rest], rest),
468 ([], None),
469 ]
470
471 for input, expected in test_cases:
472 with self.subTest(input=input):
473 res = _testcapi.unstable_exc_prep_reraise_star(orig, input)
474 self.assertExceptionIsLike(res, expected)
475
476
477 def test_raise_with_new_exceptions(self):
478 orig = self.orig
479
480 match, rest = orig.split(TypeError)
481 new1 = OSError('bad file')
482 new2 = RuntimeError('bad runtime')
483
484 test_cases = [
485 ([new1, match, rest], ExceptionGroup("", [new1, orig])),
486 ([match, new1, rest], ExceptionGroup("", [new1, orig])),
487 ([match, rest, new1], ExceptionGroup("", [new1, orig])),
488
489 ([new1, new2, match, rest], ExceptionGroup("", [new1, new2, orig])),
490 ([new1, match, new2, rest], ExceptionGroup("", [new1, new2, orig])),
491 ([new2, rest, match, new1], ExceptionGroup("", [new2, new1, orig])),
492 ([rest, new2, match, new1], ExceptionGroup("", [new2, new1, orig])),
493
494
495 ([new1, new2, rest], ExceptionGroup("", [new1, new2, rest])),
496 ([new1, match, new2], ExceptionGroup("", [new1, new2, match])),
497 ([rest, new2, new1], ExceptionGroup("", [new2, new1, rest])),
498 ([new1, new2], ExceptionGroup("", [new1, new2])),
499 ([new2, new1], ExceptionGroup("", [new2, new1])),
500 ]
501
502 for (input, expected) in test_cases:
503 with self.subTest(input=input):
504 res = _testcapi.unstable_exc_prep_reraise_star(orig, input)
505 self.assertExceptionIsLike(res, expected)
506
507
508 if __name__ == "__main__":
509 unittest.main()