blob: d288d7944a8c60280cb39ac345a472d7b2498a20 [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
Victor Stinner150016f2010-05-19 23:04:56 +000011import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000012
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000013from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000014
15try:
16 gdb_version, _ = subprocess.Popen(["gdb", "--version"],
17 stdout=subprocess.PIPE).communicate()
18except OSError:
19 # This is what "no gdb" looks like. There may, however, be other
20 # errors that manifest this way too.
21 raise unittest.SkipTest("Couldn't find gdb on the path")
22gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.", gdb_version)
23if int(gdb_version_number.group(1)) < 7:
24 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000025 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000026
27# Verify that "gdb" was built with the embedded python support enabled:
28cmd = "--eval-command=python import sys; print sys.version_info"
29p = subprocess.Popen(["gdb", "--batch", cmd],
30 stdout=subprocess.PIPE)
31gdbpy_version, _ = p.communicate()
Benjamin Peterson9faa7ec2010-04-11 23:51:24 +000032if gdbpy_version == b'':
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000033 raise unittest.SkipTest("gdb not built with embedded python support")
34
Victor Stinner50eb60e2010-04-20 22:32:07 +000035def gdb_has_frame_select():
36 # Does this build of gdb have gdb.Frame.select ?
37 cmd = "--eval-command=python print(dir(gdb.Frame))"
38 p = subprocess.Popen(["gdb", "--batch", cmd],
39 stdout=subprocess.PIPE)
40 stdout, _ = p.communicate()
41 m = re.match(br'.*\[(.*)\].*', stdout)
42 if not m:
43 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
44 gdb_frame_dir = m.group(1).split(b', ')
45 return b"'select'" in gdb_frame_dir
46
47HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000048
Martin v. Löwis5ae68102010-04-21 22:38:42 +000049BREAKPOINT_FN='builtin_id'
50
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000051class DebuggerTests(unittest.TestCase):
52
53 """Test that the debugger can debug Python."""
54
55 def run_gdb(self, *args):
56 """Runs gdb with the command line given by *args.
57
58 Returns its stdout, stderr
59 """
60 out, err = subprocess.Popen(
61 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
62 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000063 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000064
65 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000066 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000067 cmds_after_breakpoint=None,
68 import_site=False):
69 '''
70 Run 'python -c SOURCE' under gdb with a breakpoint.
71
72 Support injecting commands after the breakpoint is reached
73
74 Returns the stdout from gdb
75
76 cmds_after_breakpoint: if provided, a list of strings: gdb commands
77 '''
78 # We use "set breakpoint pending yes" to avoid blocking with a:
79 # Function "foo" not defined.
80 # Make breakpoint pending on future shared library load? (y or [n])
81 # error, which typically happens python is dynamically linked (the
82 # breakpoints of interest are to be found in the shared library)
83 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +000084 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000085 # emitted to stderr each time, alas.
86
87 # Initially I had "--eval-command=continue" here, but removed it to
88 # avoid repeated print breakpoints when traversing hierarchical data
89 # structures
90
91 # Generate a list of commands in gdb's language:
92 commands = ['set breakpoint pending yes',
93 'break %s' % breakpoint,
94 'run']
95 if cmds_after_breakpoint:
96 commands += cmds_after_breakpoint
97 else:
98 commands += ['backtrace']
99
100 # print commands
101
102 # Use "commands" to generate the arguments with which to invoke "gdb":
103 args = ["gdb", "--batch"]
104 args += ['--eval-command=%s' % cmd for cmd in commands]
105 args += ["--args",
106 sys.executable]
107
108 if not import_site:
109 # -S suppresses the default 'import site'
110 args += ["-S"]
111
112 if source:
113 args += ["-c", source]
114 elif script:
115 args += [script]
116
117 # print args
118 # print ' '.join(args)
119
120 # Use "args" to invoke gdb, capturing stdout, stderr:
121 out, err = self.run_gdb(*args)
122
123 # Ignore some noise on stderr due to the pending breakpoint:
124 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000125 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
126 err = err.replace("warning: Unable to find libthread_db matching"
127 " inferior's thread library, thread debugging will"
128 " not be available.\n",
129 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100130 err = err.replace("warning: Cannot initialize thread debugging"
131 " library: Debugger service failed\n",
132 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000133
134 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000135 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000136
137 return out
138
139 def get_gdb_repr(self, source,
140 cmds_after_breakpoint=None,
141 import_site=False):
142 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000143 # run "python -c'id(DATA)'" under gdb with a breakpoint on
144 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000145 # parameter, and verify that the gdb displays the same string
146 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000147 # Verify that the gdb displays the expected string
148 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000149 # For a nested structure, the first time we hit the breakpoint will
150 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000151 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000152 cmds_after_breakpoint=cmds_after_breakpoint,
153 import_site=import_site)
154 # gdb can insert additional '\n' and space characters in various places
155 # in its output, depending on the width of the terminal it's connected
156 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000157 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 +0000158 gdb_output, re.DOTALL)
159 if not m:
160 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
161 return m.group(1), gdb_output
162
163 def assertEndsWith(self, actual, exp_end):
164 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000165 self.assertTrue(actual.endswith(exp_end),
166 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000167
168 def assertMultilineMatches(self, actual, pattern):
169 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000170 if not m:
171 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000173 def get_sample_script(self):
174 return findfile('gdb_sample.py')
175
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176class PrettyPrintTests(DebuggerTests):
177 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000178 gdb_output = self.get_stack_trace('id(42)')
179 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000180
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000181 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000182 # Ensure that gdb's rendering of the value in a debugged process
183 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000184 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000186 if not exp_repr:
187 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000188 self.assertEqual(gdb_repr, exp_repr,
189 ('%r did not equal expected %r; full output was:\n%s'
190 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191
192 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000193 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194 self.assertGdbRepr(42)
195 self.assertGdbRepr(0)
196 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000197 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000198 self.assertGdbRepr(-1000000000000000)
199
200 def test_singletons(self):
201 'Verify the pretty-printing of True, False and None'
202 self.assertGdbRepr(True)
203 self.assertGdbRepr(False)
204 self.assertGdbRepr(None)
205
206 def test_dicts(self):
207 'Verify the pretty-printing of dictionaries'
208 self.assertGdbRepr({})
209 self.assertGdbRepr({'foo': 'bar'})
210 self.assertGdbRepr({'foo': 'bar', 'douglas':42})
211
212 def test_lists(self):
213 'Verify the pretty-printing of lists'
214 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000215 self.assertGdbRepr(list(range(5)))
216
217 def test_bytes(self):
218 'Verify the pretty-printing of bytes'
219 self.assertGdbRepr(b'')
220 self.assertGdbRepr(b'And now for something hopefully the same')
221 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
222 self.assertGdbRepr(b'this is a tab:\t'
223 b' this is a slash-N:\n'
224 b' this is a slash-R:\r'
225 )
226
227 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
228
229 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000230
231 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000232 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000233 encoding = locale.getpreferredencoding()
234 def check_repr(text):
235 try:
236 text.encode(encoding)
237 printable = True
238 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000239 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000240 else:
241 self.assertGdbRepr(text)
242
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000243 self.assertGdbRepr('')
244 self.assertGdbRepr('And now for something hopefully the same')
245 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000246
247 # Test printing a single character:
248 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000249 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000250
251 # Test printing a Japanese unicode string
252 # (I believe this reads "mojibake", using 3 characters from the CJK
253 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000254 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000255
256 # Test a character outside the BMP:
257 # U+1D121 MUSICAL SYMBOL C CLEF
258 # This is:
259 # UTF-8: 0xF0 0x9D 0x84 0xA1
260 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000261 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000262
263 def test_tuples(self):
264 'Verify the pretty-printing of tuples'
265 self.assertGdbRepr(tuple())
266 self.assertGdbRepr((1,), '(1,)')
267 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268
269 def test_sets(self):
270 'Verify the pretty-printing of sets'
271 self.assertGdbRepr(set())
272 self.assertGdbRepr(set(['a', 'b']))
273 self.assertGdbRepr(set([4, 5, 6]))
274
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000275 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276 # which happens on deletion:
277 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
278s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000279id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000280 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000281
282 def test_frozensets(self):
283 'Verify the pretty-printing of frozensets'
284 self.assertGdbRepr(frozenset())
285 self.assertGdbRepr(frozenset(['a', 'b']))
286 self.assertGdbRepr(frozenset([4, 5, 6]))
287
288 def test_exceptions(self):
289 # Test a RuntimeError
290 gdb_repr, gdb_output = self.get_gdb_repr('''
291try:
292 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000293except RuntimeError as e:
294 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000296 self.assertEqual(gdb_repr,
297 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298
299
300 # Test division by zero:
301 gdb_repr, gdb_output = self.get_gdb_repr('''
302try:
303 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000304except ZeroDivisionError as e:
305 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000306''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000307 self.assertEqual(gdb_repr,
308 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000309
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000310 def test_modern_class(self):
311 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000312 gdb_repr, gdb_output = self.get_gdb_repr('''
313class Foo:
314 pass
315foo = Foo()
316foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000317id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
319 self.assertTrue(m,
320 msg='Unexpected new-style class rendering %r' % gdb_repr)
321
322 def test_subclassing_list(self):
323 'Verify the pretty-printing of an instance of a list subclass'
324 gdb_repr, gdb_output = self.get_gdb_repr('''
325class Foo(list):
326 pass
327foo = Foo()
328foo += [1, 2, 3]
329foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000330id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000331 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 +0000332
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000333 self.assertTrue(m,
334 msg='Unexpected new-style class rendering %r' % gdb_repr)
335
336 def test_subclassing_tuple(self):
337 'Verify the pretty-printing of an instance of a tuple subclass'
338 # This should exercise the negative tp_dictoffset code in the
339 # new-style class support
340 gdb_repr, gdb_output = self.get_gdb_repr('''
341class Foo(tuple):
342 pass
343foo = Foo((1, 2, 3))
344foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000345id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000346 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 +0000347
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000348 self.assertTrue(m,
349 msg='Unexpected new-style class rendering %r' % gdb_repr)
350
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000351 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000352 '''Run Python under gdb, corrupting variables in the inferior process
353 immediately before taking a backtrace.
354
355 Verify that the variable's representation is the expected failsafe
356 representation'''
357 if corruption:
358 cmds_after_breakpoint=[corruption, 'backtrace']
359 else:
360 cmds_after_breakpoint=['backtrace']
361
362 gdb_repr, gdb_output = \
363 self.get_gdb_repr(source,
364 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000365 if exprepr:
366 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000367 # gdb managed to print the value in spite of the corruption;
368 # this is good (see http://bugs.python.org/issue8330)
369 return
370
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000371 # Match anything for the type name; 0xDEADBEEF could point to
372 # something arbitrary (see http://bugs.python.org/issue8330)
373 pattern = '<.* at remote 0x[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000374
375 m = re.match(pattern, gdb_repr)
376 if not m:
377 self.fail('Unexpected gdb representation: %r\n%s' % \
378 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000379
380 def test_NULL_ptr(self):
381 'Ensure that a NULL PyObject* is handled gracefully'
382 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000383 self.get_gdb_repr('id(42)',
384 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000385 'backtrace'])
386 )
387
Ezio Melottib3aedd42010-11-20 19:04:17 +0000388 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000389
390 def test_NULL_ob_type(self):
391 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000392 self.assertSane('id(42)',
393 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000394
395 def test_corrupt_ob_type(self):
396 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000397 self.assertSane('id(42)',
398 'set v->ob_type=0xDEADBEEF',
399 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000400
401 def test_corrupt_tp_flags(self):
402 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000403 self.assertSane('id(42)',
404 'set v->ob_type->tp_flags=0x0',
405 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000406
407 def test_corrupt_tp_name(self):
408 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409 self.assertSane('id(42)',
410 'set v->ob_type->tp_name=0xDEADBEEF',
411 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000412
413 def test_builtins_help(self):
414 'Ensure that the new-style class _Helper in site.py can be handled'
415 # (this was the issue causing tracebacks in
416 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000417 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000418
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000419 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
420 self.assertTrue(m,
421 msg='Unexpected rendering %r' % gdb_repr)
422
423 def test_selfreferential_list(self):
424 '''Ensure that a reference loop involving a list doesn't lead proxyval
425 into an infinite loop:'''
426 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000427 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000428 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000429
430 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000431 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000432 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000433
434 def test_selfreferential_dict(self):
435 '''Ensure that a reference loop involving a dict doesn't lead proxyval
436 into an infinite loop:'''
437 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000438 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000439
Ezio Melottib3aedd42010-11-20 19:04:17 +0000440 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000441
442 def test_selfreferential_old_style_instance(self):
443 gdb_repr, gdb_output = \
444 self.get_gdb_repr('''
445class Foo:
446 pass
447foo = Foo()
448foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000449id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000450 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
451 gdb_repr),
452 'Unexpected gdb representation: %r\n%s' % \
453 (gdb_repr, gdb_output))
454
455 def test_selfreferential_new_style_instance(self):
456 gdb_repr, gdb_output = \
457 self.get_gdb_repr('''
458class Foo(object):
459 pass
460foo = Foo()
461foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000462id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000463 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
464 gdb_repr),
465 'Unexpected gdb representation: %r\n%s' % \
466 (gdb_repr, gdb_output))
467
468 gdb_repr, gdb_output = \
469 self.get_gdb_repr('''
470class Foo(object):
471 pass
472a = Foo()
473b = Foo()
474a.an_attr = b
475b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000476id(a)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
478 gdb_repr),
479 'Unexpected gdb representation: %r\n%s' % \
480 (gdb_repr, gdb_output))
481
482 def test_truncation(self):
483 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000484 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000485 self.assertEqual(gdb_repr,
486 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
487 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
488 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
489 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
490 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
491 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
492 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
493 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
494 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
495 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
496 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
497 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
498 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
499 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
500 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
501 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
502 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
503 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
504 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
505 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
506 "224, 225, 226...(truncated)")
507 self.assertEqual(len(gdb_repr),
508 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000509
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000510 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000511 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
512 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 +0000513 gdb_repr),
514 'Unexpected gdb representation: %r\n%s' % \
515 (gdb_repr, gdb_output))
516
517 def test_frames(self):
518 gdb_output = self.get_stack_trace('''
519def foo(a, b, c):
520 pass
521
522foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000523id(foo.__code__)''',
524 breakpoint='builtin_id',
525 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000527 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 +0000528 gdb_output,
529 re.DOTALL),
530 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
531
532class PyListTests(DebuggerTests):
533 def assertListing(self, expected, actual):
534 self.assertEndsWith(actual, expected)
535
536 def test_basic_command(self):
537 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000538 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000539 cmds_after_breakpoint=['py-list'])
540
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000541 self.assertListing(' 5 \n'
542 ' 6 def bar(a, b, c):\n'
543 ' 7 baz(a, b, c)\n'
544 ' 8 \n'
545 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000546 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000547 ' 11 \n'
548 ' 12 foo(1, 2, 3)\n',
549 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000550
551 def test_one_abs_arg(self):
552 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000553 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000554 cmds_after_breakpoint=['py-list 9'])
555
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000556 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000557 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000558 ' 11 \n'
559 ' 12 foo(1, 2, 3)\n',
560 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000561
562 def test_two_abs_args(self):
563 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000564 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000565 cmds_after_breakpoint=['py-list 1,3'])
566
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000567 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
568 ' 2 \n'
569 ' 3 def foo(a, b, c):\n',
570 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000571
572class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000573 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000574 def test_pyup_command(self):
575 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000576 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000577 cmds_after_breakpoint=['py-up'])
578 self.assertMultilineMatches(bt,
579 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000580#[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 +0000581 baz\(a, b, c\)
582$''')
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_down_at_bottom(self):
586 'Verify handling of "py-down" at the bottom 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-down'])
589 self.assertEndsWith(bt,
590 'Unable to find a newer 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_at_top(self):
594 'Verify handling of "py-up" at the top of the stack'
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'] * 4)
597 self.assertEndsWith(bt,
598 'Unable to find an older python frame\n')
599
Victor Stinner50eb60e2010-04-20 22:32:07 +0000600 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000601 def test_up_then_down(self):
602 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000603 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000604 cmds_after_breakpoint=['py-up', 'py-down'])
605 self.assertMultilineMatches(bt,
606 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000607#[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 +0000608 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000609#[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 +0000610 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000611$''')
612
613class PyBtTests(DebuggerTests):
Victor Stinnere670c882011-05-13 17:40:15 +0200614 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000615 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000616 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000617 cmds_after_breakpoint=['py-bt'])
618 self.assertMultilineMatches(bt,
619 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200620Traceback \(most recent call first\):
621 File ".*gdb_sample.py", line 10, in baz
622 id\(42\)
623 File ".*gdb_sample.py", line 7, in bar
624 baz\(a, b, c\)
625 File ".*gdb_sample.py", line 4, in foo
626 bar\(a, b, c\)
627 File ".*gdb_sample.py", line 12, in <module>
628 foo\(1, 2, 3\)
629''')
630
631 def test_bt_full(self):
632 'Verify that the "py-bt-full" command works'
633 bt = self.get_stack_trace(script=self.get_sample_script(),
634 cmds_after_breakpoint=['py-bt-full'])
635 self.assertMultilineMatches(bt,
636 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637#[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 +0000638 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000639#[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 +0000640 bar\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000641#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000642foo\(1, 2, 3\)
643''')
644
645class PyPrintTests(DebuggerTests):
646 def test_basic_command(self):
647 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000648 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000649 cmds_after_breakpoint=['py-print args'])
650 self.assertMultilineMatches(bt,
651 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
652
Victor Stinner50eb60e2010-04-20 22:32:07 +0000653 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000654 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000655 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000656 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
657 self.assertMultilineMatches(bt,
658 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
659
660 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000661 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000662 cmds_after_breakpoint=['py-print __name__'])
663 self.assertMultilineMatches(bt,
664 r".*\nglobal '__name__' = '__main__'\n.*")
665
666 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000667 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000668 cmds_after_breakpoint=['py-print len'])
669 self.assertMultilineMatches(bt,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000670 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000671
672class PyLocalsTests(DebuggerTests):
673 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000674 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000675 cmds_after_breakpoint=['py-locals'])
676 self.assertMultilineMatches(bt,
677 r".*\nargs = \(1, 2, 3\)\n.*")
678
Victor Stinner50eb60e2010-04-20 22:32:07 +0000679 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000680 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000681 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000682 cmds_after_breakpoint=['py-up', 'py-locals'])
683 self.assertMultilineMatches(bt,
684 r".*\na = 1\nb = 2\nc = 3\n.*")
685
686def test_main():
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000687 if python_is_optimized():
688 raise unittest.SkipTest("Python was compiled with optimizations")
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000689 run_unittest(PrettyPrintTests,
690 PyListTests,
691 StackNavigationTests,
692 PyBtTests,
693 PyPrintTests,
694 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000695 )
696
697if __name__ == "__main__":
698 test_main()