blob: 870eab4e33e6336a58234290724e02715706e44d [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
Irit Katriel21b02b52021-04-28 11:38:29 +01001195 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -08001196 >>> with PdbTestInput(['break test_gen',
1197 ... 'continue',
1198 ... 'next',
1199 ... 'next',
1200 ... 'next',
1201 ... 'continue']):
1202 ... test_function()
1203 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1204 -> for i in test_gen():
1205 (Pdb) break test_gen
Irit Katrielad442a62021-04-02 17:15:21 +01001206 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 -08001207 (Pdb) continue
1208 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1209 -> yield 0
1210 (Pdb) next
1211 value 0
1212 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1213 -> return 1
1214 (Pdb) next
1215 Internal StopIteration: 1
1216 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1217 -> for i in test_gen():
1218 (Pdb) next
1219 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1220 -> x = 123
1221 (Pdb) continue
1222 """
1223
1224def test_pdb_next_command_subiterator():
1225 """The next command in a generator with a subiterator.
1226
1227 >>> def test_subgenerator():
1228 ... yield 0
1229 ... return 1
1230
1231 >>> def test_gen():
1232 ... x = yield from test_subgenerator()
1233 ... return x
1234
1235 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001236 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001237 ... for i in test_gen():
1238 ... print('value', i)
1239 ... x = 123
1240
1241 >>> with PdbTestInput(['step',
1242 ... 'step',
1243 ... 'next',
1244 ... 'next',
1245 ... 'next',
1246 ... 'continue']):
1247 ... test_function()
1248 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1249 -> for i in test_gen():
1250 (Pdb) step
1251 --Call--
1252 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1253 -> def test_gen():
1254 (Pdb) step
1255 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1256 -> x = yield from test_subgenerator()
1257 (Pdb) next
1258 value 0
1259 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1260 -> return x
1261 (Pdb) next
1262 Internal StopIteration: 1
1263 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1264 -> for i in test_gen():
1265 (Pdb) next
1266 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1267 -> x = 123
1268 (Pdb) continue
1269 """
1270
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001271def test_pdb_issue_20766():
1272 """Test for reference leaks when the SIGINT handler is set.
1273
1274 >>> def test_function():
1275 ... i = 1
1276 ... while i <= 2:
1277 ... sess = pdb.Pdb()
1278 ... sess.set_trace(sys._getframe())
1279 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1280 ... i += 1
1281
Irit Katrielad442a62021-04-02 17:15:21 +01001282 >>> reset_Breakpoint()
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001283 >>> with PdbTestInput(['continue',
1284 ... 'continue']):
1285 ... test_function()
1286 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1287 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1288 (Pdb) continue
1289 pdb 1: <built-in function default_int_handler>
1290 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
1291 -> sess.set_trace(sys._getframe())
1292 (Pdb) continue
1293 pdb 2: <built-in function default_int_handler>
1294 """
Georg Brandl46b9afc2010-07-30 09:14:20 +00001295
Georg Brandl6cccb862010-07-30 14:16:43 +00001296
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001297class PdbTestCase(unittest.TestCase):
1298 def tearDown(self):
Hai Shi604bba12020-08-04 23:51:43 +08001299 os_helper.unlink(os_helper.TESTFN)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001300
1301 def _run_pdb(self, pdb_args, commands):
Hai Shi604bba12020-08-04 23:51:43 +08001302 self.addCleanup(os_helper.rmtree, '__pycache__')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001303 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1304 with subprocess.Popen(
1305 cmd,
1306 stdout=subprocess.PIPE,
1307 stdin=subprocess.PIPE,
1308 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001309 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001310 ) as proc:
1311 stdout, stderr = proc.communicate(str.encode(commands))
1312 stdout = stdout and bytes.decode(stdout)
1313 stderr = stderr and bytes.decode(stderr)
1314 return stdout, stderr
1315
1316 def run_pdb_script(self, script, commands):
Senthil Kumaran42d70812012-05-01 10:07:49 +08001317 """Run 'script' lines with pdb and the pdb 'commands'."""
1318 filename = 'main.py'
1319 with open(filename, 'w') as f:
1320 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001321 self.addCleanup(os_helper.unlink, filename)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001322 return self._run_pdb([filename], commands)
1323
1324 def run_pdb_module(self, script, commands):
1325 """Runs the script code as part of a module"""
1326 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001327 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001328 main_file = self.module_name + '/__main__.py'
1329 init_file = self.module_name + '/__init__.py'
1330 os.mkdir(self.module_name)
1331 with open(init_file, 'w') as f:
1332 pass
1333 with open(main_file, 'w') as f:
1334 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001335 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001336 return self._run_pdb(['-m', self.module_name], commands)
Senthil Kumaran42d70812012-05-01 10:07:49 +08001337
Georg Brandl6e220552013-10-13 20:51:47 +02001338 def _assert_find_function(self, file_content, func_name, expected):
Hai Shi604bba12020-08-04 23:51:43 +08001339 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6e220552013-10-13 20:51:47 +02001340 f.write(file_content)
1341
1342 expected = None if not expected else (
Hai Shi604bba12020-08-04 23:51:43 +08001343 expected[0], os_helper.TESTFN, expected[1])
Georg Brandl6e220552013-10-13 20:51:47 +02001344 self.assertEqual(
Hai Shi604bba12020-08-04 23:51:43 +08001345 expected, pdb.find_function(func_name, os_helper.TESTFN))
Georg Brandl6e220552013-10-13 20:51:47 +02001346
1347 def test_find_function_empty_file(self):
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001348 self._assert_find_function(b'', 'foo', None)
Georg Brandl6e220552013-10-13 20:51:47 +02001349
1350 def test_find_function_found(self):
1351 self._assert_find_function(
1352 """\
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001353def foo():
1354 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001355
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001356def bœr():
1357 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001358
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001359def quux():
1360 pass
1361""".encode(),
1362 'bœr',
1363 ('bœr', 4),
1364 )
1365
1366 def test_find_function_found_with_encoding_cookie(self):
1367 self._assert_find_function(
1368 """\
1369# coding: iso-8859-15
1370def foo():
1371 pass
1372
1373def bœr():
1374 pass
1375
1376def quux():
1377 pass
1378""".encode('iso-8859-15'),
1379 'bœr',
1380 ('bœr', 5),
1381 )
1382
1383 def test_find_function_found_with_bom(self):
1384 self._assert_find_function(
1385 codecs.BOM_UTF8 + """\
1386def bœr():
1387 pass
1388""".encode(),
1389 'bœr',
1390 ('bœr', 1),
Georg Brandl6e220552013-10-13 20:51:47 +02001391 )
1392
Georg Brandl6cccb862010-07-30 14:16:43 +00001393 def test_issue7964(self):
1394 # open the file as binary so we can force \r\n newline
Hai Shi604bba12020-08-04 23:51:43 +08001395 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6cccb862010-07-30 14:16:43 +00001396 f.write(b'print("testing my pdb")\r\n')
Hai Shi604bba12020-08-04 23:51:43 +08001397 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
Georg Brandl6cccb862010-07-30 14:16:43 +00001398 proc = subprocess.Popen(cmd,
1399 stdout=subprocess.PIPE,
1400 stdin=subprocess.PIPE,
1401 stderr=subprocess.STDOUT,
1402 )
Brian Curtin994ad6c2010-11-05 15:38:47 +00001403 self.addCleanup(proc.stdout.close)
Georg Brandl6cccb862010-07-30 14:16:43 +00001404 stdout, stderr = proc.communicate(b'quit\n')
1405 self.assertNotIn(b'SyntaxError', stdout,
1406 "Got a syntax error running test script under PDB")
1407
Senthil Kumaran42d70812012-05-01 10:07:49 +08001408 def test_issue13183(self):
1409 script = """
1410 from bar import bar
1411
1412 def foo():
1413 bar()
1414
1415 def nope():
1416 pass
1417
1418 def foobar():
1419 foo()
1420 nope()
1421
1422 foobar()
1423 """
1424 commands = """
1425 from bar import bar
1426 break bar
1427 continue
1428 step
1429 step
1430 quit
1431 """
1432 bar = """
1433 def bar():
Senthil Kumarancb172042012-05-02 08:00:22 +08001434 pass
Senthil Kumaran42d70812012-05-01 10:07:49 +08001435 """
1436 with open('bar.py', 'w') as f:
1437 f.write(textwrap.dedent(bar))
Hai Shi604bba12020-08-04 23:51:43 +08001438 self.addCleanup(os_helper.unlink, 'bar.py')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001439 stdout, stderr = self.run_pdb_script(script, commands)
Georg Brandl4bde9ca2012-05-01 09:21:16 +02001440 self.assertTrue(
1441 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1442 'Fail to step into the caller after a return')
Senthil Kumaran42d70812012-05-01 10:07:49 +08001443
Daniel Hahler9139f922019-04-01 23:59:50 +02001444 def test_issue13120(self):
1445 # Invoking "continue" on a non-main thread triggered an exception
1446 # inside signal.signal.
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001447
Hai Shi604bba12020-08-04 23:51:43 +08001448 with open(os_helper.TESTFN, 'wb') as f:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001449 f.write(textwrap.dedent("""
1450 import threading
1451 import pdb
1452
1453 def start_pdb():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001454 pdb.Pdb(readrc=False).set_trace()
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001455 x = 1
1456 y = 1
1457
1458 t = threading.Thread(target=start_pdb)
1459 t.start()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001460 cmd = [sys.executable, '-u', os_helper.TESTFN]
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001461 proc = subprocess.Popen(cmd,
1462 stdout=subprocess.PIPE,
1463 stdin=subprocess.PIPE,
1464 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001465 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001466 )
1467 self.addCleanup(proc.stdout.close)
1468 stdout, stderr = proc.communicate(b'cont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001469 self.assertNotIn(b'Error', stdout,
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001470 "Got an error running test script under PDB")
1471
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001472 def test_issue36250(self):
1473
Hai Shi604bba12020-08-04 23:51:43 +08001474 with open(os_helper.TESTFN, 'wb') as f:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001475 f.write(textwrap.dedent("""
1476 import threading
1477 import pdb
1478
1479 evt = threading.Event()
1480
1481 def start_pdb():
1482 evt.wait()
1483 pdb.Pdb(readrc=False).set_trace()
1484
1485 t = threading.Thread(target=start_pdb)
1486 t.start()
1487 pdb.Pdb(readrc=False).set_trace()
1488 evt.set()
1489 t.join()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001490 cmd = [sys.executable, '-u', os_helper.TESTFN]
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001491 proc = subprocess.Popen(cmd,
1492 stdout=subprocess.PIPE,
1493 stdin=subprocess.PIPE,
1494 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001495 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001496 )
1497 self.addCleanup(proc.stdout.close)
1498 stdout, stderr = proc.communicate(b'cont\ncont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001499 self.assertNotIn(b'Error', stdout,
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001500 "Got an error running test script under PDB")
1501
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001502 def test_issue16180(self):
1503 # A syntax error in the debuggee.
1504 script = "def f: pass\n"
1505 commands = ''
1506 expected = "SyntaxError:"
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001507 stdout, stderr = self.run_pdb_script(script, commands)
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001508 self.assertIn(expected, stdout,
1509 '\n\nExpected:\n{}\nGot:\n{}\n'
1510 'Fail to handle a syntax error in the debuggee.'
1511 .format(expected, stdout))
1512
Irit Katriel652bfde2021-04-01 16:25:59 +01001513 def test_issue26053(self):
1514 # run command of pdb prompt echoes the correct args
1515 script = "print('hello')"
1516 commands = """
1517 continue
1518 run a b c
1519 run d e f
1520 quit
1521 """
1522 stdout, stderr = self.run_pdb_script(script, commands)
Irit Katrielbd4ab8e2021-04-01 20:05:51 +01001523 res = '\n'.join([x.strip() for x in stdout.splitlines()])
1524 self.assertRegex(res, "Restarting .* with arguments:\na b c")
1525 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001526
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001527 def test_readrc_kwarg(self):
Victor Stinner11ea0442016-09-09 22:56:54 -07001528 script = textwrap.dedent("""
1529 import pdb; pdb.Pdb(readrc=False).set_trace()
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001530
Victor Stinner11ea0442016-09-09 22:56:54 -07001531 print('hello')
1532 """)
Victor Stinner11ea0442016-09-09 22:56:54 -07001533
Victor Stinnerbc626262016-09-09 23:22:09 -07001534 save_home = os.environ.pop('HOME', None)
1535 try:
Hai Shi604bba12020-08-04 23:51:43 +08001536 with os_helper.temp_cwd():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001537 with open('.pdbrc', 'w') as f:
1538 f.write("invalid\n")
1539
1540 with open('main.py', 'w') as f:
1541 f.write(script)
1542
1543 cmd = [sys.executable, 'main.py']
1544 proc = subprocess.Popen(
1545 cmd,
1546 stdout=subprocess.PIPE,
1547 stdin=subprocess.PIPE,
1548 stderr=subprocess.PIPE,
1549 )
Victor Stinnerbc626262016-09-09 23:22:09 -07001550 with proc:
1551 stdout, stderr = proc.communicate(b'q\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001552 self.assertNotIn(b"NameError: name 'invalid' is not defined",
1553 stdout)
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001554
1555 finally:
Victor Stinner11ea0442016-09-09 22:56:54 -07001556 if save_home is not None:
1557 os.environ['HOME'] = save_home
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001558
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001559 def test_readrc_homedir(self):
1560 save_home = os.environ.pop("HOME", None)
Hai Shi604bba12020-08-04 23:51:43 +08001561 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001562 rc_path = os.path.join(temp_dir, ".pdbrc")
1563 os.path.expanduser.return_value = rc_path
1564 try:
1565 with open(rc_path, "w") as f:
1566 f.write("invalid")
1567 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1568 finally:
1569 if save_home is not None:
1570 os.environ["HOME"] = save_home
1571
Barry Warsaw35425d62017-09-22 12:29:42 -04001572 def test_header(self):
1573 stdout = StringIO()
1574 header = 'Nobody expects... blah, blah, blah'
1575 with ExitStack() as resources:
1576 resources.enter_context(patch('sys.stdout', stdout))
1577 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1578 pdb.set_trace(header=header)
1579 self.assertEqual(stdout.getvalue(), header + '\n')
1580
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001581 def test_run_module(self):
1582 script = """print("SUCCESS")"""
1583 commands = """
1584 continue
1585 quit
1586 """
1587 stdout, stderr = self.run_pdb_module(script, commands)
1588 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1589
1590 def test_module_is_run_as_main(self):
1591 script = """
1592 if __name__ == '__main__':
1593 print("SUCCESS")
1594 """
1595 commands = """
1596 continue
1597 quit
1598 """
1599 stdout, stderr = self.run_pdb_module(script, commands)
1600 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1601
1602 def test_breakpoint(self):
1603 script = """
1604 if __name__ == '__main__':
1605 pass
1606 print("SUCCESS")
1607 pass
1608 """
1609 commands = """
1610 b 3
1611 quit
1612 """
1613 stdout, stderr = self.run_pdb_module(script, commands)
1614 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1615 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1616
1617 def test_run_pdb_with_pdb(self):
1618 commands = """
1619 c
1620 quit
1621 """
1622 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001623 self.assertIn(
1624 pdb._usage,
1625 stdout.replace('\r', '') # remove \r for windows
1626 )
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001627
1628 def test_module_without_a_main(self):
1629 module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001630 os_helper.rmtree(module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001631 init_file = module_name + '/__init__.py'
1632 os.mkdir(module_name)
1633 with open(init_file, 'w') as f:
1634 pass
Hai Shi604bba12020-08-04 23:51:43 +08001635 self.addCleanup(os_helper.rmtree, module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001636 stdout, stderr = self._run_pdb(['-m', module_name], "")
1637 self.assertIn("ImportError: No module named t_main.__main__",
1638 stdout.splitlines())
1639
1640 def test_blocks_at_first_code_line(self):
1641 script = """
1642 #This is a comment, on line 2
1643
1644 print("SUCCESS")
1645 """
1646 commands = """
1647 quit
1648 """
1649 stdout, stderr = self.run_pdb_module(script, commands)
1650 self.assertTrue(any("__main__.py(4)<module>()"
1651 in l for l in stdout.splitlines()), stdout)
1652
1653 def test_relative_imports(self):
1654 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001655 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001656 main_file = self.module_name + '/__main__.py'
1657 init_file = self.module_name + '/__init__.py'
1658 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001659 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001660 os.mkdir(self.module_name)
1661 with open(init_file, 'w') as f:
1662 f.write(textwrap.dedent("""
1663 top_var = "VAR from top"
1664 """))
1665 with open(main_file, 'w') as f:
1666 f.write(textwrap.dedent("""
1667 from . import top_var
1668 from .module import var
1669 from . import module
1670 pass # We'll stop here and print the vars
1671 """))
1672 with open(module_file, 'w') as f:
1673 f.write(textwrap.dedent("""
1674 var = "VAR from module"
1675 var2 = "second var"
1676 """))
1677 commands = """
1678 b 5
1679 c
1680 p top_var
1681 p var
1682 p module.var2
1683 quit
1684 """
1685 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
Mario Corchero38bfa842018-02-03 06:40:11 +00001686 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001687 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1688 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Georg Brandl6cccb862010-07-30 14:16:43 +00001689
Mario Corchero38bfa842018-02-03 06:40:11 +00001690 def test_relative_imports_on_plain_module(self):
1691 # Validates running a plain module. See bpo32691
1692 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001693 os_helper.rmtree(self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001694 main_file = self.module_name + '/runme.py'
1695 init_file = self.module_name + '/__init__.py'
1696 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001697 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001698 os.mkdir(self.module_name)
1699 with open(init_file, 'w') as f:
1700 f.write(textwrap.dedent("""
1701 top_var = "VAR from top"
1702 """))
1703 with open(main_file, 'w') as f:
1704 f.write(textwrap.dedent("""
1705 from . import module
1706 pass # We'll stop here and print the vars
1707 """))
1708 with open(module_file, 'w') as f:
1709 f.write(textwrap.dedent("""
1710 var = "VAR from module"
1711 """))
1712 commands = """
1713 b 3
1714 c
1715 p module.var
1716 quit
1717 """
1718 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1719 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1720
Daniel Hahler3e936432019-03-12 04:29:04 +01001721 def test_errors_in_command(self):
1722 commands = "\n".join([
1723 'print(',
1724 'debug print(',
1725 'debug doesnotexist',
1726 'c',
1727 ])
Mark Shannon877df852020-11-12 09:43:29 +00001728 stdout, _ = self.run_pdb_script('pass', commands + '\n')
Daniel Hahler3e936432019-03-12 04:29:04 +01001729
Daniel Hahler43277052019-02-15 21:52:53 +01001730 self.assertEqual(stdout.splitlines()[1:], [
Mark Shannon877df852020-11-12 09:43:29 +00001731 '-> pass',
Pablo Galindod6d63712021-01-19 23:59:33 +00001732 '(Pdb) *** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001733
1734 '(Pdb) ENTERING RECURSIVE DEBUGGER',
Pablo Galindod6d63712021-01-19 23:59:33 +00001735 '*** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001736 'LEAVING RECURSIVE DEBUGGER',
1737
1738 '(Pdb) ENTERING RECURSIVE DEBUGGER',
1739 '> <string>(1)<module>()',
1740 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1741 'LEAVING RECURSIVE DEBUGGER',
Daniel Hahler43277052019-02-15 21:52:53 +01001742 '(Pdb) ',
1743 ])
Georg Brandl6cccb862010-07-30 14:16:43 +00001744
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001745
1746 def test_issue42384(self):
1747 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1748 script = textwrap.dedent("""
1749 import sys
1750 print('sys.path[0] is', sys.path[0])
1751 """)
1752 commands = 'c\nq'
1753
1754 with os_helper.temp_cwd() as cwd:
1755 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1756
1757 stdout, stderr = self.run_pdb_script(script, commands)
1758
1759 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1760
1761 @os_helper.skip_unless_symlink
1762 def test_issue42384_symlink(self):
1763 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1764 script = textwrap.dedent("""
1765 import sys
1766 print('sys.path[0] is', sys.path[0])
1767 """)
1768 commands = 'c\nq'
1769
1770 with os_helper.temp_cwd() as cwd:
1771 cwd = os.path.realpath(cwd)
1772 dir_one = os.path.join(cwd, 'dir_one')
1773 dir_two = os.path.join(cwd, 'dir_two')
1774 expected = f'(Pdb) sys.path[0] is {dir_one}'
1775
1776 os.mkdir(dir_one)
1777 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1778 f.write(script)
1779 os.mkdir(dir_two)
1780 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1781
1782 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1783
1784 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1785
Andrey Bienkowski501d4a52021-01-25 21:08:01 +00001786 def test_issue42383(self):
1787 with os_helper.temp_cwd() as cwd:
1788 with open('foo.py', 'w') as f:
1789 s = textwrap.dedent("""
1790 print('The correct file was executed')
1791
1792 import os
1793 os.chdir("subdir")
1794 """)
1795 f.write(s)
1796
1797 subdir = os.path.join(cwd, 'subdir')
1798 os.mkdir(subdir)
1799 os.mkdir(os.path.join(subdir, 'subdir'))
1800 wrong_file = os.path.join(subdir, 'foo.py')
1801
1802 with open(wrong_file, 'w') as f:
1803 f.write('print("The wrong file was executed")')
1804
1805 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
1806 expected = '(Pdb) The correct file was executed'
1807 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
1808
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001809
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001810def load_tests(*args):
Georg Brandl243ad662009-05-05 09:00:19 +00001811 from test import test_pdb
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001812 suites = [
1813 unittest.makeSuite(PdbTestCase),
1814 doctest.DocTestSuite(test_pdb)
1815 ]
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001816 return unittest.TestSuite(suites)
Georg Brandl243ad662009-05-05 09:00:19 +00001817
1818
1819if __name__ == '__main__':
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001820 unittest.main()