blob: 948e7ca4e76d13b7e6f722c038777826823ea1b1 [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:
Victor Stinner8bd34152014-08-16 14:31:02 +020016 gdb_version, _ = subprocess.Popen(["gdb", "-nx", "--version"],
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000017 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)
Benjamin Peterson51f461f2014-11-23 22:34:04 -060028if sys.platform.startswith("sunos"):
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060029 raise unittest.SkipTest("test doesn't work very well on Solaris")
30
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000031
R David Murray3e66f0d2012-10-27 13:47:49 -040032# Location of custom hooks file in a repository checkout.
33checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
34 'python-gdb.py')
35
36def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020037 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040038
39 Returns its (stdout, stderr)
40 """
41 if env_vars:
42 env = os.environ.copy()
43 env.update(env_vars)
44 else:
45 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020046 # -nx: Do not execute commands from any .gdbinit initialization files
47 # (issue #22188)
48 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040049 if (gdb_major_version, gdb_minor_version) >= (7, 4):
50 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
51 out, err = subprocess.Popen(base_cmd + args,
52 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
53 ).communicate()
54 return out, err
55
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010057gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040058if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000059 raise unittest.SkipTest("gdb not built with embedded python support")
60
Nick Coghlan254a3772013-09-22 19:36:09 +100061# Verify that "gdb" can load our custom hooks, as OS security settings may
62# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040063cmd = ['--args', sys.executable]
64_, gdbpy_errors = run_gdb('--args', sys.executable)
65if "auto-loading has been declined" in gdbpy_errors:
66 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100067 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100068
Victor Stinner99cff3f2011-12-19 13:59:58 +010069def python_is_optimized():
70 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
71 final_opt = ""
72 for opt in cflags.split():
73 if opt.startswith('-O'):
74 final_opt = opt
75 return (final_opt and final_opt != '-O0')
76
Victor Stinnera92e81b2010-04-20 22:28:31 +000077def gdb_has_frame_select():
78 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040079 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000080 m = re.match(r'.*\[(.*)\].*', stdout)
81 if not m:
82 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
83 gdb_frame_dir = m.group(1).split(', ')
84 return "'select'" in gdb_frame_dir
85
86HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000087
88class DebuggerTests(unittest.TestCase):
89
90 """Test that the debugger can debug Python."""
91
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000092 def get_stack_trace(self, source=None, script=None,
93 breakpoint='PyObject_Print',
94 cmds_after_breakpoint=None,
95 import_site=False):
96 '''
97 Run 'python -c SOURCE' under gdb with a breakpoint.
98
99 Support injecting commands after the breakpoint is reached
100
101 Returns the stdout from gdb
102
103 cmds_after_breakpoint: if provided, a list of strings: gdb commands
104 '''
105 # We use "set breakpoint pending yes" to avoid blocking with a:
106 # Function "foo" not defined.
107 # Make breakpoint pending on future shared library load? (y or [n])
108 # error, which typically happens python is dynamically linked (the
109 # breakpoints of interest are to be found in the shared library)
110 # When this happens, we still get:
111 # Function "PyObject_Print" not defined.
112 # emitted to stderr each time, alas.
113
114 # Initially I had "--eval-command=continue" here, but removed it to
115 # avoid repeated print breakpoints when traversing hierarchical data
116 # structures
117
118 # Generate a list of commands in gdb's language:
119 commands = ['set breakpoint pending yes',
120 'break %s' % breakpoint,
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200121
122 # GDB as of 7.4 (?) onwards can distinguish between the
123 # value of a variable at entry vs current value:
124 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
125 # which leads to the selftests failing with errors like this:
126 # AssertionError: 'v@entry=()' != '()'
127 # Disable this:
128 'set print entry-values no',
129
130 # The tests assume that the first frame of printed
131 # backtrace will not contain program counter,
132 # that is however not guaranteed by gdb
133 # therefore we need to use 'set print address off' to
134 # make sure the counter is not there. For example:
135 # #0 in PyObject_Print ...
136 # is assumed, but sometimes this can be e.g.
137 # #0 0x00003fffb7dd1798 in PyObject_Print ...
138 'set print address off',
139
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000140 'run']
141 if cmds_after_breakpoint:
142 commands += cmds_after_breakpoint
143 else:
144 commands += ['backtrace']
145
146 # print commands
147
148 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200149 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000150 args += ['--eval-command=%s' % cmd for cmd in commands]
151 args += ["--args",
152 sys.executable]
153
154 if not import_site:
155 # -S suppresses the default 'import site'
156 args += ["-S"]
157
158 if source:
159 args += ["-c", source]
160 elif script:
161 args += [script]
162
163 # print args
164 # print ' '.join(args)
165
166 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400167 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000168
Antoine Pitroub996e042013-05-01 00:15:44 +0200169 errlines = err.splitlines()
170 unexpected_errlines = []
171
172 # Ignore some benign messages on stderr.
173 ignore_patterns = (
174 'Function "%s" not defined.' % breakpoint,
175 "warning: no loadable sections found in added symbol-file"
176 " system-supplied DSO",
177 "warning: Unable to find libthread_db matching"
178 " inferior's thread library, thread debugging will"
179 " not be available.",
180 "warning: Cannot initialize thread debugging"
181 " library: Debugger service failed",
182 'warning: Could not load shared library symbols for '
183 'linux-vdso.so',
184 'warning: Could not load shared library symbols for '
185 'linux-gate.so',
186 'Do you need "set solib-search-path" or '
187 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100188 'warning: Source file is more recent than executable.',
189 # Issue #19753: missing symbols on System Z
190 'Missing separate debuginfo for ',
191 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200192 )
193 for line in errlines:
194 if not line.startswith(ignore_patterns):
195 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000196
197 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200198 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000199 return out
200
201 def get_gdb_repr(self, source,
202 cmds_after_breakpoint=None,
203 import_site=False):
204 # Given an input python source representation of data,
205 # run "python -c'print DATA'" under gdb with a breakpoint on
206 # PyObject_Print and scrape out gdb's representation of the "op"
207 # parameter, and verify that the gdb displays the same string
208 #
209 # For a nested structure, the first time we hit the breakpoint will
210 # give us the top-level structure
211 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
212 cmds_after_breakpoint=cmds_after_breakpoint,
213 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000214 # gdb can insert additional '\n' and space characters in various places
215 # in its output, depending on the width of the terminal it's connected
216 # to (using its "wrap_here" function)
217 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000218 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000219 if not m:
220 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000221 return m.group(1), gdb_output
222
223 def assertEndsWith(self, actual, exp_end):
224 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000225 self.assertTrue(actual.endswith(exp_end),
226 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000227
228 def assertMultilineMatches(self, actual, pattern):
229 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000230 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000231
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000232 def get_sample_script(self):
233 return findfile('gdb_sample.py')
234
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000235class PrettyPrintTests(DebuggerTests):
236 def test_getting_backtrace(self):
237 gdb_output = self.get_stack_trace('print 42')
238 self.assertTrue('PyObject_Print' in gdb_output)
239
240 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
241 # Ensure that gdb's rendering of the value in a debugged process
242 # matches repr(value) in this process:
243 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
244 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100245 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000246
247 def test_int(self):
248 'Verify the pretty-printing of various "int" values'
249 self.assertGdbRepr(42)
250 self.assertGdbRepr(0)
251 self.assertGdbRepr(-7)
252 self.assertGdbRepr(sys.maxint)
253 self.assertGdbRepr(-sys.maxint)
254
255 def test_long(self):
256 'Verify the pretty-printing of various "long" values'
257 self.assertGdbRepr(0L)
258 self.assertGdbRepr(1000000000000L)
259 self.assertGdbRepr(-1L)
260 self.assertGdbRepr(-1000000000000000L)
261
262 def test_singletons(self):
263 'Verify the pretty-printing of True, False and None'
264 self.assertGdbRepr(True)
265 self.assertGdbRepr(False)
266 self.assertGdbRepr(None)
267
268 def test_dicts(self):
269 'Verify the pretty-printing of dictionaries'
270 self.assertGdbRepr({})
271 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500272 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000273
274 def test_lists(self):
275 'Verify the pretty-printing of lists'
276 self.assertGdbRepr([])
277 self.assertGdbRepr(range(5))
278
279 def test_strings(self):
280 'Verify the pretty-printing of strings'
281 self.assertGdbRepr('')
282 self.assertGdbRepr('And now for something hopefully the same')
283 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
284 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
285
286 def test_tuples(self):
287 'Verify the pretty-printing of tuples'
288 self.assertGdbRepr(tuple())
289 self.assertGdbRepr((1,))
290 self.assertGdbRepr(('foo', 'bar', 'baz'))
291
292 def test_unicode(self):
293 'Verify the pretty-printing of unicode values'
294 # Test the empty unicode string:
295 self.assertGdbRepr(u'')
296
297 self.assertGdbRepr(u'hello world')
298
299 # Test printing a single character:
300 # U+2620 SKULL AND CROSSBONES
301 self.assertGdbRepr(u'\u2620')
302
303 # Test printing a Japanese unicode string
304 # (I believe this reads "mojibake", using 3 characters from the CJK
305 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
306 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
307
308 # Test a character outside the BMP:
309 # U+1D121 MUSICAL SYMBOL C CLEF
310 # This is:
311 # UTF-8: 0xF0 0x9D 0x84 0xA1
312 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000313 # This will only work on wide-unicode builds:
314 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000315
316 def test_sets(self):
317 'Verify the pretty-printing of sets'
318 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500319 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
320 self.assertTrue(rep.startswith("set(["))
321 self.assertTrue(rep.endswith("])"))
322 self.assertEqual(eval(rep), {'a', 'b'})
323 rep = self.get_gdb_repr("print set([4, 5])")[0]
324 self.assertTrue(rep.startswith("set(["))
325 self.assertTrue(rep.endswith("])"))
326 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000327
328 # Ensure that we handled sets containing the "dummy" key value,
329 # which happens on deletion:
330 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
331s.pop()
332print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000333 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000334
335 def test_frozensets(self):
336 'Verify the pretty-printing of frozensets'
337 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500338 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
339 self.assertTrue(rep.startswith("frozenset(["))
340 self.assertTrue(rep.endswith("])"))
341 self.assertEqual(eval(rep), {'a', 'b'})
342 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
343 self.assertTrue(rep.startswith("frozenset(["))
344 self.assertTrue(rep.endswith("])"))
345 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000346
347 def test_exceptions(self):
348 # Test a RuntimeError
349 gdb_repr, gdb_output = self.get_gdb_repr('''
350try:
351 raise RuntimeError("I am an error")
352except RuntimeError, e:
353 print e
354''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000355 self.assertEqual(gdb_repr,
356 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000357
358
359 # Test division by zero:
360 gdb_repr, gdb_output = self.get_gdb_repr('''
361try:
362 a = 1 / 0
363except ZeroDivisionError, e:
364 print e
365''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000366 self.assertEqual(gdb_repr,
367 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000368
369 def test_classic_class(self):
370 'Verify the pretty-printing of classic class instances'
371 gdb_repr, gdb_output = self.get_gdb_repr('''
372class Foo:
373 pass
374foo = Foo()
375foo.an_int = 42
376print foo''')
377 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
378 self.assertTrue(m,
379 msg='Unexpected classic-class rendering %r' % gdb_repr)
380
381 def test_modern_class(self):
382 'Verify the pretty-printing of new-style class instances'
383 gdb_repr, gdb_output = self.get_gdb_repr('''
384class Foo(object):
385 pass
386foo = Foo()
387foo.an_int = 42
388print foo''')
389 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
390 self.assertTrue(m,
391 msg='Unexpected new-style class rendering %r' % gdb_repr)
392
393 def test_subclassing_list(self):
394 'Verify the pretty-printing of an instance of a list subclass'
395 gdb_repr, gdb_output = self.get_gdb_repr('''
396class Foo(list):
397 pass
398foo = Foo()
399foo += [1, 2, 3]
400foo.an_int = 42
401print foo''')
402 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
403 self.assertTrue(m,
404 msg='Unexpected new-style class rendering %r' % gdb_repr)
405
406 def test_subclassing_tuple(self):
407 'Verify the pretty-printing of an instance of a tuple subclass'
408 # This should exercise the negative tp_dictoffset code in the
409 # new-style class support
410 gdb_repr, gdb_output = self.get_gdb_repr('''
411class Foo(tuple):
412 pass
413foo = Foo((1, 2, 3))
414foo.an_int = 42
415print foo''')
416 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
417 self.assertTrue(m,
418 msg='Unexpected new-style class rendering %r' % gdb_repr)
419
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000420 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000421 '''Run Python under gdb, corrupting variables in the inferior process
422 immediately before taking a backtrace.
423
424 Verify that the variable's representation is the expected failsafe
425 representation'''
426 if corruption:
427 cmds_after_breakpoint=[corruption, 'backtrace']
428 else:
429 cmds_after_breakpoint=['backtrace']
430
431 gdb_repr, gdb_output = \
432 self.get_gdb_repr(source,
433 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000434
435 if expvalue:
436 if gdb_repr == repr(expvalue):
437 # gdb managed to print the value in spite of the corruption;
438 # this is good (see http://bugs.python.org/issue8330)
439 return
440
441 if exptype:
442 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
443 else:
444 # Match anything for the type name; 0xDEADBEEF could point to
445 # something arbitrary (see http://bugs.python.org/issue8330)
446 pattern = '<.* at remote 0x[0-9a-f]+>'
447
448 m = re.match(pattern, gdb_repr)
449 if not m:
450 self.fail('Unexpected gdb representation: %r\n%s' % \
451 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000452
453 def test_NULL_ptr(self):
454 'Ensure that a NULL PyObject* is handled gracefully'
455 gdb_repr, gdb_output = (
456 self.get_gdb_repr('print 42',
457 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000458 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000459 )
460
Ezio Melotti2623a372010-11-21 13:34:58 +0000461 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000462
463 def test_NULL_ob_type(self):
464 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
465 self.assertSane('print 42',
466 'set op->ob_type=0')
467
468 def test_corrupt_ob_type(self):
469 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
470 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000471 'set op->ob_type=0xDEADBEEF',
472 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000473
474 def test_corrupt_tp_flags(self):
475 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
476 self.assertSane('print 42',
477 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000478 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000479
480 def test_corrupt_tp_name(self):
481 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
482 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000483 'set op->ob_type->tp_name=0xDEADBEEF',
484 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000485
486 def test_NULL_instance_dict(self):
487 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
488 self.assertSane('''
489class Foo:
490 pass
491foo = Foo()
492foo.an_int = 42
493print foo''',
494 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000495 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000496
497 def test_builtins_help(self):
498 'Ensure that the new-style class _Helper in site.py can be handled'
499 # (this was the issue causing tracebacks in
500 # http://bugs.python.org/issue8032#msg100537 )
501
502 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
503 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
504 self.assertTrue(m,
505 msg='Unexpected rendering %r' % gdb_repr)
506
507 def test_selfreferential_list(self):
508 '''Ensure that a reference loop involving a list doesn't lead proxyval
509 into an infinite loop:'''
510 gdb_repr, gdb_output = \
511 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
512
Ezio Melotti2623a372010-11-21 13:34:58 +0000513 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000514
515 gdb_repr, gdb_output = \
516 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
517
Ezio Melotti2623a372010-11-21 13:34:58 +0000518 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000519
520 def test_selfreferential_dict(self):
521 '''Ensure that a reference loop involving a dict doesn't lead proxyval
522 into an infinite loop:'''
523 gdb_repr, gdb_output = \
524 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
525
Ezio Melotti2623a372010-11-21 13:34:58 +0000526 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000527
528 def test_selfreferential_old_style_instance(self):
529 gdb_repr, gdb_output = \
530 self.get_gdb_repr('''
531class Foo:
532 pass
533foo = Foo()
534foo.an_attr = foo
535print foo''')
536 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
537 gdb_repr),
538 'Unexpected gdb representation: %r\n%s' % \
539 (gdb_repr, gdb_output))
540
541 def test_selfreferential_new_style_instance(self):
542 gdb_repr, gdb_output = \
543 self.get_gdb_repr('''
544class Foo(object):
545 pass
546foo = Foo()
547foo.an_attr = foo
548print foo''')
549 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
550 gdb_repr),
551 'Unexpected gdb representation: %r\n%s' % \
552 (gdb_repr, gdb_output))
553
554 gdb_repr, gdb_output = \
555 self.get_gdb_repr('''
556class Foo(object):
557 pass
558a = Foo()
559b = Foo()
560a.an_attr = b
561b.an_attr = a
562print a''')
563 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
564 gdb_repr),
565 'Unexpected gdb representation: %r\n%s' % \
566 (gdb_repr, gdb_output))
567
568 def test_truncation(self):
569 'Verify that very long output is truncated'
570 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000571 self.assertEqual(gdb_repr,
572 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
573 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
574 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
575 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
576 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
577 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
578 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
579 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
580 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
581 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
582 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
583 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
584 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
585 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
586 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
587 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
588 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
589 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
590 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
591 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
592 "224, 225, 226...(truncated)")
593 self.assertEqual(len(gdb_repr),
594 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000595
596 def test_builtin_function(self):
597 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000598 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000599
600 def test_builtin_method(self):
601 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
602 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
603 gdb_repr),
604 'Unexpected gdb representation: %r\n%s' % \
605 (gdb_repr, gdb_output))
606
607 def test_frames(self):
608 gdb_output = self.get_stack_trace('''
609def foo(a, b, c):
610 pass
611
612foo(3, 4, 5)
613print foo.__code__''',
614 breakpoint='PyObject_Print',
615 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
616 )
R. David Murray0c080092010-04-05 16:28:49 +0000617 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
618 gdb_output,
619 re.DOTALL),
620 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000621
Victor Stinner99cff3f2011-12-19 13:59:58 +0100622@unittest.skipIf(python_is_optimized(),
623 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000624class PyListTests(DebuggerTests):
625 def assertListing(self, expected, actual):
626 self.assertEndsWith(actual, expected)
627
628 def test_basic_command(self):
629 'Verify that the "py-list" 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-list'])
632
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000633 self.assertListing(' 5 \n'
634 ' 6 def bar(a, b, c):\n'
635 ' 7 baz(a, b, c)\n'
636 ' 8 \n'
637 ' 9 def baz(*args):\n'
638 ' >10 print(42)\n'
639 ' 11 \n'
640 ' 12 foo(1, 2, 3)\n',
641 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000642
643 def test_one_abs_arg(self):
644 'Verify the "py-list" command with one absolute argument'
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-list 9'])
647
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000648 self.assertListing(' 9 def baz(*args):\n'
649 ' >10 print(42)\n'
650 ' 11 \n'
651 ' 12 foo(1, 2, 3)\n',
652 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000653
654 def test_two_abs_args(self):
655 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000656 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657 cmds_after_breakpoint=['py-list 1,3'])
658
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000659 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
660 ' 2 \n'
661 ' 3 def foo(a, b, c):\n',
662 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000663
664class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000665 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100666 @unittest.skipIf(python_is_optimized(),
667 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000668 def test_pyup_command(self):
669 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000670 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000671 cmds_after_breakpoint=['py-up'])
672 self.assertMultilineMatches(bt,
673 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000674#[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 +0000675 baz\(a, b, c\)
676$''')
677
Victor Stinnera92e81b2010-04-20 22:28:31 +0000678 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000679 def test_down_at_bottom(self):
680 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000681 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000682 cmds_after_breakpoint=['py-down'])
683 self.assertEndsWith(bt,
684 'Unable to find a newer python frame\n')
685
Victor Stinnera92e81b2010-04-20 22:28:31 +0000686 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000687 def test_up_at_top(self):
688 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000689 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000690 cmds_after_breakpoint=['py-up'] * 4)
691 self.assertEndsWith(bt,
692 'Unable to find an older python frame\n')
693
Victor Stinnera92e81b2010-04-20 22:28:31 +0000694 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100695 @unittest.skipIf(python_is_optimized(),
696 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000697 def test_up_then_down(self):
698 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000699 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000700 cmds_after_breakpoint=['py-up', 'py-down'])
701 self.assertMultilineMatches(bt,
702 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000703#[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 +0000704 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000705#[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 +0000706 print\(42\)
707$''')
708
709class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100710 @unittest.skipIf(python_is_optimized(),
711 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000712 def test_basic_command(self):
713 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000714 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000715 cmds_after_breakpoint=['py-bt'])
716 self.assertMultilineMatches(bt,
717 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000718#[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 +0000719 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000720#[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 +0000721 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000722#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100723 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000724''')
725
726class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100727 @unittest.skipIf(python_is_optimized(),
728 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000729 def test_basic_command(self):
730 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000731 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000732 cmds_after_breakpoint=['py-print args'])
733 self.assertMultilineMatches(bt,
734 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
735
Victor Stinnera92e81b2010-04-20 22:28:31 +0000736 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100737 @unittest.skipIf(python_is_optimized(),
738 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000739 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000740 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000741 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
742 self.assertMultilineMatches(bt,
743 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
744
Victor Stinner99cff3f2011-12-19 13:59:58 +0100745 @unittest.skipIf(python_is_optimized(),
746 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000747 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000748 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000749 cmds_after_breakpoint=['py-print __name__'])
750 self.assertMultilineMatches(bt,
751 r".*\nglobal '__name__' = '__main__'\n.*")
752
Victor Stinner99cff3f2011-12-19 13:59:58 +0100753 @unittest.skipIf(python_is_optimized(),
754 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000755 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000756 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000757 cmds_after_breakpoint=['py-print len'])
758 self.assertMultilineMatches(bt,
759 r".*\nbuiltin 'len' = <built-in function len>\n.*")
760
761class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100762 @unittest.skipIf(python_is_optimized(),
763 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000764 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000765 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000766 cmds_after_breakpoint=['py-locals'])
767 self.assertMultilineMatches(bt,
768 r".*\nargs = \(1, 2, 3\)\n.*")
769
Victor Stinnera92e81b2010-04-20 22:28:31 +0000770 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100771 @unittest.skipIf(python_is_optimized(),
772 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000773 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000774 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000775 cmds_after_breakpoint=['py-up', 'py-locals'])
776 self.assertMultilineMatches(bt,
777 r".*\na = 1\nb = 2\nc = 3\n.*")
778
779def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000780 run_unittest(PrettyPrintTests,
781 PyListTests,
782 StackNavigationTests,
783 PyBtTests,
784 PyPrintTests,
785 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000786 )
787
788if __name__ == "__main__":
789 test_main()