blob: 92e5c5279b7bfd323d69235843519100322db2d9 [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
Victor Stinner99cff3f2011-12-19 13:59:58 +010035def python_is_optimized():
36 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
37 final_opt = ""
38 for opt in cflags.split():
39 if opt.startswith('-O'):
40 final_opt = opt
41 return (final_opt and final_opt != '-O0')
42
Victor Stinnera92e81b2010-04-20 22:28:31 +000043def gdb_has_frame_select():
44 # Does this build of gdb have gdb.Frame.select ?
45 cmd = "--eval-command=python print(dir(gdb.Frame))"
46 p = subprocess.Popen(["gdb", "--batch", cmd],
47 stdout=subprocess.PIPE)
48 stdout, _ = p.communicate()
49 m = re.match(r'.*\[(.*)\].*', stdout)
50 if not m:
51 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
52 gdb_frame_dir = m.group(1).split(', ')
53 return "'select'" in gdb_frame_dir
54
55HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056
57class DebuggerTests(unittest.TestCase):
58
59 """Test that the debugger can debug Python."""
60
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050061 def run_gdb(self, *args, **env_vars):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000062 """Runs gdb with the command line given by *args.
63
64 Returns its stdout, stderr
65 """
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050066 if env_vars:
67 env = os.environ.copy()
68 env.update(env_vars)
69 else:
70 env = None
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000071 out, err = subprocess.Popen(
Benjamin Peterson11fa11b2012-02-20 21:55:32 -050072 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000073 ).communicate()
74 return out, err
75
76 def get_stack_trace(self, source=None, script=None,
77 breakpoint='PyObject_Print',
78 cmds_after_breakpoint=None,
79 import_site=False):
80 '''
81 Run 'python -c SOURCE' under gdb with a breakpoint.
82
83 Support injecting commands after the breakpoint is reached
84
85 Returns the stdout from gdb
86
87 cmds_after_breakpoint: if provided, a list of strings: gdb commands
88 '''
89 # We use "set breakpoint pending yes" to avoid blocking with a:
90 # Function "foo" not defined.
91 # Make breakpoint pending on future shared library load? (y or [n])
92 # error, which typically happens python is dynamically linked (the
93 # breakpoints of interest are to be found in the shared library)
94 # When this happens, we still get:
95 # Function "PyObject_Print" not defined.
96 # emitted to stderr each time, alas.
97
98 # Initially I had "--eval-command=continue" here, but removed it to
99 # avoid repeated print breakpoints when traversing hierarchical data
100 # structures
101
102 # Generate a list of commands in gdb's language:
103 commands = ['set breakpoint pending yes',
104 'break %s' % breakpoint,
105 'run']
106 if cmds_after_breakpoint:
107 commands += cmds_after_breakpoint
108 else:
109 commands += ['backtrace']
110
111 # print commands
112
113 # Use "commands" to generate the arguments with which to invoke "gdb":
114 args = ["gdb", "--batch"]
115 args += ['--eval-command=%s' % cmd for cmd in commands]
116 args += ["--args",
117 sys.executable]
118
119 if not import_site:
120 # -S suppresses the default 'import site'
121 args += ["-S"]
122
123 if source:
124 args += ["-c", source]
125 elif script:
126 args += [script]
127
128 # print args
129 # print ' '.join(args)
130
131 # Use "args" to invoke gdb, capturing stdout, stderr:
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500132 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000133
134 # Ignore some noise on stderr due to the pending breakpoint:
135 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000136 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
137 err = err.replace("warning: Unable to find libthread_db matching"
138 " inferior's thread library, thread debugging will"
139 " not be available.\n",
140 '')
Jesus Cea6905de12011-03-16 01:19:49 +0100141 err = err.replace("warning: Cannot initialize thread debugging"
142 " library: Debugger service failed\n",
143 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000144
145 # Ensure no unexpected error messages:
Ezio Melotti2623a372010-11-21 13:34:58 +0000146 self.assertEqual(err, '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000147
148 return out
149
150 def get_gdb_repr(self, source,
151 cmds_after_breakpoint=None,
152 import_site=False):
153 # Given an input python source representation of data,
154 # run "python -c'print DATA'" under gdb with a breakpoint on
155 # PyObject_Print and scrape out gdb's representation of the "op"
156 # parameter, and verify that the gdb displays the same string
157 #
158 # For a nested structure, the first time we hit the breakpoint will
159 # give us the top-level structure
160 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
161 cmds_after_breakpoint=cmds_after_breakpoint,
162 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000163 # gdb can insert additional '\n' and space characters in various places
164 # in its output, depending on the width of the terminal it's connected
165 # to (using its "wrap_here" function)
166 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000167 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000168 if not m:
169 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000170 return m.group(1), gdb_output
171
172 def assertEndsWith(self, actual, exp_end):
173 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000174 self.assertTrue(actual.endswith(exp_end),
175 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000176
177 def assertMultilineMatches(self, actual, pattern):
178 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000179 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000180
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000181 def get_sample_script(self):
182 return findfile('gdb_sample.py')
183
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000184class PrettyPrintTests(DebuggerTests):
185 def test_getting_backtrace(self):
186 gdb_output = self.get_stack_trace('print 42')
187 self.assertTrue('PyObject_Print' in gdb_output)
188
189 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
190 # Ensure that gdb's rendering of the value in a debugged process
191 # matches repr(value) in this process:
192 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
193 cmds_after_breakpoint)
Ezio Melotti2623a372010-11-21 13:34:58 +0000194 self.assertEqual(gdb_repr, repr(val), gdb_output)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000195
196 def test_int(self):
197 'Verify the pretty-printing of various "int" values'
198 self.assertGdbRepr(42)
199 self.assertGdbRepr(0)
200 self.assertGdbRepr(-7)
201 self.assertGdbRepr(sys.maxint)
202 self.assertGdbRepr(-sys.maxint)
203
204 def test_long(self):
205 'Verify the pretty-printing of various "long" values'
206 self.assertGdbRepr(0L)
207 self.assertGdbRepr(1000000000000L)
208 self.assertGdbRepr(-1L)
209 self.assertGdbRepr(-1000000000000000L)
210
211 def test_singletons(self):
212 'Verify the pretty-printing of True, False and None'
213 self.assertGdbRepr(True)
214 self.assertGdbRepr(False)
215 self.assertGdbRepr(None)
216
217 def test_dicts(self):
218 'Verify the pretty-printing of dictionaries'
219 self.assertGdbRepr({})
220 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500221 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000222
223 def test_lists(self):
224 'Verify the pretty-printing of lists'
225 self.assertGdbRepr([])
226 self.assertGdbRepr(range(5))
227
228 def test_strings(self):
229 'Verify the pretty-printing of strings'
230 self.assertGdbRepr('')
231 self.assertGdbRepr('And now for something hopefully the same')
232 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
233 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
234
235 def test_tuples(self):
236 'Verify the pretty-printing of tuples'
237 self.assertGdbRepr(tuple())
238 self.assertGdbRepr((1,))
239 self.assertGdbRepr(('foo', 'bar', 'baz'))
240
241 def test_unicode(self):
242 'Verify the pretty-printing of unicode values'
243 # Test the empty unicode string:
244 self.assertGdbRepr(u'')
245
246 self.assertGdbRepr(u'hello world')
247
248 # Test printing a single character:
249 # U+2620 SKULL AND CROSSBONES
250 self.assertGdbRepr(u'\u2620')
251
252 # Test printing a Japanese unicode string
253 # (I believe this reads "mojibake", using 3 characters from the CJK
254 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
255 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
256
257 # Test a character outside the BMP:
258 # U+1D121 MUSICAL SYMBOL C CLEF
259 # This is:
260 # UTF-8: 0xF0 0x9D 0x84 0xA1
261 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000262 # This will only work on wide-unicode builds:
263 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000264
265 def test_sets(self):
266 'Verify the pretty-printing of sets'
267 self.assertGdbRepr(set())
268 self.assertGdbRepr(set(['a', 'b']))
269 self.assertGdbRepr(set([4, 5, 6]))
270
271 # Ensure that we handled sets containing the "dummy" key value,
272 # which happens on deletion:
273 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
274s.pop()
275print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000276 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000277
278 def test_frozensets(self):
279 'Verify the pretty-printing of frozensets'
280 self.assertGdbRepr(frozenset())
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500281 self.assertGdbRepr("frozenset(['a', 'b'])")
282 self.assertGdbRepr("frozenset([4, 5, 6])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000283
284 def test_exceptions(self):
285 # Test a RuntimeError
286 gdb_repr, gdb_output = self.get_gdb_repr('''
287try:
288 raise RuntimeError("I am an error")
289except RuntimeError, e:
290 print e
291''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000292 self.assertEqual(gdb_repr,
293 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000294
295
296 # Test division by zero:
297 gdb_repr, gdb_output = self.get_gdb_repr('''
298try:
299 a = 1 / 0
300except ZeroDivisionError, e:
301 print e
302''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000303 self.assertEqual(gdb_repr,
304 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000305
306 def test_classic_class(self):
307 'Verify the pretty-printing of classic class instances'
308 gdb_repr, gdb_output = self.get_gdb_repr('''
309class Foo:
310 pass
311foo = Foo()
312foo.an_int = 42
313print foo''')
314 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
315 self.assertTrue(m,
316 msg='Unexpected classic-class rendering %r' % gdb_repr)
317
318 def test_modern_class(self):
319 'Verify the pretty-printing of new-style class instances'
320 gdb_repr, gdb_output = self.get_gdb_repr('''
321class Foo(object):
322 pass
323foo = Foo()
324foo.an_int = 42
325print 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_list(self):
331 'Verify the pretty-printing of an instance of a list subclass'
332 gdb_repr, gdb_output = self.get_gdb_repr('''
333class Foo(list):
334 pass
335foo = Foo()
336foo += [1, 2, 3]
337foo.an_int = 42
338print foo''')
339 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
340 self.assertTrue(m,
341 msg='Unexpected new-style class rendering %r' % gdb_repr)
342
343 def test_subclassing_tuple(self):
344 'Verify the pretty-printing of an instance of a tuple subclass'
345 # This should exercise the negative tp_dictoffset code in the
346 # new-style class support
347 gdb_repr, gdb_output = self.get_gdb_repr('''
348class Foo(tuple):
349 pass
350foo = Foo((1, 2, 3))
351foo.an_int = 42
352print foo''')
353 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
354 self.assertTrue(m,
355 msg='Unexpected new-style class rendering %r' % gdb_repr)
356
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000357 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000358 '''Run Python under gdb, corrupting variables in the inferior process
359 immediately before taking a backtrace.
360
361 Verify that the variable's representation is the expected failsafe
362 representation'''
363 if corruption:
364 cmds_after_breakpoint=[corruption, 'backtrace']
365 else:
366 cmds_after_breakpoint=['backtrace']
367
368 gdb_repr, gdb_output = \
369 self.get_gdb_repr(source,
370 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000371
372 if expvalue:
373 if gdb_repr == repr(expvalue):
374 # gdb managed to print the value in spite of the corruption;
375 # this is good (see http://bugs.python.org/issue8330)
376 return
377
378 if exptype:
379 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
380 else:
381 # Match anything for the type name; 0xDEADBEEF could point to
382 # something arbitrary (see http://bugs.python.org/issue8330)
383 pattern = '<.* at remote 0x[0-9a-f]+>'
384
385 m = re.match(pattern, gdb_repr)
386 if not m:
387 self.fail('Unexpected gdb representation: %r\n%s' % \
388 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000389
390 def test_NULL_ptr(self):
391 'Ensure that a NULL PyObject* is handled gracefully'
392 gdb_repr, gdb_output = (
393 self.get_gdb_repr('print 42',
394 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000395 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000396 )
397
Ezio Melotti2623a372010-11-21 13:34:58 +0000398 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000399
400 def test_NULL_ob_type(self):
401 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
402 self.assertSane('print 42',
403 'set op->ob_type=0')
404
405 def test_corrupt_ob_type(self):
406 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
407 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000408 'set op->ob_type=0xDEADBEEF',
409 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000410
411 def test_corrupt_tp_flags(self):
412 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
413 self.assertSane('print 42',
414 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000415 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000416
417 def test_corrupt_tp_name(self):
418 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
419 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000420 'set op->ob_type->tp_name=0xDEADBEEF',
421 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000422
423 def test_NULL_instance_dict(self):
424 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
425 self.assertSane('''
426class Foo:
427 pass
428foo = Foo()
429foo.an_int = 42
430print foo''',
431 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000432 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000433
434 def test_builtins_help(self):
435 'Ensure that the new-style class _Helper in site.py can be handled'
436 # (this was the issue causing tracebacks in
437 # http://bugs.python.org/issue8032#msg100537 )
438
439 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
440 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
441 self.assertTrue(m,
442 msg='Unexpected rendering %r' % gdb_repr)
443
444 def test_selfreferential_list(self):
445 '''Ensure that a reference loop involving a list doesn't lead proxyval
446 into an infinite loop:'''
447 gdb_repr, gdb_output = \
448 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
449
Ezio Melotti2623a372010-11-21 13:34:58 +0000450 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000451
452 gdb_repr, gdb_output = \
453 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
454
Ezio Melotti2623a372010-11-21 13:34:58 +0000455 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000456
457 def test_selfreferential_dict(self):
458 '''Ensure that a reference loop involving a dict doesn't lead proxyval
459 into an infinite loop:'''
460 gdb_repr, gdb_output = \
461 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
462
Ezio Melotti2623a372010-11-21 13:34:58 +0000463 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000464
465 def test_selfreferential_old_style_instance(self):
466 gdb_repr, gdb_output = \
467 self.get_gdb_repr('''
468class Foo:
469 pass
470foo = Foo()
471foo.an_attr = foo
472print 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 def test_selfreferential_new_style_instance(self):
479 gdb_repr, gdb_output = \
480 self.get_gdb_repr('''
481class Foo(object):
482 pass
483foo = Foo()
484foo.an_attr = foo
485print foo''')
486 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
487 gdb_repr),
488 'Unexpected gdb representation: %r\n%s' % \
489 (gdb_repr, gdb_output))
490
491 gdb_repr, gdb_output = \
492 self.get_gdb_repr('''
493class Foo(object):
494 pass
495a = Foo()
496b = Foo()
497a.an_attr = b
498b.an_attr = a
499print a''')
500 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
501 gdb_repr),
502 'Unexpected gdb representation: %r\n%s' % \
503 (gdb_repr, gdb_output))
504
505 def test_truncation(self):
506 'Verify that very long output is truncated'
507 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000508 self.assertEqual(gdb_repr,
509 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
510 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
511 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
512 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
513 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
514 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
515 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
516 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
517 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
518 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
519 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
520 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
521 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
522 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
523 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
524 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
525 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
526 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
527 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
528 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
529 "224, 225, 226...(truncated)")
530 self.assertEqual(len(gdb_repr),
531 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000532
533 def test_builtin_function(self):
534 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000535 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000536
537 def test_builtin_method(self):
538 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
539 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
540 gdb_repr),
541 'Unexpected gdb representation: %r\n%s' % \
542 (gdb_repr, gdb_output))
543
544 def test_frames(self):
545 gdb_output = self.get_stack_trace('''
546def foo(a, b, c):
547 pass
548
549foo(3, 4, 5)
550print foo.__code__''',
551 breakpoint='PyObject_Print',
552 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
553 )
R. David Murray0c080092010-04-05 16:28:49 +0000554 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
555 gdb_output,
556 re.DOTALL),
557 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000558
Victor Stinner99cff3f2011-12-19 13:59:58 +0100559@unittest.skipIf(python_is_optimized(),
560 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000561class PyListTests(DebuggerTests):
562 def assertListing(self, expected, actual):
563 self.assertEndsWith(actual, expected)
564
565 def test_basic_command(self):
566 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000567 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000568 cmds_after_breakpoint=['py-list'])
569
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000570 self.assertListing(' 5 \n'
571 ' 6 def bar(a, b, c):\n'
572 ' 7 baz(a, b, c)\n'
573 ' 8 \n'
574 ' 9 def baz(*args):\n'
575 ' >10 print(42)\n'
576 ' 11 \n'
577 ' 12 foo(1, 2, 3)\n',
578 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000579
580 def test_one_abs_arg(self):
581 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000582 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000583 cmds_after_breakpoint=['py-list 9'])
584
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000585 self.assertListing(' 9 def baz(*args):\n'
586 ' >10 print(42)\n'
587 ' 11 \n'
588 ' 12 foo(1, 2, 3)\n',
589 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000590
591 def test_two_abs_args(self):
592 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000593 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000594 cmds_after_breakpoint=['py-list 1,3'])
595
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000596 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
597 ' 2 \n'
598 ' 3 def foo(a, b, c):\n',
599 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000600
601class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000602 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100603 @unittest.skipIf(python_is_optimized(),
604 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000605 def test_pyup_command(self):
606 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000607 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000608 cmds_after_breakpoint=['py-up'])
609 self.assertMultilineMatches(bt,
610 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000611#[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 +0000612 baz\(a, b, c\)
613$''')
614
Victor Stinnera92e81b2010-04-20 22:28:31 +0000615 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000616 def test_down_at_bottom(self):
617 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000618 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000619 cmds_after_breakpoint=['py-down'])
620 self.assertEndsWith(bt,
621 'Unable to find a newer python frame\n')
622
Victor Stinnera92e81b2010-04-20 22:28:31 +0000623 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000624 def test_up_at_top(self):
625 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000626 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000627 cmds_after_breakpoint=['py-up'] * 4)
628 self.assertEndsWith(bt,
629 'Unable to find an older python frame\n')
630
Victor Stinnera92e81b2010-04-20 22:28:31 +0000631 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100632 @unittest.skipIf(python_is_optimized(),
633 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000634 def test_up_then_down(self):
635 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000636 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000637 cmds_after_breakpoint=['py-up', 'py-down'])
638 self.assertMultilineMatches(bt,
639 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000640#[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 +0000641 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000642#[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 +0000643 print\(42\)
644$''')
645
646class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100647 @unittest.skipIf(python_is_optimized(),
648 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000649 def test_basic_command(self):
650 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000651 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000652 cmds_after_breakpoint=['py-bt'])
653 self.assertMultilineMatches(bt,
654 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000655#[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 +0000656 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000657#[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 +0000658 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000659#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100660 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000661''')
662
663class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100664 @unittest.skipIf(python_is_optimized(),
665 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000666 def test_basic_command(self):
667 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000668 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000669 cmds_after_breakpoint=['py-print args'])
670 self.assertMultilineMatches(bt,
671 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
672
Victor Stinnera92e81b2010-04-20 22:28:31 +0000673 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100674 @unittest.skipIf(python_is_optimized(),
675 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000676 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000677 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000678 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
679 self.assertMultilineMatches(bt,
680 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
681
Victor Stinner99cff3f2011-12-19 13:59:58 +0100682 @unittest.skipIf(python_is_optimized(),
683 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000684 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000685 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000686 cmds_after_breakpoint=['py-print __name__'])
687 self.assertMultilineMatches(bt,
688 r".*\nglobal '__name__' = '__main__'\n.*")
689
Victor Stinner99cff3f2011-12-19 13:59:58 +0100690 @unittest.skipIf(python_is_optimized(),
691 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000692 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000693 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000694 cmds_after_breakpoint=['py-print len'])
695 self.assertMultilineMatches(bt,
696 r".*\nbuiltin 'len' = <built-in function len>\n.*")
697
698class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100699 @unittest.skipIf(python_is_optimized(),
700 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000701 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000702 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000703 cmds_after_breakpoint=['py-locals'])
704 self.assertMultilineMatches(bt,
705 r".*\nargs = \(1, 2, 3\)\n.*")
706
Victor Stinnera92e81b2010-04-20 22:28:31 +0000707 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100708 @unittest.skipIf(python_is_optimized(),
709 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000710 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000711 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000712 cmds_after_breakpoint=['py-up', 'py-locals'])
713 self.assertMultilineMatches(bt,
714 r".*\na = 1\nb = 2\nc = 3\n.*")
715
716def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000717 run_unittest(PrettyPrintTests,
718 PyListTests,
719 StackNavigationTests,
720 PyBtTests,
721 PyPrintTests,
722 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000723 )
724
725if __name__ == "__main__":
726 test_main()