blob: f2c3c9070cac51b1e5845e8f90d31ae05fb03883 [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)
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):
Victor Stinner8bd34152014-08-16 14:31:02 +020034 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040035
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
Victor Stinner8bd34152014-08-16 14:31:02 +020043 # -nx: Do not execute commands from any .gdbinit initialization files
44 # (issue #22188)
45 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040046 if (gdb_major_version, gdb_minor_version) >= (7, 4):
47 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
48 out, err = subprocess.Popen(base_cmd + args,
49 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
50 ).communicate()
51 return out, err
52
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000053# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010054gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040055if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056 raise unittest.SkipTest("gdb not built with embedded python support")
57
Nick Coghlan254a3772013-09-22 19:36:09 +100058# Verify that "gdb" can load our custom hooks, as OS security settings may
59# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040060cmd = ['--args', sys.executable]
61_, gdbpy_errors = run_gdb('--args', sys.executable)
62if "auto-loading has been declined" in gdbpy_errors:
63 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100064 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100065
Victor Stinner99cff3f2011-12-19 13:59:58 +010066def python_is_optimized():
67 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
68 final_opt = ""
69 for opt in cflags.split():
70 if opt.startswith('-O'):
71 final_opt = opt
72 return (final_opt and final_opt != '-O0')
73
Victor Stinnera92e81b2010-04-20 22:28:31 +000074def gdb_has_frame_select():
75 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040076 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000077 m = re.match(r'.*\[(.*)\].*', stdout)
78 if not m:
79 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
80 gdb_frame_dir = m.group(1).split(', ')
81 return "'select'" in gdb_frame_dir
82
83HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000084
85class DebuggerTests(unittest.TestCase):
86
87 """Test that the debugger can debug Python."""
88
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000089 def get_stack_trace(self, source=None, script=None,
90 breakpoint='PyObject_Print',
91 cmds_after_breakpoint=None,
92 import_site=False):
93 '''
94 Run 'python -c SOURCE' under gdb with a breakpoint.
95
96 Support injecting commands after the breakpoint is reached
97
98 Returns the stdout from gdb
99
100 cmds_after_breakpoint: if provided, a list of strings: gdb commands
101 '''
102 # We use "set breakpoint pending yes" to avoid blocking with a:
103 # Function "foo" not defined.
104 # Make breakpoint pending on future shared library load? (y or [n])
105 # error, which typically happens python is dynamically linked (the
106 # breakpoints of interest are to be found in the shared library)
107 # When this happens, we still get:
108 # Function "PyObject_Print" not defined.
109 # emitted to stderr each time, alas.
110
111 # Initially I had "--eval-command=continue" here, but removed it to
112 # avoid repeated print breakpoints when traversing hierarchical data
113 # structures
114
115 # Generate a list of commands in gdb's language:
116 commands = ['set breakpoint pending yes',
117 'break %s' % breakpoint,
118 'run']
119 if cmds_after_breakpoint:
120 commands += cmds_after_breakpoint
121 else:
122 commands += ['backtrace']
123
124 # print commands
125
126 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200127 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000128 args += ['--eval-command=%s' % cmd for cmd in commands]
129 args += ["--args",
130 sys.executable]
131
132 if not import_site:
133 # -S suppresses the default 'import site'
134 args += ["-S"]
135
136 if source:
137 args += ["-c", source]
138 elif script:
139 args += [script]
140
141 # print args
142 # print ' '.join(args)
143
144 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400145 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000146
Antoine Pitroub996e042013-05-01 00:15:44 +0200147 errlines = err.splitlines()
148 unexpected_errlines = []
149
150 # Ignore some benign messages on stderr.
151 ignore_patterns = (
152 'Function "%s" not defined.' % breakpoint,
153 "warning: no loadable sections found in added symbol-file"
154 " system-supplied DSO",
155 "warning: Unable to find libthread_db matching"
156 " inferior's thread library, thread debugging will"
157 " not be available.",
158 "warning: Cannot initialize thread debugging"
159 " library: Debugger service failed",
160 'warning: Could not load shared library symbols for '
161 'linux-vdso.so',
162 'warning: Could not load shared library symbols for '
163 'linux-gate.so',
164 'Do you need "set solib-search-path" or '
165 '"set sysroot"?',
166 )
167 for line in errlines:
168 if not line.startswith(ignore_patterns):
169 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000170
171 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200172 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000173 return out
174
175 def get_gdb_repr(self, source,
176 cmds_after_breakpoint=None,
177 import_site=False):
178 # Given an input python source representation of data,
179 # run "python -c'print DATA'" under gdb with a breakpoint on
180 # PyObject_Print and scrape out gdb's representation of the "op"
181 # parameter, and verify that the gdb displays the same string
182 #
183 # For a nested structure, the first time we hit the breakpoint will
184 # give us the top-level structure
185 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
186 cmds_after_breakpoint=cmds_after_breakpoint,
187 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000188 # gdb can insert additional '\n' and space characters in various places
189 # in its output, depending on the width of the terminal it's connected
190 # to (using its "wrap_here" function)
191 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000192 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000193 if not m:
194 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000195 return m.group(1), gdb_output
196
197 def assertEndsWith(self, actual, exp_end):
198 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000199 self.assertTrue(actual.endswith(exp_end),
200 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000201
202 def assertMultilineMatches(self, actual, pattern):
203 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000204 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000205
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000206 def get_sample_script(self):
207 return findfile('gdb_sample.py')
208
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000209class PrettyPrintTests(DebuggerTests):
210 def test_getting_backtrace(self):
211 gdb_output = self.get_stack_trace('print 42')
212 self.assertTrue('PyObject_Print' in gdb_output)
213
214 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
215 # Ensure that gdb's rendering of the value in a debugged process
216 # matches repr(value) in this process:
217 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
218 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100219 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000220
221 def test_int(self):
222 'Verify the pretty-printing of various "int" values'
223 self.assertGdbRepr(42)
224 self.assertGdbRepr(0)
225 self.assertGdbRepr(-7)
226 self.assertGdbRepr(sys.maxint)
227 self.assertGdbRepr(-sys.maxint)
228
229 def test_long(self):
230 'Verify the pretty-printing of various "long" values'
231 self.assertGdbRepr(0L)
232 self.assertGdbRepr(1000000000000L)
233 self.assertGdbRepr(-1L)
234 self.assertGdbRepr(-1000000000000000L)
235
236 def test_singletons(self):
237 'Verify the pretty-printing of True, False and None'
238 self.assertGdbRepr(True)
239 self.assertGdbRepr(False)
240 self.assertGdbRepr(None)
241
242 def test_dicts(self):
243 'Verify the pretty-printing of dictionaries'
244 self.assertGdbRepr({})
245 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500246 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000247
248 def test_lists(self):
249 'Verify the pretty-printing of lists'
250 self.assertGdbRepr([])
251 self.assertGdbRepr(range(5))
252
253 def test_strings(self):
254 'Verify the pretty-printing of strings'
255 self.assertGdbRepr('')
256 self.assertGdbRepr('And now for something hopefully the same')
257 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
258 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
259
260 def test_tuples(self):
261 'Verify the pretty-printing of tuples'
262 self.assertGdbRepr(tuple())
263 self.assertGdbRepr((1,))
264 self.assertGdbRepr(('foo', 'bar', 'baz'))
265
266 def test_unicode(self):
267 'Verify the pretty-printing of unicode values'
268 # Test the empty unicode string:
269 self.assertGdbRepr(u'')
270
271 self.assertGdbRepr(u'hello world')
272
273 # Test printing a single character:
274 # U+2620 SKULL AND CROSSBONES
275 self.assertGdbRepr(u'\u2620')
276
277 # Test printing a Japanese unicode string
278 # (I believe this reads "mojibake", using 3 characters from the CJK
279 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
280 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
281
282 # Test a character outside the BMP:
283 # U+1D121 MUSICAL SYMBOL C CLEF
284 # This is:
285 # UTF-8: 0xF0 0x9D 0x84 0xA1
286 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000287 # This will only work on wide-unicode builds:
288 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000289
290 def test_sets(self):
291 'Verify the pretty-printing of sets'
292 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500293 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
294 self.assertTrue(rep.startswith("set(["))
295 self.assertTrue(rep.endswith("])"))
296 self.assertEqual(eval(rep), {'a', 'b'})
297 rep = self.get_gdb_repr("print set([4, 5])")[0]
298 self.assertTrue(rep.startswith("set(["))
299 self.assertTrue(rep.endswith("])"))
300 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000301
302 # Ensure that we handled sets containing the "dummy" key value,
303 # which happens on deletion:
304 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
305s.pop()
306print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000307 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000308
309 def test_frozensets(self):
310 'Verify the pretty-printing of frozensets'
311 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500312 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
313 self.assertTrue(rep.startswith("frozenset(["))
314 self.assertTrue(rep.endswith("])"))
315 self.assertEqual(eval(rep), {'a', 'b'})
316 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
317 self.assertTrue(rep.startswith("frozenset(["))
318 self.assertTrue(rep.endswith("])"))
319 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000320
321 def test_exceptions(self):
322 # Test a RuntimeError
323 gdb_repr, gdb_output = self.get_gdb_repr('''
324try:
325 raise RuntimeError("I am an error")
326except RuntimeError, e:
327 print e
328''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000329 self.assertEqual(gdb_repr,
330 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000331
332
333 # Test division by zero:
334 gdb_repr, gdb_output = self.get_gdb_repr('''
335try:
336 a = 1 / 0
337except ZeroDivisionError, e:
338 print e
339''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000340 self.assertEqual(gdb_repr,
341 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000342
343 def test_classic_class(self):
344 'Verify the pretty-printing of classic class instances'
345 gdb_repr, gdb_output = self.get_gdb_repr('''
346class Foo:
347 pass
348foo = Foo()
349foo.an_int = 42
350print foo''')
351 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
352 self.assertTrue(m,
353 msg='Unexpected classic-class rendering %r' % gdb_repr)
354
355 def test_modern_class(self):
356 'Verify the pretty-printing of new-style class instances'
357 gdb_repr, gdb_output = self.get_gdb_repr('''
358class Foo(object):
359 pass
360foo = Foo()
361foo.an_int = 42
362print foo''')
363 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
364 self.assertTrue(m,
365 msg='Unexpected new-style class rendering %r' % gdb_repr)
366
367 def test_subclassing_list(self):
368 'Verify the pretty-printing of an instance of a list subclass'
369 gdb_repr, gdb_output = self.get_gdb_repr('''
370class Foo(list):
371 pass
372foo = Foo()
373foo += [1, 2, 3]
374foo.an_int = 42
375print foo''')
376 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
377 self.assertTrue(m,
378 msg='Unexpected new-style class rendering %r' % gdb_repr)
379
380 def test_subclassing_tuple(self):
381 'Verify the pretty-printing of an instance of a tuple subclass'
382 # This should exercise the negative tp_dictoffset code in the
383 # new-style class support
384 gdb_repr, gdb_output = self.get_gdb_repr('''
385class Foo(tuple):
386 pass
387foo = Foo((1, 2, 3))
388foo.an_int = 42
389print foo''')
390 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
391 self.assertTrue(m,
392 msg='Unexpected new-style class rendering %r' % gdb_repr)
393
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000394 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000395 '''Run Python under gdb, corrupting variables in the inferior process
396 immediately before taking a backtrace.
397
398 Verify that the variable's representation is the expected failsafe
399 representation'''
400 if corruption:
401 cmds_after_breakpoint=[corruption, 'backtrace']
402 else:
403 cmds_after_breakpoint=['backtrace']
404
405 gdb_repr, gdb_output = \
406 self.get_gdb_repr(source,
407 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000408
409 if expvalue:
410 if gdb_repr == repr(expvalue):
411 # gdb managed to print the value in spite of the corruption;
412 # this is good (see http://bugs.python.org/issue8330)
413 return
414
415 if exptype:
416 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
417 else:
418 # Match anything for the type name; 0xDEADBEEF could point to
419 # something arbitrary (see http://bugs.python.org/issue8330)
420 pattern = '<.* at remote 0x[0-9a-f]+>'
421
422 m = re.match(pattern, gdb_repr)
423 if not m:
424 self.fail('Unexpected gdb representation: %r\n%s' % \
425 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000426
427 def test_NULL_ptr(self):
428 'Ensure that a NULL PyObject* is handled gracefully'
429 gdb_repr, gdb_output = (
430 self.get_gdb_repr('print 42',
431 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000432 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000433 )
434
Ezio Melotti2623a372010-11-21 13:34:58 +0000435 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000436
437 def test_NULL_ob_type(self):
438 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
439 self.assertSane('print 42',
440 'set op->ob_type=0')
441
442 def test_corrupt_ob_type(self):
443 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
444 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000445 'set op->ob_type=0xDEADBEEF',
446 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000447
448 def test_corrupt_tp_flags(self):
449 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
450 self.assertSane('print 42',
451 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000452 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000453
454 def test_corrupt_tp_name(self):
455 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
456 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000457 'set op->ob_type->tp_name=0xDEADBEEF',
458 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000459
460 def test_NULL_instance_dict(self):
461 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
462 self.assertSane('''
463class Foo:
464 pass
465foo = Foo()
466foo.an_int = 42
467print foo''',
468 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000469 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000470
471 def test_builtins_help(self):
472 'Ensure that the new-style class _Helper in site.py can be handled'
473 # (this was the issue causing tracebacks in
474 # http://bugs.python.org/issue8032#msg100537 )
475
476 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
477 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
478 self.assertTrue(m,
479 msg='Unexpected rendering %r' % gdb_repr)
480
481 def test_selfreferential_list(self):
482 '''Ensure that a reference loop involving a list doesn't lead proxyval
483 into an infinite loop:'''
484 gdb_repr, gdb_output = \
485 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
486
Ezio Melotti2623a372010-11-21 13:34:58 +0000487 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000488
489 gdb_repr, gdb_output = \
490 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
491
Ezio Melotti2623a372010-11-21 13:34:58 +0000492 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000493
494 def test_selfreferential_dict(self):
495 '''Ensure that a reference loop involving a dict doesn't lead proxyval
496 into an infinite loop:'''
497 gdb_repr, gdb_output = \
498 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
499
Ezio Melotti2623a372010-11-21 13:34:58 +0000500 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000501
502 def test_selfreferential_old_style_instance(self):
503 gdb_repr, gdb_output = \
504 self.get_gdb_repr('''
505class Foo:
506 pass
507foo = Foo()
508foo.an_attr = foo
509print foo''')
510 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
511 gdb_repr),
512 'Unexpected gdb representation: %r\n%s' % \
513 (gdb_repr, gdb_output))
514
515 def test_selfreferential_new_style_instance(self):
516 gdb_repr, gdb_output = \
517 self.get_gdb_repr('''
518class Foo(object):
519 pass
520foo = Foo()
521foo.an_attr = foo
522print foo''')
523 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
524 gdb_repr),
525 'Unexpected gdb representation: %r\n%s' % \
526 (gdb_repr, gdb_output))
527
528 gdb_repr, gdb_output = \
529 self.get_gdb_repr('''
530class Foo(object):
531 pass
532a = Foo()
533b = Foo()
534a.an_attr = b
535b.an_attr = a
536print a''')
537 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
538 gdb_repr),
539 'Unexpected gdb representation: %r\n%s' % \
540 (gdb_repr, gdb_output))
541
542 def test_truncation(self):
543 'Verify that very long output is truncated'
544 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000545 self.assertEqual(gdb_repr,
546 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
547 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
548 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
549 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
550 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
551 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
552 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
553 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
554 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
555 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
556 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
557 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
558 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
559 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
560 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
561 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
562 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
563 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
564 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
565 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
566 "224, 225, 226...(truncated)")
567 self.assertEqual(len(gdb_repr),
568 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000569
570 def test_builtin_function(self):
571 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000572 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000573
574 def test_builtin_method(self):
575 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
576 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
577 gdb_repr),
578 'Unexpected gdb representation: %r\n%s' % \
579 (gdb_repr, gdb_output))
580
581 def test_frames(self):
582 gdb_output = self.get_stack_trace('''
583def foo(a, b, c):
584 pass
585
586foo(3, 4, 5)
587print foo.__code__''',
588 breakpoint='PyObject_Print',
589 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
590 )
R. David Murray0c080092010-04-05 16:28:49 +0000591 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
592 gdb_output,
593 re.DOTALL),
594 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000595
Victor Stinner99cff3f2011-12-19 13:59:58 +0100596@unittest.skipIf(python_is_optimized(),
597 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000598class PyListTests(DebuggerTests):
599 def assertListing(self, expected, actual):
600 self.assertEndsWith(actual, expected)
601
602 def test_basic_command(self):
603 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000604 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000605 cmds_after_breakpoint=['py-list'])
606
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000607 self.assertListing(' 5 \n'
608 ' 6 def bar(a, b, c):\n'
609 ' 7 baz(a, b, c)\n'
610 ' 8 \n'
611 ' 9 def baz(*args):\n'
612 ' >10 print(42)\n'
613 ' 11 \n'
614 ' 12 foo(1, 2, 3)\n',
615 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000616
617 def test_one_abs_arg(self):
618 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000619 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000620 cmds_after_breakpoint=['py-list 9'])
621
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000622 self.assertListing(' 9 def baz(*args):\n'
623 ' >10 print(42)\n'
624 ' 11 \n'
625 ' 12 foo(1, 2, 3)\n',
626 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000627
628 def test_two_abs_args(self):
629 'Verify the "py-list" command with two absolute arguments'
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 1,3'])
632
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000633 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
634 ' 2 \n'
635 ' 3 def foo(a, b, c):\n',
636 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000637
638class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000639 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100640 @unittest.skipIf(python_is_optimized(),
641 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000642 def test_pyup_command(self):
643 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000644 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000645 cmds_after_breakpoint=['py-up'])
646 self.assertMultilineMatches(bt,
647 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000648#[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 +0000649 baz\(a, b, c\)
650$''')
651
Victor Stinnera92e81b2010-04-20 22:28:31 +0000652 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000653 def test_down_at_bottom(self):
654 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000655 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000656 cmds_after_breakpoint=['py-down'])
657 self.assertEndsWith(bt,
658 'Unable to find a newer python frame\n')
659
Victor Stinnera92e81b2010-04-20 22:28:31 +0000660 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000661 def test_up_at_top(self):
662 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000663 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000664 cmds_after_breakpoint=['py-up'] * 4)
665 self.assertEndsWith(bt,
666 'Unable to find an older python frame\n')
667
Victor Stinnera92e81b2010-04-20 22:28:31 +0000668 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100669 @unittest.skipIf(python_is_optimized(),
670 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000671 def test_up_then_down(self):
672 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000673 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000674 cmds_after_breakpoint=['py-up', 'py-down'])
675 self.assertMultilineMatches(bt,
676 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000677#[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 +0000678 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000679#[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 +0000680 print\(42\)
681$''')
682
683class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100684 @unittest.skipIf(python_is_optimized(),
685 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000686 def test_basic_command(self):
687 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000688 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000689 cmds_after_breakpoint=['py-bt'])
690 self.assertMultilineMatches(bt,
691 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000692#[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 +0000693 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000694#[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 +0000695 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000696#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100697 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000698''')
699
700class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100701 @unittest.skipIf(python_is_optimized(),
702 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000703 def test_basic_command(self):
704 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000705 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000706 cmds_after_breakpoint=['py-print args'])
707 self.assertMultilineMatches(bt,
708 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
709
Victor Stinnera92e81b2010-04-20 22:28:31 +0000710 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100711 @unittest.skipIf(python_is_optimized(),
712 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000713 def test_print_after_up(self):
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-up', 'py-print c', 'py-print b', 'py-print a'])
716 self.assertMultilineMatches(bt,
717 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
718
Victor Stinner99cff3f2011-12-19 13:59:58 +0100719 @unittest.skipIf(python_is_optimized(),
720 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000721 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000722 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000723 cmds_after_breakpoint=['py-print __name__'])
724 self.assertMultilineMatches(bt,
725 r".*\nglobal '__name__' = '__main__'\n.*")
726
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_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000730 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000731 cmds_after_breakpoint=['py-print len'])
732 self.assertMultilineMatches(bt,
733 r".*\nbuiltin 'len' = <built-in function len>\n.*")
734
735class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100736 @unittest.skipIf(python_is_optimized(),
737 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000738 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000739 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000740 cmds_after_breakpoint=['py-locals'])
741 self.assertMultilineMatches(bt,
742 r".*\nargs = \(1, 2, 3\)\n.*")
743
Victor Stinnera92e81b2010-04-20 22:28:31 +0000744 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
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_locals_after_up(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-up', 'py-locals'])
750 self.assertMultilineMatches(bt,
751 r".*\na = 1\nb = 2\nc = 3\n.*")
752
753def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000754 run_unittest(PrettyPrintTests,
755 PyListTests,
756 StackNavigationTests,
757 PyBtTests,
758 PyPrintTests,
759 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000760 )
761
762if __name__ == "__main__":
763 test_main()