blob: fb3941780b721c66a7bd831bf5c1ba60f1093814 [file] [log] [blame]
Georg Brandl46b9afc2010-07-30 09:14:20 +00001# A test suite for pdb; not very comprehensive at the moment.
Martin v. Löwis67880cc2012-05-02 07:41:22 +02002
Andrew Svetlovf0efea02013-03-18 10:09:50 -07003import doctest
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07004import os
Georg Brandl6cccb862010-07-30 14:16:43 +00005import pdb
Georg Brandl243ad662009-05-05 09:00:19 +00006import sys
Brett Cannon9529fbf2013-06-15 17:11:25 -04007import types
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03008import codecs
Georg Brandl6cccb862010-07-30 14:16:43 +00009import unittest
10import subprocess
Senthil Kumaran42d70812012-05-01 10:07:49 +080011import textwrap
Georg Brandl243ad662009-05-05 09:00:19 +000012
Barry Warsaw35425d62017-09-22 12:29:42 -040013from contextlib import ExitStack
14from io import StringIO
Hai Shi604bba12020-08-04 23:51:43 +080015from test.support import os_helper
Georg Brandl243ad662009-05-05 09:00:19 +000016# This little helper class is essential for testing pdb under doctest.
17from test.test_doctest import _FakeInput
Barry Warsaw35425d62017-09-22 12:29:42 -040018from unittest.mock import patch
Georg Brandl243ad662009-05-05 09:00:19 +000019
20
Georg Brandl9fa2e022009-09-16 16:40:45 +000021class PdbTestInput(object):
22 """Context manager that makes testing Pdb in doctests easier."""
23
24 def __init__(self, input):
25 self.input = input
26
27 def __enter__(self):
28 self.real_stdin = sys.stdin
29 sys.stdin = _FakeInput(self.input)
Brett Cannon31f59292011-02-21 19:29:56 +000030 self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
Georg Brandl9fa2e022009-09-16 16:40:45 +000031
32 def __exit__(self, *exc):
33 sys.stdin = self.real_stdin
Brett Cannon31f59292011-02-21 19:29:56 +000034 if self.orig_trace:
35 sys.settrace(self.orig_trace)
Georg Brandl9fa2e022009-09-16 16:40:45 +000036
37
38def test_pdb_displayhook():
39 """This tests the custom displayhook for pdb.
40
41 >>> def test_function(foo, bar):
Łukasz Langa2eb6eca2016-09-09 22:21:17 -070042 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl9fa2e022009-09-16 16:40:45 +000043 ... pass
44
45 >>> with PdbTestInput([
46 ... 'foo',
47 ... 'bar',
48 ... 'for i in range(5): print(i)',
49 ... 'continue',
50 ... ]):
51 ... test_function(1, None)
52 > <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function()
53 -> pass
54 (Pdb) foo
55 1
56 (Pdb) bar
57 (Pdb) for i in range(5): print(i)
58 0
59 1
60 2
61 3
62 4
63 (Pdb) continue
64 """
65
66
Georg Brandl0d089622010-07-30 16:00:46 +000067def test_pdb_basic_commands():
68 """Test the basic commands of pdb.
69
70 >>> def test_function_2(foo, bar='default'):
71 ... print(foo)
72 ... for i in range(5):
73 ... print(i)
74 ... print(bar)
75 ... for i in range(10):
76 ... never_executed
77 ... print('after for')
78 ... print('...')
79 ... return foo.upper()
80
Rémi Lapeyrebf457c72019-05-21 00:17:30 +020081 >>> def test_function3(arg=None, *, kwonly=None):
82 ... pass
83
Rémi Lapeyre45856032019-05-24 22:44:31 +020084 >>> def test_function4(a, b, c, /):
85 ... pass
86
Georg Brandl0d089622010-07-30 16:00:46 +000087 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -070088 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0d089622010-07-30 16:00:46 +000089 ... ret = test_function_2('baz')
Rémi Lapeyrebf457c72019-05-21 00:17:30 +020090 ... test_function3(kwonly=True)
Rémi Lapeyre45856032019-05-24 22:44:31 +020091 ... test_function4(1, 2, 3)
Georg Brandl0d089622010-07-30 16:00:46 +000092 ... print(ret)
93
94 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
95 ... 'step', # entering the function call
96 ... 'args', # display function args
97 ... 'list', # list function source
98 ... 'bt', # display backtrace
99 ... 'up', # step up to test_function()
100 ... 'down', # step down to test_function_2() again
101 ... 'next', # stepping to print(foo)
102 ... 'next', # stepping to the for loop
103 ... 'step', # stepping into the for loop
104 ... 'until', # continuing until out of the for loop
105 ... 'next', # executing the print(bar)
106 ... 'jump 8', # jump over second for loop
107 ... 'return', # return out of function
108 ... 'retval', # display return value
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200109 ... 'next', # step to test_function3()
110 ... 'step', # stepping into test_function3()
111 ... 'args', # display function args
Rémi Lapeyre45856032019-05-24 22:44:31 +0200112 ... 'return', # return out of function
113 ... 'next', # step to test_function4()
114 ... 'step', # stepping to test_function4()
115 ... 'args', # display function args
Georg Brandl0d089622010-07-30 16:00:46 +0000116 ... 'continue',
117 ... ]):
118 ... test_function()
Rémi Lapeyre45856032019-05-24 22:44:31 +0200119 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000120 -> ret = test_function_2('baz')
121 (Pdb) step
122 --Call--
123 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
124 -> def test_function_2(foo, bar='default'):
125 (Pdb) args
126 foo = 'baz'
127 bar = 'default'
128 (Pdb) list
129 1 -> def test_function_2(foo, bar='default'):
130 2 print(foo)
131 3 for i in range(5):
132 4 print(i)
133 5 print(bar)
134 6 for i in range(10):
135 7 never_executed
136 8 print('after for')
137 9 print('...')
138 10 return foo.upper()
139 [EOF]
140 (Pdb) bt
141 ...
Rémi Lapeyre45856032019-05-24 22:44:31 +0200142 <doctest test.test_pdb.test_pdb_basic_commands[4]>(25)<module>()
Georg Brandl0d089622010-07-30 16:00:46 +0000143 -> test_function()
Rémi Lapeyre45856032019-05-24 22:44:31 +0200144 <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000145 -> ret = test_function_2('baz')
146 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
147 -> def test_function_2(foo, bar='default'):
148 (Pdb) up
Rémi Lapeyre45856032019-05-24 22:44:31 +0200149 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000150 -> ret = test_function_2('baz')
151 (Pdb) down
152 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
153 -> def test_function_2(foo, bar='default'):
154 (Pdb) next
155 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
156 -> print(foo)
157 (Pdb) next
158 baz
159 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
160 -> for i in range(5):
161 (Pdb) step
162 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
163 -> print(i)
164 (Pdb) until
165 0
166 1
167 2
168 3
169 4
170 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
171 -> print(bar)
172 (Pdb) next
173 default
174 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
175 -> for i in range(10):
176 (Pdb) jump 8
177 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
178 -> print('after for')
179 (Pdb) return
180 after for
181 ...
182 --Return--
183 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
184 -> return foo.upper()
185 (Pdb) retval
186 'BAZ'
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200187 (Pdb) next
Rémi Lapeyre45856032019-05-24 22:44:31 +0200188 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(4)test_function()
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200189 -> test_function3(kwonly=True)
190 (Pdb) step
191 --Call--
192 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(1)test_function3()
193 -> def test_function3(arg=None, *, kwonly=None):
194 (Pdb) args
195 arg = None
196 kwonly = True
Rémi Lapeyre45856032019-05-24 22:44:31 +0200197 (Pdb) return
198 --Return--
199 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(2)test_function3()->None
200 -> pass
201 (Pdb) next
202 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(5)test_function()
203 -> test_function4(1, 2, 3)
204 (Pdb) step
205 --Call--
206 > <doctest test.test_pdb.test_pdb_basic_commands[2]>(1)test_function4()
207 -> def test_function4(a, b, c, /):
208 (Pdb) args
209 a = 1
210 b = 2
211 c = 3
Georg Brandl0d089622010-07-30 16:00:46 +0000212 (Pdb) continue
213 BAZ
214 """
215
Irit Katrielad442a62021-04-02 17:15:21 +0100216def reset_Breakpoint():
217 import bdb
218 bdb.Breakpoint.clearBreakpoints()
Georg Brandl0d089622010-07-30 16:00:46 +0000219
220def test_pdb_breakpoint_commands():
221 """Test basic commands related to breakpoints.
222
223 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700224 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0d089622010-07-30 16:00:46 +0000225 ... print(1)
226 ... print(2)
227 ... print(3)
228 ... print(4)
229
230 First, need to clear bdb state that might be left over from previous tests.
231 Otherwise, the new breakpoints might get assigned different numbers.
232
Irit Katrielad442a62021-04-02 17:15:21 +0100233 >>> reset_Breakpoint()
Georg Brandl0d089622010-07-30 16:00:46 +0000234
235 Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because
236 the breakpoint list outputs a tab for the "stop only" and "ignore next"
237 lines, which we don't want to put in here.
238
239 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
240 ... 'break 3',
241 ... 'disable 1',
242 ... 'ignore 1 10',
243 ... 'condition 1 1 < 2',
244 ... 'break 4',
Senthil Kumaran6f107042010-11-29 11:54:17 +0000245 ... 'break 4',
246 ... 'break',
247 ... 'clear 3',
Georg Brandl0d089622010-07-30 16:00:46 +0000248 ... 'break',
249 ... 'condition 1',
250 ... 'enable 1',
251 ... 'clear 1',
252 ... 'commands 2',
R David Murray78d692f2013-10-10 17:23:26 -0400253 ... 'p "42"',
254 ... 'print("42", 7*6)', # Issue 18764 (not about breakpoints)
Georg Brandl0d089622010-07-30 16:00:46 +0000255 ... 'end',
256 ... 'continue', # will stop at breakpoint 2 (line 4)
257 ... 'clear', # clear all!
258 ... 'y',
259 ... 'tbreak 5',
260 ... 'continue', # will stop at temporary breakpoint
261 ... 'break', # make sure breakpoint is gone
262 ... 'continue',
263 ... ]):
264 ... test_function()
265 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
266 -> print(1)
267 (Pdb) break 3
268 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
269 (Pdb) disable 1
270 Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
271 (Pdb) ignore 1 10
272 Will ignore next 10 crossings of breakpoint 1.
273 (Pdb) condition 1 1 < 2
274 New condition set for breakpoint 1.
275 (Pdb) break 4
276 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
Senthil Kumaran6f107042010-11-29 11:54:17 +0000277 (Pdb) break 4
278 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
279 (Pdb) break
280 Num Type Disp Enb Where
281 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
282 stop only if 1 < 2
283 ignore next 10 hits
284 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
285 3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
286 (Pdb) clear 3
287 Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
Georg Brandl0d089622010-07-30 16:00:46 +0000288 (Pdb) break
289 Num Type Disp Enb Where
290 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
291 stop only if 1 < 2
292 ignore next 10 hits
293 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
294 (Pdb) condition 1
295 Breakpoint 1 is now unconditional.
296 (Pdb) enable 1
297 Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
298 (Pdb) clear 1
299 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
300 (Pdb) commands 2
R David Murray78d692f2013-10-10 17:23:26 -0400301 (com) p "42"
302 (com) print("42", 7*6)
Georg Brandl0d089622010-07-30 16:00:46 +0000303 (com) end
304 (Pdb) continue
305 1
R David Murray78d692f2013-10-10 17:23:26 -0400306 '42'
307 42 42
Georg Brandl0d089622010-07-30 16:00:46 +0000308 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
309 -> print(2)
310 (Pdb) clear
311 Clear all breaks? y
312 Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
313 (Pdb) tbreak 5
Senthil Kumaran6f107042010-11-29 11:54:17 +0000314 Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
Georg Brandl0d089622010-07-30 16:00:46 +0000315 (Pdb) continue
316 2
Senthil Kumaran6f107042010-11-29 11:54:17 +0000317 Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
Georg Brandl0d089622010-07-30 16:00:46 +0000318 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
319 -> print(3)
320 (Pdb) break
321 (Pdb) continue
322 3
323 4
324 """
325
Irit Katrielad442a62021-04-02 17:15:21 +0100326def test_pdb_breakpoints_preserved_across_interactive_sessions():
327 """Breakpoints are remembered between interactive sessions
328
329 >>> reset_Breakpoint()
330 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
331 ... 'import test.test_pdb',
332 ... 'break test.test_pdb.do_something',
333 ... 'break test.test_pdb.do_nothing',
334 ... 'break',
335 ... 'continue',
336 ... ]):
337 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100338 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100339 (Pdb) import test.test_pdb
340 (Pdb) break test.test_pdb.do_something
341 Breakpoint 1 at ...test_pdb.py:...
342 (Pdb) break test.test_pdb.do_nothing
343 Breakpoint 2 at ...test_pdb.py:...
344 (Pdb) break
345 Num Type Disp Enb Where
346 1 breakpoint keep yes at ...test_pdb.py:...
347 2 breakpoint keep yes at ...test_pdb.py:...
348 (Pdb) continue
349
350 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
351 ... 'break',
352 ... 'break pdb.find_function',
353 ... 'break',
354 ... 'clear 1',
355 ... 'continue',
356 ... ]):
357 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100358 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100359 (Pdb) break
360 Num Type Disp Enb Where
361 1 breakpoint keep yes at ...test_pdb.py:...
362 2 breakpoint keep yes at ...test_pdb.py:...
363 (Pdb) break pdb.find_function
364 Breakpoint 3 at ...pdb.py:94
365 (Pdb) break
366 Num Type Disp Enb Where
367 1 breakpoint keep yes at ...test_pdb.py:...
368 2 breakpoint keep yes at ...test_pdb.py:...
369 3 breakpoint keep yes at ...pdb.py:...
370 (Pdb) clear 1
371 Deleted breakpoint 1 at ...test_pdb.py:...
372 (Pdb) continue
373
374 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
375 ... 'break',
376 ... 'clear 2',
377 ... 'clear 3',
378 ... 'continue',
379 ... ]):
380 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100381 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100382 (Pdb) break
383 Num Type Disp Enb Where
384 2 breakpoint keep yes at ...test_pdb.py:...
385 3 breakpoint keep yes at ...pdb.py:...
386 (Pdb) clear 2
387 Deleted breakpoint 2 at ...test_pdb.py:...
388 (Pdb) clear 3
389 Deleted breakpoint 3 at ...pdb.py:...
390 (Pdb) continue
391 """
Georg Brandl0d089622010-07-30 16:00:46 +0000392
Georg Brandle59ca2a2010-07-30 17:04:28 +0000393def do_nothing():
394 pass
395
396def do_something():
397 print(42)
398
399def test_list_commands():
400 """Test the list and source commands of pdb.
401
402 >>> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000403 ... import test.test_pdb
404 ... test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000405 ... 'some...'
406 ... 'more...'
407 ... 'code...'
408 ... 'to...'
409 ... 'make...'
410 ... 'a...'
411 ... 'long...'
412 ... 'listing...'
413 ... 'useful...'
414 ... '...'
415 ... '...'
416 ... return foo
417
418 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700419 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000420 ... ret = test_function_2('baz')
421
422 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
423 ... 'list', # list first function
424 ... 'step', # step into second function
425 ... 'list', # list second function
426 ... 'list', # continue listing to EOF
427 ... 'list 1,3', # list specific lines
428 ... 'list x', # invalid argument
429 ... 'next', # step to import
430 ... 'next', # step over import
431 ... 'step', # step into do_nothing
432 ... 'longlist', # list all lines
433 ... 'source do_something', # list all lines of function
Georg Brandlcdf66a92010-07-30 18:15:16 +0000434 ... 'source fooxxx', # something that doesn't exit
Georg Brandle59ca2a2010-07-30 17:04:28 +0000435 ... 'continue',
436 ... ]):
437 ... test_function()
438 > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
439 -> ret = test_function_2('baz')
440 (Pdb) list
441 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700442 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000443 3 -> ret = test_function_2('baz')
444 [EOF]
445 (Pdb) step
446 --Call--
447 > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
448 -> def test_function_2(foo):
449 (Pdb) list
450 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000451 2 import test.test_pdb
452 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000453 4 'some...'
454 5 'more...'
455 6 'code...'
456 7 'to...'
457 8 'make...'
458 9 'a...'
459 10 'long...'
460 11 'listing...'
461 (Pdb) list
462 12 'useful...'
463 13 '...'
464 14 '...'
465 15 return foo
466 [EOF]
467 (Pdb) list 1,3
468 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000469 2 import test.test_pdb
470 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000471 (Pdb) list x
472 *** ...
473 (Pdb) next
474 > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000475 -> import test.test_pdb
Georg Brandle59ca2a2010-07-30 17:04:28 +0000476 (Pdb) next
477 > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000478 -> test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000479 (Pdb) step
480 --Call--
Georg Brandle1e8df12010-07-31 08:14:16 +0000481 > ...test_pdb.py(...)do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000482 -> def do_nothing():
483 (Pdb) longlist
484 ... -> def do_nothing():
485 ... pass
486 (Pdb) source do_something
487 ... def do_something():
488 ... print(42)
Georg Brandlcdf66a92010-07-30 18:15:16 +0000489 (Pdb) source fooxxx
490 *** ...
Georg Brandle59ca2a2010-07-30 17:04:28 +0000491 (Pdb) continue
492 """
493
Irit Katriel022bc752020-08-27 01:51:12 +0100494def test_pdb_whatis_command():
495 """Test the whatis command
496
497 >>> myvar = (1,2)
498 >>> def myfunc():
499 ... pass
500
501 >>> class MyClass:
502 ... def mymethod(self):
503 ... pass
504
505 >>> def test_function():
506 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
507
508 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
509 ... 'whatis myvar',
510 ... 'whatis myfunc',
511 ... 'whatis MyClass',
512 ... 'whatis MyClass()',
513 ... 'whatis MyClass.mymethod',
514 ... 'whatis MyClass().mymethod',
515 ... 'continue',
516 ... ]):
517 ... test_function()
518 --Return--
519 > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()->None
520 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
521 (Pdb) whatis myvar
522 <class 'tuple'>
523 (Pdb) whatis myfunc
524 Function myfunc
525 (Pdb) whatis MyClass
526 Class test.test_pdb.MyClass
527 (Pdb) whatis MyClass()
528 <class 'test.test_pdb.MyClass'>
529 (Pdb) whatis MyClass.mymethod
530 Function mymethod
531 (Pdb) whatis MyClass().mymethod
532 Method mymethod
533 (Pdb) continue
534 """
Georg Brandle59ca2a2010-07-30 17:04:28 +0000535
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000536def test_post_mortem():
537 """Test post mortem traceback debugging.
538
539 >>> def test_function_2():
540 ... try:
541 ... 1/0
542 ... finally:
543 ... print('Exception!')
544
545 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700546 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000547 ... test_function_2()
548 ... print('Not reached.')
549
550 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
551 ... 'next', # step over exception-raising call
552 ... 'bt', # get a backtrace
553 ... 'list', # list code of test_function()
554 ... 'down', # step into test_function_2()
555 ... 'list', # list code of test_function_2()
556 ... 'continue',
557 ... ]):
558 ... try:
559 ... test_function()
560 ... except ZeroDivisionError:
561 ... print('Correctly reraised.')
562 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
563 -> test_function_2()
564 (Pdb) next
565 Exception!
566 ZeroDivisionError: division by zero
567 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
568 -> test_function_2()
569 (Pdb) bt
570 ...
571 <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
572 -> test_function()
573 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
574 -> test_function_2()
575 <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
576 -> 1/0
577 (Pdb) list
578 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700579 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000580 3 -> test_function_2()
581 4 print('Not reached.')
582 [EOF]
583 (Pdb) down
584 > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
585 -> 1/0
586 (Pdb) list
587 1 def test_function_2():
588 2 try:
589 3 >> 1/0
590 4 finally:
591 5 -> print('Exception!')
592 [EOF]
593 (Pdb) continue
594 Correctly reraised.
595 """
596
597
Georg Brandl243ad662009-05-05 09:00:19 +0000598def test_pdb_skip_modules():
599 """This illustrates the simple case of module skipping.
600
601 >>> def skip_module():
602 ... import string
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700603 ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000604 ... string.capwords('FOO')
Georg Brandl243ad662009-05-05 09:00:19 +0000605
Georg Brandl9fa2e022009-09-16 16:40:45 +0000606 >>> with PdbTestInput([
607 ... 'step',
608 ... 'continue',
609 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000610 ... skip_module()
Georg Brandl243ad662009-05-05 09:00:19 +0000611 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
612 -> string.capwords('FOO')
613 (Pdb) step
614 --Return--
615 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
616 -> string.capwords('FOO')
617 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000618 """
Georg Brandl243ad662009-05-05 09:00:19 +0000619
620
621# Module for testing skipping of module that makes a callback
Brett Cannon9529fbf2013-06-15 17:11:25 -0400622mod = types.ModuleType('module_to_skip')
Georg Brandl243ad662009-05-05 09:00:19 +0000623exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
624
625
626def test_pdb_skip_modules_with_callback():
627 """This illustrates skipping of modules that call into other code.
628
629 >>> def skip_module():
630 ... def callback():
631 ... return None
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700632 ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000633 ... mod.foo_pony(callback)
Georg Brandl243ad662009-05-05 09:00:19 +0000634
Georg Brandl9fa2e022009-09-16 16:40:45 +0000635 >>> with PdbTestInput([
636 ... 'step',
637 ... 'step',
638 ... 'step',
639 ... 'step',
640 ... 'step',
641 ... 'continue',
642 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000643 ... skip_module()
Georg Brandl9fa2e022009-09-16 16:40:45 +0000644 ... pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000645 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
646 -> mod.foo_pony(callback)
647 (Pdb) step
648 --Call--
649 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
650 -> def callback():
651 (Pdb) step
652 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
653 -> return None
654 (Pdb) step
655 --Return--
656 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
657 -> return None
658 (Pdb) step
659 --Return--
660 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
661 -> mod.foo_pony(callback)
662 (Pdb) step
Georg Brandl9fa2e022009-09-16 16:40:45 +0000663 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
664 -> pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000665 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000666 """
Georg Brandl243ad662009-05-05 09:00:19 +0000667
668
Georg Brandl3f940892010-07-30 10:29:19 +0000669def test_pdb_continue_in_bottomframe():
670 """Test that "continue" and "next" work properly in bottom frame (issue #5294).
671
672 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700673 ... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
Georg Brandl3f940892010-07-30 10:29:19 +0000674 ... inst.set_trace()
675 ... inst.botframe = sys._getframe() # hackery to get the right botframe
676 ... print(1)
677 ... print(2)
678 ... print(3)
679 ... print(4)
680
Georg Brandl7410dd12010-07-30 12:01:20 +0000681 >>> with PdbTestInput([ # doctest: +ELLIPSIS
Georg Brandl3f940892010-07-30 10:29:19 +0000682 ... 'next',
683 ... 'break 7',
684 ... 'continue',
685 ... 'next',
686 ... 'continue',
687 ... 'continue',
688 ... ]):
689 ... test_function()
690 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
691 -> inst.botframe = sys._getframe() # hackery to get the right botframe
692 (Pdb) next
693 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
694 -> print(1)
695 (Pdb) break 7
Georg Brandl7410dd12010-07-30 12:01:20 +0000696 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
Georg Brandl3f940892010-07-30 10:29:19 +0000697 (Pdb) continue
698 1
699 2
700 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
701 -> print(3)
702 (Pdb) next
703 3
704 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
705 -> print(4)
706 (Pdb) continue
707 4
708 """
709
710
Georg Brandl46b9afc2010-07-30 09:14:20 +0000711def pdb_invoke(method, arg):
712 """Run pdb.method(arg)."""
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700713 getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
Georg Brandl46b9afc2010-07-30 09:14:20 +0000714
715
716def test_pdb_run_with_incorrect_argument():
717 """Testing run and runeval with incorrect first argument.
718
719 >>> pti = PdbTestInput(['continue',])
720 >>> with pti:
721 ... pdb_invoke('run', lambda x: x)
722 Traceback (most recent call last):
723 TypeError: exec() arg 1 must be a string, bytes or code object
724
725 >>> with pti:
726 ... pdb_invoke('runeval', lambda x: x)
727 Traceback (most recent call last):
728 TypeError: eval() arg 1 must be a string, bytes or code object
729 """
730
731
732def test_pdb_run_with_code_object():
733 """Testing run and runeval with code object as a first argument.
734
Georg Brandle1e8df12010-07-31 08:14:16 +0000735 >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
Georg Brandl46b9afc2010-07-30 09:14:20 +0000736 ... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
Georg Brandle1e8df12010-07-31 08:14:16 +0000737 > <string>(1)<module>()...
Georg Brandl46b9afc2010-07-30 09:14:20 +0000738 (Pdb) step
739 --Return--
740 > <string>(1)<module>()->None
741 (Pdb) x
742 1
743 (Pdb) continue
744
745 >>> with PdbTestInput(['x', 'continue']):
746 ... x=0
747 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
748 > <string>(1)<module>()->None
749 (Pdb) x
750 1
751 (Pdb) continue
752 """
753
Guido van Rossum8820c232013-11-21 11:30:06 -0800754def test_next_until_return_at_return_event():
755 """Test that pdb stops after a next/until/return issued at a return debug event.
756
757 >>> def test_function_2():
758 ... x = 1
759 ... x = 2
760
761 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700762 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800763 ... test_function_2()
764 ... test_function_2()
765 ... test_function_2()
766 ... end = 1
767
Irit Katrielad442a62021-04-02 17:15:21 +0100768 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -0800769 >>> with PdbTestInput(['break test_function_2',
770 ... 'continue',
771 ... 'return',
772 ... 'next',
773 ... 'continue',
774 ... 'return',
775 ... 'until',
776 ... 'continue',
777 ... 'return',
778 ... 'return',
779 ... 'continue']):
780 ... test_function()
781 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
782 -> test_function_2()
783 (Pdb) break test_function_2
784 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
785 (Pdb) continue
786 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
787 -> x = 1
788 (Pdb) return
789 --Return--
790 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
791 -> x = 2
792 (Pdb) next
793 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
794 -> test_function_2()
795 (Pdb) continue
796 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
797 -> x = 1
798 (Pdb) return
799 --Return--
800 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
801 -> x = 2
802 (Pdb) until
803 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
804 -> test_function_2()
805 (Pdb) continue
806 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
807 -> x = 1
808 (Pdb) return
809 --Return--
810 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
811 -> x = 2
812 (Pdb) return
813 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
814 -> end = 1
815 (Pdb) continue
816 """
817
818def test_pdb_next_command_for_generator():
819 """Testing skip unwindng stack on yield for generators for "next" command
820
821 >>> def test_gen():
822 ... yield 0
823 ... return 1
824 ... yield 2
825
826 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700827 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800828 ... it = test_gen()
829 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300830 ... if next(it) != 0:
831 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800832 ... next(it)
833 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300834 ... if ex.value != 1:
835 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800836 ... print("finished")
837
838 >>> with PdbTestInput(['step',
839 ... 'step',
840 ... 'step',
841 ... 'next',
842 ... 'next',
843 ... 'step',
844 ... 'step',
845 ... 'continue']):
846 ... test_function()
847 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
848 -> it = test_gen()
849 (Pdb) step
850 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
851 -> try:
852 (Pdb) step
853 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300854 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -0800855 (Pdb) step
856 --Call--
857 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
858 -> def test_gen():
859 (Pdb) next
860 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
861 -> yield 0
862 (Pdb) next
863 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
864 -> return 1
865 (Pdb) step
866 --Return--
867 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
868 -> return 1
869 (Pdb) step
870 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300871 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -0800872 -> next(it)
873 (Pdb) continue
874 finished
875 """
876
Pablo Galindo46877022018-01-29 00:25:05 +0000877def test_pdb_next_command_for_coroutine():
878 """Testing skip unwindng stack on yield for coroutines for "next" command
879
880 >>> import asyncio
881
882 >>> async def test_coro():
883 ... await asyncio.sleep(0)
884 ... await asyncio.sleep(0)
885 ... await asyncio.sleep(0)
886
887 >>> async def test_main():
888 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
889 ... await test_coro()
890
891 >>> def test_function():
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000892 ... loop = asyncio.new_event_loop()
Pablo Galindo46877022018-01-29 00:25:05 +0000893 ... loop.run_until_complete(test_main())
894 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700895 ... asyncio.set_event_loop_policy(None)
Pablo Galindo46877022018-01-29 00:25:05 +0000896 ... print("finished")
897
898 >>> with PdbTestInput(['step',
899 ... 'step',
900 ... 'next',
901 ... 'next',
902 ... 'next',
903 ... 'step',
904 ... 'continue']):
905 ... test_function()
906 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
907 -> await test_coro()
908 (Pdb) step
909 --Call--
910 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
911 -> async def test_coro():
912 (Pdb) step
913 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
914 -> await asyncio.sleep(0)
915 (Pdb) next
916 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
917 -> await asyncio.sleep(0)
918 (Pdb) next
919 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
920 -> await asyncio.sleep(0)
921 (Pdb) next
922 Internal StopIteration
923 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
924 -> await test_coro()
925 (Pdb) step
926 --Return--
927 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
928 -> await test_coro()
929 (Pdb) continue
930 finished
931 """
932
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500933def test_pdb_next_command_for_asyncgen():
934 """Testing skip unwindng stack on yield for coroutines for "next" command
935
936 >>> import asyncio
937
938 >>> async def agen():
939 ... yield 1
940 ... await asyncio.sleep(0)
941 ... yield 2
942
943 >>> async def test_coro():
944 ... async for x in agen():
945 ... print(x)
946
947 >>> async def test_main():
948 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
949 ... await test_coro()
950
951 >>> def test_function():
952 ... loop = asyncio.new_event_loop()
953 ... loop.run_until_complete(test_main())
954 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700955 ... asyncio.set_event_loop_policy(None)
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500956 ... print("finished")
957
958 >>> with PdbTestInput(['step',
959 ... 'step',
960 ... 'next',
961 ... 'next',
962 ... 'step',
963 ... 'next',
964 ... 'continue']):
965 ... test_function()
966 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
967 -> await test_coro()
968 (Pdb) step
969 --Call--
970 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
971 -> async def test_coro():
972 (Pdb) step
973 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
974 -> async for x in agen():
975 (Pdb) next
976 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
977 -> print(x)
978 (Pdb) next
979 1
980 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
981 -> async for x in agen():
982 (Pdb) step
983 --Call--
984 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
985 -> yield 1
986 (Pdb) next
987 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
988 -> await asyncio.sleep(0)
989 (Pdb) continue
990 2
991 finished
992 """
993
Guido van Rossum8820c232013-11-21 11:30:06 -0800994def test_pdb_return_command_for_generator():
995 """Testing no unwindng stack on yield for generators
996 for "return" command
997
998 >>> def test_gen():
999 ... yield 0
1000 ... return 1
1001 ... yield 2
1002
1003 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001004 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001005 ... it = test_gen()
1006 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001007 ... if next(it) != 0:
1008 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001009 ... next(it)
1010 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001011 ... if ex.value != 1:
1012 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001013 ... print("finished")
1014
1015 >>> with PdbTestInput(['step',
1016 ... 'step',
1017 ... 'step',
1018 ... 'return',
1019 ... 'step',
1020 ... 'step',
1021 ... 'continue']):
1022 ... test_function()
1023 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
1024 -> it = test_gen()
1025 (Pdb) step
1026 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
1027 -> try:
1028 (Pdb) step
1029 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001030 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -08001031 (Pdb) step
1032 --Call--
1033 > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
1034 -> def test_gen():
1035 (Pdb) return
1036 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001037 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001038 -> next(it)
1039 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001040 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001041 -> except StopIteration as ex:
1042 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001043 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
1044 -> if ex.value != 1:
Guido van Rossum8820c232013-11-21 11:30:06 -08001045 (Pdb) continue
1046 finished
1047 """
1048
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001049def test_pdb_return_command_for_coroutine():
1050 """Testing no unwindng stack on yield for coroutines for "return" command
1051
1052 >>> import asyncio
1053
1054 >>> async def test_coro():
1055 ... await asyncio.sleep(0)
1056 ... await asyncio.sleep(0)
1057 ... await asyncio.sleep(0)
1058
1059 >>> async def test_main():
1060 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1061 ... await test_coro()
1062
1063 >>> def test_function():
1064 ... loop = asyncio.new_event_loop()
1065 ... loop.run_until_complete(test_main())
1066 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001067 ... asyncio.set_event_loop_policy(None)
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001068 ... print("finished")
1069
1070 >>> with PdbTestInput(['step',
1071 ... 'step',
1072 ... 'next',
1073 ... 'continue']):
1074 ... test_function()
1075 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
1076 -> await test_coro()
1077 (Pdb) step
1078 --Call--
1079 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
1080 -> async def test_coro():
1081 (Pdb) step
1082 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
1083 -> await asyncio.sleep(0)
1084 (Pdb) next
1085 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
1086 -> await asyncio.sleep(0)
1087 (Pdb) continue
1088 finished
1089 """
1090
Guido van Rossum8820c232013-11-21 11:30:06 -08001091def test_pdb_until_command_for_generator():
1092 """Testing no unwindng stack on yield for generators
Min ho Kimc4cacc82019-07-31 08:16:13 +10001093 for "until" command if target breakpoint is not reached
Guido van Rossum8820c232013-11-21 11:30:06 -08001094
1095 >>> def test_gen():
1096 ... yield 0
1097 ... yield 1
1098 ... yield 2
1099
1100 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001101 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001102 ... for i in test_gen():
1103 ... print(i)
1104 ... print("finished")
1105
1106 >>> with PdbTestInput(['step',
1107 ... 'until 4',
1108 ... 'step',
1109 ... 'step',
1110 ... 'continue']):
1111 ... test_function()
1112 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
1113 -> for i in test_gen():
1114 (Pdb) step
1115 --Call--
1116 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
1117 -> def test_gen():
1118 (Pdb) until 4
1119 0
1120 1
1121 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
1122 -> yield 2
1123 (Pdb) step
1124 --Return--
1125 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
1126 -> yield 2
1127 (Pdb) step
1128 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
1129 -> print(i)
1130 (Pdb) continue
1131 2
1132 finished
1133 """
1134
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001135def test_pdb_until_command_for_coroutine():
1136 """Testing no unwindng stack for coroutines
Min ho Kimc4cacc82019-07-31 08:16:13 +10001137 for "until" command if target breakpoint is not reached
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001138
1139 >>> import asyncio
1140
1141 >>> async def test_coro():
1142 ... print(0)
1143 ... await asyncio.sleep(0)
1144 ... print(1)
1145 ... await asyncio.sleep(0)
1146 ... print(2)
1147 ... await asyncio.sleep(0)
1148 ... print(3)
1149
1150 >>> async def test_main():
1151 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1152 ... await test_coro()
1153
1154 >>> def test_function():
1155 ... loop = asyncio.new_event_loop()
1156 ... loop.run_until_complete(test_main())
1157 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001158 ... asyncio.set_event_loop_policy(None)
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001159 ... print("finished")
1160
1161 >>> with PdbTestInput(['step',
1162 ... 'until 8',
1163 ... 'continue']):
1164 ... test_function()
1165 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
1166 -> await test_coro()
1167 (Pdb) step
1168 --Call--
1169 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
1170 -> async def test_coro():
1171 (Pdb) until 8
1172 0
1173 1
1174 2
1175 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
1176 -> print(3)
1177 (Pdb) continue
1178 3
1179 finished
1180 """
1181
Guido van Rossum8820c232013-11-21 11:30:06 -08001182def test_pdb_next_command_in_generator_for_loop():
Martin Panter46f50722016-05-26 05:35:26 +00001183 """The next command on returning from a generator controlled by a for loop.
Guido van Rossum8820c232013-11-21 11:30:06 -08001184
1185 >>> def test_gen():
1186 ... yield 0
1187 ... return 1
1188
1189 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001190 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001191 ... for i in test_gen():
1192 ... print('value', i)
1193 ... x = 123
1194
1195 >>> with PdbTestInput(['break test_gen',
1196 ... 'continue',
1197 ... 'next',
1198 ... 'next',
1199 ... 'next',
1200 ... 'continue']):
1201 ... test_function()
1202 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1203 -> for i in test_gen():
1204 (Pdb) break test_gen
Irit Katrielad442a62021-04-02 17:15:21 +01001205 Breakpoint 1 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:1
Guido van Rossum8820c232013-11-21 11:30:06 -08001206 (Pdb) continue
1207 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1208 -> yield 0
1209 (Pdb) next
1210 value 0
1211 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1212 -> return 1
1213 (Pdb) next
1214 Internal StopIteration: 1
1215 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1216 -> for i in test_gen():
1217 (Pdb) next
1218 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1219 -> x = 123
1220 (Pdb) continue
1221 """
1222
1223def test_pdb_next_command_subiterator():
1224 """The next command in a generator with a subiterator.
1225
1226 >>> def test_subgenerator():
1227 ... yield 0
1228 ... return 1
1229
1230 >>> def test_gen():
1231 ... x = yield from test_subgenerator()
1232 ... return x
1233
1234 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001235 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001236 ... for i in test_gen():
1237 ... print('value', i)
1238 ... x = 123
1239
1240 >>> with PdbTestInput(['step',
1241 ... 'step',
1242 ... 'next',
1243 ... 'next',
1244 ... 'next',
1245 ... 'continue']):
1246 ... test_function()
1247 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1248 -> for i in test_gen():
1249 (Pdb) step
1250 --Call--
1251 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1252 -> def test_gen():
1253 (Pdb) step
1254 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1255 -> x = yield from test_subgenerator()
1256 (Pdb) next
1257 value 0
1258 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1259 -> return x
1260 (Pdb) next
1261 Internal StopIteration: 1
1262 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1263 -> for i in test_gen():
1264 (Pdb) next
1265 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1266 -> x = 123
1267 (Pdb) continue
1268 """
1269
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001270def test_pdb_issue_20766():
1271 """Test for reference leaks when the SIGINT handler is set.
1272
1273 >>> def test_function():
1274 ... i = 1
1275 ... while i <= 2:
1276 ... sess = pdb.Pdb()
1277 ... sess.set_trace(sys._getframe())
1278 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1279 ... i += 1
1280
Irit Katrielad442a62021-04-02 17:15:21 +01001281 >>> reset_Breakpoint()
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001282 >>> with PdbTestInput(['continue',
1283 ... 'continue']):
1284 ... test_function()
1285 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1286 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1287 (Pdb) continue
1288 pdb 1: <built-in function default_int_handler>
1289 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
1290 -> sess.set_trace(sys._getframe())
1291 (Pdb) continue
1292 pdb 2: <built-in function default_int_handler>
1293 """
Georg Brandl46b9afc2010-07-30 09:14:20 +00001294
Georg Brandl6cccb862010-07-30 14:16:43 +00001295
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001296class PdbTestCase(unittest.TestCase):
1297 def tearDown(self):
Hai Shi604bba12020-08-04 23:51:43 +08001298 os_helper.unlink(os_helper.TESTFN)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001299
1300 def _run_pdb(self, pdb_args, commands):
Hai Shi604bba12020-08-04 23:51:43 +08001301 self.addCleanup(os_helper.rmtree, '__pycache__')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001302 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1303 with subprocess.Popen(
1304 cmd,
1305 stdout=subprocess.PIPE,
1306 stdin=subprocess.PIPE,
1307 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001308 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001309 ) as proc:
1310 stdout, stderr = proc.communicate(str.encode(commands))
1311 stdout = stdout and bytes.decode(stdout)
1312 stderr = stderr and bytes.decode(stderr)
1313 return stdout, stderr
1314
1315 def run_pdb_script(self, script, commands):
Senthil Kumaran42d70812012-05-01 10:07:49 +08001316 """Run 'script' lines with pdb and the pdb 'commands'."""
1317 filename = 'main.py'
1318 with open(filename, 'w') as f:
1319 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001320 self.addCleanup(os_helper.unlink, filename)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001321 return self._run_pdb([filename], commands)
1322
1323 def run_pdb_module(self, script, commands):
1324 """Runs the script code as part of a module"""
1325 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001326 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001327 main_file = self.module_name + '/__main__.py'
1328 init_file = self.module_name + '/__init__.py'
1329 os.mkdir(self.module_name)
1330 with open(init_file, 'w') as f:
1331 pass
1332 with open(main_file, 'w') as f:
1333 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001334 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001335 return self._run_pdb(['-m', self.module_name], commands)
Senthil Kumaran42d70812012-05-01 10:07:49 +08001336
Georg Brandl6e220552013-10-13 20:51:47 +02001337 def _assert_find_function(self, file_content, func_name, expected):
Hai Shi604bba12020-08-04 23:51:43 +08001338 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6e220552013-10-13 20:51:47 +02001339 f.write(file_content)
1340
1341 expected = None if not expected else (
Hai Shi604bba12020-08-04 23:51:43 +08001342 expected[0], os_helper.TESTFN, expected[1])
Georg Brandl6e220552013-10-13 20:51:47 +02001343 self.assertEqual(
Hai Shi604bba12020-08-04 23:51:43 +08001344 expected, pdb.find_function(func_name, os_helper.TESTFN))
Georg Brandl6e220552013-10-13 20:51:47 +02001345
1346 def test_find_function_empty_file(self):
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001347 self._assert_find_function(b'', 'foo', None)
Georg Brandl6e220552013-10-13 20:51:47 +02001348
1349 def test_find_function_found(self):
1350 self._assert_find_function(
1351 """\
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001352def foo():
1353 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001354
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001355def bœr():
1356 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001357
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001358def quux():
1359 pass
1360""".encode(),
1361 'bœr',
1362 ('bœr', 4),
1363 )
1364
1365 def test_find_function_found_with_encoding_cookie(self):
1366 self._assert_find_function(
1367 """\
1368# coding: iso-8859-15
1369def foo():
1370 pass
1371
1372def bœr():
1373 pass
1374
1375def quux():
1376 pass
1377""".encode('iso-8859-15'),
1378 'bœr',
1379 ('bœr', 5),
1380 )
1381
1382 def test_find_function_found_with_bom(self):
1383 self._assert_find_function(
1384 codecs.BOM_UTF8 + """\
1385def bœr():
1386 pass
1387""".encode(),
1388 'bœr',
1389 ('bœr', 1),
Georg Brandl6e220552013-10-13 20:51:47 +02001390 )
1391
Georg Brandl6cccb862010-07-30 14:16:43 +00001392 def test_issue7964(self):
1393 # open the file as binary so we can force \r\n newline
Hai Shi604bba12020-08-04 23:51:43 +08001394 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6cccb862010-07-30 14:16:43 +00001395 f.write(b'print("testing my pdb")\r\n')
Hai Shi604bba12020-08-04 23:51:43 +08001396 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
Georg Brandl6cccb862010-07-30 14:16:43 +00001397 proc = subprocess.Popen(cmd,
1398 stdout=subprocess.PIPE,
1399 stdin=subprocess.PIPE,
1400 stderr=subprocess.STDOUT,
1401 )
Brian Curtin994ad6c2010-11-05 15:38:47 +00001402 self.addCleanup(proc.stdout.close)
Georg Brandl6cccb862010-07-30 14:16:43 +00001403 stdout, stderr = proc.communicate(b'quit\n')
1404 self.assertNotIn(b'SyntaxError', stdout,
1405 "Got a syntax error running test script under PDB")
1406
Senthil Kumaran42d70812012-05-01 10:07:49 +08001407 def test_issue13183(self):
1408 script = """
1409 from bar import bar
1410
1411 def foo():
1412 bar()
1413
1414 def nope():
1415 pass
1416
1417 def foobar():
1418 foo()
1419 nope()
1420
1421 foobar()
1422 """
1423 commands = """
1424 from bar import bar
1425 break bar
1426 continue
1427 step
1428 step
1429 quit
1430 """
1431 bar = """
1432 def bar():
Senthil Kumarancb172042012-05-02 08:00:22 +08001433 pass
Senthil Kumaran42d70812012-05-01 10:07:49 +08001434 """
1435 with open('bar.py', 'w') as f:
1436 f.write(textwrap.dedent(bar))
Hai Shi604bba12020-08-04 23:51:43 +08001437 self.addCleanup(os_helper.unlink, 'bar.py')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001438 stdout, stderr = self.run_pdb_script(script, commands)
Georg Brandl4bde9ca2012-05-01 09:21:16 +02001439 self.assertTrue(
1440 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1441 'Fail to step into the caller after a return')
Senthil Kumaran42d70812012-05-01 10:07:49 +08001442
Daniel Hahler9139f922019-04-01 23:59:50 +02001443 def test_issue13120(self):
1444 # Invoking "continue" on a non-main thread triggered an exception
1445 # inside signal.signal.
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001446
Hai Shi604bba12020-08-04 23:51:43 +08001447 with open(os_helper.TESTFN, 'wb') as f:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001448 f.write(textwrap.dedent("""
1449 import threading
1450 import pdb
1451
1452 def start_pdb():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001453 pdb.Pdb(readrc=False).set_trace()
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001454 x = 1
1455 y = 1
1456
1457 t = threading.Thread(target=start_pdb)
1458 t.start()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001459 cmd = [sys.executable, '-u', os_helper.TESTFN]
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001460 proc = subprocess.Popen(cmd,
1461 stdout=subprocess.PIPE,
1462 stdin=subprocess.PIPE,
1463 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001464 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001465 )
1466 self.addCleanup(proc.stdout.close)
1467 stdout, stderr = proc.communicate(b'cont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001468 self.assertNotIn(b'Error', stdout,
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001469 "Got an error running test script under PDB")
1470
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001471 def test_issue36250(self):
1472
Hai Shi604bba12020-08-04 23:51:43 +08001473 with open(os_helper.TESTFN, 'wb') as f:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001474 f.write(textwrap.dedent("""
1475 import threading
1476 import pdb
1477
1478 evt = threading.Event()
1479
1480 def start_pdb():
1481 evt.wait()
1482 pdb.Pdb(readrc=False).set_trace()
1483
1484 t = threading.Thread(target=start_pdb)
1485 t.start()
1486 pdb.Pdb(readrc=False).set_trace()
1487 evt.set()
1488 t.join()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001489 cmd = [sys.executable, '-u', os_helper.TESTFN]
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001490 proc = subprocess.Popen(cmd,
1491 stdout=subprocess.PIPE,
1492 stdin=subprocess.PIPE,
1493 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001494 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001495 )
1496 self.addCleanup(proc.stdout.close)
1497 stdout, stderr = proc.communicate(b'cont\ncont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001498 self.assertNotIn(b'Error', stdout,
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001499 "Got an error running test script under PDB")
1500
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001501 def test_issue16180(self):
1502 # A syntax error in the debuggee.
1503 script = "def f: pass\n"
1504 commands = ''
1505 expected = "SyntaxError:"
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001506 stdout, stderr = self.run_pdb_script(script, commands)
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001507 self.assertIn(expected, stdout,
1508 '\n\nExpected:\n{}\nGot:\n{}\n'
1509 'Fail to handle a syntax error in the debuggee.'
1510 .format(expected, stdout))
1511
Irit Katriel652bfde2021-04-01 16:25:59 +01001512 def test_issue26053(self):
1513 # run command of pdb prompt echoes the correct args
1514 script = "print('hello')"
1515 commands = """
1516 continue
1517 run a b c
1518 run d e f
1519 quit
1520 """
1521 stdout, stderr = self.run_pdb_script(script, commands)
Irit Katrielbd4ab8e2021-04-01 20:05:51 +01001522 res = '\n'.join([x.strip() for x in stdout.splitlines()])
1523 self.assertRegex(res, "Restarting .* with arguments:\na b c")
1524 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001525
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001526 def test_readrc_kwarg(self):
Victor Stinner11ea0442016-09-09 22:56:54 -07001527 script = textwrap.dedent("""
1528 import pdb; pdb.Pdb(readrc=False).set_trace()
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001529
Victor Stinner11ea0442016-09-09 22:56:54 -07001530 print('hello')
1531 """)
Victor Stinner11ea0442016-09-09 22:56:54 -07001532
Victor Stinnerbc626262016-09-09 23:22:09 -07001533 save_home = os.environ.pop('HOME', None)
1534 try:
Hai Shi604bba12020-08-04 23:51:43 +08001535 with os_helper.temp_cwd():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001536 with open('.pdbrc', 'w') as f:
1537 f.write("invalid\n")
1538
1539 with open('main.py', 'w') as f:
1540 f.write(script)
1541
1542 cmd = [sys.executable, 'main.py']
1543 proc = subprocess.Popen(
1544 cmd,
1545 stdout=subprocess.PIPE,
1546 stdin=subprocess.PIPE,
1547 stderr=subprocess.PIPE,
1548 )
Victor Stinnerbc626262016-09-09 23:22:09 -07001549 with proc:
1550 stdout, stderr = proc.communicate(b'q\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001551 self.assertNotIn(b"NameError: name 'invalid' is not defined",
1552 stdout)
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001553
1554 finally:
Victor Stinner11ea0442016-09-09 22:56:54 -07001555 if save_home is not None:
1556 os.environ['HOME'] = save_home
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001557
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001558 def test_readrc_homedir(self):
1559 save_home = os.environ.pop("HOME", None)
Hai Shi604bba12020-08-04 23:51:43 +08001560 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001561 rc_path = os.path.join(temp_dir, ".pdbrc")
1562 os.path.expanduser.return_value = rc_path
1563 try:
1564 with open(rc_path, "w") as f:
1565 f.write("invalid")
1566 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1567 finally:
1568 if save_home is not None:
1569 os.environ["HOME"] = save_home
1570
Barry Warsaw35425d62017-09-22 12:29:42 -04001571 def test_header(self):
1572 stdout = StringIO()
1573 header = 'Nobody expects... blah, blah, blah'
1574 with ExitStack() as resources:
1575 resources.enter_context(patch('sys.stdout', stdout))
1576 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1577 pdb.set_trace(header=header)
1578 self.assertEqual(stdout.getvalue(), header + '\n')
1579
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001580 def test_run_module(self):
1581 script = """print("SUCCESS")"""
1582 commands = """
1583 continue
1584 quit
1585 """
1586 stdout, stderr = self.run_pdb_module(script, commands)
1587 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1588
1589 def test_module_is_run_as_main(self):
1590 script = """
1591 if __name__ == '__main__':
1592 print("SUCCESS")
1593 """
1594 commands = """
1595 continue
1596 quit
1597 """
1598 stdout, stderr = self.run_pdb_module(script, commands)
1599 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1600
1601 def test_breakpoint(self):
1602 script = """
1603 if __name__ == '__main__':
1604 pass
1605 print("SUCCESS")
1606 pass
1607 """
1608 commands = """
1609 b 3
1610 quit
1611 """
1612 stdout, stderr = self.run_pdb_module(script, commands)
1613 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1614 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1615
1616 def test_run_pdb_with_pdb(self):
1617 commands = """
1618 c
1619 quit
1620 """
1621 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001622 self.assertIn(
1623 pdb._usage,
1624 stdout.replace('\r', '') # remove \r for windows
1625 )
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001626
1627 def test_module_without_a_main(self):
1628 module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001629 os_helper.rmtree(module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001630 init_file = module_name + '/__init__.py'
1631 os.mkdir(module_name)
1632 with open(init_file, 'w') as f:
1633 pass
Hai Shi604bba12020-08-04 23:51:43 +08001634 self.addCleanup(os_helper.rmtree, module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001635 stdout, stderr = self._run_pdb(['-m', module_name], "")
1636 self.assertIn("ImportError: No module named t_main.__main__",
1637 stdout.splitlines())
1638
1639 def test_blocks_at_first_code_line(self):
1640 script = """
1641 #This is a comment, on line 2
1642
1643 print("SUCCESS")
1644 """
1645 commands = """
1646 quit
1647 """
1648 stdout, stderr = self.run_pdb_module(script, commands)
1649 self.assertTrue(any("__main__.py(4)<module>()"
1650 in l for l in stdout.splitlines()), stdout)
1651
1652 def test_relative_imports(self):
1653 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001654 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001655 main_file = self.module_name + '/__main__.py'
1656 init_file = self.module_name + '/__init__.py'
1657 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001658 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001659 os.mkdir(self.module_name)
1660 with open(init_file, 'w') as f:
1661 f.write(textwrap.dedent("""
1662 top_var = "VAR from top"
1663 """))
1664 with open(main_file, 'w') as f:
1665 f.write(textwrap.dedent("""
1666 from . import top_var
1667 from .module import var
1668 from . import module
1669 pass # We'll stop here and print the vars
1670 """))
1671 with open(module_file, 'w') as f:
1672 f.write(textwrap.dedent("""
1673 var = "VAR from module"
1674 var2 = "second var"
1675 """))
1676 commands = """
1677 b 5
1678 c
1679 p top_var
1680 p var
1681 p module.var2
1682 quit
1683 """
1684 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
Mario Corchero38bfa842018-02-03 06:40:11 +00001685 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001686 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1687 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Georg Brandl6cccb862010-07-30 14:16:43 +00001688
Mario Corchero38bfa842018-02-03 06:40:11 +00001689 def test_relative_imports_on_plain_module(self):
1690 # Validates running a plain module. See bpo32691
1691 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001692 os_helper.rmtree(self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001693 main_file = self.module_name + '/runme.py'
1694 init_file = self.module_name + '/__init__.py'
1695 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001696 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001697 os.mkdir(self.module_name)
1698 with open(init_file, 'w') as f:
1699 f.write(textwrap.dedent("""
1700 top_var = "VAR from top"
1701 """))
1702 with open(main_file, 'w') as f:
1703 f.write(textwrap.dedent("""
1704 from . import module
1705 pass # We'll stop here and print the vars
1706 """))
1707 with open(module_file, 'w') as f:
1708 f.write(textwrap.dedent("""
1709 var = "VAR from module"
1710 """))
1711 commands = """
1712 b 3
1713 c
1714 p module.var
1715 quit
1716 """
1717 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1718 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1719
Daniel Hahler3e936432019-03-12 04:29:04 +01001720 def test_errors_in_command(self):
1721 commands = "\n".join([
1722 'print(',
1723 'debug print(',
1724 'debug doesnotexist',
1725 'c',
1726 ])
Mark Shannon877df852020-11-12 09:43:29 +00001727 stdout, _ = self.run_pdb_script('pass', commands + '\n')
Daniel Hahler3e936432019-03-12 04:29:04 +01001728
Daniel Hahler43277052019-02-15 21:52:53 +01001729 self.assertEqual(stdout.splitlines()[1:], [
Mark Shannon877df852020-11-12 09:43:29 +00001730 '-> pass',
Pablo Galindod6d63712021-01-19 23:59:33 +00001731 '(Pdb) *** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001732
1733 '(Pdb) ENTERING RECURSIVE DEBUGGER',
Pablo Galindod6d63712021-01-19 23:59:33 +00001734 '*** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001735 'LEAVING RECURSIVE DEBUGGER',
1736
1737 '(Pdb) ENTERING RECURSIVE DEBUGGER',
1738 '> <string>(1)<module>()',
1739 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1740 'LEAVING RECURSIVE DEBUGGER',
Daniel Hahler43277052019-02-15 21:52:53 +01001741 '(Pdb) ',
1742 ])
Georg Brandl6cccb862010-07-30 14:16:43 +00001743
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001744
1745 def test_issue42384(self):
1746 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1747 script = textwrap.dedent("""
1748 import sys
1749 print('sys.path[0] is', sys.path[0])
1750 """)
1751 commands = 'c\nq'
1752
1753 with os_helper.temp_cwd() as cwd:
1754 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1755
1756 stdout, stderr = self.run_pdb_script(script, commands)
1757
1758 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1759
1760 @os_helper.skip_unless_symlink
1761 def test_issue42384_symlink(self):
1762 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1763 script = textwrap.dedent("""
1764 import sys
1765 print('sys.path[0] is', sys.path[0])
1766 """)
1767 commands = 'c\nq'
1768
1769 with os_helper.temp_cwd() as cwd:
1770 cwd = os.path.realpath(cwd)
1771 dir_one = os.path.join(cwd, 'dir_one')
1772 dir_two = os.path.join(cwd, 'dir_two')
1773 expected = f'(Pdb) sys.path[0] is {dir_one}'
1774
1775 os.mkdir(dir_one)
1776 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1777 f.write(script)
1778 os.mkdir(dir_two)
1779 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1780
1781 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1782
1783 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1784
Andrey Bienkowski501d4a52021-01-25 21:08:01 +00001785 def test_issue42383(self):
1786 with os_helper.temp_cwd() as cwd:
1787 with open('foo.py', 'w') as f:
1788 s = textwrap.dedent("""
1789 print('The correct file was executed')
1790
1791 import os
1792 os.chdir("subdir")
1793 """)
1794 f.write(s)
1795
1796 subdir = os.path.join(cwd, 'subdir')
1797 os.mkdir(subdir)
1798 os.mkdir(os.path.join(subdir, 'subdir'))
1799 wrong_file = os.path.join(subdir, 'foo.py')
1800
1801 with open(wrong_file, 'w') as f:
1802 f.write('print("The wrong file was executed")')
1803
1804 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
1805 expected = '(Pdb) The correct file was executed'
1806 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
1807
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001808
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001809def load_tests(*args):
Georg Brandl243ad662009-05-05 09:00:19 +00001810 from test import test_pdb
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001811 suites = [
1812 unittest.makeSuite(PdbTestCase),
1813 doctest.DocTestSuite(test_pdb)
1814 ]
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001815 return unittest.TestSuite(suites)
Georg Brandl243ad662009-05-05 09:00:19 +00001816
1817
1818if __name__ == '__main__':
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001819 unittest.main()