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