blob: 0a2d883fa41a30f76422eacf5880026b00277cc9 [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
61 def run_gdb(self, *args):
62 """Runs gdb with the command line given by *args.
63
64 Returns its stdout, stderr
65 """
66 out, err = subprocess.Popen(
67 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
68 ).communicate()
69 return out, err
70
71 def get_stack_trace(self, source=None, script=None,
72 breakpoint='PyObject_Print',
73 cmds_after_breakpoint=None,
74 import_site=False):
75 '''
76 Run 'python -c SOURCE' under gdb with a breakpoint.
77
78 Support injecting commands after the breakpoint is reached
79
80 Returns the stdout from gdb
81
82 cmds_after_breakpoint: if provided, a list of strings: gdb commands
83 '''
84 # We use "set breakpoint pending yes" to avoid blocking with a:
85 # Function "foo" not defined.
86 # Make breakpoint pending on future shared library load? (y or [n])
87 # error, which typically happens python is dynamically linked (the
88 # breakpoints of interest are to be found in the shared library)
89 # When this happens, we still get:
90 # Function "PyObject_Print" not defined.
91 # emitted to stderr each time, alas.
92
93 # Initially I had "--eval-command=continue" here, but removed it to
94 # avoid repeated print breakpoints when traversing hierarchical data
95 # structures
96
97 # Generate a list of commands in gdb's language:
98 commands = ['set breakpoint pending yes',
99 'break %s' % breakpoint,
100 'run']
101 if cmds_after_breakpoint:
102 commands += cmds_after_breakpoint
103 else:
104 commands += ['backtrace']
105
106 # print commands
107
108 # Use "commands" to generate the arguments with which to invoke "gdb":
109 args = ["gdb", "--batch"]
110 args += ['--eval-command=%s' % cmd for cmd in commands]
111 args += ["--args",
112 sys.executable]
113
114 if not import_site:
115 # -S suppresses the default 'import site'
116 args += ["-S"]
117
118 if source:
119 args += ["-c", source]
120 elif script:
121 args += [script]
122
123 # print args
124 # print ' '.join(args)
125
126 # Use "args" to invoke gdb, capturing stdout, stderr:
127 out, err = self.run_gdb(*args)
128
129 # Ignore some noise on stderr due to the pending breakpoint:
130 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000131 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
132 err = err.replace("warning: Unable to find libthread_db matching"
133 " inferior's thread library, thread debugging will"
134 " not be available.\n",
135 '')
Jesus Cea6905de12011-03-16 01:19:49 +0100136 err = err.replace("warning: Cannot initialize thread debugging"
137 " library: Debugger service failed\n",
138 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000139
140 # Ensure no unexpected error messages:
Ezio Melotti2623a372010-11-21 13:34:58 +0000141 self.assertEqual(err, '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000142
143 return out
144
145 def get_gdb_repr(self, source,
146 cmds_after_breakpoint=None,
147 import_site=False):
148 # Given an input python source representation of data,
149 # run "python -c'print DATA'" under gdb with a breakpoint on
150 # PyObject_Print and scrape out gdb's representation of the "op"
151 # parameter, and verify that the gdb displays the same string
152 #
153 # For a nested structure, the first time we hit the breakpoint will
154 # give us the top-level structure
155 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
156 cmds_after_breakpoint=cmds_after_breakpoint,
157 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000158 # gdb can insert additional '\n' and space characters in various places
159 # in its output, depending on the width of the terminal it's connected
160 # to (using its "wrap_here" function)
161 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000162 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000163 if not m:
164 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000165 return m.group(1), gdb_output
166
167 def assertEndsWith(self, actual, exp_end):
168 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000169 self.assertTrue(actual.endswith(exp_end),
170 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000171
172 def assertMultilineMatches(self, actual, pattern):
173 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000174 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000175
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000176 def get_sample_script(self):
177 return findfile('gdb_sample.py')
178
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000179class PrettyPrintTests(DebuggerTests):
180 def test_getting_backtrace(self):
181 gdb_output = self.get_stack_trace('print 42')
182 self.assertTrue('PyObject_Print' in gdb_output)
183
184 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
185 # Ensure that gdb's rendering of the value in a debugged process
186 # matches repr(value) in this process:
187 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
188 cmds_after_breakpoint)
Ezio Melotti2623a372010-11-21 13:34:58 +0000189 self.assertEqual(gdb_repr, repr(val), gdb_output)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000190
191 def test_int(self):
192 'Verify the pretty-printing of various "int" values'
193 self.assertGdbRepr(42)
194 self.assertGdbRepr(0)
195 self.assertGdbRepr(-7)
196 self.assertGdbRepr(sys.maxint)
197 self.assertGdbRepr(-sys.maxint)
198
199 def test_long(self):
200 'Verify the pretty-printing of various "long" values'
201 self.assertGdbRepr(0L)
202 self.assertGdbRepr(1000000000000L)
203 self.assertGdbRepr(-1L)
204 self.assertGdbRepr(-1000000000000000L)
205
206 def test_singletons(self):
207 'Verify the pretty-printing of True, False and None'
208 self.assertGdbRepr(True)
209 self.assertGdbRepr(False)
210 self.assertGdbRepr(None)
211
212 def test_dicts(self):
213 'Verify the pretty-printing of dictionaries'
214 self.assertGdbRepr({})
215 self.assertGdbRepr({'foo': 'bar'})
216 self.assertGdbRepr({'foo': 'bar', 'douglas':42})
217
218 def test_lists(self):
219 'Verify the pretty-printing of lists'
220 self.assertGdbRepr([])
221 self.assertGdbRepr(range(5))
222
223 def test_strings(self):
224 'Verify the pretty-printing of strings'
225 self.assertGdbRepr('')
226 self.assertGdbRepr('And now for something hopefully the same')
227 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
228 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
229
230 def test_tuples(self):
231 'Verify the pretty-printing of tuples'
232 self.assertGdbRepr(tuple())
233 self.assertGdbRepr((1,))
234 self.assertGdbRepr(('foo', 'bar', 'baz'))
235
236 def test_unicode(self):
237 'Verify the pretty-printing of unicode values'
238 # Test the empty unicode string:
239 self.assertGdbRepr(u'')
240
241 self.assertGdbRepr(u'hello world')
242
243 # Test printing a single character:
244 # U+2620 SKULL AND CROSSBONES
245 self.assertGdbRepr(u'\u2620')
246
247 # Test printing a Japanese unicode string
248 # (I believe this reads "mojibake", using 3 characters from the CJK
249 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
250 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
251
252 # Test a character outside the BMP:
253 # U+1D121 MUSICAL SYMBOL C CLEF
254 # This is:
255 # UTF-8: 0xF0 0x9D 0x84 0xA1
256 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000257 # This will only work on wide-unicode builds:
258 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000259
260 def test_sets(self):
261 'Verify the pretty-printing of sets'
262 self.assertGdbRepr(set())
263 self.assertGdbRepr(set(['a', 'b']))
264 self.assertGdbRepr(set([4, 5, 6]))
265
266 # Ensure that we handled sets containing the "dummy" key value,
267 # which happens on deletion:
268 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
269s.pop()
270print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000271 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000272
273 def test_frozensets(self):
274 'Verify the pretty-printing of frozensets'
275 self.assertGdbRepr(frozenset())
276 self.assertGdbRepr(frozenset(['a', 'b']))
277 self.assertGdbRepr(frozenset([4, 5, 6]))
278
279 def test_exceptions(self):
280 # Test a RuntimeError
281 gdb_repr, gdb_output = self.get_gdb_repr('''
282try:
283 raise RuntimeError("I am an error")
284except RuntimeError, e:
285 print e
286''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000287 self.assertEqual(gdb_repr,
288 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000289
290
291 # Test division by zero:
292 gdb_repr, gdb_output = self.get_gdb_repr('''
293try:
294 a = 1 / 0
295except ZeroDivisionError, e:
296 print e
297''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000298 self.assertEqual(gdb_repr,
299 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000300
301 def test_classic_class(self):
302 'Verify the pretty-printing of classic class instances'
303 gdb_repr, gdb_output = self.get_gdb_repr('''
304class Foo:
305 pass
306foo = Foo()
307foo.an_int = 42
308print foo''')
309 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
310 self.assertTrue(m,
311 msg='Unexpected classic-class rendering %r' % gdb_repr)
312
313 def test_modern_class(self):
314 'Verify the pretty-printing of new-style class instances'
315 gdb_repr, gdb_output = self.get_gdb_repr('''
316class Foo(object):
317 pass
318foo = Foo()
319foo.an_int = 42
320print foo''')
321 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
322 self.assertTrue(m,
323 msg='Unexpected new-style class rendering %r' % gdb_repr)
324
325 def test_subclassing_list(self):
326 'Verify the pretty-printing of an instance of a list subclass'
327 gdb_repr, gdb_output = self.get_gdb_repr('''
328class Foo(list):
329 pass
330foo = Foo()
331foo += [1, 2, 3]
332foo.an_int = 42
333print foo''')
334 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
335 self.assertTrue(m,
336 msg='Unexpected new-style class rendering %r' % gdb_repr)
337
338 def test_subclassing_tuple(self):
339 'Verify the pretty-printing of an instance of a tuple subclass'
340 # This should exercise the negative tp_dictoffset code in the
341 # new-style class support
342 gdb_repr, gdb_output = self.get_gdb_repr('''
343class Foo(tuple):
344 pass
345foo = Foo((1, 2, 3))
346foo.an_int = 42
347print foo''')
348 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
349 self.assertTrue(m,
350 msg='Unexpected new-style class rendering %r' % gdb_repr)
351
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000352 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000353 '''Run Python under gdb, corrupting variables in the inferior process
354 immediately before taking a backtrace.
355
356 Verify that the variable's representation is the expected failsafe
357 representation'''
358 if corruption:
359 cmds_after_breakpoint=[corruption, 'backtrace']
360 else:
361 cmds_after_breakpoint=['backtrace']
362
363 gdb_repr, gdb_output = \
364 self.get_gdb_repr(source,
365 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000366
367 if expvalue:
368 if gdb_repr == repr(expvalue):
369 # gdb managed to print the value in spite of the corruption;
370 # this is good (see http://bugs.python.org/issue8330)
371 return
372
373 if exptype:
374 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
375 else:
376 # Match anything for the type name; 0xDEADBEEF could point to
377 # something arbitrary (see http://bugs.python.org/issue8330)
378 pattern = '<.* at remote 0x[0-9a-f]+>'
379
380 m = re.match(pattern, gdb_repr)
381 if not m:
382 self.fail('Unexpected gdb representation: %r\n%s' % \
383 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000384
385 def test_NULL_ptr(self):
386 'Ensure that a NULL PyObject* is handled gracefully'
387 gdb_repr, gdb_output = (
388 self.get_gdb_repr('print 42',
389 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000390 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000391 )
392
Ezio Melotti2623a372010-11-21 13:34:58 +0000393 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000394
395 def test_NULL_ob_type(self):
396 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
397 self.assertSane('print 42',
398 'set op->ob_type=0')
399
400 def test_corrupt_ob_type(self):
401 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
402 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000403 'set op->ob_type=0xDEADBEEF',
404 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000405
406 def test_corrupt_tp_flags(self):
407 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
408 self.assertSane('print 42',
409 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000410 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000411
412 def test_corrupt_tp_name(self):
413 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
414 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000415 'set op->ob_type->tp_name=0xDEADBEEF',
416 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000417
418 def test_NULL_instance_dict(self):
419 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
420 self.assertSane('''
421class Foo:
422 pass
423foo = Foo()
424foo.an_int = 42
425print foo''',
426 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000427 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000428
429 def test_builtins_help(self):
430 'Ensure that the new-style class _Helper in site.py can be handled'
431 # (this was the issue causing tracebacks in
432 # http://bugs.python.org/issue8032#msg100537 )
433
434 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
435 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
436 self.assertTrue(m,
437 msg='Unexpected rendering %r' % gdb_repr)
438
439 def test_selfreferential_list(self):
440 '''Ensure that a reference loop involving a list doesn't lead proxyval
441 into an infinite loop:'''
442 gdb_repr, gdb_output = \
443 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
444
Ezio Melotti2623a372010-11-21 13:34:58 +0000445 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000446
447 gdb_repr, gdb_output = \
448 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; 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 def test_selfreferential_dict(self):
453 '''Ensure that a reference loop involving a dict doesn't lead proxyval
454 into an infinite loop:'''
455 gdb_repr, gdb_output = \
456 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
457
Ezio Melotti2623a372010-11-21 13:34:58 +0000458 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000459
460 def test_selfreferential_old_style_instance(self):
461 gdb_repr, gdb_output = \
462 self.get_gdb_repr('''
463class Foo:
464 pass
465foo = Foo()
466foo.an_attr = foo
467print foo''')
468 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
469 gdb_repr),
470 'Unexpected gdb representation: %r\n%s' % \
471 (gdb_repr, gdb_output))
472
473 def test_selfreferential_new_style_instance(self):
474 gdb_repr, gdb_output = \
475 self.get_gdb_repr('''
476class Foo(object):
477 pass
478foo = Foo()
479foo.an_attr = foo
480print foo''')
481 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
482 gdb_repr),
483 'Unexpected gdb representation: %r\n%s' % \
484 (gdb_repr, gdb_output))
485
486 gdb_repr, gdb_output = \
487 self.get_gdb_repr('''
488class Foo(object):
489 pass
490a = Foo()
491b = Foo()
492a.an_attr = b
493b.an_attr = a
494print a''')
495 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
496 gdb_repr),
497 'Unexpected gdb representation: %r\n%s' % \
498 (gdb_repr, gdb_output))
499
500 def test_truncation(self):
501 'Verify that very long output is truncated'
502 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000503 self.assertEqual(gdb_repr,
504 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
505 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
506 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
507 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
508 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
509 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
510 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
511 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
512 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
513 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
514 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
515 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
516 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
517 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
518 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
519 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
520 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
521 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
522 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
523 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
524 "224, 225, 226...(truncated)")
525 self.assertEqual(len(gdb_repr),
526 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000527
528 def test_builtin_function(self):
529 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000530 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000531
532 def test_builtin_method(self):
533 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
534 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
535 gdb_repr),
536 'Unexpected gdb representation: %r\n%s' % \
537 (gdb_repr, gdb_output))
538
539 def test_frames(self):
540 gdb_output = self.get_stack_trace('''
541def foo(a, b, c):
542 pass
543
544foo(3, 4, 5)
545print foo.__code__''',
546 breakpoint='PyObject_Print',
547 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
548 )
R. David Murray0c080092010-04-05 16:28:49 +0000549 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
550 gdb_output,
551 re.DOTALL),
552 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000553
Victor Stinner99cff3f2011-12-19 13:59:58 +0100554@unittest.skipIf(python_is_optimized(),
555 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000556class PyListTests(DebuggerTests):
557 def assertListing(self, expected, actual):
558 self.assertEndsWith(actual, expected)
559
560 def test_basic_command(self):
561 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000562 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000563 cmds_after_breakpoint=['py-list'])
564
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000565 self.assertListing(' 5 \n'
566 ' 6 def bar(a, b, c):\n'
567 ' 7 baz(a, b, c)\n'
568 ' 8 \n'
569 ' 9 def baz(*args):\n'
570 ' >10 print(42)\n'
571 ' 11 \n'
572 ' 12 foo(1, 2, 3)\n',
573 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000574
575 def test_one_abs_arg(self):
576 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000577 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000578 cmds_after_breakpoint=['py-list 9'])
579
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000580 self.assertListing(' 9 def baz(*args):\n'
581 ' >10 print(42)\n'
582 ' 11 \n'
583 ' 12 foo(1, 2, 3)\n',
584 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000585
586 def test_two_abs_args(self):
587 'Verify the "py-list" command with two absolute arguments'
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 1,3'])
590
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000591 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
592 ' 2 \n'
593 ' 3 def foo(a, b, c):\n',
594 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000595
596class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000597 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100598 @unittest.skipIf(python_is_optimized(),
599 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000600 def test_pyup_command(self):
601 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000602 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000603 cmds_after_breakpoint=['py-up'])
604 self.assertMultilineMatches(bt,
605 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000606#[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 +0000607 baz\(a, b, c\)
608$''')
609
Victor Stinnera92e81b2010-04-20 22:28:31 +0000610 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000611 def test_down_at_bottom(self):
612 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000613 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000614 cmds_after_breakpoint=['py-down'])
615 self.assertEndsWith(bt,
616 'Unable to find a newer python frame\n')
617
Victor Stinnera92e81b2010-04-20 22:28:31 +0000618 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000619 def test_up_at_top(self):
620 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000621 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000622 cmds_after_breakpoint=['py-up'] * 4)
623 self.assertEndsWith(bt,
624 'Unable to find an older python frame\n')
625
Victor Stinnera92e81b2010-04-20 22:28:31 +0000626 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100627 @unittest.skipIf(python_is_optimized(),
628 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000629 def test_up_then_down(self):
630 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000631 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000632 cmds_after_breakpoint=['py-up', 'py-down'])
633 self.assertMultilineMatches(bt,
634 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000635#[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 +0000636 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000637#[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 +0000638 print\(42\)
639$''')
640
641class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100642 @unittest.skipIf(python_is_optimized(),
643 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000644 def test_basic_command(self):
645 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000646 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000647 cmds_after_breakpoint=['py-bt'])
648 self.assertMultilineMatches(bt,
649 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000650#[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 +0000651 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000652#[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 +0000653 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000654#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100655 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000656''')
657
658class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100659 @unittest.skipIf(python_is_optimized(),
660 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000661 def test_basic_command(self):
662 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000663 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000664 cmds_after_breakpoint=['py-print args'])
665 self.assertMultilineMatches(bt,
666 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
667
Victor Stinnera92e81b2010-04-20 22:28:31 +0000668 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100669 @unittest.skipIf(python_is_optimized(),
670 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000671 def test_print_after_up(self):
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-up', 'py-print c', 'py-print b', 'py-print a'])
674 self.assertMultilineMatches(bt,
675 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
676
Victor Stinner99cff3f2011-12-19 13:59:58 +0100677 @unittest.skipIf(python_is_optimized(),
678 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000679 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000680 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000681 cmds_after_breakpoint=['py-print __name__'])
682 self.assertMultilineMatches(bt,
683 r".*\nglobal '__name__' = '__main__'\n.*")
684
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_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000688 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000689 cmds_after_breakpoint=['py-print len'])
690 self.assertMultilineMatches(bt,
691 r".*\nbuiltin 'len' = <built-in function len>\n.*")
692
693class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100694 @unittest.skipIf(python_is_optimized(),
695 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000696 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000697 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000698 cmds_after_breakpoint=['py-locals'])
699 self.assertMultilineMatches(bt,
700 r".*\nargs = \(1, 2, 3\)\n.*")
701
Victor Stinnera92e81b2010-04-20 22:28:31 +0000702 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
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_locals_after_up(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-up', 'py-locals'])
708 self.assertMultilineMatches(bt,
709 r".*\na = 1\nb = 2\nc = 3\n.*")
710
711def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000712 run_unittest(PrettyPrintTests,
713 PyListTests,
714 StackNavigationTests,
715 PyBtTests,
716 PyPrintTests,
717 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000718 )
719
720if __name__ == "__main__":
721 test_main()