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