blob: d49769e44edfb0a6d2858c66e22ac084a231a968 [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
Victor Stinnere36f94f2018-06-15 23:59:56 +02006import locale
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +00007import os
8import re
9import subprocess
10import sys
Zachary Wared833c772016-08-24 11:14:34 -050011import sysconfig
Victor Stinnere36f94f2018-06-15 23:59:56 +020012import textwrap
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000013import unittest
14
Victor Stinner3c5ce402015-09-03 09:51:59 +020015from test import test_support
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000016from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000017
Victor Stinnercc1db4b2015-09-03 10:17:28 +020018# Is this Python configured to support threads?
19try:
20 import thread
21except ImportError:
22 thread = None
23
Victor Stinner3c5ce402015-09-03 09:51:59 +020024def get_gdb_version():
25 try:
26 proc = subprocess.Popen(["gdb", "-nx", "--version"],
27 stdout=subprocess.PIPE,
Benjamin Peterson499378f2016-09-06 10:06:31 -070028 stderr=subprocess.PIPE,
Victor Stinner3c5ce402015-09-03 09:51:59 +020029 universal_newlines=True)
30 version = proc.communicate()[0]
31 except OSError:
32 # This is what "no gdb" looks like. There may, however, be other
33 # errors that manifest this way too.
34 raise unittest.SkipTest("Couldn't find gdb on the path")
35
36 # Regex to parse:
37 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
38 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinnerdf11d7c2015-09-15 00:19:47 +020039 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
40 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
41 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner3c5ce402015-09-03 09:51:59 +020042 if match is None:
43 raise Exception("unable to parse GDB version: %r" % version)
44 return (version, int(match.group(1)), int(match.group(2)))
45
46gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murray3e66f0d2012-10-27 13:47:49 -040047if gdb_major_version < 7:
Victor Stinner3c5ce402015-09-03 09:51:59 +020048 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
49 "embedding. Saw %s.%s:\n%s"
50 % (gdb_major_version, gdb_minor_version,
51 gdb_version))
52
Benjamin Peterson51f461f2014-11-23 22:34:04 -060053if sys.platform.startswith("sunos"):
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060054 raise unittest.SkipTest("test doesn't work very well on Solaris")
55
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056
R David Murray3e66f0d2012-10-27 13:47:49 -040057# Location of custom hooks file in a repository checkout.
58checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
59 'python-gdb.py')
60
61def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020062 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040063
64 Returns its (stdout, stderr)
65 """
66 if env_vars:
67 env = os.environ.copy()
68 env.update(env_vars)
69 else:
70 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020071 # -nx: Do not execute commands from any .gdbinit initialization files
72 # (issue #22188)
73 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040074 if (gdb_major_version, gdb_minor_version) >= (7, 4):
75 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
76 out, err = subprocess.Popen(base_cmd + args,
Martin Panter2179b2e2016-01-16 05:07:35 +000077 # Redirect stdin to prevent GDB from messing with terminal settings
78 stdin=subprocess.PIPE,
R David Murray3e66f0d2012-10-27 13:47:49 -040079 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
80 ).communicate()
81 return out, err
82
Zachary Wared833c772016-08-24 11:14:34 -050083if not sysconfig.is_python_build():
84 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
85
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000086# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010087gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040088if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000089 raise unittest.SkipTest("gdb not built with embedded python support")
90
Nick Coghlan254a3772013-09-22 19:36:09 +100091# Verify that "gdb" can load our custom hooks, as OS security settings may
92# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040093cmd = ['--args', sys.executable]
94_, gdbpy_errors = run_gdb('--args', sys.executable)
95if "auto-loading has been declined" in gdbpy_errors:
96 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100097 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100098
Victor Stinner99cff3f2011-12-19 13:59:58 +010099def python_is_optimized():
100 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
101 final_opt = ""
102 for opt in cflags.split():
103 if opt.startswith('-O'):
104 final_opt = opt
Victor Stinner582265f2015-03-27 15:44:13 +0100105 return final_opt not in ('', '-O0', '-Og')
Victor Stinner99cff3f2011-12-19 13:59:58 +0100106
Victor Stinnera92e81b2010-04-20 22:28:31 +0000107def gdb_has_frame_select():
108 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -0400109 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +0000110 m = re.match(r'.*\[(.*)\].*', stdout)
111 if not m:
112 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
113 gdb_frame_dir = m.group(1).split(', ')
114 return "'select'" in gdb_frame_dir
115
116HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000117
118class DebuggerTests(unittest.TestCase):
119
120 """Test that the debugger can debug Python."""
121
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000122 def get_stack_trace(self, source=None, script=None,
123 breakpoint='PyObject_Print',
124 cmds_after_breakpoint=None,
125 import_site=False):
126 '''
127 Run 'python -c SOURCE' under gdb with a breakpoint.
128
129 Support injecting commands after the breakpoint is reached
130
131 Returns the stdout from gdb
132
133 cmds_after_breakpoint: if provided, a list of strings: gdb commands
134 '''
135 # We use "set breakpoint pending yes" to avoid blocking with a:
136 # Function "foo" not defined.
137 # Make breakpoint pending on future shared library load? (y or [n])
138 # error, which typically happens python is dynamically linked (the
139 # breakpoints of interest are to be found in the shared library)
140 # When this happens, we still get:
141 # Function "PyObject_Print" not defined.
142 # emitted to stderr each time, alas.
143
144 # Initially I had "--eval-command=continue" here, but removed it to
145 # avoid repeated print breakpoints when traversing hierarchical data
146 # structures
147
148 # Generate a list of commands in gdb's language:
149 commands = ['set breakpoint pending yes',
150 'break %s' % breakpoint,
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200151
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200152 # The tests assume that the first frame of printed
153 # backtrace will not contain program counter,
154 # that is however not guaranteed by gdb
155 # therefore we need to use 'set print address off' to
156 # make sure the counter is not there. For example:
157 # #0 in PyObject_Print ...
158 # is assumed, but sometimes this can be e.g.
159 # #0 0x00003fffb7dd1798 in PyObject_Print ...
160 'set print address off',
161
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000162 'run']
Serhiy Storchakadd8430f2015-02-06 08:36:14 +0200163
164 # GDB as of 7.4 onwards can distinguish between the
165 # value of a variable at entry vs current value:
166 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
167 # which leads to the selftests failing with errors like this:
168 # AssertionError: 'v@entry=()' != '()'
169 # Disable this:
170 if (gdb_major_version, gdb_minor_version) >= (7, 4):
171 commands += ['set print entry-values no']
172
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000173 if cmds_after_breakpoint:
174 commands += cmds_after_breakpoint
175 else:
176 commands += ['backtrace']
177
178 # print commands
179
180 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200181 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000182 args += ['--eval-command=%s' % cmd for cmd in commands]
183 args += ["--args",
184 sys.executable]
185
186 if not import_site:
187 # -S suppresses the default 'import site'
188 args += ["-S"]
189
190 if source:
191 args += ["-c", source]
192 elif script:
193 args += [script]
194
195 # print args
196 # print ' '.join(args)
197
198 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400199 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000200
Antoine Pitroub996e042013-05-01 00:15:44 +0200201 errlines = err.splitlines()
202 unexpected_errlines = []
203
204 # Ignore some benign messages on stderr.
205 ignore_patterns = (
206 'Function "%s" not defined.' % breakpoint,
Antoine Pitroub996e042013-05-01 00:15:44 +0200207 'Do you need "set solib-search-path" or '
208 '"set sysroot"?',
Victor Stinner8420cd22017-02-10 14:14:04 +0100209 # BFD: /usr/lib/debug/(...): unable to initialize decompress
210 # status for section .debug_aranges
211 'BFD: ',
212 # ignore all warnings
213 'warning: ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200214 )
215 for line in errlines:
Victor Stinner8420cd22017-02-10 14:14:04 +0100216 if not line:
217 continue
Antoine Pitroub996e042013-05-01 00:15:44 +0200218 if not line.startswith(ignore_patterns):
219 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000220
221 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200222 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000223 return out
224
225 def get_gdb_repr(self, source,
226 cmds_after_breakpoint=None,
227 import_site=False):
228 # Given an input python source representation of data,
229 # run "python -c'print DATA'" under gdb with a breakpoint on
230 # PyObject_Print and scrape out gdb's representation of the "op"
231 # parameter, and verify that the gdb displays the same string
232 #
233 # For a nested structure, the first time we hit the breakpoint will
234 # give us the top-level structure
235 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
236 cmds_after_breakpoint=cmds_after_breakpoint,
237 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000238 # gdb can insert additional '\n' and space characters in various places
239 # in its output, depending on the width of the terminal it's connected
240 # to (using its "wrap_here" function)
241 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000242 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000243 if not m:
244 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000245 return m.group(1), gdb_output
246
247 def assertEndsWith(self, actual, exp_end):
248 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000249 self.assertTrue(actual.endswith(exp_end),
250 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000251
252 def assertMultilineMatches(self, actual, pattern):
253 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000254 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000255
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000256 def get_sample_script(self):
257 return findfile('gdb_sample.py')
258
Gregory P. Smith77ba5962016-09-08 21:50:44 -0700259
260@unittest.skipIf(python_is_optimized(),
261 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000262class PrettyPrintTests(DebuggerTests):
263 def test_getting_backtrace(self):
264 gdb_output = self.get_stack_trace('print 42')
265 self.assertTrue('PyObject_Print' in gdb_output)
266
267 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
268 # Ensure that gdb's rendering of the value in a debugged process
269 # matches repr(value) in this process:
270 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
271 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100272 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000273
274 def test_int(self):
275 'Verify the pretty-printing of various "int" values'
276 self.assertGdbRepr(42)
277 self.assertGdbRepr(0)
278 self.assertGdbRepr(-7)
279 self.assertGdbRepr(sys.maxint)
280 self.assertGdbRepr(-sys.maxint)
281
282 def test_long(self):
283 'Verify the pretty-printing of various "long" values'
284 self.assertGdbRepr(0L)
285 self.assertGdbRepr(1000000000000L)
286 self.assertGdbRepr(-1L)
287 self.assertGdbRepr(-1000000000000000L)
288
289 def test_singletons(self):
290 'Verify the pretty-printing of True, False and None'
291 self.assertGdbRepr(True)
292 self.assertGdbRepr(False)
293 self.assertGdbRepr(None)
294
295 def test_dicts(self):
296 'Verify the pretty-printing of dictionaries'
297 self.assertGdbRepr({})
298 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500299 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000300
301 def test_lists(self):
302 'Verify the pretty-printing of lists'
303 self.assertGdbRepr([])
304 self.assertGdbRepr(range(5))
305
306 def test_strings(self):
307 'Verify the pretty-printing of strings'
308 self.assertGdbRepr('')
309 self.assertGdbRepr('And now for something hopefully the same')
310 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
311 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
312
313 def test_tuples(self):
314 'Verify the pretty-printing of tuples'
315 self.assertGdbRepr(tuple())
316 self.assertGdbRepr((1,))
317 self.assertGdbRepr(('foo', 'bar', 'baz'))
318
319 def test_unicode(self):
320 'Verify the pretty-printing of unicode values'
321 # Test the empty unicode string:
322 self.assertGdbRepr(u'')
323
324 self.assertGdbRepr(u'hello world')
325
326 # Test printing a single character:
327 # U+2620 SKULL AND CROSSBONES
328 self.assertGdbRepr(u'\u2620')
329
330 # Test printing a Japanese unicode string
331 # (I believe this reads "mojibake", using 3 characters from the CJK
332 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
333 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
334
335 # Test a character outside the BMP:
336 # U+1D121 MUSICAL SYMBOL C CLEF
337 # This is:
338 # UTF-8: 0xF0 0x9D 0x84 0xA1
339 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000340 # This will only work on wide-unicode builds:
341 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000342
343 def test_sets(self):
344 'Verify the pretty-printing of sets'
345 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500346 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
347 self.assertTrue(rep.startswith("set(["))
348 self.assertTrue(rep.endswith("])"))
349 self.assertEqual(eval(rep), {'a', 'b'})
350 rep = self.get_gdb_repr("print set([4, 5])")[0]
351 self.assertTrue(rep.startswith("set(["))
352 self.assertTrue(rep.endswith("])"))
353 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000354
355 # Ensure that we handled sets containing the "dummy" key value,
356 # which happens on deletion:
357 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
358s.pop()
359print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000360 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000361
362 def test_frozensets(self):
363 'Verify the pretty-printing of frozensets'
364 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500365 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
366 self.assertTrue(rep.startswith("frozenset(["))
367 self.assertTrue(rep.endswith("])"))
368 self.assertEqual(eval(rep), {'a', 'b'})
369 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
370 self.assertTrue(rep.startswith("frozenset(["))
371 self.assertTrue(rep.endswith("])"))
372 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000373
374 def test_exceptions(self):
375 # Test a RuntimeError
376 gdb_repr, gdb_output = self.get_gdb_repr('''
377try:
378 raise RuntimeError("I am an error")
379except RuntimeError, e:
380 print e
381''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000382 self.assertEqual(gdb_repr,
383 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000384
385
386 # Test division by zero:
387 gdb_repr, gdb_output = self.get_gdb_repr('''
388try:
389 a = 1 / 0
390except ZeroDivisionError, e:
391 print e
392''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000393 self.assertEqual(gdb_repr,
394 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000395
396 def test_classic_class(self):
397 'Verify the pretty-printing of classic class instances'
398 gdb_repr, gdb_output = self.get_gdb_repr('''
399class Foo:
400 pass
401foo = Foo()
402foo.an_int = 42
403print foo''')
404 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
405 self.assertTrue(m,
406 msg='Unexpected classic-class rendering %r' % gdb_repr)
407
408 def test_modern_class(self):
409 'Verify the pretty-printing of new-style class instances'
410 gdb_repr, gdb_output = self.get_gdb_repr('''
411class Foo(object):
412 pass
413foo = Foo()
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
420 def test_subclassing_list(self):
421 'Verify the pretty-printing of an instance of a list subclass'
422 gdb_repr, gdb_output = self.get_gdb_repr('''
423class Foo(list):
424 pass
425foo = Foo()
426foo += [1, 2, 3]
427foo.an_int = 42
428print foo''')
429 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
430 self.assertTrue(m,
431 msg='Unexpected new-style class rendering %r' % gdb_repr)
432
433 def test_subclassing_tuple(self):
434 'Verify the pretty-printing of an instance of a tuple subclass'
435 # This should exercise the negative tp_dictoffset code in the
436 # new-style class support
437 gdb_repr, gdb_output = self.get_gdb_repr('''
438class Foo(tuple):
439 pass
440foo = Foo((1, 2, 3))
441foo.an_int = 42
442print foo''')
443 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
444 self.assertTrue(m,
445 msg='Unexpected new-style class rendering %r' % gdb_repr)
446
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000447 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000448 '''Run Python under gdb, corrupting variables in the inferior process
449 immediately before taking a backtrace.
450
451 Verify that the variable's representation is the expected failsafe
452 representation'''
453 if corruption:
454 cmds_after_breakpoint=[corruption, 'backtrace']
455 else:
456 cmds_after_breakpoint=['backtrace']
457
458 gdb_repr, gdb_output = \
459 self.get_gdb_repr(source,
460 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000461
462 if expvalue:
463 if gdb_repr == repr(expvalue):
464 # gdb managed to print the value in spite of the corruption;
465 # this is good (see http://bugs.python.org/issue8330)
466 return
467
468 if exptype:
469 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
470 else:
471 # Match anything for the type name; 0xDEADBEEF could point to
472 # something arbitrary (see http://bugs.python.org/issue8330)
473 pattern = '<.* at remote 0x[0-9a-f]+>'
474
475 m = re.match(pattern, gdb_repr)
476 if not m:
477 self.fail('Unexpected gdb representation: %r\n%s' % \
478 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000479
480 def test_NULL_ptr(self):
481 'Ensure that a NULL PyObject* is handled gracefully'
482 gdb_repr, gdb_output = (
483 self.get_gdb_repr('print 42',
484 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000485 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000486 )
487
Ezio Melotti2623a372010-11-21 13:34:58 +0000488 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000489
490 def test_NULL_ob_type(self):
491 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
492 self.assertSane('print 42',
493 'set op->ob_type=0')
494
495 def test_corrupt_ob_type(self):
496 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
497 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000498 'set op->ob_type=0xDEADBEEF',
499 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000500
501 def test_corrupt_tp_flags(self):
502 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
503 self.assertSane('print 42',
504 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000505 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000506
507 def test_corrupt_tp_name(self):
508 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
509 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000510 'set op->ob_type->tp_name=0xDEADBEEF',
511 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000512
513 def test_NULL_instance_dict(self):
514 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
515 self.assertSane('''
516class Foo:
517 pass
518foo = Foo()
519foo.an_int = 42
520print foo''',
521 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000522 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000523
524 def test_builtins_help(self):
525 'Ensure that the new-style class _Helper in site.py can be handled'
526 # (this was the issue causing tracebacks in
527 # http://bugs.python.org/issue8032#msg100537 )
528
529 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
530 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
531 self.assertTrue(m,
532 msg='Unexpected rendering %r' % gdb_repr)
533
534 def test_selfreferential_list(self):
535 '''Ensure that a reference loop involving a list doesn't lead proxyval
536 into an infinite loop:'''
537 gdb_repr, gdb_output = \
538 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
539
Ezio Melotti2623a372010-11-21 13:34:58 +0000540 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000541
542 gdb_repr, gdb_output = \
543 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
544
Ezio Melotti2623a372010-11-21 13:34:58 +0000545 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000546
547 def test_selfreferential_dict(self):
548 '''Ensure that a reference loop involving a dict doesn't lead proxyval
549 into an infinite loop:'''
550 gdb_repr, gdb_output = \
551 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
552
Ezio Melotti2623a372010-11-21 13:34:58 +0000553 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000554
555 def test_selfreferential_old_style_instance(self):
556 gdb_repr, gdb_output = \
557 self.get_gdb_repr('''
558class Foo:
559 pass
560foo = Foo()
561foo.an_attr = foo
562print foo''')
563 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) 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_selfreferential_new_style_instance(self):
569 gdb_repr, gdb_output = \
570 self.get_gdb_repr('''
571class Foo(object):
572 pass
573foo = Foo()
574foo.an_attr = foo
575print foo''')
576 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
577 gdb_repr),
578 'Unexpected gdb representation: %r\n%s' % \
579 (gdb_repr, gdb_output))
580
581 gdb_repr, gdb_output = \
582 self.get_gdb_repr('''
583class Foo(object):
584 pass
585a = Foo()
586b = Foo()
587a.an_attr = b
588b.an_attr = a
589print a''')
590 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
591 gdb_repr),
592 'Unexpected gdb representation: %r\n%s' % \
593 (gdb_repr, gdb_output))
594
595 def test_truncation(self):
596 'Verify that very long output is truncated'
597 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000598 self.assertEqual(gdb_repr,
599 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
600 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
601 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
602 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
603 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
604 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
605 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
606 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
607 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
608 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
609 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
610 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
611 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
612 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
613 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
614 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
615 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
616 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
617 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
618 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
619 "224, 225, 226...(truncated)")
620 self.assertEqual(len(gdb_repr),
621 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000622
623 def test_builtin_function(self):
624 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000625 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000626
627 def test_builtin_method(self):
628 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
629 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
630 gdb_repr),
631 'Unexpected gdb representation: %r\n%s' % \
632 (gdb_repr, gdb_output))
633
634 def test_frames(self):
635 gdb_output = self.get_stack_trace('''
636def foo(a, b, c):
637 pass
638
639foo(3, 4, 5)
640print foo.__code__''',
641 breakpoint='PyObject_Print',
642 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
643 )
R. David Murray0c080092010-04-05 16:28:49 +0000644 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
645 gdb_output,
646 re.DOTALL),
647 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000648
Victor Stinner99cff3f2011-12-19 13:59:58 +0100649@unittest.skipIf(python_is_optimized(),
650 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000651class PyListTests(DebuggerTests):
652 def assertListing(self, expected, actual):
653 self.assertEndsWith(actual, expected)
654
655 def test_basic_command(self):
656 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000657 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000658 cmds_after_breakpoint=['py-list'])
659
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000660 self.assertListing(' 5 \n'
661 ' 6 def bar(a, b, c):\n'
662 ' 7 baz(a, b, c)\n'
663 ' 8 \n'
664 ' 9 def baz(*args):\n'
665 ' >10 print(42)\n'
666 ' 11 \n'
667 ' 12 foo(1, 2, 3)\n',
668 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000669
670 def test_one_abs_arg(self):
671 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000672 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000673 cmds_after_breakpoint=['py-list 9'])
674
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000675 self.assertListing(' 9 def baz(*args):\n'
676 ' >10 print(42)\n'
677 ' 11 \n'
678 ' 12 foo(1, 2, 3)\n',
679 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000680
681 def test_two_abs_args(self):
682 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000683 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000684 cmds_after_breakpoint=['py-list 1,3'])
685
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000686 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
687 ' 2 \n'
688 ' 3 def foo(a, b, c):\n',
689 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000690
691class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000692 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100693 @unittest.skipIf(python_is_optimized(),
694 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000695 def test_pyup_command(self):
696 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000697 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000698 cmds_after_breakpoint=['py-up'])
699 self.assertMultilineMatches(bt,
700 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000701#[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 +0000702 baz\(a, b, c\)
703$''')
704
Victor Stinnera92e81b2010-04-20 22:28:31 +0000705 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000706 def test_down_at_bottom(self):
707 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000708 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000709 cmds_after_breakpoint=['py-down'])
710 self.assertEndsWith(bt,
711 'Unable to find a newer python frame\n')
712
Victor Stinnera92e81b2010-04-20 22:28:31 +0000713 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cb20a212016-09-08 21:51:26 +0000714 @unittest.skipIf(python_is_optimized(),
715 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000716 def test_up_at_top(self):
717 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000718 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000719 cmds_after_breakpoint=['py-up'] * 4)
720 self.assertEndsWith(bt,
721 'Unable to find an older python frame\n')
722
Victor Stinnera92e81b2010-04-20 22:28:31 +0000723 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100724 @unittest.skipIf(python_is_optimized(),
725 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000726 def test_up_then_down(self):
727 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000728 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000729 cmds_after_breakpoint=['py-up', 'py-down'])
730 self.assertMultilineMatches(bt,
731 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000732#[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 +0000733 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000734#[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 +0000735 print\(42\)
736$''')
737
738class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100739 @unittest.skipIf(python_is_optimized(),
740 "Python was compiled with optimizations")
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200741 def test_bt(self):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000742 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000743 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000744 cmds_after_breakpoint=['py-bt'])
745 self.assertMultilineMatches(bt,
746 r'''^.*
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200747Traceback \(most recent call first\):
748 File ".*gdb_sample.py", line 10, in baz
749 print\(42\)
750 File ".*gdb_sample.py", line 7, in bar
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000751 baz\(a, b, c\)
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200752 File ".*gdb_sample.py", line 4, in foo
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000753 bar\(a, b, c\)
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200754 File ".*gdb_sample.py", line 12, in <module>
Victor Stinner99cff3f2011-12-19 13:59:58 +0100755 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000756''')
757
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200758 @unittest.skipIf(python_is_optimized(),
759 "Python was compiled with optimizations")
760 def test_bt_full(self):
761 'Verify that the "py-bt-full" command works'
762 bt = self.get_stack_trace(script=self.get_sample_script(),
763 cmds_after_breakpoint=['py-bt-full'])
764 self.assertMultilineMatches(bt,
765 r'''^.*
766#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
767 baz\(a, b, c\)
768#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
769 bar\(a, b, c\)
770#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
771 foo\(1, 2, 3\)
772''')
773
774 @unittest.skipUnless(thread,
775 "Python was compiled without thread support")
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cb20a212016-09-08 21:51:26 +0000776 @unittest.skipIf(python_is_optimized(),
777 "Python was compiled with optimizations")
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200778 def test_threads(self):
779 'Verify that "py-bt" indicates threads that are waiting for the GIL'
780 cmd = '''
781from threading import Thread
782
783class TestThread(Thread):
784 # These threads would run forever, but we'll interrupt things with the
785 # debugger
786 def run(self):
787 i = 0
788 while 1:
789 i += 1
790
791t = {}
792for i in range(4):
793 t[i] = TestThread()
794 t[i].start()
795
796# Trigger a breakpoint on the main thread
797print 42
798
799'''
800 # Verify with "py-bt":
801 gdb_output = self.get_stack_trace(cmd,
802 cmds_after_breakpoint=['thread apply all py-bt'])
803 self.assertIn('Waiting for the GIL', gdb_output)
804
805 # Verify with "py-bt-full":
806 gdb_output = self.get_stack_trace(cmd,
807 cmds_after_breakpoint=['thread apply all py-bt-full'])
808 self.assertIn('Waiting for the GIL', gdb_output)
809
810 @unittest.skipIf(python_is_optimized(),
811 "Python was compiled with optimizations")
812 # Some older versions of gdb will fail with
813 # "Cannot find new threads: generic error"
814 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
815 @unittest.skipUnless(thread,
816 "Python was compiled without thread support")
817 def test_gc(self):
818 'Verify that "py-bt" indicates if a thread is garbage-collecting'
819 cmd = ('from gc import collect\n'
820 'print 42\n'
821 'def foo():\n'
822 ' collect()\n'
823 'def bar():\n'
824 ' foo()\n'
825 'bar()\n')
826 # Verify with "py-bt":
827 gdb_output = self.get_stack_trace(cmd,
828 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
829 )
830 self.assertIn('Garbage-collecting', gdb_output)
831
832 # Verify with "py-bt-full":
833 gdb_output = self.get_stack_trace(cmd,
834 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
835 )
836 self.assertIn('Garbage-collecting', gdb_output)
837
838 @unittest.skipIf(python_is_optimized(),
839 "Python was compiled with optimizations")
840 # Some older versions of gdb will fail with
841 # "Cannot find new threads: generic error"
842 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
843 @unittest.skipUnless(thread,
844 "Python was compiled without thread support")
845 def test_pycfunction(self):
846 'Verify that "py-bt" displays invocations of PyCFunction instances'
847 # Tested function must not be defined with METH_NOARGS or METH_O,
848 # otherwise call_function() doesn't call PyCFunction_Call()
849 cmd = ('from time import gmtime\n'
850 'def foo():\n'
851 ' gmtime(1)\n'
852 'def bar():\n'
853 ' foo()\n'
854 'bar()\n')
855 # Verify with "py-bt":
856 gdb_output = self.get_stack_trace(cmd,
857 breakpoint='time_gmtime',
858 cmds_after_breakpoint=['bt', 'py-bt'],
859 )
860 self.assertIn('<built-in function gmtime', gdb_output)
861
862 # Verify with "py-bt-full":
863 gdb_output = self.get_stack_trace(cmd,
864 breakpoint='time_gmtime',
865 cmds_after_breakpoint=['py-bt-full'],
866 )
Victor Stinnere36f94f2018-06-15 23:59:56 +0200867 self.assertIn('#1 <built-in function gmtime', gdb_output)
868
869 @unittest.skipIf(python_is_optimized(),
870 "Python was compiled with optimizations")
871 def test_wrapper_call(self):
872 cmd = textwrap.dedent('''
873 class MyList(list):
874 def __init__(self):
875 super(MyList, self).__init__() # wrapper_call()
876
877 print("first break point")
878 l = MyList()
879 ''')
880 # Verify with "py-bt":
881 gdb_output = self.get_stack_trace(cmd,
882 cmds_after_breakpoint=['break wrapper_call', 'continue', 'py-bt'])
883 self.assertRegexpMatches(gdb_output,
884 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinnercc1db4b2015-09-03 10:17:28 +0200885
886
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000887class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100888 @unittest.skipIf(python_is_optimized(),
889 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000890 def test_basic_command(self):
891 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000892 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000893 cmds_after_breakpoint=['py-print args'])
894 self.assertMultilineMatches(bt,
895 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
896
Victor Stinnera92e81b2010-04-20 22:28:31 +0000897 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100898 @unittest.skipIf(python_is_optimized(),
899 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000900 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000901 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000902 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
903 self.assertMultilineMatches(bt,
904 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
905
Victor Stinner99cff3f2011-12-19 13:59:58 +0100906 @unittest.skipIf(python_is_optimized(),
907 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000908 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000909 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000910 cmds_after_breakpoint=['py-print __name__'])
911 self.assertMultilineMatches(bt,
912 r".*\nglobal '__name__' = '__main__'\n.*")
913
Victor Stinner99cff3f2011-12-19 13:59:58 +0100914 @unittest.skipIf(python_is_optimized(),
915 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000916 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000917 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000918 cmds_after_breakpoint=['py-print len'])
919 self.assertMultilineMatches(bt,
920 r".*\nbuiltin 'len' = <built-in function len>\n.*")
921
922class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100923 @unittest.skipIf(python_is_optimized(),
924 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000925 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000926 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000927 cmds_after_breakpoint=['py-locals'])
928 self.assertMultilineMatches(bt,
929 r".*\nargs = \(1, 2, 3\)\n.*")
930
Victor Stinnera92e81b2010-04-20 22:28:31 +0000931 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100932 @unittest.skipIf(python_is_optimized(),
933 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000934 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000935 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000936 cmds_after_breakpoint=['py-up', 'py-locals'])
937 self.assertMultilineMatches(bt,
938 r".*\na = 1\nb = 2\nc = 3\n.*")
939
940def test_main():
Victor Stinner3c5ce402015-09-03 09:51:59 +0200941 if test_support.verbose:
942 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
943 for line in gdb_version.splitlines():
944 print(" " * 4 + line)
Martin v. Löwis5a965432010-04-12 05:22:25 +0000945 run_unittest(PrettyPrintTests,
946 PyListTests,
947 StackNavigationTests,
948 PyBtTests,
949 PyPrintTests,
950 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000951 )
952
953if __name__ == "__main__":
954 test_main()