blob: 15d8034c172200f810f38a4b7791d60d3c92136b [file] [log] [blame]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +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
11
Martin v. Löwis5226fd62010-04-21 06:05:58 +000012from test.support import run_unittest, findfile
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000013
14try:
15 gdb_version, _ = subprocess.Popen(["gdb", "--version"],
16 stdout=subprocess.PIPE).communicate()
17except OSError:
18 # This is what "no gdb" looks like. There may, however, be other
19 # errors that manifest this way too.
20 raise unittest.SkipTest("Couldn't find gdb on the path")
21gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.", gdb_version)
22if int(gdb_version_number.group(1)) < 7:
23 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000024 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000025
26# Verify that "gdb" was built with the embedded python support enabled:
27cmd = "--eval-command=python import sys; print sys.version_info"
28p = subprocess.Popen(["gdb", "--batch", cmd],
29 stdout=subprocess.PIPE)
30gdbpy_version, _ = p.communicate()
Benjamin Peterson9faa7ec2010-04-11 23:51:24 +000031if gdbpy_version == b'':
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000032 raise unittest.SkipTest("gdb not built with embedded python support")
33
Victor Stinner50eb60e2010-04-20 22:32:07 +000034def gdb_has_frame_select():
35 # Does this build of gdb have gdb.Frame.select ?
36 cmd = "--eval-command=python print(dir(gdb.Frame))"
37 p = subprocess.Popen(["gdb", "--batch", cmd],
38 stdout=subprocess.PIPE)
39 stdout, _ = p.communicate()
40 m = re.match(br'.*\[(.*)\].*', stdout)
41 if not m:
42 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
43 gdb_frame_dir = m.group(1).split(b', ')
44 return b"'select'" in gdb_frame_dir
45
46HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000047
Martin v. Löwis5ae68102010-04-21 22:38:42 +000048BREAKPOINT_FN='builtin_id'
49
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000050class DebuggerTests(unittest.TestCase):
51
52 """Test that the debugger can debug Python."""
53
54 def run_gdb(self, *args):
55 """Runs gdb with the command line given by *args.
56
57 Returns its stdout, stderr
58 """
59 out, err = subprocess.Popen(
60 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
61 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000062 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000063
64 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000065 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000066 cmds_after_breakpoint=None,
67 import_site=False):
68 '''
69 Run 'python -c SOURCE' under gdb with a breakpoint.
70
71 Support injecting commands after the breakpoint is reached
72
73 Returns the stdout from gdb
74
75 cmds_after_breakpoint: if provided, a list of strings: gdb commands
76 '''
77 # We use "set breakpoint pending yes" to avoid blocking with a:
78 # Function "foo" not defined.
79 # Make breakpoint pending on future shared library load? (y or [n])
80 # error, which typically happens python is dynamically linked (the
81 # breakpoints of interest are to be found in the shared library)
82 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +000083 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000084 # emitted to stderr each time, alas.
85
86 # Initially I had "--eval-command=continue" here, but removed it to
87 # avoid repeated print breakpoints when traversing hierarchical data
88 # structures
89
90 # Generate a list of commands in gdb's language:
91 commands = ['set breakpoint pending yes',
92 'break %s' % breakpoint,
93 'run']
94 if cmds_after_breakpoint:
95 commands += cmds_after_breakpoint
96 else:
97 commands += ['backtrace']
98
99 # print commands
100
101 # Use "commands" to generate the arguments with which to invoke "gdb":
102 args = ["gdb", "--batch"]
103 args += ['--eval-command=%s' % cmd for cmd in commands]
104 args += ["--args",
105 sys.executable]
106
107 if not import_site:
108 # -S suppresses the default 'import site'
109 args += ["-S"]
110
111 if source:
112 args += ["-c", source]
113 elif script:
114 args += [script]
115
116 # print args
117 # print ' '.join(args)
118
119 # Use "args" to invoke gdb, capturing stdout, stderr:
120 out, err = self.run_gdb(*args)
121
122 # Ignore some noise on stderr due to the pending breakpoint:
123 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000124 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
125 err = err.replace("warning: Unable to find libthread_db matching"
126 " inferior's thread library, thread debugging will"
127 " not be available.\n",
128 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000129
130 # Ensure no unexpected error messages:
131 self.assertEquals(err, '')
132
133 return out
134
135 def get_gdb_repr(self, source,
136 cmds_after_breakpoint=None,
137 import_site=False):
138 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000139 # run "python -c'id(DATA)'" under gdb with a breakpoint on
140 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000141 # parameter, and verify that the gdb displays the same string
142 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000143 # Verify that the gdb displays the expected string
144 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000145 # For a nested structure, the first time we hit the breakpoint will
146 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000147 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000148 cmds_after_breakpoint=cmds_after_breakpoint,
149 import_site=import_site)
150 # gdb can insert additional '\n' and space characters in various places
151 # in its output, depending on the width of the terminal it's connected
152 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000153 m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154 gdb_output, re.DOTALL)
155 if not m:
156 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
157 return m.group(1), gdb_output
158
159 def assertEndsWith(self, actual, exp_end):
160 '''Ensure that the given "actual" string ends with "exp_end"'''
161 self.assert_(actual.endswith(exp_end),
162 msg='%r did not end with %r' % (actual, exp_end))
163
164 def assertMultilineMatches(self, actual, pattern):
165 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000166 if not m:
167 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000168
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000169 def get_sample_script(self):
170 return findfile('gdb_sample.py')
171
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172class PrettyPrintTests(DebuggerTests):
173 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000174 gdb_output = self.get_stack_trace('id(42)')
175 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000177 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000178 # Ensure that gdb's rendering of the value in a debugged process
179 # matches repr(value) in this process:
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000180 gdb_repr, gdb_output = self.get_gdb_repr('id(' + repr(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000181 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000182 if not exp_repr:
183 exp_repr = repr(val)
184 self.assertEquals(gdb_repr, exp_repr,
185 ('%r did not equal expected %r; full output was:\n%s'
186 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000187
188 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000189 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000190 self.assertGdbRepr(42)
191 self.assertGdbRepr(0)
192 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000193 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194 self.assertGdbRepr(-1000000000000000)
195
196 def test_singletons(self):
197 'Verify the pretty-printing of True, False and None'
198 self.assertGdbRepr(True)
199 self.assertGdbRepr(False)
200 self.assertGdbRepr(None)
201
202 def test_dicts(self):
203 'Verify the pretty-printing of dictionaries'
204 self.assertGdbRepr({})
205 self.assertGdbRepr({'foo': 'bar'})
206 self.assertGdbRepr({'foo': 'bar', 'douglas':42})
207
208 def test_lists(self):
209 'Verify the pretty-printing of lists'
210 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000211 self.assertGdbRepr(list(range(5)))
212
213 def test_bytes(self):
214 'Verify the pretty-printing of bytes'
215 self.assertGdbRepr(b'')
216 self.assertGdbRepr(b'And now for something hopefully the same')
217 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
218 self.assertGdbRepr(b'this is a tab:\t'
219 b' this is a slash-N:\n'
220 b' this is a slash-R:\r'
221 )
222
223 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
224
225 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000226
227 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000228 'Verify the pretty-printing of unicode strings'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000229 self.assertGdbRepr('')
230 self.assertGdbRepr('And now for something hopefully the same')
231 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000232
233 # Test printing a single character:
234 # U+2620 SKULL AND CROSSBONES
235 self.assertGdbRepr('\u2620')
236
237 # Test printing a Japanese unicode string
238 # (I believe this reads "mojibake", using 3 characters from the CJK
239 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
240 self.assertGdbRepr('\u6587\u5b57\u5316\u3051')
241
242 # Test a character outside the BMP:
243 # U+1D121 MUSICAL SYMBOL C CLEF
244 # This is:
245 # UTF-8: 0xF0 0x9D 0x84 0xA1
246 # UTF-16: 0xD834 0xDD21
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000247 if sys.maxunicode == 0x10FFFF:
248 # wide unicode:
249 self.assertGdbRepr(chr(0x1D121))
250 else:
251 # narrow unicode:
252 self.assertGdbRepr(chr(0x1D121),
253 "'\\U0000d834\\U0000dd21'")
254
255 def test_tuples(self):
256 'Verify the pretty-printing of tuples'
257 self.assertGdbRepr(tuple())
258 self.assertGdbRepr((1,), '(1,)')
259 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000260
261 def test_sets(self):
262 'Verify the pretty-printing of sets'
263 self.assertGdbRepr(set())
264 self.assertGdbRepr(set(['a', 'b']))
265 self.assertGdbRepr(set([4, 5, 6]))
266
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000267 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268 # which happens on deletion:
269 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
270s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000271id(s)''')
272 self.assertEquals(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000273
274 def test_frozensets(self):
275 'Verify the pretty-printing of frozensets'
276 self.assertGdbRepr(frozenset())
277 self.assertGdbRepr(frozenset(['a', 'b']))
278 self.assertGdbRepr(frozenset([4, 5, 6]))
279
280 def test_exceptions(self):
281 # Test a RuntimeError
282 gdb_repr, gdb_output = self.get_gdb_repr('''
283try:
284 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000285except RuntimeError as e:
286 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000287''')
288 self.assertEquals(gdb_repr,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000289 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000290
291
292 # Test division by zero:
293 gdb_repr, gdb_output = self.get_gdb_repr('''
294try:
295 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000296except ZeroDivisionError as e:
297 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298''')
299 self.assertEquals(gdb_repr,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000300 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000301
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000302 def test_modern_class(self):
303 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000304 gdb_repr, gdb_output = self.get_gdb_repr('''
305class Foo:
306 pass
307foo = Foo()
308foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000309id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000310 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
311 self.assertTrue(m,
312 msg='Unexpected new-style class rendering %r' % gdb_repr)
313
314 def test_subclassing_list(self):
315 'Verify the pretty-printing of an instance of a list subclass'
316 gdb_repr, gdb_output = self.get_gdb_repr('''
317class Foo(list):
318 pass
319foo = Foo()
320foo += [1, 2, 3]
321foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000322id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000323 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000324
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325 self.assertTrue(m,
326 msg='Unexpected new-style class rendering %r' % gdb_repr)
327
328 def test_subclassing_tuple(self):
329 'Verify the pretty-printing of an instance of a tuple subclass'
330 # This should exercise the negative tp_dictoffset code in the
331 # new-style class support
332 gdb_repr, gdb_output = self.get_gdb_repr('''
333class Foo(tuple):
334 pass
335foo = Foo((1, 2, 3))
336foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000337id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000338 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000339
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000340 self.assertTrue(m,
341 msg='Unexpected new-style class rendering %r' % gdb_repr)
342
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000343 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000344 '''Run Python under gdb, corrupting variables in the inferior process
345 immediately before taking a backtrace.
346
347 Verify that the variable's representation is the expected failsafe
348 representation'''
349 if corruption:
350 cmds_after_breakpoint=[corruption, 'backtrace']
351 else:
352 cmds_after_breakpoint=['backtrace']
353
354 gdb_repr, gdb_output = \
355 self.get_gdb_repr(source,
356 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000357 if exprepr:
358 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000359 # gdb managed to print the value in spite of the corruption;
360 # this is good (see http://bugs.python.org/issue8330)
361 return
362
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000363 # Match anything for the type name; 0xDEADBEEF could point to
364 # something arbitrary (see http://bugs.python.org/issue8330)
365 pattern = '<.* at remote 0x[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000366
367 m = re.match(pattern, gdb_repr)
368 if not m:
369 self.fail('Unexpected gdb representation: %r\n%s' % \
370 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000371
372 def test_NULL_ptr(self):
373 'Ensure that a NULL PyObject* is handled gracefully'
374 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000375 self.get_gdb_repr('id(42)',
376 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000377 'backtrace'])
378 )
379
380 self.assertEquals(gdb_repr, '0x0')
381
382 def test_NULL_ob_type(self):
383 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000384 self.assertSane('id(42)',
385 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000386
387 def test_corrupt_ob_type(self):
388 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000389 self.assertSane('id(42)',
390 'set v->ob_type=0xDEADBEEF',
391 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000392
393 def test_corrupt_tp_flags(self):
394 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000395 self.assertSane('id(42)',
396 'set v->ob_type->tp_flags=0x0',
397 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000398
399 def test_corrupt_tp_name(self):
400 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000401 self.assertSane('id(42)',
402 'set v->ob_type->tp_name=0xDEADBEEF',
403 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404
405 def test_builtins_help(self):
406 'Ensure that the new-style class _Helper in site.py can be handled'
407 # (this was the issue causing tracebacks in
408 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000411 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
412 self.assertTrue(m,
413 msg='Unexpected rendering %r' % gdb_repr)
414
415 def test_selfreferential_list(self):
416 '''Ensure that a reference loop involving a list doesn't lead proxyval
417 into an infinite loop:'''
418 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000419 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000420 self.assertEquals(gdb_repr, '[3, 4, 5, [...]]')
421
422 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000423 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000424 self.assertEquals(gdb_repr, '[3, 4, 5, [[...]]]')
425
426 def test_selfreferential_dict(self):
427 '''Ensure that a reference loop involving a dict doesn't lead proxyval
428 into an infinite loop:'''
429 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000430 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000431
432 self.assertEquals(gdb_repr, "{'foo': {'bar': {...}}}")
433
434 def test_selfreferential_old_style_instance(self):
435 gdb_repr, gdb_output = \
436 self.get_gdb_repr('''
437class Foo:
438 pass
439foo = Foo()
440foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000441id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000442 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
443 gdb_repr),
444 'Unexpected gdb representation: %r\n%s' % \
445 (gdb_repr, gdb_output))
446
447 def test_selfreferential_new_style_instance(self):
448 gdb_repr, gdb_output = \
449 self.get_gdb_repr('''
450class Foo(object):
451 pass
452foo = Foo()
453foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000454id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000455 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
456 gdb_repr),
457 'Unexpected gdb representation: %r\n%s' % \
458 (gdb_repr, gdb_output))
459
460 gdb_repr, gdb_output = \
461 self.get_gdb_repr('''
462class Foo(object):
463 pass
464a = Foo()
465b = Foo()
466a.an_attr = b
467b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000468id(a)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000469 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
470 gdb_repr),
471 'Unexpected gdb representation: %r\n%s' % \
472 (gdb_repr, gdb_output))
473
474 def test_truncation(self):
475 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000476 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477 self.assertEquals(gdb_repr,
478 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
479 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
480 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
481 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
482 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
483 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
484 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
485 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
486 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
487 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
488 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
489 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
490 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
491 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
492 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
493 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
494 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
495 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
496 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
497 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
498 "224, 225, 226...(truncated)")
499 self.assertEquals(len(gdb_repr),
500 1024 + len('...(truncated)'))
501
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000502 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000503 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
504 self.assertTrue(re.match('<built-in method readlines of _io.TextIOWrapper object at remote 0x[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000505 gdb_repr),
506 'Unexpected gdb representation: %r\n%s' % \
507 (gdb_repr, gdb_output))
508
509 def test_frames(self):
510 gdb_output = self.get_stack_trace('''
511def foo(a, b, c):
512 pass
513
514foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000515id(foo.__code__)''',
516 breakpoint='builtin_id',
517 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000518 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000519 self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520 gdb_output,
521 re.DOTALL),
522 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
523
524class PyListTests(DebuggerTests):
525 def assertListing(self, expected, actual):
526 self.assertEndsWith(actual, expected)
527
528 def test_basic_command(self):
529 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000530 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000531 cmds_after_breakpoint=['py-list'])
532
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000533 self.assertListing(' 5 \n'
534 ' 6 def bar(a, b, c):\n'
535 ' 7 baz(a, b, c)\n'
536 ' 8 \n'
537 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000538 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000539 ' 11 \n'
540 ' 12 foo(1, 2, 3)\n',
541 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000542
543 def test_one_abs_arg(self):
544 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000545 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000546 cmds_after_breakpoint=['py-list 9'])
547
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000548 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000549 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000550 ' 11 \n'
551 ' 12 foo(1, 2, 3)\n',
552 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000553
554 def test_two_abs_args(self):
555 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000556 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000557 cmds_after_breakpoint=['py-list 1,3'])
558
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000559 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
560 ' 2 \n'
561 ' 3 def foo(a, b, c):\n',
562 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000563
564class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000565 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000566 def test_pyup_command(self):
567 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000568 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000569 cmds_after_breakpoint=['py-up'])
570 self.assertMultilineMatches(bt,
571 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000572#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000573 baz\(a, b, c\)
574$''')
575
Victor Stinner50eb60e2010-04-20 22:32:07 +0000576 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000577 def test_down_at_bottom(self):
578 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000579 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000580 cmds_after_breakpoint=['py-down'])
581 self.assertEndsWith(bt,
582 'Unable to find a newer python frame\n')
583
Victor Stinner50eb60e2010-04-20 22:32:07 +0000584 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000585 def test_up_at_top(self):
586 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000587 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000588 cmds_after_breakpoint=['py-up'] * 4)
589 self.assertEndsWith(bt,
590 'Unable to find an older python frame\n')
591
Victor Stinner50eb60e2010-04-20 22:32:07 +0000592 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000593 def test_up_then_down(self):
594 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000595 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000596 cmds_after_breakpoint=['py-up', 'py-down'])
597 self.assertMultilineMatches(bt,
598 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000599#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000600 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000601#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000602 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000603$''')
604
605class PyBtTests(DebuggerTests):
606 def test_basic_command(self):
607 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000608 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 cmds_after_breakpoint=['py-bt'])
610 self.assertMultilineMatches(bt,
611 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000612#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000613 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000614#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000615 bar\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000616#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000617foo\(1, 2, 3\)
618''')
619
620class PyPrintTests(DebuggerTests):
621 def test_basic_command(self):
622 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000623 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000624 cmds_after_breakpoint=['py-print args'])
625 self.assertMultilineMatches(bt,
626 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
627
Victor Stinner50eb60e2010-04-20 22:32:07 +0000628 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000630 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000631 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
632 self.assertMultilineMatches(bt,
633 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
634
635 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000636 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000637 cmds_after_breakpoint=['py-print __name__'])
638 self.assertMultilineMatches(bt,
639 r".*\nglobal '__name__' = '__main__'\n.*")
640
641 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000642 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000643 cmds_after_breakpoint=['py-print len'])
644 self.assertMultilineMatches(bt,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000645 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000646
647class PyLocalsTests(DebuggerTests):
648 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000649 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000650 cmds_after_breakpoint=['py-locals'])
651 self.assertMultilineMatches(bt,
652 r".*\nargs = \(1, 2, 3\)\n.*")
653
Victor Stinner50eb60e2010-04-20 22:32:07 +0000654 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000655 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000656 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000657 cmds_after_breakpoint=['py-up', 'py-locals'])
658 self.assertMultilineMatches(bt,
659 r".*\na = 1\nb = 2\nc = 3\n.*")
660
661def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000662 run_unittest(PrettyPrintTests,
663 PyListTests,
664 StackNavigationTests,
665 PyBtTests,
666 PyPrintTests,
667 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000668 )
669
670if __name__ == "__main__":
671 test_main()