blob: 3ade18547ea48cd600bc67f0de35eeef3306d680 [file] [log] [blame]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +00001# Verify that gdb can pretty-print the various PyObject* types
2#
3# The code for testing gdb was adapted from similar work in Unladen Swallow's
4# Lib/test/test_jit_gdb.py
5
6import os
7import re
8import subprocess
9import sys
10import unittest
Antoine Pitrou22db7352010-07-08 18:54:04 +000011import sysconfig
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000012
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000013from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000014
15try:
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(r"^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"
25 " Saw:\n" + gdb_version)
26
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()
32if gdbpy_version == '':
33 raise unittest.SkipTest("gdb not built with embedded python support")
34
Victor Stinnera92e81b2010-04-20 22:28:31 +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(r'.*\[(.*)\].*', 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(', ')
45 return "'select'" in gdb_frame_dir
46
47HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000048
49class DebuggerTests(unittest.TestCase):
50
51 """Test that the debugger can debug Python."""
52
53 def run_gdb(self, *args):
54 """Runs gdb with the command line given by *args.
55
56 Returns its stdout, stderr
57 """
58 out, err = subprocess.Popen(
59 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
60 ).communicate()
61 return out, err
62
63 def get_stack_trace(self, source=None, script=None,
64 breakpoint='PyObject_Print',
65 cmds_after_breakpoint=None,
66 import_site=False):
67 '''
68 Run 'python -c SOURCE' under gdb with a breakpoint.
69
70 Support injecting commands after the breakpoint is reached
71
72 Returns the stdout from gdb
73
74 cmds_after_breakpoint: if provided, a list of strings: gdb commands
75 '''
76 # We use "set breakpoint pending yes" to avoid blocking with a:
77 # Function "foo" not defined.
78 # Make breakpoint pending on future shared library load? (y or [n])
79 # error, which typically happens python is dynamically linked (the
80 # breakpoints of interest are to be found in the shared library)
81 # When this happens, we still get:
82 # Function "PyObject_Print" not defined.
83 # emitted to stderr each time, alas.
84
85 # Initially I had "--eval-command=continue" here, but removed it to
86 # avoid repeated print breakpoints when traversing hierarchical data
87 # structures
88
89 # Generate a list of commands in gdb's language:
90 commands = ['set breakpoint pending yes',
91 'break %s' % breakpoint,
92 'run']
93 if cmds_after_breakpoint:
94 commands += cmds_after_breakpoint
95 else:
96 commands += ['backtrace']
97
98 # print commands
99
100 # Use "commands" to generate the arguments with which to invoke "gdb":
101 args = ["gdb", "--batch"]
102 args += ['--eval-command=%s' % cmd for cmd in commands]
103 args += ["--args",
104 sys.executable]
105
106 if not import_site:
107 # -S suppresses the default 'import site'
108 args += ["-S"]
109
110 if source:
111 args += ["-c", source]
112 elif script:
113 args += [script]
114
115 # print args
116 # print ' '.join(args)
117
118 # Use "args" to invoke gdb, capturing stdout, stderr:
119 out, err = self.run_gdb(*args)
120
121 # Ignore some noise on stderr due to the pending breakpoint:
122 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua8157182010-05-05 18:29:02 +0000123 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
124 err = err.replace("warning: Unable to find libthread_db matching"
125 " inferior's thread library, thread debugging will"
126 " not be available.\n",
127 '')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000128
129 # Ensure no unexpected error messages:
130 self.assertEquals(err, '')
131
132 return out
133
134 def get_gdb_repr(self, source,
135 cmds_after_breakpoint=None,
136 import_site=False):
137 # Given an input python source representation of data,
138 # run "python -c'print DATA'" under gdb with a breakpoint on
139 # PyObject_Print and scrape out gdb's representation of the "op"
140 # parameter, and verify that the gdb displays the same string
141 #
142 # For a nested structure, the first time we hit the breakpoint will
143 # give us the top-level structure
144 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
145 cmds_after_breakpoint=cmds_after_breakpoint,
146 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000147 # gdb can insert additional '\n' and space characters in various places
148 # in its output, depending on the width of the terminal it's connected
149 # to (using its "wrap_here" function)
150 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000151 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000152 if not m:
153 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000154 return m.group(1), gdb_output
155
156 def assertEndsWith(self, actual, exp_end):
157 '''Ensure that the given "actual" string ends with "exp_end"'''
158 self.assert_(actual.endswith(exp_end),
159 msg='%r did not end with %r' % (actual, exp_end))
160
161 def assertMultilineMatches(self, actual, pattern):
162 m = re.match(pattern, actual, re.DOTALL)
163 self.assert_(m,
164 msg='%r did not match %r' % (actual, pattern))
165
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000166 def get_sample_script(self):
167 return findfile('gdb_sample.py')
168
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000169class PrettyPrintTests(DebuggerTests):
170 def test_getting_backtrace(self):
171 gdb_output = self.get_stack_trace('print 42')
172 self.assertTrue('PyObject_Print' in gdb_output)
173
174 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
175 # Ensure that gdb's rendering of the value in a debugged process
176 # matches repr(value) in this process:
177 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
178 cmds_after_breakpoint)
179 self.assertEquals(gdb_repr, repr(val), gdb_output)
180
181 def test_int(self):
182 'Verify the pretty-printing of various "int" values'
183 self.assertGdbRepr(42)
184 self.assertGdbRepr(0)
185 self.assertGdbRepr(-7)
186 self.assertGdbRepr(sys.maxint)
187 self.assertGdbRepr(-sys.maxint)
188
189 def test_long(self):
190 'Verify the pretty-printing of various "long" values'
191 self.assertGdbRepr(0L)
192 self.assertGdbRepr(1000000000000L)
193 self.assertGdbRepr(-1L)
194 self.assertGdbRepr(-1000000000000000L)
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([])
211 self.assertGdbRepr(range(5))
212
213 def test_strings(self):
214 'Verify the pretty-printing of strings'
215 self.assertGdbRepr('')
216 self.assertGdbRepr('And now for something hopefully the same')
217 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
218 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
219
220 def test_tuples(self):
221 'Verify the pretty-printing of tuples'
222 self.assertGdbRepr(tuple())
223 self.assertGdbRepr((1,))
224 self.assertGdbRepr(('foo', 'bar', 'baz'))
225
226 def test_unicode(self):
227 'Verify the pretty-printing of unicode values'
228 # Test the empty unicode string:
229 self.assertGdbRepr(u'')
230
231 self.assertGdbRepr(u'hello world')
232
233 # Test printing a single character:
234 # U+2620 SKULL AND CROSSBONES
235 self.assertGdbRepr(u'\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(u'\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
Victor Stinnerb1556c52010-05-20 11:29:45 +0000247 # This will only work on wide-unicode builds:
248 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000249
250 def test_sets(self):
251 'Verify the pretty-printing of sets'
252 self.assertGdbRepr(set())
253 self.assertGdbRepr(set(['a', 'b']))
254 self.assertGdbRepr(set([4, 5, 6]))
255
256 # Ensure that we handled sets containing the "dummy" key value,
257 # which happens on deletion:
258 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
259s.pop()
260print s''')
261 self.assertEquals(gdb_repr, "set(['b'])")
262
263 def test_frozensets(self):
264 'Verify the pretty-printing of frozensets'
265 self.assertGdbRepr(frozenset())
266 self.assertGdbRepr(frozenset(['a', 'b']))
267 self.assertGdbRepr(frozenset([4, 5, 6]))
268
269 def test_exceptions(self):
270 # Test a RuntimeError
271 gdb_repr, gdb_output = self.get_gdb_repr('''
272try:
273 raise RuntimeError("I am an error")
274except RuntimeError, e:
275 print e
276''')
277 self.assertEquals(gdb_repr,
278 "exceptions.RuntimeError('I am an error',)")
279
280
281 # Test division by zero:
282 gdb_repr, gdb_output = self.get_gdb_repr('''
283try:
284 a = 1 / 0
285except ZeroDivisionError, e:
286 print e
287''')
288 self.assertEquals(gdb_repr,
289 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
290
291 def test_classic_class(self):
292 'Verify the pretty-printing of classic class instances'
293 gdb_repr, gdb_output = self.get_gdb_repr('''
294class Foo:
295 pass
296foo = Foo()
297foo.an_int = 42
298print foo''')
299 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
300 self.assertTrue(m,
301 msg='Unexpected classic-class rendering %r' % gdb_repr)
302
303 def test_modern_class(self):
304 'Verify the pretty-printing of new-style class instances'
305 gdb_repr, gdb_output = self.get_gdb_repr('''
306class Foo(object):
307 pass
308foo = Foo()
309foo.an_int = 42
310print foo''')
311 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
312 self.assertTrue(m,
313 msg='Unexpected new-style class rendering %r' % gdb_repr)
314
315 def test_subclassing_list(self):
316 'Verify the pretty-printing of an instance of a list subclass'
317 gdb_repr, gdb_output = self.get_gdb_repr('''
318class Foo(list):
319 pass
320foo = Foo()
321foo += [1, 2, 3]
322foo.an_int = 42
323print foo''')
324 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
325 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
337print foo''')
338 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
339 self.assertTrue(m,
340 msg='Unexpected new-style class rendering %r' % gdb_repr)
341
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000342 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000343 '''Run Python under gdb, corrupting variables in the inferior process
344 immediately before taking a backtrace.
345
346 Verify that the variable's representation is the expected failsafe
347 representation'''
348 if corruption:
349 cmds_after_breakpoint=[corruption, 'backtrace']
350 else:
351 cmds_after_breakpoint=['backtrace']
352
353 gdb_repr, gdb_output = \
354 self.get_gdb_repr(source,
355 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000356
357 if expvalue:
358 if gdb_repr == repr(expvalue):
359 # gdb managed to print the value in spite of the corruption;
360 # this is good (see http://bugs.python.org/issue8330)
361 return
362
363 if exptype:
364 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
365 else:
366 # Match anything for the type name; 0xDEADBEEF could point to
367 # something arbitrary (see http://bugs.python.org/issue8330)
368 pattern = '<.* at remote 0x[0-9a-f]+>'
369
370 m = re.match(pattern, gdb_repr)
371 if not m:
372 self.fail('Unexpected gdb representation: %r\n%s' % \
373 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000374
375 def test_NULL_ptr(self):
376 'Ensure that a NULL PyObject* is handled gracefully'
377 gdb_repr, gdb_output = (
378 self.get_gdb_repr('print 42',
379 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000380 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000381 )
382
383 self.assertEquals(gdb_repr, '0x0')
384
385 def test_NULL_ob_type(self):
386 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
387 self.assertSane('print 42',
388 'set op->ob_type=0')
389
390 def test_corrupt_ob_type(self):
391 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
392 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000393 'set op->ob_type=0xDEADBEEF',
394 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000395
396 def test_corrupt_tp_flags(self):
397 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
398 self.assertSane('print 42',
399 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000400 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000401
402 def test_corrupt_tp_name(self):
403 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
404 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000405 'set op->ob_type->tp_name=0xDEADBEEF',
406 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000407
408 def test_NULL_instance_dict(self):
409 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
410 self.assertSane('''
411class Foo:
412 pass
413foo = Foo()
414foo.an_int = 42
415print foo''',
416 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000417 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000418
419 def test_builtins_help(self):
420 'Ensure that the new-style class _Helper in site.py can be handled'
421 # (this was the issue causing tracebacks in
422 # http://bugs.python.org/issue8032#msg100537 )
423
424 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
425 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
426 self.assertTrue(m,
427 msg='Unexpected rendering %r' % gdb_repr)
428
429 def test_selfreferential_list(self):
430 '''Ensure that a reference loop involving a list doesn't lead proxyval
431 into an infinite loop:'''
432 gdb_repr, gdb_output = \
433 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
434
435 self.assertEquals(gdb_repr, '[3, 4, 5, [...]]')
436
437 gdb_repr, gdb_output = \
438 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
439
440 self.assertEquals(gdb_repr, '[3, 4, 5, [[...]]]')
441
442 def test_selfreferential_dict(self):
443 '''Ensure that a reference loop involving a dict doesn't lead proxyval
444 into an infinite loop:'''
445 gdb_repr, gdb_output = \
446 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
447
448 self.assertEquals(gdb_repr, "{'foo': {'bar': {...}}}")
449
450 def test_selfreferential_old_style_instance(self):
451 gdb_repr, gdb_output = \
452 self.get_gdb_repr('''
453class Foo:
454 pass
455foo = Foo()
456foo.an_attr = foo
457print foo''')
458 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
459 gdb_repr),
460 'Unexpected gdb representation: %r\n%s' % \
461 (gdb_repr, gdb_output))
462
463 def test_selfreferential_new_style_instance(self):
464 gdb_repr, gdb_output = \
465 self.get_gdb_repr('''
466class Foo(object):
467 pass
468foo = Foo()
469foo.an_attr = foo
470print foo''')
471 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
472 gdb_repr),
473 'Unexpected gdb representation: %r\n%s' % \
474 (gdb_repr, gdb_output))
475
476 gdb_repr, gdb_output = \
477 self.get_gdb_repr('''
478class Foo(object):
479 pass
480a = Foo()
481b = Foo()
482a.an_attr = b
483b.an_attr = a
484print a''')
485 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
486 gdb_repr),
487 'Unexpected gdb representation: %r\n%s' % \
488 (gdb_repr, gdb_output))
489
490 def test_truncation(self):
491 'Verify that very long output is truncated'
492 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
493 self.assertEquals(gdb_repr,
R. David Murray0c080092010-04-05 16:28:49 +0000494 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000495 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
496 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
497 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
498 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
499 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
500 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
501 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
502 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
503 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
504 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
505 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
506 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
507 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
508 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
509 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
510 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
511 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
512 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
513 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
514 "224, 225, 226...(truncated)")
515 self.assertEquals(len(gdb_repr),
R. David Murray0c080092010-04-05 16:28:49 +0000516 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000517
518 def test_builtin_function(self):
519 gdb_repr, gdb_output = self.get_gdb_repr('print len')
520 self.assertEquals(gdb_repr, '<built-in function len>')
521
522 def test_builtin_method(self):
523 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
524 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
525 gdb_repr),
526 'Unexpected gdb representation: %r\n%s' % \
527 (gdb_repr, gdb_output))
528
529 def test_frames(self):
530 gdb_output = self.get_stack_trace('''
531def foo(a, b, c):
532 pass
533
534foo(3, 4, 5)
535print foo.__code__''',
536 breakpoint='PyObject_Print',
537 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
538 )
R. David Murray0c080092010-04-05 16:28:49 +0000539 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
540 gdb_output,
541 re.DOTALL),
542 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000543
544class PyListTests(DebuggerTests):
545 def assertListing(self, expected, actual):
546 self.assertEndsWith(actual, expected)
547
548 def test_basic_command(self):
549 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000550 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000551 cmds_after_breakpoint=['py-list'])
552
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000553 self.assertListing(' 5 \n'
554 ' 6 def bar(a, b, c):\n'
555 ' 7 baz(a, b, c)\n'
556 ' 8 \n'
557 ' 9 def baz(*args):\n'
558 ' >10 print(42)\n'
559 ' 11 \n'
560 ' 12 foo(1, 2, 3)\n',
561 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000562
563 def test_one_abs_arg(self):
564 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000565 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000566 cmds_after_breakpoint=['py-list 9'])
567
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000568 self.assertListing(' 9 def baz(*args):\n'
569 ' >10 print(42)\n'
570 ' 11 \n'
571 ' 12 foo(1, 2, 3)\n',
572 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000573
574 def test_two_abs_args(self):
575 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000576 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000577 cmds_after_breakpoint=['py-list 1,3'])
578
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000579 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
580 ' 2 \n'
581 ' 3 def foo(a, b, c):\n',
582 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000583
584class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000585 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000586 def test_pyup_command(self):
587 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000588 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000589 cmds_after_breakpoint=['py-up'])
590 self.assertMultilineMatches(bt,
591 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000592#[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 +0000593 baz\(a, b, c\)
594$''')
595
Victor Stinnera92e81b2010-04-20 22:28:31 +0000596 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000597 def test_down_at_bottom(self):
598 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000599 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000600 cmds_after_breakpoint=['py-down'])
601 self.assertEndsWith(bt,
602 'Unable to find a newer python frame\n')
603
Victor Stinnera92e81b2010-04-20 22:28:31 +0000604 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000605 def test_up_at_top(self):
606 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000607 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000608 cmds_after_breakpoint=['py-up'] * 4)
609 self.assertEndsWith(bt,
610 'Unable to find an older python frame\n')
611
Victor Stinnera92e81b2010-04-20 22:28:31 +0000612 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000613 def test_up_then_down(self):
614 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000615 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000616 cmds_after_breakpoint=['py-up', 'py-down'])
617 self.assertMultilineMatches(bt,
618 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000619#[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 +0000620 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000621#[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 +0000622 print\(42\)
623$''')
624
625class PyBtTests(DebuggerTests):
626 def test_basic_command(self):
627 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000628 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000629 cmds_after_breakpoint=['py-bt'])
630 self.assertMultilineMatches(bt,
631 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000632#[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 +0000633 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000634#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000635 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000636#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000637foo\(1, 2, 3\)
638''')
639
640class PyPrintTests(DebuggerTests):
641 def test_basic_command(self):
642 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000643 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000644 cmds_after_breakpoint=['py-print args'])
645 self.assertMultilineMatches(bt,
646 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
647
Victor Stinnera92e81b2010-04-20 22:28:31 +0000648 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000649 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000650 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000651 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
652 self.assertMultilineMatches(bt,
653 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
654
655 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000656 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657 cmds_after_breakpoint=['py-print __name__'])
658 self.assertMultilineMatches(bt,
659 r".*\nglobal '__name__' = '__main__'\n.*")
660
661 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000662 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000663 cmds_after_breakpoint=['py-print len'])
664 self.assertMultilineMatches(bt,
665 r".*\nbuiltin 'len' = <built-in function len>\n.*")
666
667class PyLocalsTests(DebuggerTests):
668 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000669 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000670 cmds_after_breakpoint=['py-locals'])
671 self.assertMultilineMatches(bt,
672 r".*\nargs = \(1, 2, 3\)\n.*")
673
Victor Stinnera92e81b2010-04-20 22:28:31 +0000674 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000675 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000676 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000677 cmds_after_breakpoint=['py-up', 'py-locals'])
678 self.assertMultilineMatches(bt,
679 r".*\na = 1\nb = 2\nc = 3\n.*")
680
681def test_main():
Antoine Pitrou22db7352010-07-08 18:54:04 +0000682 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
683 final_opt = ""
684 for opt in cflags.split():
685 if opt.startswith('-O'):
686 final_opt = opt
687 if final_opt and final_opt != '-O0':
688 raise unittest.SkipTest("Python was built with compiler optimizations, "
689 "tests can't reliably succeed")
690
Martin v. Löwis5a965432010-04-12 05:22:25 +0000691 run_unittest(PrettyPrintTests,
692 PyListTests,
693 StackNavigationTests,
694 PyBtTests,
695 PyPrintTests,
696 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000697 )
698
699if __name__ == "__main__":
700 test_main()