1 # Verify that gdb can pretty-print the various PyObject* types 2 # 3 # The code for testing gdb was adapted from similar work in Unladen Swallow's 4 # Lib/test/test_jit_gdb.py 5 6 import os 7 import re 8 import subprocess 9 import sys 10 import unittest 11 import sysconfig 12 13 from test.test_support import run_unittest, findfile 14 15 try: 16 gdb_version, _ = subprocess.Popen(["gdb", "--version"], 17 stdout=subprocess.PIPE).communicate() 18 except OSError: 19 # This is what "no gdb" looks like. There may, however, be other 20 # errors that manifest this way too. 21 raise unittest.SkipTest("Couldn't find gdb on the path") 22 gdb_version_number = re.search(r"^GNU gdb [^\d]*(\d+)\.", gdb_version) 23 if int(gdb_version_number.group(1)) < 7: 24 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding" 25 " Saw:\n" + gdb_version) 26 27 # Verify that "gdb" was built with the embedded python support enabled: 28 cmd = "--eval-command=python import sys; print sys.version_info" 29 p = subprocess.Popen(["gdb", "--batch", cmd], 30 stdout=subprocess.PIPE) 31 gdbpy_version, _ = p.communicate() 32 if gdbpy_version == '': 33 raise unittest.SkipTest("gdb not built with embedded python support") 34 35 def gdb_has_frame_select(): 36 # Does this build of gdb have gdb.Frame.select ? 37 cmd = "--eval-command=python print(dir(gdb.Frame))" 38 p = subprocess.Popen(["gdb", "--batch", cmd], 39 stdout=subprocess.PIPE) 40 stdout, _ = p.communicate() 41 m = re.match(r'.*\[(.*)\].*', stdout) 42 if not m: 43 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test") 44 gdb_frame_dir = m.group(1).split(', ') 45 return "'select'" in gdb_frame_dir 46 47 HAS_PYUP_PYDOWN = gdb_has_frame_select() 48 49 class DebuggerTests(unittest.TestCase): 50 51 """Test that the debugger can debug Python.""" 52 53 def run_gdb(self, *args): 54 """Runs gdb with the command line given by *args. 55 56 Returns its stdout, stderr 57 """ 58 out, err = subprocess.Popen( 59 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 60 ).communicate() 61 return out, err 62 63 def get_stack_trace(self, source=None, script=None, 64 breakpoint='PyObject_Print', 65 cmds_after_breakpoint=None, 66 import_site=False): 67 ''' 68 Run 'python -c SOURCE' under gdb with a breakpoint. 69 70 Support injecting commands after the breakpoint is reached 71 72 Returns the stdout from gdb 73 74 cmds_after_breakpoint: if provided, a list of strings: gdb commands 75 ''' 76 # We use "set breakpoint pending yes" to avoid blocking with a: 77 # Function "foo" not defined. 78 # Make breakpoint pending on future shared library load? (y or [n]) 79 # error, which typically happens python is dynamically linked (the 80 # breakpoints of interest are to be found in the shared library) 81 # When this happens, we still get: 82 # Function "PyObject_Print" not defined. 83 # emitted to stderr each time, alas. 84 85 # Initially I had "--eval-command=continue" here, but removed it to 86 # avoid repeated print breakpoints when traversing hierarchical data 87 # structures 88 89 # Generate a list of commands in gdb's language: 90 commands = ['set breakpoint pending yes', 91 'break %s' % breakpoint, 92 'run'] 93 if cmds_after_breakpoint: 94 commands += cmds_after_breakpoint 95 else: 96 commands += ['backtrace'] 97 98 # print commands 99 100 # Use "commands" to generate the arguments with which to invoke "gdb": 101 args = ["gdb", "--batch"] 102 args += ['--eval-command=%s' % cmd for cmd in commands] 103 args += ["--args", 104 sys.executable] 105 106 if not import_site: 107 # -S suppresses the default 'import site' 108 args += ["-S"] 109 110 if source: 111 args += ["-c", source] 112 elif script: 113 args += [script] 114 115 # print args 116 # print ' '.join(args) 117 118 # Use "args" to invoke gdb, capturing stdout, stderr: 119 out, err = self.run_gdb(*args) 120 121 # Ignore some noise on stderr due to the pending breakpoint: 122 err = err.replace('Function "%s" not defined.\n' % breakpoint, '') 123 # Ignore some other noise on stderr (http://bugs.python.org/issue8600) 124 err = err.replace("warning: Unable to find libthread_db matching" 125 " inferior's thread library, thread debugging will" 126 " not be available.\n", 127 '') 128 err = err.replace("warning: Cannot initialize thread debugging" 129 " library: Debugger service failed\n", 130 '') 131 132 # Ensure no unexpected error messages: 133 self.assertEqual(err, '') 134 135 return out 136 137 def get_gdb_repr(self, source, 138 cmds_after_breakpoint=None, 139 import_site=False): 140 # Given an input python source representation of data, 141 # run "python -c'print DATA'" under gdb with a breakpoint on 142 # PyObject_Print and scrape out gdb's representation of the "op" 143 # parameter, and verify that the gdb displays the same string 144 # 145 # For a nested structure, the first time we hit the breakpoint will 146 # give us the top-level structure 147 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print', 148 cmds_after_breakpoint=cmds_after_breakpoint, 149 import_site=import_site) 150 # gdb can insert additional '\n' and space characters in various places 151 # in its output, depending on the width of the terminal it's connected 152 # to (using its "wrap_here" function) 153 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*', 154 gdb_output, re.DOTALL) 155 if not m: 156 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output)) 157 return m.group(1), gdb_output 158 159 def assertEndsWith(self, actual, exp_end): 160 '''Ensure that the given "actual" string ends with "exp_end"''' 161 self.assertTrue(actual.endswith(exp_end), 162 msg='%r did not end with %r' % (actual, exp_end)) 163 164 def assertMultilineMatches(self, actual, pattern): 165 m = re.match(pattern, actual, re.DOTALL) 166 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern)) 167 168 def get_sample_script(self): 169 return findfile('gdb_sample.py') 170 171 class PrettyPrintTests(DebuggerTests): 172 def test_getting_backtrace(self): 173 gdb_output = self.get_stack_trace('print 42') 174 self.assertTrue('PyObject_Print' in gdb_output) 175 176 def assertGdbRepr(self, val, cmds_after_breakpoint=None): 177 # Ensure that gdb's rendering of the value in a debugged process 178 # matches repr(value) in this process: 179 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val), 180 cmds_after_breakpoint) 181 self.assertEqual(gdb_repr, repr(val), gdb_output) 182 183 def test_int(self): 184 'Verify the pretty-printing of various "int" values' 185 self.assertGdbRepr(42) 186 self.assertGdbRepr(0) 187 self.assertGdbRepr(-7) 188 self.assertGdbRepr(sys.maxint) 189 self.assertGdbRepr(-sys.maxint) 190 191 def test_long(self): 192 'Verify the pretty-printing of various "long" values' 193 self.assertGdbRepr(0L) 194 self.assertGdbRepr(1000000000000L) 195 self.assertGdbRepr(-1L) 196 self.assertGdbRepr(-1000000000000000L) 197 198 def test_singletons(self): 199 'Verify the pretty-printing of True, False and None' 200 self.assertGdbRepr(True) 201 self.assertGdbRepr(False) 202 self.assertGdbRepr(None) 203 204 def test_dicts(self): 205 'Verify the pretty-printing of dictionaries' 206 self.assertGdbRepr({}) 207 self.assertGdbRepr({'foo': 'bar'}) 208 self.assertGdbRepr({'foo': 'bar', 'douglas':42}) 209 210 def test_lists(self): 211 'Verify the pretty-printing of lists' 212 self.assertGdbRepr([]) 213 self.assertGdbRepr(range(5)) 214 215 def test_strings(self): 216 'Verify the pretty-printing of strings' 217 self.assertGdbRepr('') 218 self.assertGdbRepr('And now for something hopefully the same') 219 self.assertGdbRepr('string with embedded NUL here \0 and then some more text') 220 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80') 221 222 def test_tuples(self): 223 'Verify the pretty-printing of tuples' 224 self.assertGdbRepr(tuple()) 225 self.assertGdbRepr((1,)) 226 self.assertGdbRepr(('foo', 'bar', 'baz')) 227 228 def test_unicode(self): 229 'Verify the pretty-printing of unicode values' 230 # Test the empty unicode string: 231 self.assertGdbRepr(u'') 232 233 self.assertGdbRepr(u'hello world') 234 235 # Test printing a single character: 236 # U+2620 SKULL AND CROSSBONES 237 self.assertGdbRepr(u'\u2620') 238 239 # Test printing a Japanese unicode string 240 # (I believe this reads "mojibake", using 3 characters from the CJK 241 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE) 242 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051') 243 244 # Test a character outside the BMP: 245 # U+1D121 MUSICAL SYMBOL C CLEF 246 # This is: 247 # UTF-8: 0xF0 0x9D 0x84 0xA1 248 # UTF-16: 0xD834 0xDD21 249 # This will only work on wide-unicode builds: 250 self.assertGdbRepr(u"\U0001D121") 251 252 def test_sets(self): 253 'Verify the pretty-printing of sets' 254 self.assertGdbRepr(set()) 255 self.assertGdbRepr(set(['a', 'b'])) 256 self.assertGdbRepr(set([4, 5, 6])) 257 258 # Ensure that we handled sets containing the "dummy" key value, 259 # which happens on deletion: 260 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b']) 261 s.pop() 262 print s''') 263 self.assertEqual(gdb_repr, "set(['b'])") 264 265 def test_frozensets(self): 266 'Verify the pretty-printing of frozensets' 267 self.assertGdbRepr(frozenset()) 268 self.assertGdbRepr(frozenset(['a', 'b'])) 269 self.assertGdbRepr(frozenset([4, 5, 6])) 270 271 def test_exceptions(self): 272 # Test a RuntimeError 273 gdb_repr, gdb_output = self.get_gdb_repr(''' 274 try: 275 raise RuntimeError("I am an error") 276 except RuntimeError, e: 277 print e 278 ''') 279 self.assertEqual(gdb_repr, 280 "exceptions.RuntimeError('I am an error',)") 281 282 283 # Test division by zero: 284 gdb_repr, gdb_output = self.get_gdb_repr(''' 285 try: 286 a = 1 / 0 287 except ZeroDivisionError, e: 288 print e 289 ''') 290 self.assertEqual(gdb_repr, 291 "exceptions.ZeroDivisionError('integer division or modulo by zero',)") 292 293 def test_classic_class(self): 294 'Verify the pretty-printing of classic class instances' 295 gdb_repr, gdb_output = self.get_gdb_repr(''' 296 class Foo: 297 pass 298 foo = Foo() 299 foo.an_int = 42 300 print foo''') 301 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 302 self.assertTrue(m, 303 msg='Unexpected classic-class rendering %r' % gdb_repr) 304 305 def test_modern_class(self): 306 'Verify the pretty-printing of new-style class instances' 307 gdb_repr, gdb_output = self.get_gdb_repr(''' 308 class Foo(object): 309 pass 310 foo = Foo() 311 foo.an_int = 42 312 print foo''') 313 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 314 self.assertTrue(m, 315 msg='Unexpected new-style class rendering %r' % gdb_repr) 316 317 def test_subclassing_list(self): 318 'Verify the pretty-printing of an instance of a list subclass' 319 gdb_repr, gdb_output = self.get_gdb_repr(''' 320 class Foo(list): 321 pass 322 foo = Foo() 323 foo += [1, 2, 3] 324 foo.an_int = 42 325 print foo''') 326 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 327 self.assertTrue(m, 328 msg='Unexpected new-style class rendering %r' % gdb_repr) 329 330 def test_subclassing_tuple(self): 331 'Verify the pretty-printing of an instance of a tuple subclass' 332 # This should exercise the negative tp_dictoffset code in the 333 # new-style class support 334 gdb_repr, gdb_output = self.get_gdb_repr(''' 335 class Foo(tuple): 336 pass 337 foo = Foo((1, 2, 3)) 338 foo.an_int = 42 339 print foo''') 340 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 341 self.assertTrue(m, 342 msg='Unexpected new-style class rendering %r' % gdb_repr) 343 344 def assertSane(self, source, corruption, expvalue=None, exptype=None): 345 '''Run Python under gdb, corrupting variables in the inferior process 346 immediately before taking a backtrace. 347 348 Verify that the variable's representation is the expected failsafe 349 representation''' 350 if corruption: 351 cmds_after_breakpoint=[corruption, 'backtrace'] 352 else: 353 cmds_after_breakpoint=['backtrace'] 354 355 gdb_repr, gdb_output = \ 356 self.get_gdb_repr(source, 357 cmds_after_breakpoint=cmds_after_breakpoint) 358 359 if expvalue: 360 if gdb_repr == repr(expvalue): 361 # gdb managed to print the value in spite of the corruption; 362 # this is good (see http://bugs.python.org/issue8330) 363 return 364 365 if exptype: 366 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>' 367 else: 368 # Match anything for the type name; 0xDEADBEEF could point to 369 # something arbitrary (see http://bugs.python.org/issue8330) 370 pattern = '<.* at remote 0x[0-9a-f]+>' 371 372 m = re.match(pattern, gdb_repr) 373 if not m: 374 self.fail('Unexpected gdb representation: %r\n%s' % \ 375 (gdb_repr, gdb_output)) 376 377 def test_NULL_ptr(self): 378 'Ensure that a NULL PyObject* is handled gracefully' 379 gdb_repr, gdb_output = ( 380 self.get_gdb_repr('print 42', 381 cmds_after_breakpoint=['set variable op=0', 382 'backtrace']) 383 ) 384 385 self.assertEqual(gdb_repr, '0x0') 386 387 def test_NULL_ob_type(self): 388 'Ensure that a PyObject* with NULL ob_type is handled gracefully' 389 self.assertSane('print 42', 390 'set op->ob_type=0') 391 392 def test_corrupt_ob_type(self): 393 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully' 394 self.assertSane('print 42', 395 'set op->ob_type=0xDEADBEEF', 396 expvalue=42) 397 398 def test_corrupt_tp_flags(self): 399 'Ensure that a PyObject* with a type with corrupt tp_flags is handled' 400 self.assertSane('print 42', 401 'set op->ob_type->tp_flags=0x0', 402 expvalue=42) 403 404 def test_corrupt_tp_name(self): 405 'Ensure that a PyObject* with a type with corrupt tp_name is handled' 406 self.assertSane('print 42', 407 'set op->ob_type->tp_name=0xDEADBEEF', 408 expvalue=42) 409 410 def test_NULL_instance_dict(self): 411 'Ensure that a PyInstanceObject with with a NULL in_dict is handled' 412 self.assertSane(''' 413 class Foo: 414 pass 415 foo = Foo() 416 foo.an_int = 42 417 print foo''', 418 'set ((PyInstanceObject*)op)->in_dict = 0', 419 exptype='Foo') 420 421 def test_builtins_help(self): 422 'Ensure that the new-style class _Helper in site.py can be handled' 423 # (this was the issue causing tracebacks in 424 # http://bugs.python.org/issue8032#msg100537 ) 425 426 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True) 427 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr) 428 self.assertTrue(m, 429 msg='Unexpected rendering %r' % gdb_repr) 430 431 def test_selfreferential_list(self): 432 '''Ensure that a reference loop involving a list doesn't lead proxyval 433 into an infinite loop:''' 434 gdb_repr, gdb_output = \ 435 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a") 436 437 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]') 438 439 gdb_repr, gdb_output = \ 440 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a") 441 442 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]') 443 444 def test_selfreferential_dict(self): 445 '''Ensure that a reference loop involving a dict doesn't lead proxyval 446 into an infinite loop:''' 447 gdb_repr, gdb_output = \ 448 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a") 449 450 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}") 451 452 def test_selfreferential_old_style_instance(self): 453 gdb_repr, gdb_output = \ 454 self.get_gdb_repr(''' 455 class Foo: 456 pass 457 foo = Foo() 458 foo.an_attr = foo 459 print foo''') 460 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>', 461 gdb_repr), 462 'Unexpected gdb representation: %r\n%s' % \ 463 (gdb_repr, gdb_output)) 464 465 def test_selfreferential_new_style_instance(self): 466 gdb_repr, gdb_output = \ 467 self.get_gdb_repr(''' 468 class Foo(object): 469 pass 470 foo = Foo() 471 foo.an_attr = foo 472 print foo''') 473 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>', 474 gdb_repr), 475 'Unexpected gdb representation: %r\n%s' % \ 476 (gdb_repr, gdb_output)) 477 478 gdb_repr, gdb_output = \ 479 self.get_gdb_repr(''' 480 class Foo(object): 481 pass 482 a = Foo() 483 b = Foo() 484 a.an_attr = b 485 b.an_attr = a 486 print a''') 487 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>', 488 gdb_repr), 489 'Unexpected gdb representation: %r\n%s' % \ 490 (gdb_repr, gdb_output)) 491 492 def test_truncation(self): 493 'Verify that very long output is truncated' 494 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)') 495 self.assertEqual(gdb_repr, 496 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, " 497 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, " 498 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, " 499 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, " 500 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, " 501 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, " 502 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, " 503 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, " 504 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, " 505 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, " 506 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, " 507 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, " 508 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, " 509 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, " 510 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, " 511 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, " 512 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, " 513 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, " 514 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, " 515 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, " 516 "224, 225, 226...(truncated)") 517 self.assertEqual(len(gdb_repr), 518 1024 + len('...(truncated)')) 519 520 def test_builtin_function(self): 521 gdb_repr, gdb_output = self.get_gdb_repr('print len') 522 self.assertEqual(gdb_repr, '<built-in function len>') 523 524 def test_builtin_method(self): 525 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines') 526 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>', 527 gdb_repr), 528 'Unexpected gdb representation: %r\n%s' % \ 529 (gdb_repr, gdb_output)) 530 531 def test_frames(self): 532 gdb_output = self.get_stack_trace(''' 533 def foo(a, b, c): 534 pass 535 536 foo(3, 4, 5) 537 print foo.__code__''', 538 breakpoint='PyObject_Print', 539 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)'] 540 ) 541 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*', 542 gdb_output, 543 re.DOTALL), 544 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output)) 545 546 class PyListTests(DebuggerTests): 547 def assertListing(self, expected, actual): 548 self.assertEndsWith(actual, expected) 549 550 def test_basic_command(self): 551 'Verify that the "py-list" command works' 552 bt = self.get_stack_trace(script=self.get_sample_script(), 553 cmds_after_breakpoint=['py-list']) 554 555 self.assertListing(' 5 \n' 556 ' 6 def bar(a, b, c):\n' 557 ' 7 baz(a, b, c)\n' 558 ' 8 \n' 559 ' 9 def baz(*args):\n' 560 ' >10 print(42)\n' 561 ' 11 \n' 562 ' 12 foo(1, 2, 3)\n', 563 bt) 564 565 def test_one_abs_arg(self): 566 'Verify the "py-list" command with one absolute argument' 567 bt = self.get_stack_trace(script=self.get_sample_script(), 568 cmds_after_breakpoint=['py-list 9']) 569 570 self.assertListing(' 9 def baz(*args):\n' 571 ' >10 print(42)\n' 572 ' 11 \n' 573 ' 12 foo(1, 2, 3)\n', 574 bt) 575 576 def test_two_abs_args(self): 577 'Verify the "py-list" command with two absolute arguments' 578 bt = self.get_stack_trace(script=self.get_sample_script(), 579 cmds_after_breakpoint=['py-list 1,3']) 580 581 self.assertListing(' 1 # Sample script for use by test_gdb.py\n' 582 ' 2 \n' 583 ' 3 def foo(a, b, c):\n', 584 bt) 585 586 class StackNavigationTests(DebuggerTests): 587 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 588 def test_pyup_command(self): 589 'Verify that the "py-up" command works' 590 bt = self.get_stack_trace(script=self.get_sample_script(), 591 cmds_after_breakpoint=['py-up']) 592 self.assertMultilineMatches(bt, 593 r'''^.* 594 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 595 baz\(a, b, c\) 596 $''') 597 598 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 599 def test_down_at_bottom(self): 600 'Verify handling of "py-down" at the bottom of the stack' 601 bt = self.get_stack_trace(script=self.get_sample_script(), 602 cmds_after_breakpoint=['py-down']) 603 self.assertEndsWith(bt, 604 'Unable to find a newer python frame\n') 605 606 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 607 def test_up_at_top(self): 608 'Verify handling of "py-up" at the top of the stack' 609 bt = self.get_stack_trace(script=self.get_sample_script(), 610 cmds_after_breakpoint=['py-up'] * 4) 611 self.assertEndsWith(bt, 612 'Unable to find an older python frame\n') 613 614 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 615 def test_up_then_down(self): 616 'Verify "py-up" followed by "py-down"' 617 bt = self.get_stack_trace(script=self.get_sample_script(), 618 cmds_after_breakpoint=['py-up', 'py-down']) 619 self.assertMultilineMatches(bt, 620 r'''^.* 621 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 622 baz\(a, b, c\) 623 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\) 624 print\(42\) 625 $''') 626 627 class PyBtTests(DebuggerTests): 628 def test_basic_command(self): 629 'Verify that the "py-bt" command works' 630 bt = self.get_stack_trace(script=self.get_sample_script(), 631 cmds_after_breakpoint=['py-bt']) 632 self.assertMultilineMatches(bt, 633 r'''^.* 634 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 635 baz\(a, b, c\) 636 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\) 637 bar\(a, b, c\) 638 #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\) 639 foo\(1, 2, 3\) 640 ''') 641 642 class PyPrintTests(DebuggerTests): 643 def test_basic_command(self): 644 'Verify that the "py-print" command works' 645 bt = self.get_stack_trace(script=self.get_sample_script(), 646 cmds_after_breakpoint=['py-print args']) 647 self.assertMultilineMatches(bt, 648 r".*\nlocal 'args' = \(1, 2, 3\)\n.*") 649 650 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 651 def test_print_after_up(self): 652 bt = self.get_stack_trace(script=self.get_sample_script(), 653 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a']) 654 self.assertMultilineMatches(bt, 655 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*") 656 657 def test_printing_global(self): 658 bt = self.get_stack_trace(script=self.get_sample_script(), 659 cmds_after_breakpoint=['py-print __name__']) 660 self.assertMultilineMatches(bt, 661 r".*\nglobal '__name__' = '__main__'\n.*") 662 663 def test_printing_builtin(self): 664 bt = self.get_stack_trace(script=self.get_sample_script(), 665 cmds_after_breakpoint=['py-print len']) 666 self.assertMultilineMatches(bt, 667 r".*\nbuiltin 'len' = <built-in function len>\n.*") 668 669 class PyLocalsTests(DebuggerTests): 670 def test_basic_command(self): 671 bt = self.get_stack_trace(script=self.get_sample_script(), 672 cmds_after_breakpoint=['py-locals']) 673 self.assertMultilineMatches(bt, 674 r".*\nargs = \(1, 2, 3\)\n.*") 675 676 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 677 def test_locals_after_up(self): 678 bt = self.get_stack_trace(script=self.get_sample_script(), 679 cmds_after_breakpoint=['py-up', 'py-locals']) 680 self.assertMultilineMatches(bt, 681 r".*\na = 1\nb = 2\nc = 3\n.*") 682 683 def test_main(): 684 cflags = sysconfig.get_config_vars()['PY_CFLAGS'] 685 final_opt = "" 686 for opt in cflags.split(): 687 if opt.startswith('-O'): 688 final_opt = opt 689 if final_opt and final_opt != '-O0': 690 raise unittest.SkipTest("Python was built with compiler optimizations, " 691 "tests can't reliably succeed") 692 693 run_unittest(PrettyPrintTests, 694 PyListTests, 695 StackNavigationTests, 696 PyBtTests, 697 PyPrintTests, 698 PyLocalsTests 699 ) 700 701 if __name__ == "__main__": 702 test_main() 703