blob: 6d4fda1ba333fd5fd817daac095bea598ab7abac [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 Stinnera92e81b2010-04-20 22:28:31 +000035def gdb_has_frame_select():
36 # Does this build of gdb have gdb.Frame.select ?
37 cmd = "--eval-command=python print(dir(gdb.Frame))"
38 p = subprocess.Popen(["gdb", "--batch", cmd],
39 stdout=subprocess.PIPE)
40 stdout, _ = p.communicate()
41 m = re.match(r'.*\[(.*)\].*', stdout)
42 if not m:
43 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
44 gdb_frame_dir = m.group(1).split(', ')
45 return "'select'" in gdb_frame_dir
46
47HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000048
49class DebuggerTests(unittest.TestCase):
50
51 """Test that the debugger can debug Python."""
52
53 def run_gdb(self, *args):
54 """Runs gdb with the command line given by *args.
55
56 Returns its stdout, stderr
57 """
58 out, err = subprocess.Popen(
59 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
60 ).communicate()
61 return out, err
62
63 def get_stack_trace(self, source=None, script=None,
64 breakpoint='PyObject_Print',
65 cmds_after_breakpoint=None,
66 import_site=False):
67 '''
68 Run 'python -c SOURCE' under gdb with a breakpoint.
69
70 Support injecting commands after the breakpoint is reached
71
72 Returns the stdout from gdb
73
74 cmds_after_breakpoint: if provided, a list of strings: gdb commands
75 '''
76 # We use "set breakpoint pending yes" to avoid blocking with a:
77 # Function "foo" not defined.
78 # Make breakpoint pending on future shared library load? (y or [n])
79 # error, which typically happens python is dynamically linked (the
80 # breakpoints of interest are to be found in the shared library)
81 # When this happens, we still get:
82 # Function "PyObject_Print" not defined.
83 # emitted to stderr each time, alas.
84
85 # Initially I had "--eval-command=continue" here, but removed it to
86 # avoid repeated print breakpoints when traversing hierarchical data
87 # structures
88
89 # Generate a list of commands in gdb's language:
90 commands = ['set breakpoint pending yes',
91 'break %s' % breakpoint,
92 'run']
93 if cmds_after_breakpoint:
94 commands += cmds_after_breakpoint
95 else:
96 commands += ['backtrace']
97
98 # print commands
99
100 # Use "commands" to generate the arguments with which to invoke "gdb":
101 args = ["gdb", "--batch"]
102 args += ['--eval-command=%s' % cmd for cmd in commands]
103 args += ["--args",
104 sys.executable]
105
106 if not import_site:
107 # -S suppresses the default 'import site'
108 args += ["-S"]
109
110 if source:
111 args += ["-c", source]
112 elif script:
113 args += [script]
114
115 # print args
116 # print ' '.join(args)
117
118 # Use "args" to invoke gdb, capturing stdout, stderr:
119 out, err = self.run_gdb(*args)
120
121 # Ignore some noise on stderr due to the pending breakpoint:
122 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000123 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
124 err = err.replace("warning: Unable to find libthread_db matching"
125 " inferior's thread library, thread debugging will"
126 " not be available.\n",
127 '')
Jesus Cea6905de12011-03-16 01:19:49 +0100128 err = err.replace("warning: Cannot initialize thread debugging"
129 " library: Debugger service failed\n",
130 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000131
132 # Ensure no unexpected error messages:
Ezio Melotti2623a372010-11-21 13:34:58 +0000133 self.assertEqual(err, '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000134
135 return out
136
137 def get_gdb_repr(self, source,
138 cmds_after_breakpoint=None,
139 import_site=False):
140 # Given an input python source representation of data,
141 # run "python -c'print DATA'" under gdb with a breakpoint on
142 # PyObject_Print and scrape out gdb's representation of the "op"
143 # parameter, and verify that the gdb displays the same string
144 #
145 # For a nested structure, the first time we hit the breakpoint will
146 # give us the top-level structure
147 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
148 cmds_after_breakpoint=cmds_after_breakpoint,
149 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000150 # gdb can insert additional '\n' and space characters in various places
151 # in its output, depending on the width of the terminal it's connected
152 # to (using its "wrap_here" function)
153 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000154 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000155 if not m:
156 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000157 return m.group(1), gdb_output
158
159 def assertEndsWith(self, actual, exp_end):
160 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000161 self.assertTrue(actual.endswith(exp_end),
162 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000163
164 def assertMultilineMatches(self, actual, pattern):
165 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000166 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000167
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000168 def get_sample_script(self):
169 return findfile('gdb_sample.py')
170
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000171class PrettyPrintTests(DebuggerTests):
172 def test_getting_backtrace(self):
173 gdb_output = self.get_stack_trace('print 42')
174 self.assertTrue('PyObject_Print' in gdb_output)
175
176 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
177 # Ensure that gdb's rendering of the value in a debugged process
178 # matches repr(value) in this process:
179 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
180 cmds_after_breakpoint)
Ezio Melotti2623a372010-11-21 13:34:58 +0000181 self.assertEqual(gdb_repr, repr(val), gdb_output)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000182
183 def test_int(self):
184 'Verify the pretty-printing of various "int" values'
185 self.assertGdbRepr(42)
186 self.assertGdbRepr(0)
187 self.assertGdbRepr(-7)
188 self.assertGdbRepr(sys.maxint)
189 self.assertGdbRepr(-sys.maxint)
190
191 def test_long(self):
192 'Verify the pretty-printing of various "long" values'
193 self.assertGdbRepr(0L)
194 self.assertGdbRepr(1000000000000L)
195 self.assertGdbRepr(-1L)
196 self.assertGdbRepr(-1000000000000000L)
197
198 def test_singletons(self):
199 'Verify the pretty-printing of True, False and None'
200 self.assertGdbRepr(True)
201 self.assertGdbRepr(False)
202 self.assertGdbRepr(None)
203
204 def test_dicts(self):
205 'Verify the pretty-printing of dictionaries'
206 self.assertGdbRepr({})
207 self.assertGdbRepr({'foo': 'bar'})
208 self.assertGdbRepr({'foo': 'bar', 'douglas':42})
209
210 def test_lists(self):
211 'Verify the pretty-printing of lists'
212 self.assertGdbRepr([])
213 self.assertGdbRepr(range(5))
214
215 def test_strings(self):
216 'Verify the pretty-printing of strings'
217 self.assertGdbRepr('')
218 self.assertGdbRepr('And now for something hopefully the same')
219 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
220 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
221
222 def test_tuples(self):
223 'Verify the pretty-printing of tuples'
224 self.assertGdbRepr(tuple())
225 self.assertGdbRepr((1,))
226 self.assertGdbRepr(('foo', 'bar', 'baz'))
227
228 def test_unicode(self):
229 'Verify the pretty-printing of unicode values'
230 # Test the empty unicode string:
231 self.assertGdbRepr(u'')
232
233 self.assertGdbRepr(u'hello world')
234
235 # Test printing a single character:
236 # U+2620 SKULL AND CROSSBONES
237 self.assertGdbRepr(u'\u2620')
238
239 # Test printing a Japanese unicode string
240 # (I believe this reads "mojibake", using 3 characters from the CJK
241 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
242 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
243
244 # Test a character outside the BMP:
245 # U+1D121 MUSICAL SYMBOL C CLEF
246 # This is:
247 # UTF-8: 0xF0 0x9D 0x84 0xA1
248 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000249 # This will only work on wide-unicode builds:
250 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000251
252 def test_sets(self):
253 'Verify the pretty-printing of sets'
254 self.assertGdbRepr(set())
255 self.assertGdbRepr(set(['a', 'b']))
256 self.assertGdbRepr(set([4, 5, 6]))
257
258 # Ensure that we handled sets containing the "dummy" key value,
259 # which happens on deletion:
260 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
261s.pop()
262print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000263 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000264
265 def test_frozensets(self):
266 'Verify the pretty-printing of frozensets'
267 self.assertGdbRepr(frozenset())
268 self.assertGdbRepr(frozenset(['a', 'b']))
269 self.assertGdbRepr(frozenset([4, 5, 6]))
270
271 def test_exceptions(self):
272 # Test a RuntimeError
273 gdb_repr, gdb_output = self.get_gdb_repr('''
274try:
275 raise RuntimeError("I am an error")
276except RuntimeError, e:
277 print e
278''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000279 self.assertEqual(gdb_repr,
280 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000281
282
283 # Test division by zero:
284 gdb_repr, gdb_output = self.get_gdb_repr('''
285try:
286 a = 1 / 0
287except ZeroDivisionError, e:
288 print e
289''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000290 self.assertEqual(gdb_repr,
291 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000292
293 def test_classic_class(self):
294 'Verify the pretty-printing of classic class instances'
295 gdb_repr, gdb_output = self.get_gdb_repr('''
296class Foo:
297 pass
298foo = Foo()
299foo.an_int = 42
300print foo''')
301 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
302 self.assertTrue(m,
303 msg='Unexpected classic-class rendering %r' % gdb_repr)
304
305 def test_modern_class(self):
306 'Verify the pretty-printing of new-style class instances'
307 gdb_repr, gdb_output = self.get_gdb_repr('''
308class Foo(object):
309 pass
310foo = Foo()
311foo.an_int = 42
312print foo''')
313 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
314 self.assertTrue(m,
315 msg='Unexpected new-style class rendering %r' % gdb_repr)
316
317 def test_subclassing_list(self):
318 'Verify the pretty-printing of an instance of a list subclass'
319 gdb_repr, gdb_output = self.get_gdb_repr('''
320class Foo(list):
321 pass
322foo = Foo()
323foo += [1, 2, 3]
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_tuple(self):
331 'Verify the pretty-printing of an instance of a tuple subclass'
332 # This should exercise the negative tp_dictoffset code in the
333 # new-style class support
334 gdb_repr, gdb_output = self.get_gdb_repr('''
335class Foo(tuple):
336 pass
337foo = Foo((1, 2, 3))
338foo.an_int = 42
339print foo''')
340 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
341 self.assertTrue(m,
342 msg='Unexpected new-style class rendering %r' % gdb_repr)
343
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000344 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000345 '''Run Python under gdb, corrupting variables in the inferior process
346 immediately before taking a backtrace.
347
348 Verify that the variable's representation is the expected failsafe
349 representation'''
350 if corruption:
351 cmds_after_breakpoint=[corruption, 'backtrace']
352 else:
353 cmds_after_breakpoint=['backtrace']
354
355 gdb_repr, gdb_output = \
356 self.get_gdb_repr(source,
357 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000358
359 if expvalue:
360 if gdb_repr == repr(expvalue):
361 # gdb managed to print the value in spite of the corruption;
362 # this is good (see http://bugs.python.org/issue8330)
363 return
364
365 if exptype:
366 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
367 else:
368 # Match anything for the type name; 0xDEADBEEF could point to
369 # something arbitrary (see http://bugs.python.org/issue8330)
370 pattern = '<.* at remote 0x[0-9a-f]+>'
371
372 m = re.match(pattern, gdb_repr)
373 if not m:
374 self.fail('Unexpected gdb representation: %r\n%s' % \
375 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000376
377 def test_NULL_ptr(self):
378 'Ensure that a NULL PyObject* is handled gracefully'
379 gdb_repr, gdb_output = (
380 self.get_gdb_repr('print 42',
381 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000382 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000383 )
384
Ezio Melotti2623a372010-11-21 13:34:58 +0000385 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000386
387 def test_NULL_ob_type(self):
388 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
389 self.assertSane('print 42',
390 'set op->ob_type=0')
391
392 def test_corrupt_ob_type(self):
393 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
394 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000395 'set op->ob_type=0xDEADBEEF',
396 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000397
398 def test_corrupt_tp_flags(self):
399 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
400 self.assertSane('print 42',
401 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000402 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000403
404 def test_corrupt_tp_name(self):
405 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
406 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000407 'set op->ob_type->tp_name=0xDEADBEEF',
408 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000409
410 def test_NULL_instance_dict(self):
411 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
412 self.assertSane('''
413class Foo:
414 pass
415foo = Foo()
416foo.an_int = 42
417print foo''',
418 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000419 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000420
421 def test_builtins_help(self):
422 'Ensure that the new-style class _Helper in site.py can be handled'
423 # (this was the issue causing tracebacks in
424 # http://bugs.python.org/issue8032#msg100537 )
425
426 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
427 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
428 self.assertTrue(m,
429 msg='Unexpected rendering %r' % gdb_repr)
430
431 def test_selfreferential_list(self):
432 '''Ensure that a reference loop involving a list doesn't lead proxyval
433 into an infinite loop:'''
434 gdb_repr, gdb_output = \
435 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
436
Ezio Melotti2623a372010-11-21 13:34:58 +0000437 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000438
439 gdb_repr, gdb_output = \
440 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
441
Ezio Melotti2623a372010-11-21 13:34:58 +0000442 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000443
444 def test_selfreferential_dict(self):
445 '''Ensure that a reference loop involving a dict doesn't lead proxyval
446 into an infinite loop:'''
447 gdb_repr, gdb_output = \
448 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
449
Ezio Melotti2623a372010-11-21 13:34:58 +0000450 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000451
452 def test_selfreferential_old_style_instance(self):
453 gdb_repr, gdb_output = \
454 self.get_gdb_repr('''
455class Foo:
456 pass
457foo = Foo()
458foo.an_attr = foo
459print foo''')
460 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
461 gdb_repr),
462 'Unexpected gdb representation: %r\n%s' % \
463 (gdb_repr, gdb_output))
464
465 def test_selfreferential_new_style_instance(self):
466 gdb_repr, gdb_output = \
467 self.get_gdb_repr('''
468class Foo(object):
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 gdb_repr, gdb_output = \
479 self.get_gdb_repr('''
480class Foo(object):
481 pass
482a = Foo()
483b = Foo()
484a.an_attr = b
485b.an_attr = a
486print a''')
487 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
488 gdb_repr),
489 'Unexpected gdb representation: %r\n%s' % \
490 (gdb_repr, gdb_output))
491
492 def test_truncation(self):
493 'Verify that very long output is truncated'
494 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000495 self.assertEqual(gdb_repr,
496 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
497 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
498 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
499 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
500 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
501 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
502 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
503 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
504 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
505 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
506 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
507 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
508 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
509 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
510 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
511 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
512 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
513 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
514 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
515 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
516 "224, 225, 226...(truncated)")
517 self.assertEqual(len(gdb_repr),
518 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000519
520 def test_builtin_function(self):
521 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000522 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000523
524 def test_builtin_method(self):
525 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
526 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
527 gdb_repr),
528 'Unexpected gdb representation: %r\n%s' % \
529 (gdb_repr, gdb_output))
530
531 def test_frames(self):
532 gdb_output = self.get_stack_trace('''
533def foo(a, b, c):
534 pass
535
536foo(3, 4, 5)
537print foo.__code__''',
538 breakpoint='PyObject_Print',
539 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
540 )
R. David Murray0c080092010-04-05 16:28:49 +0000541 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
542 gdb_output,
543 re.DOTALL),
544 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000545
546class PyListTests(DebuggerTests):
547 def assertListing(self, expected, actual):
548 self.assertEndsWith(actual, expected)
549
550 def test_basic_command(self):
551 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000552 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000553 cmds_after_breakpoint=['py-list'])
554
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000555 self.assertListing(' 5 \n'
556 ' 6 def bar(a, b, c):\n'
557 ' 7 baz(a, b, c)\n'
558 ' 8 \n'
559 ' 9 def baz(*args):\n'
560 ' >10 print(42)\n'
561 ' 11 \n'
562 ' 12 foo(1, 2, 3)\n',
563 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000564
565 def test_one_abs_arg(self):
566 'Verify the "py-list" command with one absolute argument'
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 9'])
569
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000570 self.assertListing(' 9 def baz(*args):\n'
571 ' >10 print(42)\n'
572 ' 11 \n'
573 ' 12 foo(1, 2, 3)\n',
574 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000575
576 def test_two_abs_args(self):
577 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000578 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000579 cmds_after_breakpoint=['py-list 1,3'])
580
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000581 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
582 ' 2 \n'
583 ' 3 def foo(a, b, c):\n',
584 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000585
586class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000587 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000588 def test_pyup_command(self):
589 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000590 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000591 cmds_after_breakpoint=['py-up'])
592 self.assertMultilineMatches(bt,
593 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000594#[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 +0000595 baz\(a, b, c\)
596$''')
597
Victor Stinnera92e81b2010-04-20 22:28:31 +0000598 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000599 def test_down_at_bottom(self):
600 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000601 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000602 cmds_after_breakpoint=['py-down'])
603 self.assertEndsWith(bt,
604 'Unable to find a newer python frame\n')
605
Victor Stinnera92e81b2010-04-20 22:28:31 +0000606 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000607 def test_up_at_top(self):
608 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000609 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000610 cmds_after_breakpoint=['py-up'] * 4)
611 self.assertEndsWith(bt,
612 'Unable to find an older python frame\n')
613
Victor Stinnera92e81b2010-04-20 22:28:31 +0000614 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000615 def test_up_then_down(self):
616 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000617 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000618 cmds_after_breakpoint=['py-up', 'py-down'])
619 self.assertMultilineMatches(bt,
620 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000621#[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 +0000622 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000623#[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 +0000624 print\(42\)
625$''')
626
627class PyBtTests(DebuggerTests):
628 def test_basic_command(self):
629 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000630 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000631 cmds_after_breakpoint=['py-bt'])
632 self.assertMultilineMatches(bt,
633 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000634#[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 +0000635 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000636#[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 +0000637 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000638#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000639foo\(1, 2, 3\)
640''')
641
642class PyPrintTests(DebuggerTests):
643 def test_basic_command(self):
644 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000645 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000646 cmds_after_breakpoint=['py-print args'])
647 self.assertMultilineMatches(bt,
648 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
649
Victor Stinnera92e81b2010-04-20 22:28:31 +0000650 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000651 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000652 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000653 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
654 self.assertMultilineMatches(bt,
655 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
656
657 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000658 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000659 cmds_after_breakpoint=['py-print __name__'])
660 self.assertMultilineMatches(bt,
661 r".*\nglobal '__name__' = '__main__'\n.*")
662
663 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000664 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000665 cmds_after_breakpoint=['py-print len'])
666 self.assertMultilineMatches(bt,
667 r".*\nbuiltin 'len' = <built-in function len>\n.*")
668
669class PyLocalsTests(DebuggerTests):
670 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000671 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000672 cmds_after_breakpoint=['py-locals'])
673 self.assertMultilineMatches(bt,
674 r".*\nargs = \(1, 2, 3\)\n.*")
675
Victor Stinnera92e81b2010-04-20 22:28:31 +0000676 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000677 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000678 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000679 cmds_after_breakpoint=['py-up', 'py-locals'])
680 self.assertMultilineMatches(bt,
681 r".*\na = 1\nb = 2\nc = 3\n.*")
682
683def test_main():
Antoine Pitrou22db7352010-07-08 18:54:04 +0000684 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
685 final_opt = ""
686 for opt in cflags.split():
687 if opt.startswith('-O'):
688 final_opt = opt
689 if final_opt and final_opt != '-O0':
690 raise unittest.SkipTest("Python was built with compiler optimizations, "
691 "tests can't reliably succeed")
692
Martin v. Löwis5a965432010-04-12 05:22:25 +0000693 run_unittest(PrettyPrintTests,
694 PyListTests,
695 StackNavigationTests,
696 PyBtTests,
697 PyPrintTests,
698 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000699 )
700
701if __name__ == "__main__":
702 test_main()