blob: 8d3d772e1c1332110f26aa7d543fca761059328c [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
Zachary Wared833c772016-08-24 11:14:34 -050010import sysconfig
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000011import unittest
Antoine Pitrou22db7352010-07-08 18:54:04 +000012import sysconfig
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000013
Victor Stinner3c5ce402015-09-03 09:51:59 +020014from test import test_support
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000015from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000016
Victor Stinnercc1db4b2015-09-03 10:17:28 +020017# Is this Python configured to support threads?
18try:
19 import thread
20except ImportError:
21 thread = None
22
Victor Stinner3c5ce402015-09-03 09:51:59 +020023def get_gdb_version():
24 try:
25 proc = subprocess.Popen(["gdb", "-nx", "--version"],
26 stdout=subprocess.PIPE,
Benjamin Peterson499378f2016-09-06 10:06:31 -070027 stderr=subprocess.PIPE,
Victor Stinner3c5ce402015-09-03 09:51:59 +020028 universal_newlines=True)
29 version = proc.communicate()[0]
30 except OSError:
31 # This is what "no gdb" looks like. There may, however, be other
32 # errors that manifest this way too.
33 raise unittest.SkipTest("Couldn't find gdb on the path")
34
35 # Regex to parse:
36 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
37 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinnerdf11d7c2015-09-15 00:19:47 +020038 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
39 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
40 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner3c5ce402015-09-03 09:51:59 +020041 if match is None:
42 raise Exception("unable to parse GDB version: %r" % version)
43 return (version, int(match.group(1)), int(match.group(2)))
44
45gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murray3e66f0d2012-10-27 13:47:49 -040046if gdb_major_version < 7:
Victor Stinner3c5ce402015-09-03 09:51:59 +020047 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
48 "embedding. Saw %s.%s:\n%s"
49 % (gdb_major_version, gdb_minor_version,
50 gdb_version))
51
Benjamin Peterson51f461f2014-11-23 22:34:04 -060052if sys.platform.startswith("sunos"):
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060053 raise unittest.SkipTest("test doesn't work very well on Solaris")
54
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000055
R David Murray3e66f0d2012-10-27 13:47:49 -040056# Location of custom hooks file in a repository checkout.
57checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
58 'python-gdb.py')
59
60def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020061 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040062
63 Returns its (stdout, stderr)
64 """
65 if env_vars:
66 env = os.environ.copy()
67 env.update(env_vars)
68 else:
69 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020070 # -nx: Do not execute commands from any .gdbinit initialization files
71 # (issue #22188)
72 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040073 if (gdb_major_version, gdb_minor_version) >= (7, 4):
74 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
75 out, err = subprocess.Popen(base_cmd + args,
Martin Panter2179b2e2016-01-16 05:07:35 +000076 # Redirect stdin to prevent GDB from messing with terminal settings
77 stdin=subprocess.PIPE,
R David Murray3e66f0d2012-10-27 13:47:49 -040078 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
79 ).communicate()
80 return out, err
81
Zachary Wared833c772016-08-24 11:14:34 -050082if not sysconfig.is_python_build():
83 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
84
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000085# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010086gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040087if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000088 raise unittest.SkipTest("gdb not built with embedded python support")
89
Nick Coghlan254a3772013-09-22 19:36:09 +100090# Verify that "gdb" can load our custom hooks, as OS security settings may
91# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040092cmd = ['--args', sys.executable]
93_, gdbpy_errors = run_gdb('--args', sys.executable)
94if "auto-loading has been declined" in gdbpy_errors:
95 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100096 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100097
Victor Stinner99cff3f2011-12-19 13:59:58 +010098def python_is_optimized():
99 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
100 final_opt = ""
101 for opt in cflags.split():
102 if opt.startswith('-O'):
103 final_opt = opt
Victor Stinner582265f2015-03-27 15:44:13 +0100104 return final_opt not in ('', '-O0', '-Og')
Victor Stinner99cff3f2011-12-19 13:59:58 +0100105
Victor Stinnera92e81b2010-04-20 22:28:31 +0000106def gdb_has_frame_select():
107 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -0400108 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +0000109 m = re.match(r'.*\[(.*)\].*', stdout)
110 if not m:
111 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
112 gdb_frame_dir = m.group(1).split(', ')
113 return "'select'" in gdb_frame_dir
114
115HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000116
117class DebuggerTests(unittest.TestCase):
118
119 """Test that the debugger can debug Python."""
120
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000121 def get_stack_trace(self, source=None, script=None,
122 breakpoint='PyObject_Print',
123 cmds_after_breakpoint=None,
124 import_site=False):
125 '''
126 Run 'python -c SOURCE' under gdb with a breakpoint.
127
128 Support injecting commands after the breakpoint is reached
129
130 Returns the stdout from gdb
131
132 cmds_after_breakpoint: if provided, a list of strings: gdb commands
133 '''
134 # We use "set breakpoint pending yes" to avoid blocking with a:
135 # Function "foo" not defined.
136 # Make breakpoint pending on future shared library load? (y or [n])
137 # error, which typically happens python is dynamically linked (the
138 # breakpoints of interest are to be found in the shared library)
139 # When this happens, we still get:
140 # Function "PyObject_Print" not defined.
141 # emitted to stderr each time, alas.
142
143 # Initially I had "--eval-command=continue" here, but removed it to
144 # avoid repeated print breakpoints when traversing hierarchical data
145 # structures
146
147 # Generate a list of commands in gdb's language:
148 commands = ['set breakpoint pending yes',
149 'break %s' % breakpoint,
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200150
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200151 # The tests assume that the first frame of printed
152 # backtrace will not contain program counter,
153 # that is however not guaranteed by gdb
154 # therefore we need to use 'set print address off' to
155 # make sure the counter is not there. For example:
156 # #0 in PyObject_Print ...
157 # is assumed, but sometimes this can be e.g.
158 # #0 0x00003fffb7dd1798 in PyObject_Print ...
159 'set print address off',
160
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000161 'run']
Serhiy Storchakadd8430f2015-02-06 08:36:14 +0200162
163 # GDB as of 7.4 onwards can distinguish between the
164 # value of a variable at entry vs current value:
165 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
166 # which leads to the selftests failing with errors like this:
167 # AssertionError: 'v@entry=()' != '()'
168 # Disable this:
169 if (gdb_major_version, gdb_minor_version) >= (7, 4):
170 commands += ['set print entry-values no']
171
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000172 if cmds_after_breakpoint:
173 commands += cmds_after_breakpoint
174 else:
175 commands += ['backtrace']
176
177 # print commands
178
179 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200180 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000181 args += ['--eval-command=%s' % cmd for cmd in commands]
182 args += ["--args",
183 sys.executable]
184
185 if not import_site:
186 # -S suppresses the default 'import site'
187 args += ["-S"]
188
189 if source:
190 args += ["-c", source]
191 elif script:
192 args += [script]
193
194 # print args
195 # print ' '.join(args)
196
197 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400198 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000199
Antoine Pitroub996e042013-05-01 00:15:44 +0200200 errlines = err.splitlines()
201 unexpected_errlines = []
202
203 # Ignore some benign messages on stderr.
204 ignore_patterns = (
205 'Function "%s" not defined.' % breakpoint,
206 "warning: no loadable sections found in added symbol-file"
207 " system-supplied DSO",
208 "warning: Unable to find libthread_db matching"
209 " inferior's thread library, thread debugging will"
210 " not be available.",
211 "warning: Cannot initialize thread debugging"
212 " library: Debugger service failed",
213 'warning: Could not load shared library symbols for '
214 'linux-vdso.so',
215 'warning: Could not load shared library symbols for '
216 'linux-gate.so',
Serhiy Storchakab6b48e62015-02-14 22:44:35 +0200217 'warning: Could not load shared library symbols for '
218 'linux-vdso64.so',
Antoine Pitroub996e042013-05-01 00:15:44 +0200219 'Do you need "set solib-search-path" or '
220 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100221 'warning: Source file is more recent than executable.',
222 # Issue #19753: missing symbols on System Z
223 'Missing separate debuginfo for ',
224 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200225 )
226 for line in errlines:
227 if not line.startswith(ignore_patterns):
228 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000229
230 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200231 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000232 return out
233
234 def get_gdb_repr(self, source,
235 cmds_after_breakpoint=None,
236 import_site=False):
237 # Given an input python source representation of data,
238 # run "python -c'print DATA'" under gdb with a breakpoint on
239 # PyObject_Print and scrape out gdb's representation of the "op"
240 # parameter, and verify that the gdb displays the same string
241 #
242 # For a nested structure, the first time we hit the breakpoint will
243 # give us the top-level structure
244 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
245 cmds_after_breakpoint=cmds_after_breakpoint,
246 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000247 # gdb can insert additional '\n' and space characters in various places
248 # in its output, depending on the width of the terminal it's connected
249 # to (using its "wrap_here" function)
250 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000251 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000252 if not m:
253 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000254 return m.group(1), gdb_output
255
256 def assertEndsWith(self, actual, exp_end):
257 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000258 self.assertTrue(actual.endswith(exp_end),
259 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000260
261 def assertMultilineMatches(self, actual, pattern):
262 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000263 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000264
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000265 def get_sample_script(self):
266 return findfile('gdb_sample.py')
267
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000268class PrettyPrintTests(DebuggerTests):
269 def test_getting_backtrace(self):
270 gdb_output = self.get_stack_trace('print 42')
271 self.assertTrue('PyObject_Print' in gdb_output)
272
273 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
274 # Ensure that gdb's rendering of the value in a debugged process
275 # matches repr(value) in this process:
276 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
277 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100278 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000279
280 def test_int(self):
281 'Verify the pretty-printing of various "int" values'
282 self.assertGdbRepr(42)
283 self.assertGdbRepr(0)
284 self.assertGdbRepr(-7)
285 self.assertGdbRepr(sys.maxint)
286 self.assertGdbRepr(-sys.maxint)
287
288 def test_long(self):
289 'Verify the pretty-printing of various "long" values'
290 self.assertGdbRepr(0L)
291 self.assertGdbRepr(1000000000000L)
292 self.assertGdbRepr(-1L)
293 self.assertGdbRepr(-1000000000000000L)
294
295 def test_singletons(self):
296 'Verify the pretty-printing of True, False and None'
297 self.assertGdbRepr(True)
298 self.assertGdbRepr(False)
299 self.assertGdbRepr(None)
300
301 def test_dicts(self):
302 'Verify the pretty-printing of dictionaries'
303 self.assertGdbRepr({})
304 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500305 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000306
307 def test_lists(self):
308 'Verify the pretty-printing of lists'
309 self.assertGdbRepr([])
310 self.assertGdbRepr(range(5))
311
312 def test_strings(self):
313 'Verify the pretty-printing of strings'
314 self.assertGdbRepr('')
315 self.assertGdbRepr('And now for something hopefully the same')
316 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
317 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
318
319 def test_tuples(self):
320 'Verify the pretty-printing of tuples'
321 self.assertGdbRepr(tuple())
322 self.assertGdbRepr((1,))
323 self.assertGdbRepr(('foo', 'bar', 'baz'))
324
325 def test_unicode(self):
326 'Verify the pretty-printing of unicode values'
327 # Test the empty unicode string:
328 self.assertGdbRepr(u'')
329
330 self.assertGdbRepr(u'hello world')
331
332 # Test printing a single character:
333 # U+2620 SKULL AND CROSSBONES
334 self.assertGdbRepr(u'\u2620')
335
336 # Test printing a Japanese unicode string
337 # (I believe this reads "mojibake", using 3 characters from the CJK
338 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
339 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
340
341 # Test a character outside the BMP:
342 # U+1D121 MUSICAL SYMBOL C CLEF
343 # This is:
344 # UTF-8: 0xF0 0x9D 0x84 0xA1
345 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000346 # This will only work on wide-unicode builds:
347 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000348
349 def test_sets(self):
350 'Verify the pretty-printing of sets'
351 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500352 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
353 self.assertTrue(rep.startswith("set(["))
354 self.assertTrue(rep.endswith("])"))
355 self.assertEqual(eval(rep), {'a', 'b'})
356 rep = self.get_gdb_repr("print set([4, 5])")[0]
357 self.assertTrue(rep.startswith("set(["))
358 self.assertTrue(rep.endswith("])"))
359 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000360
361 # Ensure that we handled sets containing the "dummy" key value,
362 # which happens on deletion:
363 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
364s.pop()
365print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000366 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000367
368 def test_frozensets(self):
369 'Verify the pretty-printing of frozensets'
370 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500371 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
372 self.assertTrue(rep.startswith("frozenset(["))
373 self.assertTrue(rep.endswith("])"))
374 self.assertEqual(eval(rep), {'a', 'b'})
375 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
376 self.assertTrue(rep.startswith("frozenset(["))
377 self.assertTrue(rep.endswith("])"))
378 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000379
380 def test_exceptions(self):
381 # Test a RuntimeError
382 gdb_repr, gdb_output = self.get_gdb_repr('''
383try:
384 raise RuntimeError("I am an error")
385except RuntimeError, e:
386 print e
387''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000388 self.assertEqual(gdb_repr,
389 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000390
391
392 # Test division by zero:
393 gdb_repr, gdb_output = self.get_gdb_repr('''
394try:
395 a = 1 / 0
396except ZeroDivisionError, e:
397 print e
398''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000399 self.assertEqual(gdb_repr,
400 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000401
402 def test_classic_class(self):
403 'Verify the pretty-printing of classic class instances'
404 gdb_repr, gdb_output = self.get_gdb_repr('''
405class Foo:
406 pass
407foo = Foo()
408foo.an_int = 42
409print foo''')
410 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
411 self.assertTrue(m,
412 msg='Unexpected classic-class rendering %r' % gdb_repr)
413
414 def test_modern_class(self):
415 'Verify the pretty-printing of new-style class instances'
416 gdb_repr, gdb_output = self.get_gdb_repr('''
417class Foo(object):
418 pass
419foo = Foo()
420foo.an_int = 42
421print foo''')
422 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
423 self.assertTrue(m,
424 msg='Unexpected new-style class rendering %r' % gdb_repr)
425
426 def test_subclassing_list(self):
427 'Verify the pretty-printing of an instance of a list subclass'
428 gdb_repr, gdb_output = self.get_gdb_repr('''
429class Foo(list):
430 pass
431foo = Foo()
432foo += [1, 2, 3]
433foo.an_int = 42
434print foo''')
435 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
436 self.assertTrue(m,
437 msg='Unexpected new-style class rendering %r' % gdb_repr)
438
439 def test_subclassing_tuple(self):
440 'Verify the pretty-printing of an instance of a tuple subclass'
441 # This should exercise the negative tp_dictoffset code in the
442 # new-style class support
443 gdb_repr, gdb_output = self.get_gdb_repr('''
444class Foo(tuple):
445 pass
446foo = Foo((1, 2, 3))
447foo.an_int = 42
448print foo''')
449 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
450 self.assertTrue(m,
451 msg='Unexpected new-style class rendering %r' % gdb_repr)
452
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000453 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000454 '''Run Python under gdb, corrupting variables in the inferior process
455 immediately before taking a backtrace.
456
457 Verify that the variable's representation is the expected failsafe
458 representation'''
459 if corruption:
460 cmds_after_breakpoint=[corruption, 'backtrace']
461 else:
462 cmds_after_breakpoint=['backtrace']
463
464 gdb_repr, gdb_output = \
465 self.get_gdb_repr(source,
466 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000467
468 if expvalue:
469 if gdb_repr == repr(expvalue):
470 # gdb managed to print the value in spite of the corruption;
471 # this is good (see http://bugs.python.org/issue8330)
472 return
473
474 if exptype:
475 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
476 else:
477 # Match anything for the type name; 0xDEADBEEF could point to
478 # something arbitrary (see http://bugs.python.org/issue8330)
479 pattern = '<.* at remote 0x[0-9a-f]+>'
480
481 m = re.match(pattern, gdb_repr)
482 if not m:
483 self.fail('Unexpected gdb representation: %r\n%s' % \
484 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000485
486 def test_NULL_ptr(self):
487 'Ensure that a NULL PyObject* is handled gracefully'
488 gdb_repr, gdb_output = (
489 self.get_gdb_repr('print 42',
490 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000491 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000492 )
493
Ezio Melotti2623a372010-11-21 13:34:58 +0000494 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000495
496 def test_NULL_ob_type(self):
497 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
498 self.assertSane('print 42',
499 'set op->ob_type=0')
500
501 def test_corrupt_ob_type(self):
502 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
503 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000504 'set op->ob_type=0xDEADBEEF',
505 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000506
507 def test_corrupt_tp_flags(self):
508 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
509 self.assertSane('print 42',
510 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000511 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000512
513 def test_corrupt_tp_name(self):
514 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
515 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000516 'set op->ob_type->tp_name=0xDEADBEEF',
517 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000518
519 def test_NULL_instance_dict(self):
520 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
521 self.assertSane('''
522class Foo:
523 pass
524foo = Foo()
525foo.an_int = 42
526print foo''',
527 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000528 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000529
530 def test_builtins_help(self):
531 'Ensure that the new-style class _Helper in site.py can be handled'
532 # (this was the issue causing tracebacks in
533 # http://bugs.python.org/issue8032#msg100537 )
534
535 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
536 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
537 self.assertTrue(m,
538 msg='Unexpected rendering %r' % gdb_repr)
539
540 def test_selfreferential_list(self):
541 '''Ensure that a reference loop involving a list doesn't lead proxyval
542 into an infinite loop:'''
543 gdb_repr, gdb_output = \
544 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
545
Ezio Melotti2623a372010-11-21 13:34:58 +0000546 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000547
548 gdb_repr, gdb_output = \
549 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
550
Ezio Melotti2623a372010-11-21 13:34:58 +0000551 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000552
553 def test_selfreferential_dict(self):
554 '''Ensure that a reference loop involving a dict doesn't lead proxyval
555 into an infinite loop:'''
556 gdb_repr, gdb_output = \
557 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
558
Ezio Melotti2623a372010-11-21 13:34:58 +0000559 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000560
561 def test_selfreferential_old_style_instance(self):
562 gdb_repr, gdb_output = \
563 self.get_gdb_repr('''
564class Foo:
565 pass
566foo = Foo()
567foo.an_attr = foo
568print foo''')
569 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
570 gdb_repr),
571 'Unexpected gdb representation: %r\n%s' % \
572 (gdb_repr, gdb_output))
573
574 def test_selfreferential_new_style_instance(self):
575 gdb_repr, gdb_output = \
576 self.get_gdb_repr('''
577class Foo(object):
578 pass
579foo = Foo()
580foo.an_attr = foo
581print foo''')
582 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
583 gdb_repr),
584 'Unexpected gdb representation: %r\n%s' % \
585 (gdb_repr, gdb_output))
586
587 gdb_repr, gdb_output = \
588 self.get_gdb_repr('''
589class Foo(object):
590 pass
591a = Foo()
592b = Foo()
593a.an_attr = b
594b.an_attr = a
595print a''')
596 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
597 gdb_repr),
598 'Unexpected gdb representation: %r\n%s' % \
599 (gdb_repr, gdb_output))
600
601 def test_truncation(self):
602 'Verify that very long output is truncated'
603 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000604 self.assertEqual(gdb_repr,
605 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
606 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
607 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
608 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
609 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
610 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
611 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
612 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
613 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
614 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
615 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
616 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
617 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
618 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
619 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
620 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
621 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
622 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
623 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
624 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
625 "224, 225, 226...(truncated)")
626 self.assertEqual(len(gdb_repr),
627 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000628
629 def test_builtin_function(self):
630 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000631 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000632
633 def test_builtin_method(self):
634 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
635 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
636 gdb_repr),
637 'Unexpected gdb representation: %r\n%s' % \
638 (gdb_repr, gdb_output))
639
640 def test_frames(self):
641 gdb_output = self.get_stack_trace('''
642def foo(a, b, c):
643 pass
644
645foo(3, 4, 5)
646print foo.__code__''',
647 breakpoint='PyObject_Print',
648 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
649 )
R. David Murray0c080092010-04-05 16:28:49 +0000650 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
651 gdb_output,
652 re.DOTALL),
653 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000654
Victor Stinner99cff3f2011-12-19 13:59:58 +0100655@unittest.skipIf(python_is_optimized(),
656 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657class PyListTests(DebuggerTests):
658 def assertListing(self, expected, actual):
659 self.assertEndsWith(actual, expected)
660
661 def test_basic_command(self):
662 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000663 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000664 cmds_after_breakpoint=['py-list'])
665
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000666 self.assertListing(' 5 \n'
667 ' 6 def bar(a, b, c):\n'
668 ' 7 baz(a, b, c)\n'
669 ' 8 \n'
670 ' 9 def baz(*args):\n'
671 ' >10 print(42)\n'
672 ' 11 \n'
673 ' 12 foo(1, 2, 3)\n',
674 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000675
676 def test_one_abs_arg(self):
677 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000678 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000679 cmds_after_breakpoint=['py-list 9'])
680
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000681 self.assertListing(' 9 def baz(*args):\n'
682 ' >10 print(42)\n'
683 ' 11 \n'
684 ' 12 foo(1, 2, 3)\n',
685 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000686
687 def test_two_abs_args(self):
688 'Verify the "py-list" command with two absolute arguments'
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-list 1,3'])
691
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000692 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
693 ' 2 \n'
694 ' 3 def foo(a, b, c):\n',
695 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000696
697class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000698 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100699 @unittest.skipIf(python_is_optimized(),
700 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000701 def test_pyup_command(self):
702 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000703 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000704 cmds_after_breakpoint=['py-up'])
705 self.assertMultilineMatches(bt,
706 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000707#[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 +0000708 baz\(a, b, c\)
709$''')
710
Victor Stinnera92e81b2010-04-20 22:28:31 +0000711 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000712 def test_down_at_bottom(self):
713 'Verify handling of "py-down" at the bottom of the stack'
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-down'])
716 self.assertEndsWith(bt,
717 'Unable to find a newer python frame\n')
718
Victor Stinnera92e81b2010-04-20 22:28:31 +0000719 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000720 def test_up_at_top(self):
721 'Verify handling of "py-up" at the top of the stack'
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-up'] * 4)
724 self.assertEndsWith(bt,
725 'Unable to find an older python frame\n')
726
Victor Stinnera92e81b2010-04-20 22:28:31 +0000727 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100728 @unittest.skipIf(python_is_optimized(),
729 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000730 def test_up_then_down(self):
731 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000732 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000733 cmds_after_breakpoint=['py-up', 'py-down'])
734 self.assertMultilineMatches(bt,
735 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000736#[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 +0000737 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000738#[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 +0000739 print\(42\)
740$''')
741
742class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100743 @unittest.skipIf(python_is_optimized(),
744 "Python was compiled with optimizations")
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200745 def test_bt(self):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000746 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000747 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000748 cmds_after_breakpoint=['py-bt'])
749 self.assertMultilineMatches(bt,
750 r'''^.*
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200751Traceback \(most recent call first\):
752 File ".*gdb_sample.py", line 10, in baz
753 print\(42\)
754 File ".*gdb_sample.py", line 7, in bar
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000755 baz\(a, b, c\)
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200756 File ".*gdb_sample.py", line 4, in foo
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000757 bar\(a, b, c\)
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200758 File ".*gdb_sample.py", line 12, in <module>
Victor Stinner99cff3f2011-12-19 13:59:58 +0100759 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000760''')
761
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200762 @unittest.skipIf(python_is_optimized(),
763 "Python was compiled with optimizations")
764 def test_bt_full(self):
765 'Verify that the "py-bt-full" command works'
766 bt = self.get_stack_trace(script=self.get_sample_script(),
767 cmds_after_breakpoint=['py-bt-full'])
768 self.assertMultilineMatches(bt,
769 r'''^.*
770#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
771 baz\(a, b, c\)
772#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
773 bar\(a, b, c\)
774#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
775 foo\(1, 2, 3\)
776''')
777
778 @unittest.skipUnless(thread,
779 "Python was compiled without thread support")
780 def test_threads(self):
781 'Verify that "py-bt" indicates threads that are waiting for the GIL'
782 cmd = '''
783from threading import Thread
784
785class TestThread(Thread):
786 # These threads would run forever, but we'll interrupt things with the
787 # debugger
788 def run(self):
789 i = 0
790 while 1:
791 i += 1
792
793t = {}
794for i in range(4):
795 t[i] = TestThread()
796 t[i].start()
797
798# Trigger a breakpoint on the main thread
799print 42
800
801'''
802 # Verify with "py-bt":
803 gdb_output = self.get_stack_trace(cmd,
804 cmds_after_breakpoint=['thread apply all py-bt'])
805 self.assertIn('Waiting for the GIL', gdb_output)
806
807 # Verify with "py-bt-full":
808 gdb_output = self.get_stack_trace(cmd,
809 cmds_after_breakpoint=['thread apply all py-bt-full'])
810 self.assertIn('Waiting for the GIL', gdb_output)
811
812 @unittest.skipIf(python_is_optimized(),
813 "Python was compiled with optimizations")
814 # Some older versions of gdb will fail with
815 # "Cannot find new threads: generic error"
816 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
817 @unittest.skipUnless(thread,
818 "Python was compiled without thread support")
819 def test_gc(self):
820 'Verify that "py-bt" indicates if a thread is garbage-collecting'
821 cmd = ('from gc import collect\n'
822 'print 42\n'
823 'def foo():\n'
824 ' collect()\n'
825 'def bar():\n'
826 ' foo()\n'
827 'bar()\n')
828 # Verify with "py-bt":
829 gdb_output = self.get_stack_trace(cmd,
830 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
831 )
832 self.assertIn('Garbage-collecting', gdb_output)
833
834 # Verify with "py-bt-full":
835 gdb_output = self.get_stack_trace(cmd,
836 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
837 )
838 self.assertIn('Garbage-collecting', gdb_output)
839
840 @unittest.skipIf(python_is_optimized(),
841 "Python was compiled with optimizations")
842 # Some older versions of gdb will fail with
843 # "Cannot find new threads: generic error"
844 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
845 @unittest.skipUnless(thread,
846 "Python was compiled without thread support")
847 def test_pycfunction(self):
848 'Verify that "py-bt" displays invocations of PyCFunction instances'
849 # Tested function must not be defined with METH_NOARGS or METH_O,
850 # otherwise call_function() doesn't call PyCFunction_Call()
851 cmd = ('from time import gmtime\n'
852 'def foo():\n'
853 ' gmtime(1)\n'
854 'def bar():\n'
855 ' foo()\n'
856 'bar()\n')
857 # Verify with "py-bt":
858 gdb_output = self.get_stack_trace(cmd,
859 breakpoint='time_gmtime',
860 cmds_after_breakpoint=['bt', 'py-bt'],
861 )
862 self.assertIn('<built-in function gmtime', gdb_output)
863
864 # Verify with "py-bt-full":
865 gdb_output = self.get_stack_trace(cmd,
866 breakpoint='time_gmtime',
867 cmds_after_breakpoint=['py-bt-full'],
868 )
869 self.assertIn('#0 <built-in function gmtime', gdb_output)
870
871
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000872class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100873 @unittest.skipIf(python_is_optimized(),
874 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000875 def test_basic_command(self):
876 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000877 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000878 cmds_after_breakpoint=['py-print args'])
879 self.assertMultilineMatches(bt,
880 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
881
Victor Stinnera92e81b2010-04-20 22:28:31 +0000882 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100883 @unittest.skipIf(python_is_optimized(),
884 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000885 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000886 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000887 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
888 self.assertMultilineMatches(bt,
889 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
890
Victor Stinner99cff3f2011-12-19 13:59:58 +0100891 @unittest.skipIf(python_is_optimized(),
892 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000893 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000894 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000895 cmds_after_breakpoint=['py-print __name__'])
896 self.assertMultilineMatches(bt,
897 r".*\nglobal '__name__' = '__main__'\n.*")
898
Victor Stinner99cff3f2011-12-19 13:59:58 +0100899 @unittest.skipIf(python_is_optimized(),
900 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000901 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000902 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000903 cmds_after_breakpoint=['py-print len'])
904 self.assertMultilineMatches(bt,
905 r".*\nbuiltin 'len' = <built-in function len>\n.*")
906
907class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100908 @unittest.skipIf(python_is_optimized(),
909 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000910 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000911 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000912 cmds_after_breakpoint=['py-locals'])
913 self.assertMultilineMatches(bt,
914 r".*\nargs = \(1, 2, 3\)\n.*")
915
Victor Stinnera92e81b2010-04-20 22:28:31 +0000916 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100917 @unittest.skipIf(python_is_optimized(),
918 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000919 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000920 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000921 cmds_after_breakpoint=['py-up', 'py-locals'])
922 self.assertMultilineMatches(bt,
923 r".*\na = 1\nb = 2\nc = 3\n.*")
924
925def test_main():
Victor Stinner3c5ce402015-09-03 09:51:59 +0200926 if test_support.verbose:
927 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
928 for line in gdb_version.splitlines():
929 print(" " * 4 + line)
Martin v. Löwis5a965432010-04-12 05:22:25 +0000930 run_unittest(PrettyPrintTests,
931 PyListTests,
932 StackNavigationTests,
933 PyBtTests,
934 PyPrintTests,
935 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000936 )
937
938if __name__ == "__main__":
939 test_main()