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