| 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 or _testinternalcapi module isn't available. |
| 17 |
_testcapi = import_helper.import_module('_testcapi') |
| 18 |
_testinternalcapi = import_helper.import_module('_testinternalcapi') |
| 19 |
|
| 20 |
NULL = None |
| 21 |
|
| 22 |
class CustomError(Exception): |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
class Test_Exceptions(unittest.TestCase): |
| 27 |
|
| 28 |
def test_exception(self): |
| 29 |
raised_exception = ValueError("5") |
| 30 |
new_exc = TypeError("TEST") |
| 31 |
try: |
| 32 |
raise raised_exception |
| 33 |
except ValueError as e: |
| 34 |
orig_sys_exception = sys.exception() |
| 35 |
orig_exception = _testcapi.set_exception(new_exc) |
| 36 |
new_sys_exception = sys.exception() |
| 37 |
new_exception = _testcapi.set_exception(orig_exception) |
| 38 |
reset_sys_exception = sys.exception() |
| 39 |
|
| 40 |
self.assertEqual(orig_exception, e) |
| 41 |
|
| 42 |
self.assertEqual(orig_exception, raised_exception) |
| 43 |
self.assertEqual(orig_sys_exception, orig_exception) |
| 44 |
self.assertEqual(reset_sys_exception, orig_exception) |
| 45 |
self.assertEqual(new_exception, new_exc) |
| 46 |
self.assertEqual(new_sys_exception, new_exception) |
| 47 |
else: |
| 48 |
self.fail("Exception not raised") |
| 49 |
|
| 50 |
def test_exc_info(self): |
| 51 |
raised_exception = ValueError("5") |
| 52 |
new_exc = TypeError("TEST") |
| 53 |
try: |
| 54 |
raise raised_exception |
| 55 |
except ValueError as e: |
| 56 |
tb = e.__traceback__ |
| 57 |
orig_sys_exc_info = sys.exc_info() |
| 58 |
orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None) |
| 59 |
new_sys_exc_info = sys.exc_info() |
| 60 |
new_exc_info = _testcapi.set_exc_info(*orig_exc_info) |
| 61 |
reset_sys_exc_info = sys.exc_info() |
| 62 |
|
| 63 |
self.assertEqual(orig_exc_info[1], e) |
| 64 |
|
| 65 |
self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb)) |
| 66 |
self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info) |
| 67 |
self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info) |
| 68 |
self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None)) |
| 69 |
self.assertSequenceEqual(new_sys_exc_info, new_exc_info) |
| 70 |
else: |
| 71 |
self.assertTrue(False) |
| 72 |
|
| 73 |
def test_warn_with_stacklevel(self): |
| 74 |
code = textwrap.dedent('''\ |
| 75 |
import _testcapi |
| 76 |
|
| 77 |
def foo(): |
| 78 |
_testcapi.function_set_warning() |
| 79 |
|
| 80 |
foo() # line 6 |
| 81 |
|
| 82 |
|
| 83 |
foo() # line 9 |
| 84 |
''') |
| 85 |
proc = assert_python_ok("-c", code) |
| 86 |
warnings = proc.err.splitlines() |
| 87 |
self.assertEqual(warnings, [ |
| 88 |
b'<string>:6: RuntimeWarning: Testing PyErr_WarnEx', |
| 89 |
b'<string>:9: RuntimeWarning: Testing PyErr_WarnEx', |
| 90 |
]) |
| 91 |
|
| 92 |
def test_warn_during_finalization(self): |
| 93 |
code = textwrap.dedent('''\ |
| 94 |
import _testcapi |
| 95 |
|
| 96 |
class Foo: |
| 97 |
def foo(self): |
| 98 |
_testcapi.function_set_warning() |
| 99 |
def __del__(self): |
| 100 |
self.foo() |
| 101 |
|
| 102 |
ref = Foo() |
| 103 |
''') |
| 104 |
proc = assert_python_ok("-c", code) |
| 105 |
warnings = proc.err.splitlines() |
| 106 |
# Due to the finalization of the interpreter, the source will be omitted |
| 107 |
# because the ``warnings`` module cannot be imported at this time |
| 108 |
self.assertEqual(warnings, [ |
| 109 |
b'<string>:7: RuntimeWarning: Testing PyErr_WarnEx', |
| 110 |
]) |
| 111 |
|
| 112 |
def test__pyerr_setkeyerror(self): |
| 113 |
# Test _PyErr_SetKeyError() |
| 114 |
_pyerr_setkeyerror = _testinternalcapi._pyerr_setkeyerror |
| 115 |
for arg in ( |
| 116 |
"key", |
| 117 |
# check that a tuple argument is not unpacked |
| 118 |
(1, 2, 3), |
| 119 |
# PyErr_SetObject(exc_type, exc_value) uses exc_value if it's |
| 120 |
# already an exception, but _PyErr_SetKeyError() always creates a |
| 121 |
# new KeyError. |
| 122 |
KeyError('arg'), |
| 123 |
): |
| 124 |
with self.subTest(arg=arg): |
| 125 |
with self.assertRaises(KeyError) as cm: |
| 126 |
# Test calling _PyErr_SetKeyError() with an exception set |
| 127 |
# to check that the function overrides the current |
| 128 |
# exception. |
| 129 |
_pyerr_setkeyerror(arg) |
| 130 |
self.assertEqual(cm.exception.args, (arg,)) |
| 131 |
|
| 132 |
|
| 133 |
class Test_FatalError(unittest.TestCase): |
| 134 |
|
| 135 |
def check_fatal_error(self, code, expected, not_expected=()): |
| 136 |
with support.SuppressCrashReport(): |
| 137 |
rc, out, err = assert_python_failure('-sSI', '-c', code) |
| 138 |
|
| 139 |
err = decode_stderr(err) |
| 140 |
self.assertIn('Fatal Python error: _testcapi_fatal_error_impl: MESSAGE\n', |
| 141 |
err) |
| 142 |
|
| 143 |
match = re.search(r'^Extension modules:(.*) \(total: ([0-9]+)\)$', |
| 144 |
err, re.MULTILINE) |
| 145 |
if not match: |
| 146 |
self.fail(f"Cannot find 'Extension modules:' in {err!r}") |
| 147 |
modules = set(match.group(1).strip().split(', ')) |
| 148 |
total = int(match.group(2)) |
| 149 |
|
| 150 |
for name in expected: |
| 151 |
self.assertIn(name, modules) |
| 152 |
for name in not_expected: |
| 153 |
self.assertNotIn(name, modules) |
| 154 |
self.assertEqual(len(modules), total) |
| 155 |
|
| 156 |
@support.requires_subprocess() |
| 157 |
def test_fatal_error(self): |
| 158 |
# By default, stdlib extension modules are ignored, |
| 159 |
# but not test modules. |
| 160 |
expected = ('_testcapi',) |
| 161 |
not_expected = ('sys',) |
| 162 |
code = 'import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")' |
| 163 |
self.check_fatal_error(code, expected, not_expected) |
| 164 |
|
| 165 |
# Mark _testcapi as stdlib module, but not sys |
| 166 |
expected = ('sys',) |
| 167 |
not_expected = ('_testcapi',) |
| 168 |
code = """if True: |
| 169 |
import _testcapi, sys |
| 170 |
sys.stdlib_module_names = frozenset({"_testcapi"}) |
| 171 |
_testcapi.fatal_error(b"MESSAGE") |
| 172 |
""" |
| 173 |
self.check_fatal_error(code, expected) |
| 174 |
|
| 175 |
|
| 176 |
class Test_ErrSetAndRestore(unittest.TestCase): |
| 177 |
|
| 178 |
def test_err_set_raised(self): |
| 179 |
with self.assertRaises(ValueError): |
| 180 |
_testcapi.err_set_raised(ValueError()) |
| 181 |
v = ValueError() |
| 182 |
try: |
| 183 |
_testcapi.err_set_raised(v) |
| 184 |
except ValueError as ex: |
| 185 |
self.assertIs(v, ex) |
| 186 |
|
| 187 |
def test_err_restore(self): |
| 188 |
with self.assertRaises(ValueError): |
| 189 |
_testcapi.err_restore(ValueError) |
| 190 |
with self.assertRaises(ValueError): |
| 191 |
_testcapi.err_restore(ValueError, 1) |
| 192 |
with self.assertRaises(ValueError): |
| 193 |
_testcapi.err_restore(ValueError, 1, None) |
| 194 |
with self.assertRaises(ValueError): |
| 195 |
_testcapi.err_restore(ValueError, ValueError()) |
| 196 |
try: |
| 197 |
_testcapi.err_restore(KeyError, "hi") |
| 198 |
except KeyError as k: |
| 199 |
self.assertEqual("hi", k.args[0]) |
| 200 |
try: |
| 201 |
1/0 |
| 202 |
except Exception as e: |
| 203 |
tb = e.__traceback__ |
| 204 |
with self.assertRaises(ValueError): |
| 205 |
_testcapi.err_restore(ValueError, 1, tb) |
| 206 |
with self.assertRaises(TypeError): |
| 207 |
_testcapi.err_restore(ValueError, 1, 0) |
| 208 |
try: |
| 209 |
_testcapi.err_restore(ValueError, 1, tb) |
| 210 |
except ValueError as v: |
| 211 |
self.assertEqual(1, v.args[0]) |
| 212 |
self.assertIs(tb, v.__traceback__.tb_next) |
| 213 |
|
| 214 |
def test_set_object(self): |
| 215 |
|
| 216 |
# new exception as obj is not an exception |
| 217 |
with self.assertRaises(ValueError) as e: |
| 218 |
_testcapi.exc_set_object(ValueError, 42) |
| 219 |
self.assertEqual(e.exception.args, (42,)) |
| 220 |
|
| 221 |
# wraps the exception because unrelated types |
| 222 |
with self.assertRaises(ValueError) as e: |
| 223 |
_testcapi.exc_set_object(ValueError, TypeError(1,2,3)) |
| 224 |
wrapped = e.exception.args[0] |
| 225 |
self.assertIsInstance(wrapped, TypeError) |
| 226 |
self.assertEqual(wrapped.args, (1, 2, 3)) |
| 227 |
|
| 228 |
# is superclass, so does not wrap |
| 229 |
with self.assertRaises(PermissionError) as e: |
| 230 |
_testcapi.exc_set_object(OSError, PermissionError(24)) |
| 231 |
self.assertEqual(e.exception.args, (24,)) |
| 232 |
|
| 233 |
class Meta(type): |
| 234 |
def __subclasscheck__(cls, sub): |
| 235 |
1/0 |
| 236 |
|
| 237 |
class Broken(Exception, metaclass=Meta): |
| 238 |
pass |
| 239 |
|
| 240 |
with self.assertRaises(ZeroDivisionError) as e: |
| 241 |
_testcapi.exc_set_object(Broken, Broken()) |
| 242 |
|
| 243 |
def test_set_object_and_fetch(self): |
| 244 |
class Broken(Exception): |
| 245 |
def __init__(self, *arg): |
| 246 |
raise ValueError("Broken __init__") |
| 247 |
|
| 248 |
exc = _testcapi.exc_set_object_fetch(Broken, 'abcd') |
| 249 |
self.assertIsInstance(exc, ValueError) |
| 250 |
self.assertEqual(exc.__notes__[0], |
| 251 |
"Normalization failed: type=Broken args='abcd'") |
| 252 |
|
| 253 |
class BadArg: |
| 254 |
def __repr__(self): |
| 255 |
raise TypeError('Broken arg type') |
| 256 |
|
| 257 |
exc = _testcapi.exc_set_object_fetch(Broken, BadArg()) |
| 258 |
self.assertIsInstance(exc, ValueError) |
| 259 |
self.assertEqual(exc.__notes__[0], |
| 260 |
'Normalization failed: type=Broken args=<unknown>') |
| 261 |
|
| 262 |
def test_set_string(self): |
| 263 |
"""Test PyErr_SetString()""" |
| 264 |
setstring = _testcapi.err_setstring |
| 265 |
with self.assertRaises(ZeroDivisionError) as e: |
| 266 |
setstring(ZeroDivisionError, b'error') |
| 267 |
self.assertEqual(e.exception.args, ('error',)) |
| 268 |
with self.assertRaises(ZeroDivisionError) as e: |
| 269 |
setstring(ZeroDivisionError, 'помилка'.encode()) |
| 270 |
self.assertEqual(e.exception.args, ('помилка',)) |
| 271 |
|
| 272 |
with self.assertRaises(UnicodeDecodeError): |
| 273 |
setstring(ZeroDivisionError, b'\xff') |
| 274 |
self.assertRaises(SystemError, setstring, list, b'error') |
| 275 |
# CRASHES setstring(ZeroDivisionError, NULL) |
| 276 |
# CRASHES setstring(NULL, b'error') |
| 277 |
|
| 278 |
def test_format(self): |
| 279 |
"""Test PyErr_Format()""" |
| 280 |
import_helper.import_module('ctypes') |
| 281 |
from ctypes import pythonapi, py_object, c_char_p, c_int |
| 282 |
name = "PyErr_Format" |
| 283 |
PyErr_Format = getattr(pythonapi, name) |
| 284 |
PyErr_Format.argtypes = (py_object, c_char_p,) |
| 285 |
PyErr_Format.restype = py_object |
| 286 |
with self.assertRaises(ZeroDivisionError) as e: |
| 287 |
PyErr_Format(ZeroDivisionError, b'%s %d', b'error', c_int(42)) |
| 288 |
self.assertEqual(e.exception.args, ('error 42',)) |
| 289 |
with self.assertRaises(ZeroDivisionError) as e: |
| 290 |
PyErr_Format(ZeroDivisionError, b'%s', 'помилка'.encode()) |
| 291 |
self.assertEqual(e.exception.args, ('помилка',)) |
| 292 |
|
| 293 |
with self.assertRaisesRegex(OverflowError, 'not in range'): |
| 294 |
PyErr_Format(ZeroDivisionError, b'%c', c_int(-1)) |
| 295 |
with self.assertRaisesRegex(ValueError, 'format string'): |
| 296 |
PyErr_Format(ZeroDivisionError, b'\xff') |
| 297 |
self.assertRaises(SystemError, PyErr_Format, list, b'error') |
| 298 |
# CRASHES PyErr_Format(ZeroDivisionError, NULL) |
| 299 |
# CRASHES PyErr_Format(py_object(), b'error') |
| 300 |
|
| 301 |
def test_setfromerrnowithfilename(self): |
| 302 |
"""Test PyErr_SetFromErrnoWithFilename()""" |
| 303 |
setfromerrnowithfilename = _testcapi.err_setfromerrnowithfilename |
| 304 |
ENOENT = errno.ENOENT |
| 305 |
with self.assertRaises(FileNotFoundError) as e: |
| 306 |
setfromerrnowithfilename(ENOENT, OSError, b'file') |
| 307 |
self.assertEqual(e.exception.args, |
| 308 |
(ENOENT, 'No such file or directory')) |
| 309 |
self.assertEqual(e.exception.errno, ENOENT) |
| 310 |
self.assertEqual(e.exception.filename, 'file') |
| 311 |
|
| 312 |
with self.assertRaises(FileNotFoundError) as e: |
| 313 |
setfromerrnowithfilename(ENOENT, OSError, os.fsencode(TESTFN)) |
| 314 |
self.assertEqual(e.exception.filename, TESTFN) |
| 315 |
|
| 316 |
if TESTFN_UNDECODABLE: |
| 317 |
with self.assertRaises(FileNotFoundError) as e: |
| 318 |
setfromerrnowithfilename(ENOENT, OSError, TESTFN_UNDECODABLE) |
| 319 |
self.assertEqual(e.exception.filename, |
| 320 |
os.fsdecode(TESTFN_UNDECODABLE)) |
| 321 |
|
| 322 |
with self.assertRaises(FileNotFoundError) as e: |
| 323 |
setfromerrnowithfilename(ENOENT, OSError, NULL) |
| 324 |
self.assertIsNone(e.exception.filename) |
| 325 |
|
| 326 |
with self.assertRaises(OSError) as e: |
| 327 |
setfromerrnowithfilename(0, OSError, b'file') |
| 328 |
self.assertEqual(e.exception.args, (0, 'Error')) |
| 329 |
self.assertEqual(e.exception.errno, 0) |
| 330 |
self.assertEqual(e.exception.filename, 'file') |
| 331 |
|
| 332 |
with self.assertRaises(ZeroDivisionError) as e: |
| 333 |
setfromerrnowithfilename(ENOENT, ZeroDivisionError, b'file') |
| 334 |
self.assertEqual(e.exception.args, |
| 335 |
(ENOENT, 'No such file or directory', 'file')) |
| 336 |
# CRASHES setfromerrnowithfilename(ENOENT, NULL, b'error') |
| 337 |
|
| 338 |
def test_err_writeunraisable(self): |
| 339 |
# Test PyErr_WriteUnraisable() |
| 340 |
writeunraisable = _testcapi.err_writeunraisable |
| 341 |
firstline = self.test_err_writeunraisable.__code__.co_firstlineno |
| 342 |
|
| 343 |
with support.catch_unraisable_exception() as cm: |
| 344 |
writeunraisable(CustomError('oops!'), hex) |
| 345 |
self.assertEqual(cm.unraisable.exc_type, CustomError) |
| 346 |
self.assertEqual(str(cm.unraisable.exc_value), 'oops!') |
| 347 |
self.assertEqual(cm.unraisable.exc_traceback.tb_lineno, |
| 348 |
firstline + 6) |
| 349 |
self.assertIsNone(cm.unraisable.err_msg) |
| 350 |
self.assertEqual(cm.unraisable.object, hex) |
| 351 |
|
| 352 |
with support.catch_unraisable_exception() as cm: |
| 353 |
writeunraisable(CustomError('oops!'), NULL) |
| 354 |
self.assertEqual(cm.unraisable.exc_type, CustomError) |
| 355 |
self.assertEqual(str(cm.unraisable.exc_value), 'oops!') |
| 356 |
self.assertEqual(cm.unraisable.exc_traceback.tb_lineno, |
| 357 |
firstline + 15) |
| 358 |
self.assertIsNone(cm.unraisable.err_msg) |
| 359 |
self.assertIsNone(cm.unraisable.object) |
| 360 |
|
| 361 |
with (support.swap_attr(sys, 'unraisablehook', None), |
| 362 |
support.captured_stderr() as stderr): |
| 363 |
writeunraisable(CustomError('oops!'), hex) |
| 364 |
lines = stderr.getvalue().splitlines() |
| 365 |
self.assertEqual(lines[0], f'Exception ignored in: {hex!r}') |
| 366 |
self.assertEqual(lines[1], 'Traceback (most recent call last):') |
| 367 |
self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!') |
| 368 |
|
| 369 |
with (support.swap_attr(sys, 'unraisablehook', None), |
| 370 |
support.captured_stderr() as stderr): |
| 371 |
writeunraisable(CustomError('oops!'), NULL) |
| 372 |
lines = stderr.getvalue().splitlines() |
| 373 |
self.assertEqual(lines[0], 'Traceback (most recent call last):') |
| 374 |
self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!') |
| 375 |
|
| 376 |
# CRASHES writeunraisable(NULL, hex) |
| 377 |
# CRASHES writeunraisable(NULL, NULL) |
| 378 |
|
| 379 |
def test_err_formatunraisable(self): |
| 380 |
# Test PyErr_FormatUnraisable() |
| 381 |
formatunraisable = _testcapi.err_formatunraisable |
| 382 |
firstline = self.test_err_formatunraisable.__code__.co_firstlineno |
| 383 |
|
| 384 |
with support.catch_unraisable_exception() as cm: |
| 385 |
formatunraisable(CustomError('oops!'), b'Error in %R', []) |
| 386 |
self.assertEqual(cm.unraisable.exc_type, CustomError) |
| 387 |
self.assertEqual(str(cm.unraisable.exc_value), 'oops!') |
| 388 |
self.assertEqual(cm.unraisable.exc_traceback.tb_lineno, |
| 389 |
firstline + 6) |
| 390 |
self.assertEqual(cm.unraisable.err_msg, 'Error in []') |
| 391 |
self.assertIsNone(cm.unraisable.object) |
| 392 |
|
| 393 |
with support.catch_unraisable_exception() as cm: |
| 394 |
formatunraisable(CustomError('oops!'), b'undecodable \xff') |
| 395 |
self.assertEqual(cm.unraisable.exc_type, CustomError) |
| 396 |
self.assertEqual(str(cm.unraisable.exc_value), 'oops!') |
| 397 |
self.assertEqual(cm.unraisable.exc_traceback.tb_lineno, |
| 398 |
firstline + 15) |
| 399 |
self.assertIsNone(cm.unraisable.err_msg) |
| 400 |
self.assertIsNone(cm.unraisable.object) |
| 401 |
|
| 402 |
with support.catch_unraisable_exception() as cm: |
| 403 |
formatunraisable(CustomError('oops!'), NULL) |
| 404 |
self.assertEqual(cm.unraisable.exc_type, CustomError) |
| 405 |
self.assertEqual(str(cm.unraisable.exc_value), 'oops!') |
| 406 |
self.assertEqual(cm.unraisable.exc_traceback.tb_lineno, |
| 407 |
firstline + 24) |
| 408 |
self.assertIsNone(cm.unraisable.err_msg) |
| 409 |
self.assertIsNone(cm.unraisable.object) |
| 410 |
|
| 411 |
with (support.swap_attr(sys, 'unraisablehook', None), |
| 412 |
support.captured_stderr() as stderr): |
| 413 |
formatunraisable(CustomError('oops!'), b'Error in %R', []) |
| 414 |
lines = stderr.getvalue().splitlines() |
| 415 |
self.assertEqual(lines[0], f'Error in []:') |
| 416 |
self.assertEqual(lines[1], 'Traceback (most recent call last):') |
| 417 |
self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!') |
| 418 |
|
| 419 |
with (support.swap_attr(sys, 'unraisablehook', None), |
| 420 |
support.captured_stderr() as stderr): |
| 421 |
formatunraisable(CustomError('oops!'), b'undecodable \xff') |
| 422 |
lines = stderr.getvalue().splitlines() |
| 423 |
self.assertEqual(lines[0], 'Traceback (most recent call last):') |
| 424 |
self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!') |
| 425 |
|
| 426 |
with (support.swap_attr(sys, 'unraisablehook', None), |
| 427 |
support.captured_stderr() as stderr): |
| 428 |
formatunraisable(CustomError('oops!'), NULL) |
| 429 |
lines = stderr.getvalue().splitlines() |
| 430 |
self.assertEqual(lines[0], 'Traceback (most recent call last):') |
| 431 |
self.assertEqual(lines[-1], f'{__name__}.CustomError: oops!') |
| 432 |
|
| 433 |
# CRASHES formatunraisable(NULL, b'Error in %R', []) |
| 434 |
# CRASHES formatunraisable(NULL, NULL) |
| 435 |
|
| 436 |
|
| 437 |
class TestUnicodeTranslateError(UnicodeTranslateError): |
| 438 |
# UnicodeTranslateError takes 4 arguments instead of 5, |
| 439 |
# so we just make a UnicodeTranslateError class that is |
| 440 |
# compatible with the UnicodeError.__init__. |
| 441 |
def __init__(self, encoding, *args, **kwargs): |
| 442 |
super().__init__(*args, **kwargs) |
| 443 |
|
| 444 |
|
| 445 |
class TestUnicodeError(unittest.TestCase): |
| 446 |
|
| 447 |
def _check_no_crash(self, exc): |
| 448 |
# ensure that the __str__() method does not crash |
| 449 |
_ = str(exc) |
| 450 |
|
| 451 |
def test_unicode_encode_error_get_start(self): |
| 452 |
get_start = _testcapi.unicode_encode_get_start |
| 453 |
self._test_unicode_error_get_start('x', UnicodeEncodeError, get_start) |
| 454 |
|
| 455 |
def test_unicode_decode_error_get_start(self): |
| 456 |
get_start = _testcapi.unicode_decode_get_start |
| 457 |
self._test_unicode_error_get_start(b'x', UnicodeDecodeError, get_start) |
| 458 |
|
| 459 |
def test_unicode_translate_error_get_start(self): |
| 460 |
get_start = _testcapi.unicode_translate_get_start |
| 461 |
self._test_unicode_error_get_start('x', TestUnicodeTranslateError, get_start) |
| 462 |
|
| 463 |
def _test_unicode_error_get_start(self, literal, exc_type, get_start): |
| 464 |
for obj_len, start, c_start in [ |
| 465 |
# normal cases |
| 466 |
(5, 0, 0), |
| 467 |
(5, 1, 1), |
| 468 |
(5, 2, 2), |
| 469 |
# out of range start is clamped to max(0, obj_len - 1) |
| 470 |
(0, 0, 0), |
| 471 |
(0, 1, 0), |
| 472 |
(0, 10, 0), |
| 473 |
(5, 5, 4), |
| 474 |
(5, 10, 4), |
| 475 |
# negative values are allowed but clipped in the getter |
| 476 |
(0, -1, 0), |
| 477 |
(1, -1, 0), |
| 478 |
(2, -1, 0), |
| 479 |
(2, -2, 0), |
| 480 |
]: |
| 481 |
obj = literal * obj_len |
| 482 |
with self.subTest(obj, exc_type=exc_type, start=start): |
| 483 |
exc = exc_type('utf-8', obj, start, obj_len, 'reason') |
| 484 |
self.assertEqual(get_start(exc), c_start) |
| 485 |
self._check_no_crash(exc) |
| 486 |
|
| 487 |
def test_unicode_encode_error_set_start(self): |
| 488 |
set_start = _testcapi.unicode_encode_set_start |
| 489 |
self._test_unicode_error_set_start('x', UnicodeEncodeError, set_start) |
| 490 |
|
| 491 |
def test_unicode_decode_error_set_start(self): |
| 492 |
set_start = _testcapi.unicode_decode_set_start |
| 493 |
self._test_unicode_error_set_start(b'x', UnicodeDecodeError, set_start) |
| 494 |
|
| 495 |
def test_unicode_translate_error_set_start(self): |
| 496 |
set_start = _testcapi.unicode_translate_set_start |
| 497 |
self._test_unicode_error_set_start('x', TestUnicodeTranslateError, set_start) |
| 498 |
|
| 499 |
def _test_unicode_error_set_start(self, literal, exc_type, set_start): |
| 500 |
obj_len = 5 |
| 501 |
obj = literal * obj_len |
| 502 |
for new_start in range(-2 * obj_len, 2 * obj_len): |
| 503 |
with self.subTest('C-API', obj=obj, exc_type=exc_type, new_start=new_start): |
| 504 |
exc = exc_type('utf-8', obj, 0, obj_len, 'reason') |
| 505 |
# arbitrary value is allowed in the C API setter |
| 506 |
set_start(exc, new_start) |
| 507 |
self.assertEqual(exc.start, new_start) |
| 508 |
self._check_no_crash(exc) |
| 509 |
|
| 510 |
with self.subTest('Py-API', obj=obj, exc_type=exc_type, new_start=new_start): |
| 511 |
exc = exc_type('utf-8', obj, 0, obj_len, 'reason') |
| 512 |
# arbitrary value is allowed in the attribute setter |
| 513 |
exc.start = new_start |
| 514 |
self.assertEqual(exc.start, new_start) |
| 515 |
self._check_no_crash(exc) |
| 516 |
|
| 517 |
def test_unicode_encode_error_get_end(self): |
| 518 |
get_end = _testcapi.unicode_encode_get_end |
| 519 |
self._test_unicode_error_get_end('x', UnicodeEncodeError, get_end) |
| 520 |
|
| 521 |
def test_unicode_decode_error_get_end(self): |
| 522 |
get_end = _testcapi.unicode_decode_get_end |
| 523 |
self._test_unicode_error_get_end(b'x', UnicodeDecodeError, get_end) |
| 524 |
|
| 525 |
def test_unicode_translate_error_get_end(self): |
| 526 |
get_end = _testcapi.unicode_translate_get_end |
| 527 |
self._test_unicode_error_get_end('x', TestUnicodeTranslateError, get_end) |
| 528 |
|
| 529 |
def _test_unicode_error_get_end(self, literal, exc_type, get_end): |
| 530 |
for obj_len, end, c_end in [ |
| 531 |
# normal cases |
| 532 |
(5, 0, 1), |
| 533 |
(5, 1, 1), |
| 534 |
(5, 2, 2), |
| 535 |
# out-of-range clipped in [MIN(1, OBJLEN), MAX(MIN(1, OBJLEN), OBJLEN)] |
| 536 |
(0, 0, 0), |
| 537 |
(0, 1, 0), |
| 538 |
(0, 10, 0), |
| 539 |
(1, 1, 1), |
| 540 |
(1, 2, 1), |
| 541 |
(5, 5, 5), |
| 542 |
(5, 5, 5), |
| 543 |
(5, 10, 5), |
| 544 |
# negative values are allowed but clipped in the getter |
| 545 |
(0, -1, 0), |
| 546 |
(1, -1, 1), |
| 547 |
(2, -1, 1), |
| 548 |
(2, -2, 1), |
| 549 |
]: |
| 550 |
obj = literal * obj_len |
| 551 |
with self.subTest(obj, exc_type=exc_type, end=end): |
| 552 |
exc = exc_type('utf-8', obj, 0, end, 'reason') |
| 553 |
self.assertEqual(get_end(exc), c_end) |
| 554 |
self._check_no_crash(exc) |
| 555 |
|
| 556 |
def test_unicode_encode_error_set_end(self): |
| 557 |
set_end = _testcapi.unicode_encode_set_end |
| 558 |
self._test_unicode_error_set_end('x', UnicodeEncodeError, set_end) |
| 559 |
|
| 560 |
def test_unicode_decode_error_set_end(self): |
| 561 |
set_end = _testcapi.unicode_decode_set_end |
| 562 |
self._test_unicode_error_set_end(b'x', UnicodeDecodeError, set_end) |
| 563 |
|
| 564 |
def test_unicode_translate_error_set_end(self): |
| 565 |
set_end = _testcapi.unicode_translate_set_end |
| 566 |
self._test_unicode_error_set_end('x', TestUnicodeTranslateError, set_end) |
| 567 |
|
| 568 |
def _test_unicode_error_set_end(self, literal, exc_type, set_end): |
| 569 |
obj_len = 5 |
| 570 |
obj = literal * obj_len |
| 571 |
for new_end in range(-2 * obj_len, 2 * obj_len): |
| 572 |
with self.subTest('C-API', obj=obj, exc_type=exc_type, new_end=new_end): |
| 573 |
exc = exc_type('utf-8', obj, 0, obj_len, 'reason') |
| 574 |
# arbitrary value is allowed in the C API setter |
| 575 |
set_end(exc, new_end) |
| 576 |
self.assertEqual(exc.end, new_end) |
| 577 |
self._check_no_crash(exc) |
| 578 |
|
| 579 |
with self.subTest('Py-API', obj=obj, exc_type=exc_type, new_end=new_end): |
| 580 |
exc = exc_type('utf-8', obj, 0, obj_len, 'reason') |
| 581 |
# arbitrary value is allowed in the attribute setter |
| 582 |
exc.end = new_end |
| 583 |
self.assertEqual(exc.end, new_end) |
| 584 |
self._check_no_crash(exc) |
| 585 |
|
| 586 |
|
| 587 |
class Test_PyUnstable_Exc_PrepReraiseStar(ExceptionIsLikeMixin, unittest.TestCase): |
| 588 |
|
| 589 |
def setUp(self): |
| 590 |
super().setUp() |
| 591 |
try: |
| 592 |
raise ExceptionGroup("eg", [TypeError('bad type'), ValueError(42)]) |
| 593 |
except ExceptionGroup as e: |
| 594 |
self.orig = e |
| 595 |
|
| 596 |
def test_invalid_args(self): |
| 597 |
with self.assertRaisesRegex(TypeError, "orig must be an exception"): |
| 598 |
_testcapi.unstable_exc_prep_reraise_star(42, [None]) |
| 599 |
|
| 600 |
with self.assertRaisesRegex(TypeError, "excs must be a list"): |
| 601 |
_testcapi.unstable_exc_prep_reraise_star(self.orig, 42) |
| 602 |
|
| 603 |
with self.assertRaisesRegex(TypeError, "not an exception"): |
| 604 |
_testcapi.unstable_exc_prep_reraise_star(self.orig, [TypeError(42), 42]) |
| 605 |
|
| 606 |
with self.assertRaisesRegex(ValueError, "orig must be a raised exception"): |
| 607 |
_testcapi.unstable_exc_prep_reraise_star(ValueError(42), [TypeError(42)]) |
| 608 |
|
| 609 |
with self.assertRaisesRegex(ValueError, "orig must be a raised exception"): |
| 610 |
_testcapi.unstable_exc_prep_reraise_star(ExceptionGroup("eg", [ValueError(42)]), |
| 611 |
[TypeError(42)]) |
| 612 |
|
| 613 |
|
| 614 |
def test_nothing_to_reraise(self): |
| 615 |
self.assertEqual( |
| 616 |
_testcapi.unstable_exc_prep_reraise_star(self.orig, [None]), None) |
| 617 |
|
| 618 |
try: |
| 619 |
raise ValueError(42) |
| 620 |
except ValueError as e: |
| 621 |
orig = e |
| 622 |
self.assertEqual( |
| 623 |
_testcapi.unstable_exc_prep_reraise_star(orig, [None]), None) |
| 624 |
|
| 625 |
def test_reraise_orig(self): |
| 626 |
orig = self.orig |
| 627 |
res = _testcapi.unstable_exc_prep_reraise_star(orig, [orig]) |
| 628 |
self.assertExceptionIsLike(res, orig) |
| 629 |
|
| 630 |
def test_raise_orig_parts(self): |
| 631 |
orig = self.orig |
| 632 |
match, rest = orig.split(TypeError) |
| 633 |
|
| 634 |
test_cases = [ |
| 635 |
([match, rest], orig), |
| 636 |
([rest, match], orig), |
| 637 |
([match], match), |
| 638 |
([rest], rest), |
| 639 |
([], None), |
| 640 |
] |
| 641 |
|
| 642 |
for input, expected in test_cases: |
| 643 |
with self.subTest(input=input): |
| 644 |
res = _testcapi.unstable_exc_prep_reraise_star(orig, input) |
| 645 |
self.assertExceptionIsLike(res, expected) |
| 646 |
|
| 647 |
|
| 648 |
def test_raise_with_new_exceptions(self): |
| 649 |
orig = self.orig |
| 650 |
|
| 651 |
match, rest = orig.split(TypeError) |
| 652 |
new1 = OSError('bad file') |
| 653 |
new2 = RuntimeError('bad runtime') |
| 654 |
|
| 655 |
test_cases = [ |
| 656 |
([new1, match, rest], ExceptionGroup("", [new1, orig])), |
| 657 |
([match, new1, rest], ExceptionGroup("", [new1, orig])), |
| 658 |
([match, rest, new1], ExceptionGroup("", [new1, orig])), |
| 659 |
|
| 660 |
([new1, new2, match, rest], ExceptionGroup("", [new1, new2, orig])), |
| 661 |
([new1, match, new2, rest], ExceptionGroup("", [new1, new2, orig])), |
| 662 |
([new2, rest, match, new1], ExceptionGroup("", [new2, new1, orig])), |
| 663 |
([rest, new2, match, new1], ExceptionGroup("", [new2, new1, orig])), |
| 664 |
|
| 665 |
|
| 666 |
([new1, new2, rest], ExceptionGroup("", [new1, new2, rest])), |
| 667 |
([new1, match, new2], ExceptionGroup("", [new1, new2, match])), |
| 668 |
([rest, new2, new1], ExceptionGroup("", [new2, new1, rest])), |
| 669 |
([new1, new2], ExceptionGroup("", [new1, new2])), |
| 670 |
([new2, new1], ExceptionGroup("", [new2, new1])), |
| 671 |
] |
| 672 |
|
| 673 |
for (input, expected) in test_cases: |
| 674 |
with self.subTest(input=input): |
| 675 |
res = _testcapi.unstable_exc_prep_reraise_star(orig, input) |
| 676 |
self.assertExceptionIsLike(res, expected) |
| 677 |
|
| 678 |
|
| 679 |
if __name__ == "__main__": |
| 680 |
unittest.main() |