1# Minimal tests for dis module 2 3from test.support import captured_stdout 4from test.support.bytecode_helper import BytecodeTestCase 5import unittest 6import sys 7import dis 8import io 9import re 10import types 11import contextlib 12 13def get_tb(): 14 def _error(): 15 try: 16 1 / 0 17 except Exception as e: 18 tb = e.__traceback__ 19 return tb 20 21 tb = _error() 22 while tb.tb_next: 23 tb = tb.tb_next 24 return tb 25 26TRACEBACK_CODE = get_tb().tb_frame.f_code 27 28class _C: 29 def __init__(self, x): 30 self.x = x == 1 31 32 @staticmethod 33 def sm(x): 34 x = x == 1 35 36 @classmethod 37 def cm(cls, x): 38 cls.x = x == 1 39 40dis_c_instance_method = """\ 41%3d 0 LOAD_FAST 1 (x) 42 2 LOAD_CONST 1 (1) 43 4 COMPARE_OP 2 (==) 44 6 LOAD_FAST 0 (self) 45 8 STORE_ATTR 0 (x) 46 10 LOAD_CONST 0 (None) 47 12 RETURN_VALUE 48""" % (_C.__init__.__code__.co_firstlineno + 1,) 49 50dis_c_instance_method_bytes = """\ 51 0 LOAD_FAST 1 (1) 52 2 LOAD_CONST 1 (1) 53 4 COMPARE_OP 2 (==) 54 6 LOAD_FAST 0 (0) 55 8 STORE_ATTR 0 (0) 56 10 LOAD_CONST 0 (0) 57 12 RETURN_VALUE 58""" 59 60dis_c_class_method = """\ 61%3d 0 LOAD_FAST 1 (x) 62 2 LOAD_CONST 1 (1) 63 4 COMPARE_OP 2 (==) 64 6 LOAD_FAST 0 (cls) 65 8 STORE_ATTR 0 (x) 66 10 LOAD_CONST 0 (None) 67 12 RETURN_VALUE 68""" % (_C.cm.__code__.co_firstlineno + 2,) 69 70dis_c_static_method = """\ 71%3d 0 LOAD_FAST 0 (x) 72 2 LOAD_CONST 1 (1) 73 4 COMPARE_OP 2 (==) 74 6 STORE_FAST 0 (x) 75 8 LOAD_CONST 0 (None) 76 10 RETURN_VALUE 77""" % (_C.sm.__code__.co_firstlineno + 2,) 78 79# Class disassembling info has an extra newline at end. 80dis_c = """\ 81Disassembly of %s: 82%s 83Disassembly of %s: 84%s 85Disassembly of %s: 86%s 87""" % (_C.__init__.__name__, dis_c_instance_method, 88 _C.cm.__name__, dis_c_class_method, 89 _C.sm.__name__, dis_c_static_method) 90 91def _f(a): 92 print(a) 93 return 1 94 95dis_f = """\ 96%3d 0 LOAD_GLOBAL 0 (print) 97 2 LOAD_FAST 0 (a) 98 4 CALL_FUNCTION 1 99 6 POP_TOP 100 101%3d 8 LOAD_CONST 1 (1) 102 10 RETURN_VALUE 103""" % (_f.__code__.co_firstlineno + 1, 104 _f.__code__.co_firstlineno + 2) 105 106 107dis_f_co_code = """\ 108 0 LOAD_GLOBAL 0 (0) 109 2 LOAD_FAST 0 (0) 110 4 CALL_FUNCTION 1 111 6 POP_TOP 112 8 LOAD_CONST 1 (1) 113 10 RETURN_VALUE 114""" 115 116 117def bug708901(): 118 for res in range(1, 119 10): 120 pass 121 122dis_bug708901 = """\ 123%3d 0 LOAD_GLOBAL 0 (range) 124 2 LOAD_CONST 1 (1) 125 126%3d 4 LOAD_CONST 2 (10) 127 128%3d 6 CALL_FUNCTION 2 129 8 GET_ITER 130 >> 10 FOR_ITER 2 (to 16) 131 12 STORE_FAST 0 (res) 132 133%3d 14 JUMP_ABSOLUTE 5 (to 10) 134 135%3d >> 16 LOAD_CONST 0 (None) 136 18 RETURN_VALUE 137""" % (bug708901.__code__.co_firstlineno + 1, 138 bug708901.__code__.co_firstlineno + 2, 139 bug708901.__code__.co_firstlineno + 1, 140 bug708901.__code__.co_firstlineno + 3, 141 bug708901.__code__.co_firstlineno + 1) 142 143 144def bug1333982(x=[]): 145 assert 0, ([s for s in x] + 146 1) 147 pass 148 149dis_bug1333982 = """\ 150%3d 0 LOAD_ASSERTION_ERROR 151 2 LOAD_CONST 2 (<code object <listcomp> at 0x..., file "%s", line %d>) 152 4 LOAD_CONST 3 ('bug1333982.<locals>.<listcomp>') 153 6 MAKE_FUNCTION 0 154 8 LOAD_FAST 0 (x) 155 10 GET_ITER 156 12 CALL_FUNCTION 1 157 158%3d 14 LOAD_CONST 4 (1) 159 160%3d 16 BINARY_ADD 161 18 CALL_FUNCTION 1 162 20 RAISE_VARARGS 1 163""" % (bug1333982.__code__.co_firstlineno + 1, 164 __file__, 165 bug1333982.__code__.co_firstlineno + 1, 166 bug1333982.__code__.co_firstlineno + 2, 167 bug1333982.__code__.co_firstlineno + 1) 168 169 170def bug42562(): 171 pass 172 173 174# Set line number for 'pass' to None 175bug42562.__code__ = bug42562.__code__.replace(co_linetable=b'\x04\x80') 176 177 178dis_bug42562 = """\ 179 0 LOAD_CONST 0 (None) 180 2 RETURN_VALUE 181""" 182 183# Extended arg followed by NOP 184code_bug_45757 = bytes([ 185 0x90, 0x01, # EXTENDED_ARG 0x01 186 0x09, 0xFF, # NOP 0xFF 187 0x90, 0x01, # EXTENDED_ARG 0x01 188 0x64, 0x29, # LOAD_CONST 0x29 189 0x53, 0x00, # RETURN_VALUE 0x00 190 ]) 191 192dis_bug_45757 = """\ 193 0 EXTENDED_ARG 1 194 2 NOP 195 4 EXTENDED_ARG 1 196 6 LOAD_CONST 297 (297) 197 8 RETURN_VALUE 198""" 199 200_BIG_LINENO_FORMAT = """\ 201%3d 0 LOAD_GLOBAL 0 (spam) 202 2 POP_TOP 203 4 LOAD_CONST 0 (None) 204 6 RETURN_VALUE 205""" 206 207_BIG_LINENO_FORMAT2 = """\ 208%4d 0 LOAD_GLOBAL 0 (spam) 209 2 POP_TOP 210 4 LOAD_CONST 0 (None) 211 6 RETURN_VALUE 212""" 213 214dis_module_expected_results = """\ 215Disassembly of f: 216 4 0 LOAD_CONST 0 (None) 217 2 RETURN_VALUE 218 219Disassembly of g: 220 5 0 LOAD_CONST 0 (None) 221 2 RETURN_VALUE 222 223""" 224 225expr_str = "x + 1" 226 227dis_expr_str = """\ 228 1 0 LOAD_NAME 0 (x) 229 2 LOAD_CONST 0 (1) 230 4 BINARY_ADD 231 6 RETURN_VALUE 232""" 233 234simple_stmt_str = "x = x + 1" 235 236dis_simple_stmt_str = """\ 237 1 0 LOAD_NAME 0 (x) 238 2 LOAD_CONST 0 (1) 239 4 BINARY_ADD 240 6 STORE_NAME 0 (x) 241 8 LOAD_CONST 1 (None) 242 10 RETURN_VALUE 243""" 244 245annot_stmt_str = """\ 246 247x: int = 1 248y: fun(1) 249lst[fun(0)]: int = 1 250""" 251# leading newline is for a reason (tests lineno) 252 253dis_annot_stmt_str = """\ 254 2 0 SETUP_ANNOTATIONS 255 2 LOAD_CONST 0 (1) 256 4 STORE_NAME 0 (x) 257 6 LOAD_NAME 1 (int) 258 8 LOAD_NAME 2 (__annotations__) 259 10 LOAD_CONST 1 ('x') 260 12 STORE_SUBSCR 261 262 3 14 LOAD_NAME 3 (fun) 263 16 LOAD_CONST 0 (1) 264 18 CALL_FUNCTION 1 265 20 LOAD_NAME 2 (__annotations__) 266 22 LOAD_CONST 2 ('y') 267 24 STORE_SUBSCR 268 269 4 26 LOAD_CONST 0 (1) 270 28 LOAD_NAME 4 (lst) 271 30 LOAD_NAME 3 (fun) 272 32 LOAD_CONST 3 (0) 273 34 CALL_FUNCTION 1 274 36 STORE_SUBSCR 275 38 LOAD_NAME 1 (int) 276 40 POP_TOP 277 42 LOAD_CONST 4 (None) 278 44 RETURN_VALUE 279""" 280 281compound_stmt_str = """\ 282x = 0 283while 1: 284 x += 1""" 285# Trailing newline has been deliberately omitted 286 287dis_compound_stmt_str = """\ 288 1 0 LOAD_CONST 0 (0) 289 2 STORE_NAME 0 (x) 290 291 2 4 NOP 292 293 3 >> 6 LOAD_NAME 0 (x) 294 8 LOAD_CONST 1 (1) 295 10 INPLACE_ADD 296 12 STORE_NAME 0 (x) 297 298 2 14 JUMP_ABSOLUTE 3 (to 6) 299""" 300 301dis_traceback = """\ 302%3d 0 SETUP_FINALLY 7 (to 16) 303 304%3d 2 LOAD_CONST 1 (1) 305 4 LOAD_CONST 2 (0) 306 --> 6 BINARY_TRUE_DIVIDE 307 8 POP_TOP 308 10 POP_BLOCK 309 310%3d 12 LOAD_FAST 1 (tb) 311 14 RETURN_VALUE 312 313%3d >> 16 DUP_TOP 314 18 LOAD_GLOBAL 0 (Exception) 315 20 JUMP_IF_NOT_EXC_MATCH 29 (to 58) 316 22 POP_TOP 317 24 STORE_FAST 0 (e) 318 26 POP_TOP 319 28 SETUP_FINALLY 10 (to 50) 320 321%3d 30 LOAD_FAST 0 (e) 322 32 LOAD_ATTR 1 (__traceback__) 323 34 STORE_FAST 1 (tb) 324 36 POP_BLOCK 325 38 POP_EXCEPT 326 40 LOAD_CONST 0 (None) 327 42 STORE_FAST 0 (e) 328 44 DELETE_FAST 0 (e) 329 330%3d 46 LOAD_FAST 1 (tb) 331 48 RETURN_VALUE 332 >> 50 LOAD_CONST 0 (None) 333 52 STORE_FAST 0 (e) 334 54 DELETE_FAST 0 (e) 335 56 RERAISE 1 336 337%3d >> 58 RERAISE 0 338""" % (TRACEBACK_CODE.co_firstlineno + 1, 339 TRACEBACK_CODE.co_firstlineno + 2, 340 TRACEBACK_CODE.co_firstlineno + 5, 341 TRACEBACK_CODE.co_firstlineno + 3, 342 TRACEBACK_CODE.co_firstlineno + 4, 343 TRACEBACK_CODE.co_firstlineno + 5, 344 TRACEBACK_CODE.co_firstlineno + 3) 345 346def _fstring(a, b, c, d): 347 return f'{a} {b:4} {c!r} {d!r:4}' 348 349dis_fstring = """\ 350%3d 0 LOAD_FAST 0 (a) 351 2 FORMAT_VALUE 0 352 4 LOAD_CONST 1 (' ') 353 6 LOAD_FAST 1 (b) 354 8 LOAD_CONST 2 ('4') 355 10 FORMAT_VALUE 4 (with format) 356 12 LOAD_CONST 1 (' ') 357 14 LOAD_FAST 2 (c) 358 16 FORMAT_VALUE 2 (repr) 359 18 LOAD_CONST 1 (' ') 360 20 LOAD_FAST 3 (d) 361 22 LOAD_CONST 2 ('4') 362 24 FORMAT_VALUE 6 (repr, with format) 363 26 BUILD_STRING 7 364 28 RETURN_VALUE 365""" % (_fstring.__code__.co_firstlineno + 1,) 366 367def _tryfinally(a, b): 368 try: 369 return a 370 finally: 371 b() 372 373def _tryfinallyconst(b): 374 try: 375 return 1 376 finally: 377 b() 378 379dis_tryfinally = """\ 380%3d 0 SETUP_FINALLY 6 (to 14) 381 382%3d 2 LOAD_FAST 0 (a) 383 4 POP_BLOCK 384 385%3d 6 LOAD_FAST 1 (b) 386 8 CALL_FUNCTION 0 387 10 POP_TOP 388 12 RETURN_VALUE 389 >> 14 LOAD_FAST 1 (b) 390 16 CALL_FUNCTION 0 391 18 POP_TOP 392 20 RERAISE 0 393""" % (_tryfinally.__code__.co_firstlineno + 1, 394 _tryfinally.__code__.co_firstlineno + 2, 395 _tryfinally.__code__.co_firstlineno + 4, 396 ) 397 398dis_tryfinallyconst = """\ 399%3d 0 SETUP_FINALLY 6 (to 14) 400 401%3d 2 POP_BLOCK 402 403%3d 4 LOAD_FAST 0 (b) 404 6 CALL_FUNCTION 0 405 8 POP_TOP 406 10 LOAD_CONST 1 (1) 407 12 RETURN_VALUE 408 >> 14 LOAD_FAST 0 (b) 409 16 CALL_FUNCTION 0 410 18 POP_TOP 411 20 RERAISE 0 412""" % (_tryfinallyconst.__code__.co_firstlineno + 1, 413 _tryfinallyconst.__code__.co_firstlineno + 2, 414 _tryfinallyconst.__code__.co_firstlineno + 4, 415 ) 416 417def _g(x): 418 yield x 419 420async def _ag(x): 421 yield x 422 423async def _co(x): 424 async for item in _ag(x): 425 pass 426 427def _h(y): 428 def foo(x): 429 '''funcdoc''' 430 return [x + z for z in y] 431 return foo 432 433dis_nested_0 = """\ 434%3d 0 LOAD_CLOSURE 0 (y) 435 2 BUILD_TUPLE 1 436 4 LOAD_CONST 1 (<code object foo at 0x..., file "%s", line %d>) 437 6 LOAD_CONST 2 ('_h.<locals>.foo') 438 8 MAKE_FUNCTION 8 (closure) 439 10 STORE_FAST 1 (foo) 440 441%3d 12 LOAD_FAST 1 (foo) 442 14 RETURN_VALUE 443""" % (_h.__code__.co_firstlineno + 1, 444 __file__, 445 _h.__code__.co_firstlineno + 1, 446 _h.__code__.co_firstlineno + 4, 447) 448 449dis_nested_1 = """%s 450Disassembly of <code object foo at 0x..., file "%s", line %d>: 451%3d 0 LOAD_CLOSURE 0 (x) 452 2 BUILD_TUPLE 1 453 4 LOAD_CONST 1 (<code object <listcomp> at 0x..., file "%s", line %d>) 454 6 LOAD_CONST 2 ('_h.<locals>.foo.<locals>.<listcomp>') 455 8 MAKE_FUNCTION 8 (closure) 456 10 LOAD_DEREF 1 (y) 457 12 GET_ITER 458 14 CALL_FUNCTION 1 459 16 RETURN_VALUE 460""" % (dis_nested_0, 461 __file__, 462 _h.__code__.co_firstlineno + 1, 463 _h.__code__.co_firstlineno + 3, 464 __file__, 465 _h.__code__.co_firstlineno + 3, 466) 467 468dis_nested_2 = """%s 469Disassembly of <code object <listcomp> at 0x..., file "%s", line %d>: 470%3d 0 BUILD_LIST 0 471 2 LOAD_FAST 0 (.0) 472 >> 4 FOR_ITER 6 (to 18) 473 6 STORE_FAST 1 (z) 474 8 LOAD_DEREF 0 (x) 475 10 LOAD_FAST 1 (z) 476 12 BINARY_ADD 477 14 LIST_APPEND 2 478 16 JUMP_ABSOLUTE 2 (to 4) 479 >> 18 RETURN_VALUE 480""" % (dis_nested_1, 481 __file__, 482 _h.__code__.co_firstlineno + 3, 483 _h.__code__.co_firstlineno + 3, 484) 485 486 487class DisTests(unittest.TestCase): 488 489 maxDiff = None 490 491 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): 492 # We want to test the default printing behaviour, not the file arg 493 output = io.StringIO() 494 with contextlib.redirect_stdout(output): 495 if wrapper: 496 dis.dis(func, **kwargs) 497 else: 498 dis.disassemble(func, lasti, **kwargs) 499 return output.getvalue() 500 501 def get_disassemble_as_string(self, func, lasti=-1): 502 return self.get_disassembly(func, lasti, False) 503 504 def strip_addresses(self, text): 505 return re.sub(r'\b0x[0-9A-Fa-f]+\b', '0x...', text) 506 507 def do_disassembly_test(self, func, expected): 508 got = self.get_disassembly(func, depth=0) 509 if got != expected: 510 got = self.strip_addresses(got) 511 self.assertEqual(got, expected) 512 513 def test_opmap(self): 514 self.assertEqual(dis.opmap["NOP"], 9) 515 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst) 516 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname) 517 518 def test_opname(self): 519 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") 520 521 def test_boundaries(self): 522 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG) 523 self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT) 524 525 def test_widths(self): 526 for opcode, opname in enumerate(dis.opname): 527 if opname in ('BUILD_MAP_UNPACK_WITH_CALL', 528 'BUILD_TUPLE_UNPACK_WITH_CALL', 529 'JUMP_IF_NOT_EXC_MATCH'): 530 continue 531 with self.subTest(opname=opname): 532 width = dis._OPNAME_WIDTH 533 if opcode < dis.HAVE_ARGUMENT: 534 width += 1 + dis._OPARG_WIDTH 535 self.assertLessEqual(len(opname), width) 536 537 def test_dis(self): 538 self.do_disassembly_test(_f, dis_f) 539 540 def test_bug_708901(self): 541 self.do_disassembly_test(bug708901, dis_bug708901) 542 543 def test_bug_1333982(self): 544 # This one is checking bytecodes generated for an `assert` statement, 545 # so fails if the tests are run with -O. Skip this test then. 546 if not __debug__: 547 self.skipTest('need asserts, run without -O') 548 549 self.do_disassembly_test(bug1333982, dis_bug1333982) 550 551 def test_bug_42562(self): 552 self.do_disassembly_test(bug42562, dis_bug42562) 553 554 def test_bug_45757(self): 555 # Extended arg followed by NOP 556 self.do_disassembly_test(code_bug_45757, dis_bug_45757) 557 558 def test_big_linenos(self): 559 def func(count): 560 namespace = {} 561 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"]) 562 exec(func, namespace) 563 return namespace['foo'] 564 565 # Test all small ranges 566 for i in range(1, 300): 567 expected = _BIG_LINENO_FORMAT % (i + 2) 568 self.do_disassembly_test(func(i), expected) 569 570 # Test some larger ranges too 571 for i in range(300, 1000, 10): 572 expected = _BIG_LINENO_FORMAT % (i + 2) 573 self.do_disassembly_test(func(i), expected) 574 575 for i in range(1000, 5000, 10): 576 expected = _BIG_LINENO_FORMAT2 % (i + 2) 577 self.do_disassembly_test(func(i), expected) 578 579 from test import dis_module 580 self.do_disassembly_test(dis_module, dis_module_expected_results) 581 582 def test_big_offsets(self): 583 def func(count): 584 namespace = {} 585 func = "def foo(x):\n " + ";".join(["x = x + 1"] * count) + "\n return x" 586 exec(func, namespace) 587 return namespace['foo'] 588 589 def expected(count, w): 590 s = ['''\ 591 %*d LOAD_FAST 0 (x) 592 %*d LOAD_CONST 1 (1) 593 %*d BINARY_ADD 594 %*d STORE_FAST 0 (x) 595''' % (w, 8*i, w, 8*i + 2, w, 8*i + 4, w, 8*i + 6) 596 for i in range(count)] 597 s += ['''\ 598 599 3 %*d LOAD_FAST 0 (x) 600 %*d RETURN_VALUE 601''' % (w, 8*count, w, 8*count + 2)] 602 s[0] = ' 2' + s[0][3:] 603 return ''.join(s) 604 605 for i in range(1, 5): 606 self.do_disassembly_test(func(i), expected(i, 4)) 607 self.do_disassembly_test(func(1249), expected(1249, 4)) 608 self.do_disassembly_test(func(1250), expected(1250, 5)) 609 610 def test_disassemble_str(self): 611 self.do_disassembly_test(expr_str, dis_expr_str) 612 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str) 613 self.do_disassembly_test(annot_stmt_str, dis_annot_stmt_str) 614 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str) 615 616 def test_disassemble_bytes(self): 617 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code) 618 619 def test_disassemble_class(self): 620 self.do_disassembly_test(_C, dis_c) 621 622 def test_disassemble_instance_method(self): 623 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method) 624 625 def test_disassemble_instance_method_bytes(self): 626 method_bytecode = _C(1).__init__.__code__.co_code 627 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes) 628 629 def test_disassemble_static_method(self): 630 self.do_disassembly_test(_C.sm, dis_c_static_method) 631 632 def test_disassemble_class_method(self): 633 self.do_disassembly_test(_C.cm, dis_c_class_method) 634 635 def test_disassemble_generator(self): 636 gen_func_disas = self.get_disassembly(_g) # Generator function 637 gen_disas = self.get_disassembly(_g(1)) # Generator iterator 638 self.assertEqual(gen_disas, gen_func_disas) 639 640 def test_disassemble_async_generator(self): 641 agen_func_disas = self.get_disassembly(_ag) # Async generator function 642 agen_disas = self.get_disassembly(_ag(1)) # Async generator iterator 643 self.assertEqual(agen_disas, agen_func_disas) 644 645 def test_disassemble_coroutine(self): 646 coro_func_disas = self.get_disassembly(_co) # Coroutine function 647 coro = _co(1) # Coroutine object 648 coro.close() # Avoid a RuntimeWarning (never awaited) 649 coro_disas = self.get_disassembly(coro) 650 self.assertEqual(coro_disas, coro_func_disas) 651 652 def test_disassemble_fstring(self): 653 self.do_disassembly_test(_fstring, dis_fstring) 654 655 def test_disassemble_try_finally(self): 656 self.do_disassembly_test(_tryfinally, dis_tryfinally) 657 self.do_disassembly_test(_tryfinallyconst, dis_tryfinallyconst) 658 659 def test_dis_none(self): 660 try: 661 del sys.last_traceback 662 except AttributeError: 663 pass 664 self.assertRaises(RuntimeError, dis.dis, None) 665 666 def test_dis_traceback(self): 667 try: 668 del sys.last_traceback 669 except AttributeError: 670 pass 671 672 try: 673 1/0 674 except Exception as e: 675 tb = e.__traceback__ 676 sys.last_traceback = tb 677 678 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti) 679 self.do_disassembly_test(None, tb_dis) 680 681 def test_dis_object(self): 682 self.assertRaises(TypeError, dis.dis, object()) 683 684 def test_disassemble_recursive(self): 685 def check(expected, **kwargs): 686 dis = self.get_disassembly(_h, **kwargs) 687 dis = self.strip_addresses(dis) 688 self.assertEqual(dis, expected) 689 690 check(dis_nested_0, depth=0) 691 check(dis_nested_1, depth=1) 692 check(dis_nested_2, depth=2) 693 check(dis_nested_2, depth=3) 694 check(dis_nested_2, depth=None) 695 check(dis_nested_2) 696 697 698class DisWithFileTests(DisTests): 699 700 # Run the tests again, using the file arg instead of print 701 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): 702 output = io.StringIO() 703 if wrapper: 704 dis.dis(func, file=output, **kwargs) 705 else: 706 dis.disassemble(func, lasti, file=output, **kwargs) 707 return output.getvalue() 708 709 710if sys.flags.optimize: 711 code_info_consts = "0: None" 712else: 713 code_info_consts = "0: 'Formatted details of methods, functions, or code.'" 714 715code_info_code_info = f"""\ 716Name: code_info 717Filename: (.*) 718Argument count: 1 719Positional-only arguments: 0 720Kw-only arguments: 0 721Number of locals: 1 722Stack size: 3 723Flags: OPTIMIZED, NEWLOCALS, NOFREE 724Constants: 725 {code_info_consts} 726Names: 727 0: _format_code_info 728 1: _get_code_object 729Variable names: 730 0: x""" 731 732 733@staticmethod 734def tricky(a, b, /, x, y, z=True, *args, c, d, e=[], **kwds): 735 def f(c=c): 736 print(a, b, x, y, z, c, d, e, f) 737 yield a, b, x, y, z, c, d, e, f 738 739code_info_tricky = """\ 740Name: tricky 741Filename: (.*) 742Argument count: 5 743Positional-only arguments: 2 744Kw-only arguments: 3 745Number of locals: 10 746Stack size: 9 747Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR 748Constants: 749 0: None 750 1: <code object f at (.*), file "(.*)", line (.*)> 751 2: 'tricky.<locals>.f' 752Variable names: 753 0: a 754 1: b 755 2: x 756 3: y 757 4: z 758 5: c 759 6: d 760 7: e 761 8: args 762 9: kwds 763Cell variables: 764 0: [abedfxyz] 765 1: [abedfxyz] 766 2: [abedfxyz] 767 3: [abedfxyz] 768 4: [abedfxyz] 769 5: [abedfxyz]""" 770# NOTE: the order of the cell variables above depends on dictionary order! 771 772co_tricky_nested_f = tricky.__func__.__code__.co_consts[1] 773 774code_info_tricky_nested_f = """\ 775Filename: (.*) 776Argument count: 1 777Positional-only arguments: 0 778Kw-only arguments: 0 779Number of locals: 1 780Stack size: 10 781Flags: OPTIMIZED, NEWLOCALS, NESTED 782Constants: 783 0: None 784Names: 785 0: print 786Variable names: 787 0: c 788Free variables: 789 0: [abedfxyz] 790 1: [abedfxyz] 791 2: [abedfxyz] 792 3: [abedfxyz] 793 4: [abedfxyz] 794 5: [abedfxyz]""" 795 796code_info_expr_str = """\ 797Name: <module> 798Filename: <disassembly> 799Argument count: 0 800Positional-only arguments: 0 801Kw-only arguments: 0 802Number of locals: 0 803Stack size: 2 804Flags: NOFREE 805Constants: 806 0: 1 807Names: 808 0: x""" 809 810code_info_simple_stmt_str = """\ 811Name: <module> 812Filename: <disassembly> 813Argument count: 0 814Positional-only arguments: 0 815Kw-only arguments: 0 816Number of locals: 0 817Stack size: 2 818Flags: NOFREE 819Constants: 820 0: 1 821 1: None 822Names: 823 0: x""" 824 825code_info_compound_stmt_str = """\ 826Name: <module> 827Filename: <disassembly> 828Argument count: 0 829Positional-only arguments: 0 830Kw-only arguments: 0 831Number of locals: 0 832Stack size: 2 833Flags: NOFREE 834Constants: 835 0: 0 836 1: 1 837Names: 838 0: x""" 839 840 841async def async_def(): 842 await 1 843 async for a in b: pass 844 async with c as d: pass 845 846code_info_async_def = """\ 847Name: async_def 848Filename: (.*) 849Argument count: 0 850Positional-only arguments: 0 851Kw-only arguments: 0 852Number of locals: 2 853Stack size: 9 854Flags: OPTIMIZED, NEWLOCALS, NOFREE, COROUTINE 855Constants: 856 0: None 857 1: 1 858Names: 859 0: b 860 1: c 861Variable names: 862 0: a 863 1: d""" 864 865class CodeInfoTests(unittest.TestCase): 866 test_pairs = [ 867 (dis.code_info, code_info_code_info), 868 (tricky, code_info_tricky), 869 (co_tricky_nested_f, code_info_tricky_nested_f), 870 (expr_str, code_info_expr_str), 871 (simple_stmt_str, code_info_simple_stmt_str), 872 (compound_stmt_str, code_info_compound_stmt_str), 873 (async_def, code_info_async_def) 874 ] 875 876 def test_code_info(self): 877 self.maxDiff = 1000 878 for x, expected in self.test_pairs: 879 self.assertRegex(dis.code_info(x), expected) 880 881 def test_show_code(self): 882 self.maxDiff = 1000 883 for x, expected in self.test_pairs: 884 with captured_stdout() as output: 885 dis.show_code(x) 886 self.assertRegex(output.getvalue(), expected+"\n") 887 output = io.StringIO() 888 dis.show_code(x, file=output) 889 self.assertRegex(output.getvalue(), expected) 890 891 def test_code_info_object(self): 892 self.assertRaises(TypeError, dis.code_info, object()) 893 894 def test_pretty_flags_no_flags(self): 895 self.assertEqual(dis.pretty_flags(0), '0x0') 896 897 898# Fodder for instruction introspection tests 899# Editing any of these may require recalculating the expected output 900def outer(a=1, b=2): 901 def f(c=3, d=4): 902 def inner(e=5, f=6): 903 print(a, b, c, d, e, f) 904 print(a, b, c, d) 905 return inner 906 print(a, b, '', 1, [], {}, "Hello world!") 907 return f 908 909def jumpy(): 910 # This won't actually run (but that's OK, we only disassemble it) 911 for i in range(10): 912 print(i) 913 if i < 4: 914 continue 915 if i > 6: 916 break 917 else: 918 print("I can haz else clause?") 919 while i: 920 print(i) 921 i -= 1 922 if i > 6: 923 continue 924 if i < 4: 925 break 926 else: 927 print("Who let lolcatz into this test suite?") 928 try: 929 1 / 0 930 except ZeroDivisionError: 931 print("Here we go, here we go, here we go...") 932 else: 933 with i as dodgy: 934 print("Never reach this") 935 finally: 936 print("OK, now we're done") 937 938# End fodder for opinfo generation tests 939expected_outer_line = 1 940_line_offset = outer.__code__.co_firstlineno - 1 941code_object_f = outer.__code__.co_consts[3] 942expected_f_line = code_object_f.co_firstlineno - _line_offset 943code_object_inner = code_object_f.co_consts[3] 944expected_inner_line = code_object_inner.co_firstlineno - _line_offset 945expected_jumpy_line = 1 946 947# The following lines are useful to regenerate the expected results after 948# either the fodder is modified or the bytecode generation changes 949# After regeneration, update the references to code_object_f and 950# code_object_inner before rerunning the tests 951 952#_instructions = dis.get_instructions(outer, first_line=expected_outer_line) 953#print('expected_opinfo_outer = [\n ', 954 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 955#_instructions = dis.get_instructions(outer(), first_line=expected_f_line) 956#print('expected_opinfo_f = [\n ', 957 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 958#_instructions = dis.get_instructions(outer()(), first_line=expected_inner_line) 959#print('expected_opinfo_inner = [\n ', 960 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 961#_instructions = dis.get_instructions(jumpy, first_line=expected_jumpy_line) 962#print('expected_opinfo_jumpy = [\n ', 963 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 964 965 966Instruction = dis.Instruction 967expected_opinfo_outer = [ 968 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval=(3, 4), argrepr='(3, 4)', offset=0, starts_line=2, is_jump_target=False), 969 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 970 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 971 Instruction(opname='BUILD_TUPLE', opcode=102, arg=2, argval=2, argrepr='', offset=6, starts_line=None, is_jump_target=False), 972 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_f, argrepr=repr(code_object_f), offset=8, starts_line=None, is_jump_target=False), 973 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f', argrepr="'outer.<locals>.f'", offset=10, starts_line=None, is_jump_target=False), 974 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=12, starts_line=None, is_jump_target=False), 975 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='f', argrepr='f', offset=14, starts_line=None, is_jump_target=False), 976 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=16, starts_line=7, is_jump_target=False), 977 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=18, starts_line=None, is_jump_target=False), 978 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=20, starts_line=None, is_jump_target=False), 979 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval='', argrepr="''", offset=22, starts_line=None, is_jump_target=False), 980 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval=1, argrepr='1', offset=24, starts_line=None, is_jump_target=False), 981 Instruction(opname='BUILD_LIST', opcode=103, arg=0, argval=0, argrepr='', offset=26, starts_line=None, is_jump_target=False), 982 Instruction(opname='BUILD_MAP', opcode=105, arg=0, argval=0, argrepr='', offset=28, starts_line=None, is_jump_target=False), 983 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval='Hello world!', argrepr="'Hello world!'", offset=30, starts_line=None, is_jump_target=False), 984 Instruction(opname='CALL_FUNCTION', opcode=131, arg=7, argval=7, argrepr='', offset=32, starts_line=None, is_jump_target=False), 985 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=34, starts_line=None, is_jump_target=False), 986 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='f', argrepr='f', offset=36, starts_line=8, is_jump_target=False), 987 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=38, starts_line=None, is_jump_target=False), 988] 989 990expected_opinfo_f = [ 991 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=(5, 6), argrepr='(5, 6)', offset=0, starts_line=3, is_jump_target=False), 992 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=2, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 993 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=3, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 994 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), 995 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), 996 Instruction(opname='BUILD_TUPLE', opcode=102, arg=4, argval=4, argrepr='', offset=10, starts_line=None, is_jump_target=False), 997 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_inner, argrepr=repr(code_object_inner), offset=12, starts_line=None, is_jump_target=False), 998 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f.<locals>.inner', argrepr="'outer.<locals>.f.<locals>.inner'", offset=14, starts_line=None, is_jump_target=False), 999 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=16, starts_line=None, is_jump_target=False), 1000 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='inner', argrepr='inner', offset=18, starts_line=None, is_jump_target=False), 1001 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=20, starts_line=5, is_jump_target=False), 1002 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='a', argrepr='a', offset=22, starts_line=None, is_jump_target=False), 1003 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='b', argrepr='b', offset=24, starts_line=None, is_jump_target=False), 1004 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='c', argrepr='c', offset=26, starts_line=None, is_jump_target=False), 1005 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='d', argrepr='d', offset=28, starts_line=None, is_jump_target=False), 1006 Instruction(opname='CALL_FUNCTION', opcode=131, arg=4, argval=4, argrepr='', offset=30, starts_line=None, is_jump_target=False), 1007 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=32, starts_line=None, is_jump_target=False), 1008 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='inner', argrepr='inner', offset=34, starts_line=6, is_jump_target=False), 1009 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=36, starts_line=None, is_jump_target=False), 1010] 1011 1012expected_opinfo_inner = [ 1013 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=0, starts_line=4, is_jump_target=False), 1014 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 1015 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 1016 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), 1017 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), 1018 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='e', argrepr='e', offset=10, starts_line=None, is_jump_target=False), 1019 Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='f', argrepr='f', offset=12, starts_line=None, is_jump_target=False), 1020 Instruction(opname='CALL_FUNCTION', opcode=131, arg=6, argval=6, argrepr='', offset=14, starts_line=None, is_jump_target=False), 1021 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False), 1022 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=18, starts_line=None, is_jump_target=False), 1023 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=20, starts_line=None, is_jump_target=False), 1024] 1025 1026expected_opinfo_jumpy = [ 1027 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='range', argrepr='range', offset=0, starts_line=3, is_jump_target=False), 1028 Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval=10, argrepr='10', offset=2, starts_line=None, is_jump_target=False), 1029 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=4, starts_line=None, is_jump_target=False), 1030 Instruction(opname='GET_ITER', opcode=68, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False), 1031 Instruction(opname='FOR_ITER', opcode=93, arg=17, argval=44, argrepr='to 44', offset=8, starts_line=None, is_jump_target=True), 1032 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=10, starts_line=None, is_jump_target=False), 1033 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=12, starts_line=4, is_jump_target=False), 1034 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=14, starts_line=None, is_jump_target=False), 1035 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=16, starts_line=None, is_jump_target=False), 1036 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=18, starts_line=None, is_jump_target=False), 1037 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=20, starts_line=5, is_jump_target=False), 1038 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=22, starts_line=None, is_jump_target=False), 1039 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=24, starts_line=None, is_jump_target=False), 1040 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=15, argval=30, argrepr='to 30', offset=26, starts_line=None, is_jump_target=False), 1041 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=4, argval=8, argrepr='to 8', offset=28, starts_line=6, is_jump_target=False), 1042 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=30, starts_line=7, is_jump_target=True), 1043 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=32, starts_line=None, is_jump_target=False), 1044 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=34, starts_line=None, is_jump_target=False), 1045 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=21, argval=42, argrepr='to 42', offset=36, starts_line=None, is_jump_target=False), 1046 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=38, starts_line=8, is_jump_target=False), 1047 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=26, argval=52, argrepr='to 52', offset=40, starts_line=None, is_jump_target=False), 1048 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=4, argval=8, argrepr='to 8', offset=42, starts_line=7, is_jump_target=True), 1049 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=44, starts_line=10, is_jump_target=True), 1050 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=46, starts_line=None, is_jump_target=False), 1051 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=48, starts_line=None, is_jump_target=False), 1052 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=50, starts_line=None, is_jump_target=False), 1053 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=52, starts_line=11, is_jump_target=True), 1054 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=48, argval=96, argrepr='to 96', offset=54, starts_line=None, is_jump_target=False), 1055 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=56, starts_line=12, is_jump_target=True), 1056 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=58, starts_line=None, is_jump_target=False), 1057 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=60, starts_line=None, is_jump_target=False), 1058 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=62, starts_line=None, is_jump_target=False), 1059 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=64, starts_line=13, is_jump_target=False), 1060 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=66, starts_line=None, is_jump_target=False), 1061 Instruction(opname='INPLACE_SUBTRACT', opcode=56, arg=None, argval=None, argrepr='', offset=68, starts_line=None, is_jump_target=False), 1062 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=70, starts_line=None, is_jump_target=False), 1063 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=72, starts_line=14, is_jump_target=False), 1064 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=74, starts_line=None, is_jump_target=False), 1065 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=76, starts_line=None, is_jump_target=False), 1066 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=41, argval=82, argrepr='to 82', offset=78, starts_line=None, is_jump_target=False), 1067 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=26, argval=52, argrepr='to 52', offset=80, starts_line=15, is_jump_target=False), 1068 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=82, starts_line=16, is_jump_target=True), 1069 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=84, starts_line=None, is_jump_target=False), 1070 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=86, starts_line=None, is_jump_target=False), 1071 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=46, argval=92, argrepr='to 92', offset=88, starts_line=None, is_jump_target=False), 1072 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=52, argval=104, argrepr='to 104', offset=90, starts_line=17, is_jump_target=False), 1073 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=92, starts_line=11, is_jump_target=True), 1074 Instruction(opname='POP_JUMP_IF_TRUE', opcode=115, arg=28, argval=56, argrepr='to 56', offset=94, starts_line=None, is_jump_target=False), 1075 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=96, starts_line=19, is_jump_target=True), 1076 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=98, starts_line=None, is_jump_target=False), 1077 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=100, starts_line=None, is_jump_target=False), 1078 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=102, starts_line=None, is_jump_target=False), 1079 Instruction(opname='SETUP_FINALLY', opcode=122, arg=63, argval=232, argrepr='to 232', offset=104, starts_line=20, is_jump_target=True), 1080 Instruction(opname='SETUP_FINALLY', opcode=122, arg=6, argval=120, argrepr='to 120', offset=106, starts_line=None, is_jump_target=False), 1081 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=108, starts_line=21, is_jump_target=False), 1082 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval=0, argrepr='0', offset=110, starts_line=None, is_jump_target=False), 1083 Instruction(opname='BINARY_TRUE_DIVIDE', opcode=27, arg=None, argval=None, argrepr='', offset=112, starts_line=None, is_jump_target=False), 1084 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=114, starts_line=None, is_jump_target=False), 1085 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=116, starts_line=None, is_jump_target=False), 1086 Instruction(opname='JUMP_FORWARD', opcode=110, arg=13, argval=146, argrepr='to 146', offset=118, starts_line=None, is_jump_target=False), 1087 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=120, starts_line=22, is_jump_target=True), 1088 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=2, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=122, starts_line=None, is_jump_target=False), 1089 Instruction(opname='JUMP_IF_NOT_EXC_MATCH', opcode=121, arg=72, argval=144, argrepr='to 144', offset=124, starts_line=None, is_jump_target=False), 1090 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=126, starts_line=None, is_jump_target=False), 1091 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=128, starts_line=None, is_jump_target=False), 1092 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=130, starts_line=None, is_jump_target=False), 1093 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=132, starts_line=23, is_jump_target=False), 1094 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=134, starts_line=None, is_jump_target=False), 1095 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=136, starts_line=None, is_jump_target=False), 1096 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=138, starts_line=None, is_jump_target=False), 1097 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=140, starts_line=None, is_jump_target=False), 1098 Instruction(opname='JUMP_FORWARD', opcode=110, arg=30, argval=204, argrepr='to 204', offset=142, starts_line=None, is_jump_target=False), 1099 Instruction(opname='RERAISE', opcode=119, arg=0, argval=0, argrepr='', offset=144, starts_line=22, is_jump_target=True), 1100 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=146, starts_line=25, is_jump_target=True), 1101 Instruction(opname='SETUP_WITH', opcode=143, arg=12, argval=174, argrepr='to 174', offset=148, starts_line=None, is_jump_target=False), 1102 Instruction(opname='STORE_FAST', opcode=125, arg=1, argval='dodgy', argrepr='dodgy', offset=150, starts_line=None, is_jump_target=False), 1103 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=152, starts_line=26, is_jump_target=False), 1104 Instruction(opname='LOAD_CONST', opcode=100, arg=9, argval='Never reach this', argrepr="'Never reach this'", offset=154, starts_line=None, is_jump_target=False), 1105 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=156, starts_line=None, is_jump_target=False), 1106 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=158, starts_line=None, is_jump_target=False), 1107 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=160, starts_line=None, is_jump_target=False), 1108 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=162, starts_line=25, is_jump_target=False), 1109 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=164, starts_line=None, is_jump_target=False), 1110 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=166, starts_line=None, is_jump_target=False), 1111 Instruction(opname='CALL_FUNCTION', opcode=131, arg=3, argval=3, argrepr='', offset=168, starts_line=None, is_jump_target=False), 1112 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=170, starts_line=None, is_jump_target=False), 1113 Instruction(opname='JUMP_FORWARD', opcode=110, arg=22, argval=218, argrepr='to 218', offset=172, starts_line=None, is_jump_target=False), 1114 Instruction(opname='WITH_EXCEPT_START', opcode=49, arg=None, argval=None, argrepr='', offset=174, starts_line=None, is_jump_target=True), 1115 Instruction(opname='POP_JUMP_IF_TRUE', opcode=115, arg=90, argval=180, argrepr='to 180', offset=176, starts_line=None, is_jump_target=False), 1116 Instruction(opname='RERAISE', opcode=119, arg=1, argval=1, argrepr='', offset=178, starts_line=None, is_jump_target=False), 1117 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=180, starts_line=None, is_jump_target=True), 1118 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=182, starts_line=None, is_jump_target=False), 1119 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=184, starts_line=None, is_jump_target=False), 1120 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=186, starts_line=None, is_jump_target=False), 1121 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=188, starts_line=None, is_jump_target=False), 1122 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=190, starts_line=None, is_jump_target=False), 1123 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=192, starts_line=28, is_jump_target=False), 1124 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=194, starts_line=None, is_jump_target=False), 1125 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=196, starts_line=None, is_jump_target=False), 1126 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=198, starts_line=None, is_jump_target=False), 1127 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=200, starts_line=None, is_jump_target=False), 1128 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=202, starts_line=None, is_jump_target=False), 1129 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=204, starts_line=23, is_jump_target=True), 1130 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=206, starts_line=28, is_jump_target=False), 1131 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=208, starts_line=None, is_jump_target=False), 1132 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=210, starts_line=None, is_jump_target=False), 1133 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=212, starts_line=None, is_jump_target=False), 1134 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=214, starts_line=None, is_jump_target=False), 1135 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=216, starts_line=None, is_jump_target=False), 1136 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=218, starts_line=25, is_jump_target=True), 1137 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=220, starts_line=28, is_jump_target=False), 1138 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=222, starts_line=None, is_jump_target=False), 1139 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=224, starts_line=None, is_jump_target=False), 1140 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=226, starts_line=None, is_jump_target=False), 1141 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=228, starts_line=None, is_jump_target=False), 1142 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=230, starts_line=None, is_jump_target=False), 1143 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=232, starts_line=None, is_jump_target=True), 1144 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=234, starts_line=None, is_jump_target=False), 1145 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=236, starts_line=None, is_jump_target=False), 1146 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=238, starts_line=None, is_jump_target=False), 1147 Instruction(opname='RERAISE', opcode=119, arg=0, argval=0, argrepr='', offset=240, starts_line=None, is_jump_target=False), 1148] 1149 1150# One last piece of inspect fodder to check the default line number handling 1151def simple(): pass 1152expected_opinfo_simple = [ 1153 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=0, starts_line=simple.__code__.co_firstlineno, is_jump_target=False), 1154 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=2, starts_line=None, is_jump_target=False) 1155] 1156 1157 1158class InstructionTests(BytecodeTestCase): 1159 1160 def __init__(self, *args): 1161 super().__init__(*args) 1162 self.maxDiff = None 1163 1164 def test_default_first_line(self): 1165 actual = dis.get_instructions(simple) 1166 self.assertEqual(list(actual), expected_opinfo_simple) 1167 1168 def test_first_line_set_to_None(self): 1169 actual = dis.get_instructions(simple, first_line=None) 1170 self.assertEqual(list(actual), expected_opinfo_simple) 1171 1172 def test_outer(self): 1173 actual = dis.get_instructions(outer, first_line=expected_outer_line) 1174 self.assertEqual(list(actual), expected_opinfo_outer) 1175 1176 def test_nested(self): 1177 with captured_stdout(): 1178 f = outer() 1179 actual = dis.get_instructions(f, first_line=expected_f_line) 1180 self.assertEqual(list(actual), expected_opinfo_f) 1181 1182 def test_doubly_nested(self): 1183 with captured_stdout(): 1184 inner = outer()() 1185 actual = dis.get_instructions(inner, first_line=expected_inner_line) 1186 self.assertEqual(list(actual), expected_opinfo_inner) 1187 1188 def test_jumpy(self): 1189 actual = dis.get_instructions(jumpy, first_line=expected_jumpy_line) 1190 self.assertEqual(list(actual), expected_opinfo_jumpy) 1191 1192# get_instructions has its own tests above, so can rely on it to validate 1193# the object oriented API 1194class BytecodeTests(unittest.TestCase): 1195 1196 def test_instantiation(self): 1197 # Test with function, method, code string and code object 1198 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]: 1199 with self.subTest(obj=obj): 1200 b = dis.Bytecode(obj) 1201 self.assertIsInstance(b.codeobj, types.CodeType) 1202 1203 self.assertRaises(TypeError, dis.Bytecode, object()) 1204 1205 def test_iteration(self): 1206 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]: 1207 with self.subTest(obj=obj): 1208 via_object = list(dis.Bytecode(obj)) 1209 via_generator = list(dis.get_instructions(obj)) 1210 self.assertEqual(via_object, via_generator) 1211 1212 def test_explicit_first_line(self): 1213 actual = dis.Bytecode(outer, first_line=expected_outer_line) 1214 self.assertEqual(list(actual), expected_opinfo_outer) 1215 1216 def test_source_line_in_disassembly(self): 1217 # Use the line in the source code 1218 actual = dis.Bytecode(simple).dis() 1219 actual = actual.strip().partition(" ")[0] # extract the line no 1220 expected = str(simple.__code__.co_firstlineno) 1221 self.assertEqual(actual, expected) 1222 # Use an explicit first line number 1223 actual = dis.Bytecode(simple, first_line=350).dis() 1224 actual = actual.strip().partition(" ")[0] # extract the line no 1225 self.assertEqual(actual, "350") 1226 1227 def test_info(self): 1228 self.maxDiff = 1000 1229 for x, expected in CodeInfoTests.test_pairs: 1230 b = dis.Bytecode(x) 1231 self.assertRegex(b.info(), expected) 1232 1233 def test_disassembled(self): 1234 actual = dis.Bytecode(_f).dis() 1235 self.assertEqual(actual, dis_f) 1236 1237 def test_from_traceback(self): 1238 tb = get_tb() 1239 b = dis.Bytecode.from_traceback(tb) 1240 while tb.tb_next: tb = tb.tb_next 1241 1242 self.assertEqual(b.current_offset, tb.tb_lasti) 1243 1244 def test_from_traceback_dis(self): 1245 tb = get_tb() 1246 b = dis.Bytecode.from_traceback(tb) 1247 self.assertEqual(b.dis(), dis_traceback) 1248 1249 1250class TestBytecodeTestCase(BytecodeTestCase): 1251 def test_assert_not_in_with_op_not_in_bytecode(self): 1252 code = compile("a = 1", "<string>", "exec") 1253 self.assertInBytecode(code, "LOAD_CONST", 1) 1254 self.assertNotInBytecode(code, "LOAD_NAME") 1255 self.assertNotInBytecode(code, "LOAD_NAME", "a") 1256 1257 def test_assert_not_in_with_arg_not_in_bytecode(self): 1258 code = compile("a = 1", "<string>", "exec") 1259 self.assertInBytecode(code, "LOAD_CONST") 1260 self.assertInBytecode(code, "LOAD_CONST", 1) 1261 self.assertNotInBytecode(code, "LOAD_CONST", 2) 1262 1263 def test_assert_not_in_with_arg_in_bytecode(self): 1264 code = compile("a = 1", "<string>", "exec") 1265 with self.assertRaises(AssertionError): 1266 self.assertNotInBytecode(code, "LOAD_CONST", 1) 1267 1268 1269class TestDisTraceback(unittest.TestCase): 1270 def setUp(self) -> None: 1271 try: # We need to clean up existing tracebacks 1272 del sys.last_traceback 1273 except AttributeError: 1274 pass 1275 return super().setUp() 1276 1277 def get_disassembly(self, tb): 1278 output = io.StringIO() 1279 with contextlib.redirect_stdout(output): 1280 dis.distb(tb) 1281 return output.getvalue() 1282 1283 def test_distb_empty(self): 1284 with self.assertRaises(RuntimeError): 1285 dis.distb() 1286 1287 def test_distb_last_traceback(self): 1288 # We need to have an existing last traceback in `sys`: 1289 tb = get_tb() 1290 sys.last_traceback = tb 1291 1292 self.assertEqual(self.get_disassembly(None), dis_traceback) 1293 1294 def test_distb_explicit_arg(self): 1295 tb = get_tb() 1296 1297 self.assertEqual(self.get_disassembly(tb), dis_traceback) 1298 1299 1300class TestDisTracebackWithFile(TestDisTraceback): 1301 # Run the `distb` tests again, using the file arg instead of print 1302 def get_disassembly(self, tb): 1303 output = io.StringIO() 1304 with contextlib.redirect_stdout(output): 1305 dis.distb(tb, file=output) 1306 return output.getvalue() 1307 1308 1309if __name__ == "__main__": 1310 unittest.main() 1311