blob: 3c4162586029217e3b4d494957f55f9088e1e1cb [file] [log] [blame]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +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
Antoine Pitrou22db7352010-07-08 18:54:04 +000011import sysconfig
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000012
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000013from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000014
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(r"^GNU gdb [^\d]*(\d+)\.", gdb_version)
23if 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:
28cmd = "--eval-command=python import sys; print sys.version_info"
29p = subprocess.Popen(["gdb", "--batch", cmd],
30 stdout=subprocess.PIPE)
31gdbpy_version, _ = p.communicate()
32if gdbpy_version == '':
33 raise unittest.SkipTest("gdb not built with embedded python support")
34
Nick Coghlana0933122012-06-17 19:03:39 +100035# Verify that "gdb" can load our custom hooks
36p = subprocess.Popen(["gdb", "--batch", cmd,
37 "--args", sys.executable],
38 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
39__, gdbpy_errors = p.communicate()
40if b"auto-loading has been declined" in gdbpy_errors:
41 msg = "gdb security settings prevent use of custom hooks: %s"
42 raise unittest.SkipTest(msg % gdbpy_errors)
43
Victor Stinner99cff3f2011-12-19 13:59:58 +010044def python_is_optimized():
45 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
46 final_opt = ""
47 for opt in cflags.split():
48 if opt.startswith('-O'):
49 final_opt = opt
50 return (final_opt and final_opt != '-O0')
51
Victor Stinnera92e81b2010-04-20 22:28:31 +000052def gdb_has_frame_select():
53 # Does this build of gdb have gdb.Frame.select ?
54 cmd = "--eval-command=python print(dir(gdb.Frame))"
55 p = subprocess.Popen(["gdb", "--batch", cmd],
56 stdout=subprocess.PIPE)
57 stdout, _ = p.communicate()
58 m = re.match(r'.*\[(.*)\].*', stdout)
59 if not m:
60 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
61 gdb_frame_dir = m.group(1).split(', ')
62 return "'select'" in gdb_frame_dir
63
64HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000065
66class DebuggerTests(unittest.TestCase):
67
68 """Test that the debugger can debug Python."""
69
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050070 def run_gdb(self, *args, **env_vars):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000071 """Runs gdb with the command line given by *args.
72
73 Returns its stdout, stderr
74 """
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050075 if env_vars:
76 env = os.environ.copy()
77 env.update(env_vars)
78 else:
79 env = None
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000080 out, err = subprocess.Popen(
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050081 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000082 ).communicate()
83 return out, err
84
85 def get_stack_trace(self, source=None, script=None,
86 breakpoint='PyObject_Print',
87 cmds_after_breakpoint=None,
88 import_site=False):
89 '''
90 Run 'python -c SOURCE' under gdb with a breakpoint.
91
92 Support injecting commands after the breakpoint is reached
93
94 Returns the stdout from gdb
95
96 cmds_after_breakpoint: if provided, a list of strings: gdb commands
97 '''
98 # We use "set breakpoint pending yes" to avoid blocking with a:
99 # Function "foo" not defined.
100 # Make breakpoint pending on future shared library load? (y or [n])
101 # error, which typically happens python is dynamically linked (the
102 # breakpoints of interest are to be found in the shared library)
103 # When this happens, we still get:
104 # Function "PyObject_Print" not defined.
105 # emitted to stderr each time, alas.
106
107 # Initially I had "--eval-command=continue" here, but removed it to
108 # avoid repeated print breakpoints when traversing hierarchical data
109 # structures
110
111 # Generate a list of commands in gdb's language:
112 commands = ['set breakpoint pending yes',
113 'break %s' % breakpoint,
114 'run']
115 if cmds_after_breakpoint:
116 commands += cmds_after_breakpoint
117 else:
118 commands += ['backtrace']
119
120 # print commands
121
122 # Use "commands" to generate the arguments with which to invoke "gdb":
123 args = ["gdb", "--batch"]
124 args += ['--eval-command=%s' % cmd for cmd in commands]
125 args += ["--args",
126 sys.executable]
127
128 if not import_site:
129 # -S suppresses the default 'import site'
130 args += ["-S"]
131
132 if source:
133 args += ["-c", source]
134 elif script:
135 args += [script]
136
137 # print args
138 # print ' '.join(args)
139
140 # Use "args" to invoke gdb, capturing stdout, stderr:
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500141 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000142
143 # Ignore some noise on stderr due to the pending breakpoint:
144 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000145 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
146 err = err.replace("warning: Unable to find libthread_db matching"
147 " inferior's thread library, thread debugging will"
148 " not be available.\n",
149 '')
Jesus Cea6905de12011-03-16 01:19:49 +0100150 err = err.replace("warning: Cannot initialize thread debugging"
151 " library: Debugger service failed\n",
152 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000153
154 # Ensure no unexpected error messages:
Ezio Melotti2623a372010-11-21 13:34:58 +0000155 self.assertEqual(err, '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000156
157 return out
158
159 def get_gdb_repr(self, source,
160 cmds_after_breakpoint=None,
161 import_site=False):
162 # Given an input python source representation of data,
163 # run "python -c'print DATA'" under gdb with a breakpoint on
164 # PyObject_Print and scrape out gdb's representation of the "op"
165 # parameter, and verify that the gdb displays the same string
166 #
167 # For a nested structure, the first time we hit the breakpoint will
168 # give us the top-level structure
169 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
170 cmds_after_breakpoint=cmds_after_breakpoint,
171 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000172 # gdb can insert additional '\n' and space characters in various places
173 # in its output, depending on the width of the terminal it's connected
174 # to (using its "wrap_here" function)
175 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000176 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000177 if not m:
178 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000179 return m.group(1), gdb_output
180
181 def assertEndsWith(self, actual, exp_end):
182 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000183 self.assertTrue(actual.endswith(exp_end),
184 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000185
186 def assertMultilineMatches(self, actual, pattern):
187 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000188 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000189
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000190 def get_sample_script(self):
191 return findfile('gdb_sample.py')
192
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000193class PrettyPrintTests(DebuggerTests):
194 def test_getting_backtrace(self):
195 gdb_output = self.get_stack_trace('print 42')
196 self.assertTrue('PyObject_Print' in gdb_output)
197
198 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
199 # Ensure that gdb's rendering of the value in a debugged process
200 # matches repr(value) in this process:
201 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
202 cmds_after_breakpoint)
Ezio Melotti2623a372010-11-21 13:34:58 +0000203 self.assertEqual(gdb_repr, repr(val), gdb_output)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000204
205 def test_int(self):
206 'Verify the pretty-printing of various "int" values'
207 self.assertGdbRepr(42)
208 self.assertGdbRepr(0)
209 self.assertGdbRepr(-7)
210 self.assertGdbRepr(sys.maxint)
211 self.assertGdbRepr(-sys.maxint)
212
213 def test_long(self):
214 'Verify the pretty-printing of various "long" values'
215 self.assertGdbRepr(0L)
216 self.assertGdbRepr(1000000000000L)
217 self.assertGdbRepr(-1L)
218 self.assertGdbRepr(-1000000000000000L)
219
220 def test_singletons(self):
221 'Verify the pretty-printing of True, False and None'
222 self.assertGdbRepr(True)
223 self.assertGdbRepr(False)
224 self.assertGdbRepr(None)
225
226 def test_dicts(self):
227 'Verify the pretty-printing of dictionaries'
228 self.assertGdbRepr({})
229 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500230 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000231
232 def test_lists(self):
233 'Verify the pretty-printing of lists'
234 self.assertGdbRepr([])
235 self.assertGdbRepr(range(5))
236
237 def test_strings(self):
238 'Verify the pretty-printing of strings'
239 self.assertGdbRepr('')
240 self.assertGdbRepr('And now for something hopefully the same')
241 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
242 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
243
244 def test_tuples(self):
245 'Verify the pretty-printing of tuples'
246 self.assertGdbRepr(tuple())
247 self.assertGdbRepr((1,))
248 self.assertGdbRepr(('foo', 'bar', 'baz'))
249
250 def test_unicode(self):
251 'Verify the pretty-printing of unicode values'
252 # Test the empty unicode string:
253 self.assertGdbRepr(u'')
254
255 self.assertGdbRepr(u'hello world')
256
257 # Test printing a single character:
258 # U+2620 SKULL AND CROSSBONES
259 self.assertGdbRepr(u'\u2620')
260
261 # Test printing a Japanese unicode string
262 # (I believe this reads "mojibake", using 3 characters from the CJK
263 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
264 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
265
266 # Test a character outside the BMP:
267 # U+1D121 MUSICAL SYMBOL C CLEF
268 # This is:
269 # UTF-8: 0xF0 0x9D 0x84 0xA1
270 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000271 # This will only work on wide-unicode builds:
272 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000273
274 def test_sets(self):
275 'Verify the pretty-printing of sets'
276 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500277 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
278 self.assertTrue(rep.startswith("set(["))
279 self.assertTrue(rep.endswith("])"))
280 self.assertEqual(eval(rep), {'a', 'b'})
281 rep = self.get_gdb_repr("print set([4, 5])")[0]
282 self.assertTrue(rep.startswith("set(["))
283 self.assertTrue(rep.endswith("])"))
284 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000285
286 # Ensure that we handled sets containing the "dummy" key value,
287 # which happens on deletion:
288 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
289s.pop()
290print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000291 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000292
293 def test_frozensets(self):
294 'Verify the pretty-printing of frozensets'
295 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500296 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
297 self.assertTrue(rep.startswith("frozenset(["))
298 self.assertTrue(rep.endswith("])"))
299 self.assertEqual(eval(rep), {'a', 'b'})
300 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
301 self.assertTrue(rep.startswith("frozenset(["))
302 self.assertTrue(rep.endswith("])"))
303 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000304
305 def test_exceptions(self):
306 # Test a RuntimeError
307 gdb_repr, gdb_output = self.get_gdb_repr('''
308try:
309 raise RuntimeError("I am an error")
310except RuntimeError, e:
311 print e
312''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000313 self.assertEqual(gdb_repr,
314 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000315
316
317 # Test division by zero:
318 gdb_repr, gdb_output = self.get_gdb_repr('''
319try:
320 a = 1 / 0
321except ZeroDivisionError, e:
322 print e
323''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000324 self.assertEqual(gdb_repr,
325 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000326
327 def test_classic_class(self):
328 'Verify the pretty-printing of classic class instances'
329 gdb_repr, gdb_output = self.get_gdb_repr('''
330class Foo:
331 pass
332foo = Foo()
333foo.an_int = 42
334print foo''')
335 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
336 self.assertTrue(m,
337 msg='Unexpected classic-class rendering %r' % gdb_repr)
338
339 def test_modern_class(self):
340 'Verify the pretty-printing of new-style class instances'
341 gdb_repr, gdb_output = self.get_gdb_repr('''
342class Foo(object):
343 pass
344foo = Foo()
345foo.an_int = 42
346print foo''')
347 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
348 self.assertTrue(m,
349 msg='Unexpected new-style class rendering %r' % gdb_repr)
350
351 def test_subclassing_list(self):
352 'Verify the pretty-printing of an instance of a list subclass'
353 gdb_repr, gdb_output = self.get_gdb_repr('''
354class Foo(list):
355 pass
356foo = Foo()
357foo += [1, 2, 3]
358foo.an_int = 42
359print foo''')
360 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
361 self.assertTrue(m,
362 msg='Unexpected new-style class rendering %r' % gdb_repr)
363
364 def test_subclassing_tuple(self):
365 'Verify the pretty-printing of an instance of a tuple subclass'
366 # This should exercise the negative tp_dictoffset code in the
367 # new-style class support
368 gdb_repr, gdb_output = self.get_gdb_repr('''
369class Foo(tuple):
370 pass
371foo = Foo((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
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000378 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000379 '''Run Python under gdb, corrupting variables in the inferior process
380 immediately before taking a backtrace.
381
382 Verify that the variable's representation is the expected failsafe
383 representation'''
384 if corruption:
385 cmds_after_breakpoint=[corruption, 'backtrace']
386 else:
387 cmds_after_breakpoint=['backtrace']
388
389 gdb_repr, gdb_output = \
390 self.get_gdb_repr(source,
391 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000392
393 if expvalue:
394 if gdb_repr == repr(expvalue):
395 # gdb managed to print the value in spite of the corruption;
396 # this is good (see http://bugs.python.org/issue8330)
397 return
398
399 if exptype:
400 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
401 else:
402 # Match anything for the type name; 0xDEADBEEF could point to
403 # something arbitrary (see http://bugs.python.org/issue8330)
404 pattern = '<.* at remote 0x[0-9a-f]+>'
405
406 m = re.match(pattern, gdb_repr)
407 if not m:
408 self.fail('Unexpected gdb representation: %r\n%s' % \
409 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000410
411 def test_NULL_ptr(self):
412 'Ensure that a NULL PyObject* is handled gracefully'
413 gdb_repr, gdb_output = (
414 self.get_gdb_repr('print 42',
415 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000416 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000417 )
418
Ezio Melotti2623a372010-11-21 13:34:58 +0000419 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000420
421 def test_NULL_ob_type(self):
422 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
423 self.assertSane('print 42',
424 'set op->ob_type=0')
425
426 def test_corrupt_ob_type(self):
427 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
428 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000429 'set op->ob_type=0xDEADBEEF',
430 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000431
432 def test_corrupt_tp_flags(self):
433 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
434 self.assertSane('print 42',
435 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000436 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000437
438 def test_corrupt_tp_name(self):
439 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
440 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000441 'set op->ob_type->tp_name=0xDEADBEEF',
442 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000443
444 def test_NULL_instance_dict(self):
445 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
446 self.assertSane('''
447class Foo:
448 pass
449foo = Foo()
450foo.an_int = 42
451print foo''',
452 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000453 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000454
455 def test_builtins_help(self):
456 'Ensure that the new-style class _Helper in site.py can be handled'
457 # (this was the issue causing tracebacks in
458 # http://bugs.python.org/issue8032#msg100537 )
459
460 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
461 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
462 self.assertTrue(m,
463 msg='Unexpected rendering %r' % gdb_repr)
464
465 def test_selfreferential_list(self):
466 '''Ensure that a reference loop involving a list doesn't lead proxyval
467 into an infinite loop:'''
468 gdb_repr, gdb_output = \
469 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
470
Ezio Melotti2623a372010-11-21 13:34:58 +0000471 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000472
473 gdb_repr, gdb_output = \
474 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
475
Ezio Melotti2623a372010-11-21 13:34:58 +0000476 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000477
478 def test_selfreferential_dict(self):
479 '''Ensure that a reference loop involving a dict doesn't lead proxyval
480 into an infinite loop:'''
481 gdb_repr, gdb_output = \
482 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
483
Ezio Melotti2623a372010-11-21 13:34:58 +0000484 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000485
486 def test_selfreferential_old_style_instance(self):
487 gdb_repr, gdb_output = \
488 self.get_gdb_repr('''
489class Foo:
490 pass
491foo = Foo()
492foo.an_attr = foo
493print foo''')
494 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
495 gdb_repr),
496 'Unexpected gdb representation: %r\n%s' % \
497 (gdb_repr, gdb_output))
498
499 def test_selfreferential_new_style_instance(self):
500 gdb_repr, gdb_output = \
501 self.get_gdb_repr('''
502class Foo(object):
503 pass
504foo = Foo()
505foo.an_attr = foo
506print foo''')
507 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
508 gdb_repr),
509 'Unexpected gdb representation: %r\n%s' % \
510 (gdb_repr, gdb_output))
511
512 gdb_repr, gdb_output = \
513 self.get_gdb_repr('''
514class Foo(object):
515 pass
516a = Foo()
517b = Foo()
518a.an_attr = b
519b.an_attr = a
520print a''')
521 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
522 gdb_repr),
523 'Unexpected gdb representation: %r\n%s' % \
524 (gdb_repr, gdb_output))
525
526 def test_truncation(self):
527 'Verify that very long output is truncated'
528 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000529 self.assertEqual(gdb_repr,
530 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
531 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
532 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
533 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
534 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
535 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
536 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
537 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
538 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
539 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
540 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
541 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
542 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
543 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
544 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
545 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
546 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
547 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
548 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
549 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
550 "224, 225, 226...(truncated)")
551 self.assertEqual(len(gdb_repr),
552 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000553
554 def test_builtin_function(self):
555 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000556 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000557
558 def test_builtin_method(self):
559 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
560 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
561 gdb_repr),
562 'Unexpected gdb representation: %r\n%s' % \
563 (gdb_repr, gdb_output))
564
565 def test_frames(self):
566 gdb_output = self.get_stack_trace('''
567def foo(a, b, c):
568 pass
569
570foo(3, 4, 5)
571print foo.__code__''',
572 breakpoint='PyObject_Print',
573 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
574 )
R. David Murray0c080092010-04-05 16:28:49 +0000575 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
576 gdb_output,
577 re.DOTALL),
578 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000579
Victor Stinner99cff3f2011-12-19 13:59:58 +0100580@unittest.skipIf(python_is_optimized(),
581 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000582class PyListTests(DebuggerTests):
583 def assertListing(self, expected, actual):
584 self.assertEndsWith(actual, expected)
585
586 def test_basic_command(self):
587 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000588 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000589 cmds_after_breakpoint=['py-list'])
590
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000591 self.assertListing(' 5 \n'
592 ' 6 def bar(a, b, c):\n'
593 ' 7 baz(a, b, c)\n'
594 ' 8 \n'
595 ' 9 def baz(*args):\n'
596 ' >10 print(42)\n'
597 ' 11 \n'
598 ' 12 foo(1, 2, 3)\n',
599 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000600
601 def test_one_abs_arg(self):
602 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000603 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000604 cmds_after_breakpoint=['py-list 9'])
605
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000606 self.assertListing(' 9 def baz(*args):\n'
607 ' >10 print(42)\n'
608 ' 11 \n'
609 ' 12 foo(1, 2, 3)\n',
610 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000611
612 def test_two_abs_args(self):
613 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000614 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000615 cmds_after_breakpoint=['py-list 1,3'])
616
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000617 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
618 ' 2 \n'
619 ' 3 def foo(a, b, c):\n',
620 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000621
622class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000623 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100624 @unittest.skipIf(python_is_optimized(),
625 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000626 def test_pyup_command(self):
627 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000628 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000629 cmds_after_breakpoint=['py-up'])
630 self.assertMultilineMatches(bt,
631 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000632#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000633 baz\(a, b, c\)
634$''')
635
Victor Stinnera92e81b2010-04-20 22:28:31 +0000636 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000637 def test_down_at_bottom(self):
638 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000639 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000640 cmds_after_breakpoint=['py-down'])
641 self.assertEndsWith(bt,
642 'Unable to find a newer python frame\n')
643
Victor Stinnera92e81b2010-04-20 22:28:31 +0000644 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000645 def test_up_at_top(self):
646 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000647 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000648 cmds_after_breakpoint=['py-up'] * 4)
649 self.assertEndsWith(bt,
650 'Unable to find an older python frame\n')
651
Victor Stinnera92e81b2010-04-20 22:28:31 +0000652 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100653 @unittest.skipIf(python_is_optimized(),
654 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000655 def test_up_then_down(self):
656 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000657 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000658 cmds_after_breakpoint=['py-up', 'py-down'])
659 self.assertMultilineMatches(bt,
660 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000661#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000662 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000663#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000664 print\(42\)
665$''')
666
667class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100668 @unittest.skipIf(python_is_optimized(),
669 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000670 def test_basic_command(self):
671 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000672 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000673 cmds_after_breakpoint=['py-bt'])
674 self.assertMultilineMatches(bt,
675 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000676#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000677 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000678#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000679 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000680#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100681 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000682''')
683
684class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100685 @unittest.skipIf(python_is_optimized(),
686 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000687 def test_basic_command(self):
688 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000689 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000690 cmds_after_breakpoint=['py-print args'])
691 self.assertMultilineMatches(bt,
692 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
693
Victor Stinnera92e81b2010-04-20 22:28:31 +0000694 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100695 @unittest.skipIf(python_is_optimized(),
696 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000697 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000698 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000699 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
700 self.assertMultilineMatches(bt,
701 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
702
Victor Stinner99cff3f2011-12-19 13:59:58 +0100703 @unittest.skipIf(python_is_optimized(),
704 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000705 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000706 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000707 cmds_after_breakpoint=['py-print __name__'])
708 self.assertMultilineMatches(bt,
709 r".*\nglobal '__name__' = '__main__'\n.*")
710
Victor Stinner99cff3f2011-12-19 13:59:58 +0100711 @unittest.skipIf(python_is_optimized(),
712 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000713 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000714 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000715 cmds_after_breakpoint=['py-print len'])
716 self.assertMultilineMatches(bt,
717 r".*\nbuiltin 'len' = <built-in function len>\n.*")
718
719class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100720 @unittest.skipIf(python_is_optimized(),
721 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000722 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000723 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000724 cmds_after_breakpoint=['py-locals'])
725 self.assertMultilineMatches(bt,
726 r".*\nargs = \(1, 2, 3\)\n.*")
727
Victor Stinnera92e81b2010-04-20 22:28:31 +0000728 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100729 @unittest.skipIf(python_is_optimized(),
730 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000731 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000732 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000733 cmds_after_breakpoint=['py-up', 'py-locals'])
734 self.assertMultilineMatches(bt,
735 r".*\na = 1\nb = 2\nc = 3\n.*")
736
737def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000738 run_unittest(PrettyPrintTests,
739 PyListTests,
740 StackNavigationTests,
741 PyBtTests,
742 PyPrintTests,
743 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000744 )
745
746if __name__ == "__main__":
747 test_main()