| 1 |
import sys, dis |
| 2 |
from pytest import raises |
| 3 |
|
| 4 |
|
| 5 |
def test_with_try_except_as_reraise(): |
| 6 |
"""with + try/except T as name where the handler raises: the new exception |
| 7 |
must propagate through the with block's __exit__ without crashing. |
| 8 |
Mirrors import_helper.import_module: with CM(): try: ... except E as msg: raise Other""" |
| 9 |
class CM: |
| 10 |
def __init__(self): self.exited = False; self.exc_type = None |
| 11 |
def __enter__(self): return self |
| 12 |
def __exit__(self, tp, val, tb): |
| 13 |
self.exited = True |
| 14 |
self.exc_type = tp |
| 15 |
return False |
| 16 |
|
| 17 |
cm = CM() |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
def inner(cm, raise_in_handler): |
| 22 |
with cm: |
| 23 |
try: |
| 24 |
if raise_in_handler: |
| 25 |
raise ValueError("original") |
| 26 |
return "ok" |
| 27 |
except ValueError as e: |
| 28 |
raise TypeError("new") |
| 29 |
|
| 30 |
print("=== dis(inner) ===") |
| 31 |
dis.dis(inner) |
| 32 |
|
| 33 |
assert inner(cm, False) == "ok" |
| 34 |
|
| 35 |
try: |
| 36 |
inner(cm, True) |
| 37 |
except TypeError: |
| 38 |
pass |
| 39 |
assert cm.exited, "__exit__ was not called" |
| 40 |
assert cm.exc_type is TypeError, "wrong exc type to __exit__: %r" % cm.exc_type |
| 41 |
|
| 42 |
def test_simple(): |
| 43 |
try: |
| 44 |
raise TypeError() |
| 45 |
except* TypeError: |
| 46 |
a = 1 |
| 47 |
except* ValueError: |
| 48 |
a = 2 |
| 49 |
assert a == 1 |
| 50 |
|
| 51 |
def test_both_excepts_run(): |
| 52 |
l = [] |
| 53 |
try: |
| 54 |
raise ExceptionGroup('abc', [ValueError(), TypeError()]) |
| 55 |
except* TypeError: |
| 56 |
l.append(1) |
| 57 |
except* ValueError: |
| 58 |
l.append(2) |
| 59 |
print(l) |
| 60 |
assert l == [1, 2] |
| 61 |
|
| 62 |
def raises_one(): |
| 63 |
try: |
| 64 |
raise ExceptionGroup('abc', [ValueError(), TypeError()]) |
| 65 |
except* TypeError: |
| 66 |
pass |
| 67 |
|
| 68 |
def test_reraise(): |
| 69 |
a = 1 |
| 70 |
try: |
| 71 |
raises_one() |
| 72 |
except* ValueError: |
| 73 |
a = 0 |
| 74 |
assert a == 0 |
| 75 |
|
| 76 |
def error_in_handler(): |
| 77 |
try: |
| 78 |
raise ExceptionGroup('abc', [ValueError(), TypeError()]) |
| 79 |
except* TypeError: |
| 80 |
1 / 0 |
| 81 |
|
| 82 |
def test_error_in_exception_handler(): |
| 83 |
a = 1 |
| 84 |
try: |
| 85 |
error_in_handler() |
| 86 |
except ExceptionGroup as e: |
| 87 |
assert repr(e) == "ExceptionGroup('', [ZeroDivisionError('division by zero'), ExceptionGroup('abc', [ValueError()])])" |
| 88 |
|
| 89 |
|
| 90 |
else: |
| 91 |
assert 0, "an ExceptionGroup should be raised" |
| 92 |
|
| 93 |
def _name_except_star_func(): |
| 94 |
l = [] |
| 95 |
value = ValueError() |
| 96 |
typ = TypeError() |
| 97 |
try: |
| 98 |
raise ExceptionGroup('abc', [value, typ]) |
| 99 |
except* TypeError as e1: |
| 100 |
l.append(1) |
| 101 |
except* ValueError as e2: |
| 102 |
l.append(2) |
| 103 |
|
| 104 |
def test_name_except_star(): |
| 105 |
l = [] |
| 106 |
value = ValueError() |
| 107 |
typ = TypeError() |
| 108 |
try: |
| 109 |
raise ExceptionGroup('abc', [value, typ]) |
| 110 |
except* TypeError as e1: |
| 111 |
assert e1.exceptions[0] is typ |
| 112 |
l.append(1) |
| 113 |
except* ValueError as e2: |
| 114 |
assert e2.exceptions[0] is value |
| 115 |
l.append(2) |
| 116 |
print(l) |
| 117 |
assert l == [1, 2] |
| 118 |
with raises(UnboundLocalError): |
| 119 |
e1 |
| 120 |
with raises(UnboundLocalError): |
| 121 |
e2 |
| 122 |
|
| 123 |
def test_try_star_name_raise_in_except_handler(): |
| 124 |
l = [] |
| 125 |
value = ValueError() |
| 126 |
typ = TypeError() |
| 127 |
try: |
| 128 |
try: |
| 129 |
raise ExceptionGroup('abc', [value, typ]) |
| 130 |
except* TypeError as e1: |
| 131 |
1 / 0 |
| 132 |
except Exception as e: |
| 133 |
assert "ZeroDivisionError" in repr(e) |
| 134 |
with raises(UnboundLocalError): |
| 135 |
e1 |
| 136 |
|
| 137 |
def maybe_raise_typeerror(x): |
| 138 |
if x: |
| 139 |
raise TypeError |
| 140 |
|
| 141 |
def try_except_star_with_else(x): |
| 142 |
try: |
| 143 |
maybe_raise_typeerror(x) |
| 144 |
except* TypeError: |
| 145 |
a = 1 |
| 146 |
else: |
| 147 |
a = 2 |
| 148 |
return a |
| 149 |
|
| 150 |
def test_try_except_star_with_else(): |
| 151 |
assert try_except_star_with_else(True) == 1 |
| 152 |
assert try_except_star_with_else(False) == 2 |
| 153 |
|
| 154 |
def test_return_break_continue_in_except_group_handler(): |
| 155 |
for kw in "return break continue".split(): |
| 156 |
src = f"""\ |
| 157 |
def try_except_star_with_else_direct_return(x): |
| 158 |
try: |
| 159 |
pass |
| 160 |
except* TypeError: |
| 161 |
{kw} |
| 162 |
""" |
| 163 |
with raises(SyntaxError) as info: |
| 164 |
exec(src) |
| 165 |
assert "cannot appear in an except* block" in str(info.value) |
| 166 |
|
| 167 |
def test_return_in_except_star_outside_function(): |
| 168 |
src = """\ |
| 169 |
try: |
| 170 |
pass |
| 171 |
except* TypeError: |
| 172 |
return |
| 173 |
""" |
| 174 |
with raises(SyntaxError) as info: |
| 175 |
exec(src) |
| 176 |
|
| 177 |
assert "return" in str(info.value) |
| 178 |
|
| 179 |
def test_syntax_error_both_except_except_star(): |
| 180 |
src = """\ |
| 181 |
try: |
| 182 |
pass |
| 183 |
except ValueError: |
| 184 |
pass |
| 185 |
except* TypeError: |
| 186 |
pass |
| 187 |
""" |
| 188 |
with raises(SyntaxError) as info: |
| 189 |
exec(src) |
| 190 |
assert str(info.value).startswith("cannot have both 'except' and 'except*' on the same 'try'") |
| 191 |
|
| 192 |
|
| 193 |
def maybe_raise(err): |
| 194 |
if err: |
| 195 |
raise err |
| 196 |
|
| 197 |
|
| 198 |
def with_finally(l, err): |
| 199 |
try: |
| 200 |
maybe_raise(err) |
| 201 |
except* TypeError: |
| 202 |
l.append(1) |
| 203 |
except* ValueError: |
| 204 |
l.append(2) |
| 205 |
else: |
| 206 |
l.append(3) |
| 207 |
finally: |
| 208 |
l.append(4) |
| 209 |
|
| 210 |
def test_finally(): |
| 211 |
l = [] |
| 212 |
with_finally(l, None) |
| 213 |
assert l == [3, 4] |
| 214 |
l = [] |
| 215 |
with_finally(l, ValueError()) |
| 216 |
assert l == [2, 4] |
| 217 |
l = [] |
| 218 |
with_finally(l, TypeError()) |
| 219 |
assert l == [1, 4] |
| 220 |
l = [] |
| 221 |
with_finally(l, ExceptionGroup('abc', [ValueError(), TypeError()])) |
| 222 |
assert l == [1, 2, 4] |
| 223 |
with raises(ZeroDivisionError): |
| 224 |
l = [] |
| 225 |
with_finally(l, ZeroDivisionError()) |
| 226 |
assert l == [4] |
| 227 |
|
| 228 |
def test_invalid_catching_class(): |
| 229 |
for cls, eg in [(int, False), (ExceptionGroup, True), (BaseExceptionGroup, True), ((ValueError, ExceptionGroup), True), ((int, ), False)]: |
| 230 |
with raises(TypeError) as info: |
| 231 |
try: |
| 232 |
1/0 |
| 233 |
except* cls: |
| 234 |
pass |
| 235 |
if eg: |
| 236 |
assert "catching ExceptionGroup with except* is not allowed. Use except instead." in str(info.value) |
| 237 |
else: |
| 238 |
assert "catching classes that do not inherit from BaseException is not allowed" in str(info.value) |
| 239 |
assert isinstance(info.value.__context__, ZeroDivisionError) |
| 240 |
|
| 241 |
def test_exceptiongroup_is_generic(): |
| 242 |
assert isinstance(ExceptionGroup[int], type(list[int])) |
| 243 |
assert isinstance(BaseExceptionGroup[int], type(list[int])) |
| 244 |
|
| 245 |
def test_split_does_not_copy_non_sequence_notes(): |
| 246 |
|
| 247 |
|
| 248 |
eg = ExceptionGroup("eg", [ValueError(1), TypeError(2)]) |
| 249 |
eg.__notes__ = 123 |
| 250 |
match, rest = eg.split(TypeError) |
| 251 |
assert not hasattr(match, '__notes__') |
| 252 |
assert not hasattr(rest, '__notes__') |
| 253 |
|
| 254 |
|
| 255 |
def assert_exception_is_like(exc, template): |
| 256 |
if exc is None and template is None: |
| 257 |
return |
| 258 |
|
| 259 |
assert template is not None |
| 260 |
assert exc is not None |
| 261 |
|
| 262 |
if not isinstance(exc, ExceptionGroup): |
| 263 |
assert exc.__class__ == template.__class__ |
| 264 |
assert exc.args[0] == template.args[0] |
| 265 |
else: |
| 266 |
assert exc.message == template.message |
| 267 |
assert len(exc.exceptions) == len(template.exceptions) |
| 268 |
for e, t in zip(exc.exceptions, template.exceptions): |
| 269 |
assert_exception_is_like(e, t) |
| 270 |
|
| 271 |
|
| 272 |
def do_split_test_named(exc, T, match_template, rest_template): |
| 273 |
initial_sys_exception = sys.exc_info()[1] |
| 274 |
sys_exception = match = rest = None |
| 275 |
try: |
| 276 |
try: |
| 277 |
raise exc |
| 278 |
except* T as e: |
| 279 |
sys_exception = sys.exc_info()[1] |
| 280 |
match = e |
| 281 |
except BaseException as e: |
| 282 |
rest = e |
| 283 |
|
| 284 |
assert sys_exception == match |
| 285 |
assert_exception_is_like(match, match_template) |
| 286 |
assert_exception_is_like(rest, rest_template) |
| 287 |
assert sys.exc_info()[1] == initial_sys_exception |
| 288 |
do_split_test = do_split_test_named |
| 289 |
|
| 290 |
def test_exception_group_except_star_Exception_not_wrapped(): |
| 291 |
do_split_test( |
| 292 |
ExceptionGroup("eg", [ValueError("V")]), |
| 293 |
Exception, |
| 294 |
ExceptionGroup("eg", [ValueError("V")]), |
| 295 |
None) |
| 296 |
|
| 297 |
def test_match_single_type_partial_match(): |
| 298 |
do_split_test( |
| 299 |
ExceptionGroup( |
| 300 |
"test3", |
| 301 |
[ValueError("V1"), OSError("OS"), ValueError("V2")]), |
| 302 |
ValueError, |
| 303 |
ExceptionGroup("test3", [ValueError("V1"), ValueError("V2")]), |
| 304 |
ExceptionGroup("test3", [OSError("OS")])) |
| 305 |
|
| 306 |
def test_reraise_plain_exception_named(): |
| 307 |
try: |
| 308 |
try: |
| 309 |
raise ValueError(42) |
| 310 |
except* ValueError as e: |
| 311 |
print('sys.exc_info', sys.exc_info()) |
| 312 |
print('except* e', e) |
| 313 |
raise e |
| 314 |
except ExceptionGroup as e: |
| 315 |
print('ExceptionGroup', e) |
| 316 |
exc = e |
| 317 |
|
| 318 |
assert_exception_is_like( |
| 319 |
exc, ExceptionGroup("", [ValueError(42)])) |
| 320 |
|
| 321 |
def except_type(eg, type): |
| 322 |
match, rest = None, None |
| 323 |
try: |
| 324 |
try: |
| 325 |
raise eg |
| 326 |
except* type as e: |
| 327 |
match = e |
| 328 |
except Exception as e: |
| 329 |
rest = e |
| 330 |
return match, rest |
| 331 |
|
| 332 |
def test_unhashable(): |
| 333 |
class UnhashableExc(ValueError): |
| 334 |
__hash__ = None |
| 335 |
|
| 336 |
eg = ExceptionGroup("eg", [TypeError(1), UnhashableExc(2)]) |
| 337 |
match, rest = except_type(eg, UnhashableExc) |
| 338 |
assert_exception_is_like( |
| 339 |
match, ExceptionGroup("eg", [UnhashableExc(2)])) |
| 340 |
assert_exception_is_like( |
| 341 |
rest, ExceptionGroup("eg", [TypeError(1)])) |
| 342 |
|
| 343 |
def test_broken_eq(): |
| 344 |
class Bad(ValueError): |
| 345 |
def __eq__(self, other): |
| 346 |
raise RuntimeError() |
| 347 |
|
| 348 |
eg = ExceptionGroup("eg", [TypeError(1), Bad(2)]) |
| 349 |
match, rest = except_type(eg, TypeError) |
| 350 |
assert_exception_is_like( |
| 351 |
match, ExceptionGroup("eg", [TypeError(1)])) |
| 352 |
assert_exception_is_like( |
| 353 |
rest, ExceptionGroup("eg", [Bad(2)])) |
| 354 |
|
| 355 |
def _except_star_clause_line(func): |
| 356 |
"""Return the line number of the except* clause in func via CHECK_EG_MATCH.""" |
| 357 |
instrs = list(dis.get_instructions(func)) |
| 358 |
check_eg = [i for i in instrs if i.opname == 'CHECK_EG_MATCH'] |
| 359 |
assert check_eg, "no CHECK_EG_MATCH found in %r" % func |
| 360 |
return check_eg[0].positions.lineno |
| 361 |
|
| 362 |
def test_except_star_cleanup_lineno(): |
| 363 |
"""Cleanup opcodes (LIST_APPEND) after except* must not be attributed to a |
| 364 |
line before the except* clause (e.g. co_firstlineno of the function) — that |
| 365 |
would misreport where the cleanup runs.""" |
| 366 |
def func(): |
| 367 |
try: |
| 368 |
raise KeyError |
| 369 |
except* Exception as e: |
| 370 |
pass |
| 371 |
|
| 372 |
except_star_line = _except_star_clause_line(func) |
| 373 |
instrs = list(dis.get_instructions(func)) |
| 374 |
la1 = [i for i in instrs if i.opname == 'LIST_APPEND' and i.arg == 1] |
| 375 |
assert la1, "no LIST_APPEND 1 found" |
| 376 |
for i in la1: |
| 377 |
if i.positions is not None and i.positions.lineno is not None: |
| 378 |
assert i.positions.lineno >= except_star_line, ( |
| 379 |
"LIST_APPEND 1 lineno=%r is before except* clause line %r" % |
| 380 |
(i.positions.lineno, except_star_line)) |
| 381 |
|
| 382 |
def test_traceback_frames_preserved_through_except_star(): |
| 383 |
|
| 384 |
|
| 385 |
import traceback |
| 386 |
|
| 387 |
def inner(): |
| 388 |
try: |
| 389 |
raise ExceptionGroup("group", [ValueError(1)]) |
| 390 |
except* ValueError: |
| 391 |
raise ValueError(2) |
| 392 |
|
| 393 |
def outer(): |
| 394 |
try: |
| 395 |
raise ExceptionGroup("group", [TypeError(1)]) |
| 396 |
except* TypeError: |
| 397 |
inner() |
| 398 |
|
| 399 |
try: |
| 400 |
outer() |
| 401 |
except ValueError as e: |
| 402 |
tb_frames = [frame.f_code.co_name for frame, _ in traceback.walk_tb(e.__traceback__)] |
| 403 |
|
| 404 |
|
| 405 |
assert 'inner' in tb_frames, "inner() missing from traceback: %r" % tb_frames |
| 406 |
assert 'outer' in tb_frames, "outer() missing from traceback: %r" % tb_frames |
| 407 |
|
| 408 |
|
| 409 |
def test_except_star_trace_return_lineno(): |
| 410 |
"""The 'return' trace event after an except* block should report the except* |
| 411 |
clause line, not co_firstlineno (which was the wrong pre-fix behaviour).""" |
| 412 |
events = [] |
| 413 |
|
| 414 |
def tracer(frame, event, arg): |
| 415 |
if frame.f_code.co_name == 'func': |
| 416 |
events.append((event, frame.f_lineno)) |
| 417 |
return tracer |
| 418 |
|
| 419 |
def func(): |
| 420 |
try: |
| 421 |
raise KeyError |
| 422 |
except* Exception as e: |
| 423 |
pass |
| 424 |
|
| 425 |
except_star_line = _except_star_clause_line(func) |
| 426 |
|
| 427 |
sys.settrace(tracer) |
| 428 |
try: |
| 429 |
func() |
| 430 |
finally: |
| 431 |
sys.settrace(None) |
| 432 |
|
| 433 |
ret_events = [lineno for event, lineno in events if event == 'return'] |
| 434 |
assert ret_events, "no return event recorded" |
| 435 |
assert ret_events[-1] >= except_star_line, ( |
| 436 |
"return event at line %d, expected >= except* clause line %d " |
| 437 |
"(cleanup must not report a line before the except* block)" % |
| 438 |
(ret_events[-1], except_star_line)) |
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
def _run_coro(coro): |
| 446 |
"""Drive a coroutine to completion without asyncio.""" |
| 447 |
try: |
| 448 |
coro.send(None) |
| 449 |
while True: |
| 450 |
coro.send(None) |
| 451 |
except StopIteration as e: |
| 452 |
return e.value |
| 453 |
|
| 454 |
|
| 455 |
def test_async_for_inside_async_with_exits_once(): |
| 456 |
"""StopAsyncIteration that ends an async for loop must not be delivered |
| 457 |
to the enclosing async with's __aexit__. Before the fix, handle_operation_error |
| 458 |
found the async-with's exception table entry instead of routing through the |
| 459 |
ExceptBlock pushed by SETUP_EXCEPT for the async iterator, so __aexit__ was |
| 460 |
called with StopAsyncIteration and then called a second time on normal exit.""" |
| 461 |
exit_calls = [] |
| 462 |
|
| 463 |
class ACM: |
| 464 |
async def __aenter__(self): |
| 465 |
return self |
| 466 |
async def __aexit__(self, tp, val, tb): |
| 467 |
exit_calls.append(tp) |
| 468 |
return False |
| 469 |
|
| 470 |
class AIter: |
| 471 |
def __init__(self, n): |
| 472 |
self.i = 0 |
| 473 |
self.n = n |
| 474 |
def __aiter__(self): |
| 475 |
return self |
| 476 |
async def __anext__(self): |
| 477 |
if self.i >= self.n: |
| 478 |
raise StopAsyncIteration |
| 479 |
self.i += 1 |
| 480 |
return self.i |
| 481 |
|
| 482 |
async def main(): |
| 483 |
async with ACM(): |
| 484 |
async for _ in AIter(3): |
| 485 |
pass |
| 486 |
|
| 487 |
_run_coro(main()) |
| 488 |
assert exit_calls == [None], \ |
| 489 |
"__aexit__ call list wrong: %r (expected [None])" % exit_calls |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
def test_generator_exception_in_enter(): |
| 499 |
"""The exception is raised inside __enter__ (after the |
| 500 |
CM expression succeeds).""" |
| 501 |
log = [] |
| 502 |
|
| 503 |
class CM: |
| 504 |
def __enter__(self): |
| 505 |
log.append(('enter')) |
| 506 |
raise OSError("enter failed") |
| 507 |
return self |
| 508 |
|
| 509 |
def __exit__(self, tp, val, tb): |
| 510 |
log.append(('exit')) |
| 511 |
return False |
| 512 |
|
| 513 |
def __iter__(self): |
| 514 |
log.append(('exit')) |
| 515 |
return self |
| 516 |
|
| 517 |
def __next__(self): |
| 518 |
raise OSError("enter failed") |
| 519 |
|
| 520 |
|
| 521 |
def gen(dummy): |
| 522 |
try: |
| 523 |
try: |
| 524 |
with CM() as it: |
| 525 |
for x in it: |
| 526 |
yield x |
| 527 |
except OSError: |
| 528 |
raise |
| 529 |
finally: |
| 530 |
if not dummy: |
| 531 |
log.append('finally') |
| 532 |
except OSError: |
| 533 |
log.append('caught') |
| 534 |
return |
| 535 |
|
| 536 |
if 0: |
| 537 |
import dis |
| 538 |
print("========= gen ============ ") |
| 539 |
print(dis.dis(gen)) |
| 540 |
print("========= gen ============ ") |
| 541 |
list(gen(True)) |
| 542 |
assert log == ['enter', 'caught'], "log=%r" % log |