blob: 9d8ff8ed8a1a7e6d12b5f7562938e80d0a5451bb [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")
R David Murray3e66f0d2012-10-27 13:47:49 -040022gdb_version_number = re.search("^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
23gdb_major_version = int(gdb_version_number.group(1))
24gdb_minor_version = int(gdb_version_number.group(2))
25if gdb_major_version < 7:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000026 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
27 " Saw:\n" + gdb_version)
28
R David Murray3e66f0d2012-10-27 13:47:49 -040029# Location of custom hooks file in a repository checkout.
30checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
31 'python-gdb.py')
32
33def run_gdb(*args, **env_vars):
34 """Runs gdb in --batch mode with the additional arguments given by *args.
35
36 Returns its (stdout, stderr)
37 """
38 if env_vars:
39 env = os.environ.copy()
40 env.update(env_vars)
41 else:
42 env = None
43 base_cmd = ('gdb', '--batch')
44 if (gdb_major_version, gdb_minor_version) >= (7, 4):
45 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
46 out, err = subprocess.Popen(base_cmd + args,
47 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
48 ).communicate()
49 return out, err
50
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000051# Verify that "gdb" was built with the embedded python support enabled:
R David Murray3e66f0d2012-10-27 13:47:49 -040052gdbpy_version, _ = run_gdb("--eval-command=python import sys; print sys.version_info")
53if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000054 raise unittest.SkipTest("gdb not built with embedded python support")
55
R David Murray3e66f0d2012-10-27 13:47:49 -040056# Verify that "gdb" can load our custom hooks. In theory this should never
57# fail, but we don't handle the case of the hooks file not existing if the
58# tests are run from an installed Python (we'll produce failures in that case).
59cmd = ['--args', sys.executable]
60_, gdbpy_errors = run_gdb('--args', sys.executable)
61if "auto-loading has been declined" in gdbpy_errors:
62 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlana0933122012-06-17 19:03:39 +100063
Victor Stinner99cff3f2011-12-19 13:59:58 +010064def python_is_optimized():
65 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
66 final_opt = ""
67 for opt in cflags.split():
68 if opt.startswith('-O'):
69 final_opt = opt
70 return (final_opt and final_opt != '-O0')
71
Victor Stinnera92e81b2010-04-20 22:28:31 +000072def gdb_has_frame_select():
73 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040074 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000075 m = re.match(r'.*\[(.*)\].*', stdout)
76 if not m:
77 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
78 gdb_frame_dir = m.group(1).split(', ')
79 return "'select'" in gdb_frame_dir
80
81HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000082
83class DebuggerTests(unittest.TestCase):
84
85 """Test that the debugger can debug Python."""
86
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000087 def get_stack_trace(self, source=None, script=None,
88 breakpoint='PyObject_Print',
89 cmds_after_breakpoint=None,
90 import_site=False):
91 '''
92 Run 'python -c SOURCE' under gdb with a breakpoint.
93
94 Support injecting commands after the breakpoint is reached
95
96 Returns the stdout from gdb
97
98 cmds_after_breakpoint: if provided, a list of strings: gdb commands
99 '''
100 # We use "set breakpoint pending yes" to avoid blocking with a:
101 # Function "foo" not defined.
102 # Make breakpoint pending on future shared library load? (y or [n])
103 # error, which typically happens python is dynamically linked (the
104 # breakpoints of interest are to be found in the shared library)
105 # When this happens, we still get:
106 # Function "PyObject_Print" not defined.
107 # emitted to stderr each time, alas.
108
109 # Initially I had "--eval-command=continue" here, but removed it to
110 # avoid repeated print breakpoints when traversing hierarchical data
111 # structures
112
113 # Generate a list of commands in gdb's language:
114 commands = ['set breakpoint pending yes',
115 'break %s' % breakpoint,
116 'run']
117 if cmds_after_breakpoint:
118 commands += cmds_after_breakpoint
119 else:
120 commands += ['backtrace']
121
122 # print commands
123
124 # Use "commands" to generate the arguments with which to invoke "gdb":
125 args = ["gdb", "--batch"]
126 args += ['--eval-command=%s' % cmd for cmd in commands]
127 args += ["--args",
128 sys.executable]
129
130 if not import_site:
131 # -S suppresses the default 'import site'
132 args += ["-S"]
133
134 if source:
135 args += ["-c", source]
136 elif script:
137 args += [script]
138
139 # print args
140 # print ' '.join(args)
141
142 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400143 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000144
145 # Ignore some noise on stderr due to the pending breakpoint:
146 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000147 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
148 err = err.replace("warning: Unable to find libthread_db matching"
149 " inferior's thread library, thread debugging will"
150 " not be available.\n",
151 '')
Jesus Cea6905de12011-03-16 01:19:49 +0100152 err = err.replace("warning: Cannot initialize thread debugging"
153 " library: Debugger service failed\n",
154 '')
Benjamin Petersonfb2f4092012-09-20 23:48:23 -0400155 err = err.replace('warning: Could not load shared library symbols for '
156 'linux-vdso.so.1.\n'
157 'Do you need "set solib-search-path" or '
158 '"set sysroot"?\n',
159 '')
R David Murray3e66f0d2012-10-27 13:47:49 -0400160 err = err.replace('warning: Could not load shared library symbols for '
161 'linux-gate.so.1.\n'
162 'Do you need "set solib-search-path" or '
163 '"set sysroot"?\n',
164 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000165
166 # Ensure no unexpected error messages:
Ezio Melotti2623a372010-11-21 13:34:58 +0000167 self.assertEqual(err, '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000168
169 return out
170
171 def get_gdb_repr(self, source,
172 cmds_after_breakpoint=None,
173 import_site=False):
174 # Given an input python source representation of data,
175 # run "python -c'print DATA'" under gdb with a breakpoint on
176 # PyObject_Print and scrape out gdb's representation of the "op"
177 # parameter, and verify that the gdb displays the same string
178 #
179 # For a nested structure, the first time we hit the breakpoint will
180 # give us the top-level structure
181 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
182 cmds_after_breakpoint=cmds_after_breakpoint,
183 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000184 # gdb can insert additional '\n' and space characters in various places
185 # in its output, depending on the width of the terminal it's connected
186 # to (using its "wrap_here" function)
187 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000188 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000189 if not m:
190 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000191 return m.group(1), gdb_output
192
193 def assertEndsWith(self, actual, exp_end):
194 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000195 self.assertTrue(actual.endswith(exp_end),
196 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000197
198 def assertMultilineMatches(self, actual, pattern):
199 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000200 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000201
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000202 def get_sample_script(self):
203 return findfile('gdb_sample.py')
204
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000205class PrettyPrintTests(DebuggerTests):
206 def test_getting_backtrace(self):
207 gdb_output = self.get_stack_trace('print 42')
208 self.assertTrue('PyObject_Print' in gdb_output)
209
210 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
211 # Ensure that gdb's rendering of the value in a debugged process
212 # matches repr(value) in this process:
213 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
214 cmds_after_breakpoint)
Ezio Melotti2623a372010-11-21 13:34:58 +0000215 self.assertEqual(gdb_repr, repr(val), gdb_output)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000216
217 def test_int(self):
218 'Verify the pretty-printing of various "int" values'
219 self.assertGdbRepr(42)
220 self.assertGdbRepr(0)
221 self.assertGdbRepr(-7)
222 self.assertGdbRepr(sys.maxint)
223 self.assertGdbRepr(-sys.maxint)
224
225 def test_long(self):
226 'Verify the pretty-printing of various "long" values'
227 self.assertGdbRepr(0L)
228 self.assertGdbRepr(1000000000000L)
229 self.assertGdbRepr(-1L)
230 self.assertGdbRepr(-1000000000000000L)
231
232 def test_singletons(self):
233 'Verify the pretty-printing of True, False and None'
234 self.assertGdbRepr(True)
235 self.assertGdbRepr(False)
236 self.assertGdbRepr(None)
237
238 def test_dicts(self):
239 'Verify the pretty-printing of dictionaries'
240 self.assertGdbRepr({})
241 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500242 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000243
244 def test_lists(self):
245 'Verify the pretty-printing of lists'
246 self.assertGdbRepr([])
247 self.assertGdbRepr(range(5))
248
249 def test_strings(self):
250 'Verify the pretty-printing of strings'
251 self.assertGdbRepr('')
252 self.assertGdbRepr('And now for something hopefully the same')
253 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
254 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
255
256 def test_tuples(self):
257 'Verify the pretty-printing of tuples'
258 self.assertGdbRepr(tuple())
259 self.assertGdbRepr((1,))
260 self.assertGdbRepr(('foo', 'bar', 'baz'))
261
262 def test_unicode(self):
263 'Verify the pretty-printing of unicode values'
264 # Test the empty unicode string:
265 self.assertGdbRepr(u'')
266
267 self.assertGdbRepr(u'hello world')
268
269 # Test printing a single character:
270 # U+2620 SKULL AND CROSSBONES
271 self.assertGdbRepr(u'\u2620')
272
273 # Test printing a Japanese unicode string
274 # (I believe this reads "mojibake", using 3 characters from the CJK
275 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
276 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
277
278 # Test a character outside the BMP:
279 # U+1D121 MUSICAL SYMBOL C CLEF
280 # This is:
281 # UTF-8: 0xF0 0x9D 0x84 0xA1
282 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000283 # This will only work on wide-unicode builds:
284 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000285
286 def test_sets(self):
287 'Verify the pretty-printing of sets'
288 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500289 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
290 self.assertTrue(rep.startswith("set(["))
291 self.assertTrue(rep.endswith("])"))
292 self.assertEqual(eval(rep), {'a', 'b'})
293 rep = self.get_gdb_repr("print set([4, 5])")[0]
294 self.assertTrue(rep.startswith("set(["))
295 self.assertTrue(rep.endswith("])"))
296 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000297
298 # Ensure that we handled sets containing the "dummy" key value,
299 # which happens on deletion:
300 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
301s.pop()
302print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000303 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000304
305 def test_frozensets(self):
306 'Verify the pretty-printing of frozensets'
307 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500308 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
309 self.assertTrue(rep.startswith("frozenset(["))
310 self.assertTrue(rep.endswith("])"))
311 self.assertEqual(eval(rep), {'a', 'b'})
312 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
313 self.assertTrue(rep.startswith("frozenset(["))
314 self.assertTrue(rep.endswith("])"))
315 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000316
317 def test_exceptions(self):
318 # Test a RuntimeError
319 gdb_repr, gdb_output = self.get_gdb_repr('''
320try:
321 raise RuntimeError("I am an error")
322except RuntimeError, e:
323 print e
324''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000325 self.assertEqual(gdb_repr,
326 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000327
328
329 # Test division by zero:
330 gdb_repr, gdb_output = self.get_gdb_repr('''
331try:
332 a = 1 / 0
333except ZeroDivisionError, e:
334 print e
335''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000336 self.assertEqual(gdb_repr,
337 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000338
339 def test_classic_class(self):
340 'Verify the pretty-printing of classic class instances'
341 gdb_repr, gdb_output = self.get_gdb_repr('''
342class Foo:
343 pass
344foo = Foo()
345foo.an_int = 42
346print foo''')
347 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
348 self.assertTrue(m,
349 msg='Unexpected classic-class rendering %r' % gdb_repr)
350
351 def test_modern_class(self):
352 'Verify the pretty-printing of new-style class instances'
353 gdb_repr, gdb_output = self.get_gdb_repr('''
354class Foo(object):
355 pass
356foo = Foo()
357foo.an_int = 42
358print foo''')
359 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
360 self.assertTrue(m,
361 msg='Unexpected new-style class rendering %r' % gdb_repr)
362
363 def test_subclassing_list(self):
364 'Verify the pretty-printing of an instance of a list subclass'
365 gdb_repr, gdb_output = self.get_gdb_repr('''
366class Foo(list):
367 pass
368foo = Foo()
369foo += [1, 2, 3]
370foo.an_int = 42
371print foo''')
372 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
373 self.assertTrue(m,
374 msg='Unexpected new-style class rendering %r' % gdb_repr)
375
376 def test_subclassing_tuple(self):
377 'Verify the pretty-printing of an instance of a tuple subclass'
378 # This should exercise the negative tp_dictoffset code in the
379 # new-style class support
380 gdb_repr, gdb_output = self.get_gdb_repr('''
381class Foo(tuple):
382 pass
383foo = Foo((1, 2, 3))
384foo.an_int = 42
385print foo''')
386 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
387 self.assertTrue(m,
388 msg='Unexpected new-style class rendering %r' % gdb_repr)
389
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000390 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000391 '''Run Python under gdb, corrupting variables in the inferior process
392 immediately before taking a backtrace.
393
394 Verify that the variable's representation is the expected failsafe
395 representation'''
396 if corruption:
397 cmds_after_breakpoint=[corruption, 'backtrace']
398 else:
399 cmds_after_breakpoint=['backtrace']
400
401 gdb_repr, gdb_output = \
402 self.get_gdb_repr(source,
403 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000404
405 if expvalue:
406 if gdb_repr == repr(expvalue):
407 # gdb managed to print the value in spite of the corruption;
408 # this is good (see http://bugs.python.org/issue8330)
409 return
410
411 if exptype:
412 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
413 else:
414 # Match anything for the type name; 0xDEADBEEF could point to
415 # something arbitrary (see http://bugs.python.org/issue8330)
416 pattern = '<.* at remote 0x[0-9a-f]+>'
417
418 m = re.match(pattern, gdb_repr)
419 if not m:
420 self.fail('Unexpected gdb representation: %r\n%s' % \
421 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000422
423 def test_NULL_ptr(self):
424 'Ensure that a NULL PyObject* is handled gracefully'
425 gdb_repr, gdb_output = (
426 self.get_gdb_repr('print 42',
427 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000428 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000429 )
430
Ezio Melotti2623a372010-11-21 13:34:58 +0000431 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000432
433 def test_NULL_ob_type(self):
434 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
435 self.assertSane('print 42',
436 'set op->ob_type=0')
437
438 def test_corrupt_ob_type(self):
439 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
440 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000441 'set op->ob_type=0xDEADBEEF',
442 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000443
444 def test_corrupt_tp_flags(self):
445 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
446 self.assertSane('print 42',
447 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000448 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000449
450 def test_corrupt_tp_name(self):
451 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
452 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000453 'set op->ob_type->tp_name=0xDEADBEEF',
454 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000455
456 def test_NULL_instance_dict(self):
457 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
458 self.assertSane('''
459class Foo:
460 pass
461foo = Foo()
462foo.an_int = 42
463print foo''',
464 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000465 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000466
467 def test_builtins_help(self):
468 'Ensure that the new-style class _Helper in site.py can be handled'
469 # (this was the issue causing tracebacks in
470 # http://bugs.python.org/issue8032#msg100537 )
471
472 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
473 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
474 self.assertTrue(m,
475 msg='Unexpected rendering %r' % gdb_repr)
476
477 def test_selfreferential_list(self):
478 '''Ensure that a reference loop involving a list doesn't lead proxyval
479 into an infinite loop:'''
480 gdb_repr, gdb_output = \
481 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
482
Ezio Melotti2623a372010-11-21 13:34:58 +0000483 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000484
485 gdb_repr, gdb_output = \
486 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
487
Ezio Melotti2623a372010-11-21 13:34:58 +0000488 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000489
490 def test_selfreferential_dict(self):
491 '''Ensure that a reference loop involving a dict doesn't lead proxyval
492 into an infinite loop:'''
493 gdb_repr, gdb_output = \
494 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
495
Ezio Melotti2623a372010-11-21 13:34:58 +0000496 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000497
498 def test_selfreferential_old_style_instance(self):
499 gdb_repr, gdb_output = \
500 self.get_gdb_repr('''
501class Foo:
502 pass
503foo = Foo()
504foo.an_attr = foo
505print foo''')
506 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
507 gdb_repr),
508 'Unexpected gdb representation: %r\n%s' % \
509 (gdb_repr, gdb_output))
510
511 def test_selfreferential_new_style_instance(self):
512 gdb_repr, gdb_output = \
513 self.get_gdb_repr('''
514class Foo(object):
515 pass
516foo = Foo()
517foo.an_attr = foo
518print foo''')
519 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
520 gdb_repr),
521 'Unexpected gdb representation: %r\n%s' % \
522 (gdb_repr, gdb_output))
523
524 gdb_repr, gdb_output = \
525 self.get_gdb_repr('''
526class Foo(object):
527 pass
528a = Foo()
529b = Foo()
530a.an_attr = b
531b.an_attr = a
532print a''')
533 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
534 gdb_repr),
535 'Unexpected gdb representation: %r\n%s' % \
536 (gdb_repr, gdb_output))
537
538 def test_truncation(self):
539 'Verify that very long output is truncated'
540 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000541 self.assertEqual(gdb_repr,
542 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
543 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
544 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
545 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
546 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
547 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
548 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
549 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
550 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
551 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
552 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
553 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
554 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
555 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
556 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
557 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
558 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
559 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
560 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
561 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
562 "224, 225, 226...(truncated)")
563 self.assertEqual(len(gdb_repr),
564 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000565
566 def test_builtin_function(self):
567 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000568 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000569
570 def test_builtin_method(self):
571 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
572 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
573 gdb_repr),
574 'Unexpected gdb representation: %r\n%s' % \
575 (gdb_repr, gdb_output))
576
577 def test_frames(self):
578 gdb_output = self.get_stack_trace('''
579def foo(a, b, c):
580 pass
581
582foo(3, 4, 5)
583print foo.__code__''',
584 breakpoint='PyObject_Print',
585 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
586 )
R. David Murray0c080092010-04-05 16:28:49 +0000587 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
588 gdb_output,
589 re.DOTALL),
590 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000591
Victor Stinner99cff3f2011-12-19 13:59:58 +0100592@unittest.skipIf(python_is_optimized(),
593 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000594class PyListTests(DebuggerTests):
595 def assertListing(self, expected, actual):
596 self.assertEndsWith(actual, expected)
597
598 def test_basic_command(self):
599 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000600 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000601 cmds_after_breakpoint=['py-list'])
602
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000603 self.assertListing(' 5 \n'
604 ' 6 def bar(a, b, c):\n'
605 ' 7 baz(a, b, c)\n'
606 ' 8 \n'
607 ' 9 def baz(*args):\n'
608 ' >10 print(42)\n'
609 ' 11 \n'
610 ' 12 foo(1, 2, 3)\n',
611 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000612
613 def test_one_abs_arg(self):
614 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000615 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000616 cmds_after_breakpoint=['py-list 9'])
617
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000618 self.assertListing(' 9 def baz(*args):\n'
619 ' >10 print(42)\n'
620 ' 11 \n'
621 ' 12 foo(1, 2, 3)\n',
622 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000623
624 def test_two_abs_args(self):
625 'Verify the "py-list" command with two absolute arguments'
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-list 1,3'])
628
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000629 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
630 ' 2 \n'
631 ' 3 def foo(a, b, c):\n',
632 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000633
634class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000635 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100636 @unittest.skipIf(python_is_optimized(),
637 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000638 def test_pyup_command(self):
639 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000640 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000641 cmds_after_breakpoint=['py-up'])
642 self.assertMultilineMatches(bt,
643 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000644#[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 +0000645 baz\(a, b, c\)
646$''')
647
Victor Stinnera92e81b2010-04-20 22:28:31 +0000648 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000649 def test_down_at_bottom(self):
650 'Verify handling of "py-down" at the bottom of the stack'
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-down'])
653 self.assertEndsWith(bt,
654 'Unable to find a newer python frame\n')
655
Victor Stinnera92e81b2010-04-20 22:28:31 +0000656 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657 def test_up_at_top(self):
658 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000659 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000660 cmds_after_breakpoint=['py-up'] * 4)
661 self.assertEndsWith(bt,
662 'Unable to find an older python frame\n')
663
Victor Stinnera92e81b2010-04-20 22:28:31 +0000664 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100665 @unittest.skipIf(python_is_optimized(),
666 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000667 def test_up_then_down(self):
668 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000669 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000670 cmds_after_breakpoint=['py-up', 'py-down'])
671 self.assertMultilineMatches(bt,
672 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000673#[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 +0000674 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000675#[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 +0000676 print\(42\)
677$''')
678
679class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100680 @unittest.skipIf(python_is_optimized(),
681 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000682 def test_basic_command(self):
683 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000684 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000685 cmds_after_breakpoint=['py-bt'])
686 self.assertMultilineMatches(bt,
687 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000688#[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 +0000689 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000690#[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 +0000691 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000692#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100693 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000694''')
695
696class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100697 @unittest.skipIf(python_is_optimized(),
698 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000699 def test_basic_command(self):
700 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000701 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000702 cmds_after_breakpoint=['py-print args'])
703 self.assertMultilineMatches(bt,
704 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
705
Victor Stinnera92e81b2010-04-20 22:28:31 +0000706 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100707 @unittest.skipIf(python_is_optimized(),
708 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000709 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000710 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000711 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
712 self.assertMultilineMatches(bt,
713 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
714
Victor Stinner99cff3f2011-12-19 13:59:58 +0100715 @unittest.skipIf(python_is_optimized(),
716 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000717 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000718 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000719 cmds_after_breakpoint=['py-print __name__'])
720 self.assertMultilineMatches(bt,
721 r".*\nglobal '__name__' = '__main__'\n.*")
722
Victor Stinner99cff3f2011-12-19 13:59:58 +0100723 @unittest.skipIf(python_is_optimized(),
724 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000725 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000726 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000727 cmds_after_breakpoint=['py-print len'])
728 self.assertMultilineMatches(bt,
729 r".*\nbuiltin 'len' = <built-in function len>\n.*")
730
731class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100732 @unittest.skipIf(python_is_optimized(),
733 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000734 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000735 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000736 cmds_after_breakpoint=['py-locals'])
737 self.assertMultilineMatches(bt,
738 r".*\nargs = \(1, 2, 3\)\n.*")
739
Victor Stinnera92e81b2010-04-20 22:28:31 +0000740 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100741 @unittest.skipIf(python_is_optimized(),
742 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000743 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000744 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000745 cmds_after_breakpoint=['py-up', 'py-locals'])
746 self.assertMultilineMatches(bt,
747 r".*\na = 1\nb = 2\nc = 3\n.*")
748
749def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000750 run_unittest(PrettyPrintTests,
751 PyListTests,
752 StackNavigationTests,
753 PyBtTests,
754 PyPrintTests,
755 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000756 )
757
758if __name__ == "__main__":
759 test_main()