blob: f944acd69204369e36588d4182041f5cbf31b03e [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
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -070012import linecache
Georg Brandl243ad662009-05-05 09:00:19 +000013
Barry Warsaw35425d62017-09-22 12:29:42 -040014from contextlib import ExitStack
15from io import StringIO
Hai Shi604bba12020-08-04 23:51:43 +080016from test.support import os_helper
Georg Brandl243ad662009-05-05 09:00:19 +000017# This little helper class is essential for testing pdb under doctest.
18from test.test_doctest import _FakeInput
Barry Warsaw35425d62017-09-22 12:29:42 -040019from unittest.mock import patch
Georg Brandl243ad662009-05-05 09:00:19 +000020
21
Georg Brandl9fa2e022009-09-16 16:40:45 +000022class PdbTestInput(object):
23 """Context manager that makes testing Pdb in doctests easier."""
24
25 def __init__(self, input):
26 self.input = input
27
28 def __enter__(self):
29 self.real_stdin = sys.stdin
30 sys.stdin = _FakeInput(self.input)
Brett Cannon31f59292011-02-21 19:29:56 +000031 self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
Georg Brandl9fa2e022009-09-16 16:40:45 +000032
33 def __exit__(self, *exc):
34 sys.stdin = self.real_stdin
Brett Cannon31f59292011-02-21 19:29:56 +000035 if self.orig_trace:
36 sys.settrace(self.orig_trace)
Georg Brandl9fa2e022009-09-16 16:40:45 +000037
38
39def test_pdb_displayhook():
40 """This tests the custom displayhook for pdb.
41
42 >>> def test_function(foo, bar):
Łukasz Langa2eb6eca2016-09-09 22:21:17 -070043 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl9fa2e022009-09-16 16:40:45 +000044 ... pass
45
46 >>> with PdbTestInput([
47 ... 'foo',
48 ... 'bar',
49 ... 'for i in range(5): print(i)',
50 ... 'continue',
51 ... ]):
52 ... test_function(1, None)
53 > <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function()
54 -> pass
55 (Pdb) foo
56 1
57 (Pdb) bar
58 (Pdb) for i in range(5): print(i)
59 0
60 1
61 2
62 3
63 4
64 (Pdb) continue
65 """
66
67
Georg Brandl0d089622010-07-30 16:00:46 +000068def test_pdb_basic_commands():
69 """Test the basic commands of pdb.
70
71 >>> def test_function_2(foo, bar='default'):
72 ... print(foo)
73 ... for i in range(5):
74 ... print(i)
75 ... print(bar)
76 ... for i in range(10):
77 ... never_executed
78 ... print('after for')
79 ... print('...')
80 ... return foo.upper()
81
Rémi Lapeyrebf457c72019-05-21 00:17:30 +020082 >>> def test_function3(arg=None, *, kwonly=None):
83 ... pass
84
Rémi Lapeyre45856032019-05-24 22:44:31 +020085 >>> def test_function4(a, b, c, /):
86 ... pass
87
Georg Brandl0d089622010-07-30 16:00:46 +000088 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -070089 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0d089622010-07-30 16:00:46 +000090 ... ret = test_function_2('baz')
Rémi Lapeyrebf457c72019-05-21 00:17:30 +020091 ... test_function3(kwonly=True)
Rémi Lapeyre45856032019-05-24 22:44:31 +020092 ... test_function4(1, 2, 3)
Georg Brandl0d089622010-07-30 16:00:46 +000093 ... print(ret)
94
95 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
96 ... 'step', # entering the function call
97 ... 'args', # display function args
98 ... 'list', # list function source
99 ... 'bt', # display backtrace
100 ... 'up', # step up to test_function()
101 ... 'down', # step down to test_function_2() again
102 ... 'next', # stepping to print(foo)
103 ... 'next', # stepping to the for loop
104 ... 'step', # stepping into the for loop
105 ... 'until', # continuing until out of the for loop
106 ... 'next', # executing the print(bar)
107 ... 'jump 8', # jump over second for loop
108 ... 'return', # return out of function
109 ... 'retval', # display return value
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200110 ... 'next', # step to test_function3()
111 ... 'step', # stepping into test_function3()
112 ... 'args', # display function args
Rémi Lapeyre45856032019-05-24 22:44:31 +0200113 ... 'return', # return out of function
114 ... 'next', # step to test_function4()
115 ... 'step', # stepping to test_function4()
116 ... 'args', # display function args
Georg Brandl0d089622010-07-30 16:00:46 +0000117 ... 'continue',
118 ... ]):
119 ... test_function()
Rémi Lapeyre45856032019-05-24 22:44:31 +0200120 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000121 -> ret = test_function_2('baz')
122 (Pdb) step
123 --Call--
124 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
125 -> def test_function_2(foo, bar='default'):
126 (Pdb) args
127 foo = 'baz'
128 bar = 'default'
129 (Pdb) list
130 1 -> def test_function_2(foo, bar='default'):
131 2 print(foo)
132 3 for i in range(5):
133 4 print(i)
134 5 print(bar)
135 6 for i in range(10):
136 7 never_executed
137 8 print('after for')
138 9 print('...')
139 10 return foo.upper()
140 [EOF]
141 (Pdb) bt
142 ...
Rémi Lapeyre45856032019-05-24 22:44:31 +0200143 <doctest test.test_pdb.test_pdb_basic_commands[4]>(25)<module>()
Georg Brandl0d089622010-07-30 16:00:46 +0000144 -> test_function()
Rémi Lapeyre45856032019-05-24 22:44:31 +0200145 <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000146 -> ret = test_function_2('baz')
147 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
148 -> def test_function_2(foo, bar='default'):
149 (Pdb) up
Rémi Lapeyre45856032019-05-24 22:44:31 +0200150 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
Georg Brandl0d089622010-07-30 16:00:46 +0000151 -> ret = test_function_2('baz')
152 (Pdb) down
153 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
154 -> def test_function_2(foo, bar='default'):
155 (Pdb) next
156 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
157 -> print(foo)
158 (Pdb) next
159 baz
160 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
161 -> for i in range(5):
162 (Pdb) step
163 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
164 -> print(i)
165 (Pdb) until
166 0
167 1
168 2
169 3
170 4
171 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
172 -> print(bar)
173 (Pdb) next
174 default
175 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
176 -> for i in range(10):
177 (Pdb) jump 8
178 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
179 -> print('after for')
180 (Pdb) return
181 after for
182 ...
183 --Return--
184 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
185 -> return foo.upper()
186 (Pdb) retval
187 'BAZ'
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200188 (Pdb) next
Rémi Lapeyre45856032019-05-24 22:44:31 +0200189 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(4)test_function()
Rémi Lapeyrebf457c72019-05-21 00:17:30 +0200190 -> test_function3(kwonly=True)
191 (Pdb) step
192 --Call--
193 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(1)test_function3()
194 -> def test_function3(arg=None, *, kwonly=None):
195 (Pdb) args
196 arg = None
197 kwonly = True
Rémi Lapeyre45856032019-05-24 22:44:31 +0200198 (Pdb) return
199 --Return--
200 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(2)test_function3()->None
201 -> pass
202 (Pdb) next
203 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(5)test_function()
204 -> test_function4(1, 2, 3)
205 (Pdb) step
206 --Call--
207 > <doctest test.test_pdb.test_pdb_basic_commands[2]>(1)test_function4()
208 -> def test_function4(a, b, c, /):
209 (Pdb) args
210 a = 1
211 b = 2
212 c = 3
Georg Brandl0d089622010-07-30 16:00:46 +0000213 (Pdb) continue
214 BAZ
215 """
216
Irit Katrielad442a62021-04-02 17:15:21 +0100217def reset_Breakpoint():
218 import bdb
219 bdb.Breakpoint.clearBreakpoints()
Georg Brandl0d089622010-07-30 16:00:46 +0000220
221def test_pdb_breakpoint_commands():
222 """Test basic commands related to breakpoints.
223
224 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700225 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0d089622010-07-30 16:00:46 +0000226 ... print(1)
227 ... print(2)
228 ... print(3)
229 ... print(4)
230
231 First, need to clear bdb state that might be left over from previous tests.
232 Otherwise, the new breakpoints might get assigned different numbers.
233
Irit Katrielad442a62021-04-02 17:15:21 +0100234 >>> reset_Breakpoint()
Georg Brandl0d089622010-07-30 16:00:46 +0000235
236 Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because
237 the breakpoint list outputs a tab for the "stop only" and "ignore next"
238 lines, which we don't want to put in here.
239
240 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
241 ... 'break 3',
242 ... 'disable 1',
243 ... 'ignore 1 10',
244 ... 'condition 1 1 < 2',
245 ... 'break 4',
Senthil Kumaran6f107042010-11-29 11:54:17 +0000246 ... 'break 4',
247 ... 'break',
248 ... 'clear 3',
Georg Brandl0d089622010-07-30 16:00:46 +0000249 ... 'break',
250 ... 'condition 1',
251 ... 'enable 1',
252 ... 'clear 1',
253 ... 'commands 2',
R David Murray78d692f2013-10-10 17:23:26 -0400254 ... 'p "42"',
255 ... 'print("42", 7*6)', # Issue 18764 (not about breakpoints)
Georg Brandl0d089622010-07-30 16:00:46 +0000256 ... 'end',
257 ... 'continue', # will stop at breakpoint 2 (line 4)
258 ... 'clear', # clear all!
259 ... 'y',
260 ... 'tbreak 5',
261 ... 'continue', # will stop at temporary breakpoint
262 ... 'break', # make sure breakpoint is gone
263 ... 'continue',
264 ... ]):
265 ... test_function()
266 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
267 -> print(1)
268 (Pdb) break 3
269 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
270 (Pdb) disable 1
271 Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
272 (Pdb) ignore 1 10
273 Will ignore next 10 crossings of breakpoint 1.
274 (Pdb) condition 1 1 < 2
275 New condition set for breakpoint 1.
276 (Pdb) break 4
277 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
Senthil Kumaran6f107042010-11-29 11:54:17 +0000278 (Pdb) break 4
279 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
280 (Pdb) break
281 Num Type Disp Enb Where
282 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
283 stop only if 1 < 2
284 ignore next 10 hits
285 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
286 3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
287 (Pdb) clear 3
288 Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
Georg Brandl0d089622010-07-30 16:00:46 +0000289 (Pdb) break
290 Num Type Disp Enb Where
291 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
292 stop only if 1 < 2
293 ignore next 10 hits
294 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
295 (Pdb) condition 1
296 Breakpoint 1 is now unconditional.
297 (Pdb) enable 1
298 Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
299 (Pdb) clear 1
300 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
301 (Pdb) commands 2
R David Murray78d692f2013-10-10 17:23:26 -0400302 (com) p "42"
303 (com) print("42", 7*6)
Georg Brandl0d089622010-07-30 16:00:46 +0000304 (com) end
305 (Pdb) continue
306 1
R David Murray78d692f2013-10-10 17:23:26 -0400307 '42'
308 42 42
Georg Brandl0d089622010-07-30 16:00:46 +0000309 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
310 -> print(2)
311 (Pdb) clear
312 Clear all breaks? y
313 Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
314 (Pdb) tbreak 5
Senthil Kumaran6f107042010-11-29 11:54:17 +0000315 Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
Georg Brandl0d089622010-07-30 16:00:46 +0000316 (Pdb) continue
317 2
Senthil Kumaran6f107042010-11-29 11:54:17 +0000318 Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
Georg Brandl0d089622010-07-30 16:00:46 +0000319 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
320 -> print(3)
321 (Pdb) break
322 (Pdb) continue
323 3
324 4
325 """
326
Irit Katrielad442a62021-04-02 17:15:21 +0100327def test_pdb_breakpoints_preserved_across_interactive_sessions():
328 """Breakpoints are remembered between interactive sessions
329
330 >>> reset_Breakpoint()
331 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
332 ... 'import test.test_pdb',
333 ... 'break test.test_pdb.do_something',
334 ... 'break test.test_pdb.do_nothing',
335 ... 'break',
336 ... 'continue',
337 ... ]):
338 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100339 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100340 (Pdb) import test.test_pdb
341 (Pdb) break test.test_pdb.do_something
342 Breakpoint 1 at ...test_pdb.py:...
343 (Pdb) break test.test_pdb.do_nothing
344 Breakpoint 2 at ...test_pdb.py:...
345 (Pdb) break
346 Num Type Disp Enb Where
347 1 breakpoint keep yes at ...test_pdb.py:...
348 2 breakpoint keep yes at ...test_pdb.py:...
349 (Pdb) continue
350
351 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
352 ... 'break',
353 ... 'break pdb.find_function',
354 ... 'break',
355 ... 'clear 1',
356 ... 'continue',
357 ... ]):
358 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100359 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100360 (Pdb) break
361 Num Type Disp Enb Where
362 1 breakpoint keep yes at ...test_pdb.py:...
363 2 breakpoint keep yes at ...test_pdb.py:...
364 (Pdb) break pdb.find_function
365 Breakpoint 3 at ...pdb.py:94
366 (Pdb) break
367 Num Type Disp Enb Where
368 1 breakpoint keep yes at ...test_pdb.py:...
369 2 breakpoint keep yes at ...test_pdb.py:...
370 3 breakpoint keep yes at ...pdb.py:...
371 (Pdb) clear 1
372 Deleted breakpoint 1 at ...test_pdb.py:...
373 (Pdb) continue
374
375 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
376 ... 'break',
377 ... 'clear 2',
378 ... 'clear 3',
379 ... 'continue',
380 ... ]):
381 ... pdb.run('print()')
Irit Katrielaadd4e12021-04-04 16:04:53 +0100382 > <string>(1)<module>()...
Irit Katrielad442a62021-04-02 17:15:21 +0100383 (Pdb) break
384 Num Type Disp Enb Where
385 2 breakpoint keep yes at ...test_pdb.py:...
386 3 breakpoint keep yes at ...pdb.py:...
387 (Pdb) clear 2
388 Deleted breakpoint 2 at ...test_pdb.py:...
389 (Pdb) clear 3
390 Deleted breakpoint 3 at ...pdb.py:...
391 (Pdb) continue
392 """
Georg Brandl0d089622010-07-30 16:00:46 +0000393
Miss Islington (bot)e3bc32f2021-06-10 13:56:57 -0700394def test_pdb_pp_repr_exc():
395 """Test that do_p/do_pp do not swallow exceptions.
396
397 >>> class BadRepr:
398 ... def __repr__(self):
399 ... raise Exception('repr_exc')
400 >>> obj = BadRepr()
401
402 >>> def test_function():
403 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
404
405 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
406 ... 'p obj',
407 ... 'pp obj',
408 ... 'continue',
409 ... ]):
410 ... test_function()
411 --Return--
412 > <doctest test.test_pdb.test_pdb_pp_repr_exc[2]>(2)test_function()->None
413 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
414 (Pdb) p obj
415 *** Exception: repr_exc
416 (Pdb) pp obj
417 *** Exception: repr_exc
418 (Pdb) continue
419 """
420
421
Georg Brandle59ca2a2010-07-30 17:04:28 +0000422def do_nothing():
423 pass
424
425def do_something():
426 print(42)
427
428def test_list_commands():
429 """Test the list and source commands of pdb.
430
431 >>> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000432 ... import test.test_pdb
433 ... test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000434 ... 'some...'
435 ... 'more...'
436 ... 'code...'
437 ... 'to...'
438 ... 'make...'
439 ... 'a...'
440 ... 'long...'
441 ... 'listing...'
442 ... 'useful...'
443 ... '...'
444 ... '...'
445 ... return foo
446
447 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700448 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000449 ... ret = test_function_2('baz')
450
451 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
452 ... 'list', # list first function
453 ... 'step', # step into second function
454 ... 'list', # list second function
455 ... 'list', # continue listing to EOF
456 ... 'list 1,3', # list specific lines
457 ... 'list x', # invalid argument
458 ... 'next', # step to import
459 ... 'next', # step over import
460 ... 'step', # step into do_nothing
461 ... 'longlist', # list all lines
462 ... 'source do_something', # list all lines of function
Georg Brandlcdf66a92010-07-30 18:15:16 +0000463 ... 'source fooxxx', # something that doesn't exit
Georg Brandle59ca2a2010-07-30 17:04:28 +0000464 ... 'continue',
465 ... ]):
466 ... test_function()
467 > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
468 -> ret = test_function_2('baz')
469 (Pdb) list
470 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700471 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000472 3 -> ret = test_function_2('baz')
473 [EOF]
474 (Pdb) step
475 --Call--
476 > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
477 -> def test_function_2(foo):
478 (Pdb) list
479 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000480 2 import test.test_pdb
481 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000482 4 'some...'
483 5 'more...'
484 6 'code...'
485 7 'to...'
486 8 'make...'
487 9 'a...'
488 10 'long...'
489 11 'listing...'
490 (Pdb) list
491 12 'useful...'
492 13 '...'
493 14 '...'
494 15 return foo
495 [EOF]
496 (Pdb) list 1,3
497 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000498 2 import test.test_pdb
499 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000500 (Pdb) list x
501 *** ...
502 (Pdb) next
503 > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000504 -> import test.test_pdb
Georg Brandle59ca2a2010-07-30 17:04:28 +0000505 (Pdb) next
506 > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000507 -> test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000508 (Pdb) step
509 --Call--
Georg Brandle1e8df12010-07-31 08:14:16 +0000510 > ...test_pdb.py(...)do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000511 -> def do_nothing():
512 (Pdb) longlist
513 ... -> def do_nothing():
514 ... pass
515 (Pdb) source do_something
516 ... def do_something():
517 ... print(42)
Georg Brandlcdf66a92010-07-30 18:15:16 +0000518 (Pdb) source fooxxx
519 *** ...
Georg Brandle59ca2a2010-07-30 17:04:28 +0000520 (Pdb) continue
521 """
522
Irit Katriel022bc752020-08-27 01:51:12 +0100523def test_pdb_whatis_command():
524 """Test the whatis command
525
526 >>> myvar = (1,2)
527 >>> def myfunc():
528 ... pass
529
530 >>> class MyClass:
531 ... def mymethod(self):
532 ... pass
533
534 >>> def test_function():
535 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
536
537 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
538 ... 'whatis myvar',
539 ... 'whatis myfunc',
540 ... 'whatis MyClass',
541 ... 'whatis MyClass()',
542 ... 'whatis MyClass.mymethod',
543 ... 'whatis MyClass().mymethod',
544 ... 'continue',
545 ... ]):
546 ... test_function()
547 --Return--
548 > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()->None
549 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
550 (Pdb) whatis myvar
551 <class 'tuple'>
552 (Pdb) whatis myfunc
553 Function myfunc
554 (Pdb) whatis MyClass
555 Class test.test_pdb.MyClass
556 (Pdb) whatis MyClass()
557 <class 'test.test_pdb.MyClass'>
558 (Pdb) whatis MyClass.mymethod
559 Function mymethod
560 (Pdb) whatis MyClass().mymethod
561 Method mymethod
562 (Pdb) continue
563 """
Georg Brandle59ca2a2010-07-30 17:04:28 +0000564
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000565def test_post_mortem():
566 """Test post mortem traceback debugging.
567
568 >>> def test_function_2():
569 ... try:
570 ... 1/0
571 ... finally:
572 ... print('Exception!')
573
574 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700575 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000576 ... test_function_2()
577 ... print('Not reached.')
578
579 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
580 ... 'next', # step over exception-raising call
581 ... 'bt', # get a backtrace
582 ... 'list', # list code of test_function()
583 ... 'down', # step into test_function_2()
584 ... 'list', # list code of test_function_2()
585 ... 'continue',
586 ... ]):
587 ... try:
588 ... test_function()
589 ... except ZeroDivisionError:
590 ... print('Correctly reraised.')
591 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
592 -> test_function_2()
593 (Pdb) next
594 Exception!
595 ZeroDivisionError: division by zero
596 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
597 -> test_function_2()
598 (Pdb) bt
599 ...
600 <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
601 -> test_function()
602 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
603 -> test_function_2()
604 <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
605 -> 1/0
606 (Pdb) list
607 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700608 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000609 3 -> test_function_2()
610 4 print('Not reached.')
611 [EOF]
612 (Pdb) down
613 > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
614 -> 1/0
615 (Pdb) list
616 1 def test_function_2():
617 2 try:
618 3 >> 1/0
619 4 finally:
620 5 -> print('Exception!')
621 [EOF]
622 (Pdb) continue
623 Correctly reraised.
624 """
625
626
Georg Brandl243ad662009-05-05 09:00:19 +0000627def test_pdb_skip_modules():
628 """This illustrates the simple case of module skipping.
629
630 >>> def skip_module():
631 ... import string
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700632 ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000633 ... string.capwords('FOO')
Georg Brandl243ad662009-05-05 09:00:19 +0000634
Georg Brandl9fa2e022009-09-16 16:40:45 +0000635 >>> with PdbTestInput([
636 ... 'step',
637 ... 'continue',
638 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000639 ... skip_module()
Georg Brandl243ad662009-05-05 09:00:19 +0000640 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
641 -> string.capwords('FOO')
642 (Pdb) step
643 --Return--
644 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
645 -> string.capwords('FOO')
646 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000647 """
Georg Brandl243ad662009-05-05 09:00:19 +0000648
649
650# Module for testing skipping of module that makes a callback
Brett Cannon9529fbf2013-06-15 17:11:25 -0400651mod = types.ModuleType('module_to_skip')
Georg Brandl243ad662009-05-05 09:00:19 +0000652exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
653
654
655def test_pdb_skip_modules_with_callback():
656 """This illustrates skipping of modules that call into other code.
657
658 >>> def skip_module():
659 ... def callback():
660 ... return None
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700661 ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000662 ... mod.foo_pony(callback)
Georg Brandl243ad662009-05-05 09:00:19 +0000663
Georg Brandl9fa2e022009-09-16 16:40:45 +0000664 >>> with PdbTestInput([
665 ... 'step',
666 ... 'step',
667 ... 'step',
668 ... 'step',
669 ... 'step',
670 ... 'continue',
671 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000672 ... skip_module()
Georg Brandl9fa2e022009-09-16 16:40:45 +0000673 ... pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000674 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
675 -> mod.foo_pony(callback)
676 (Pdb) step
677 --Call--
678 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
679 -> def callback():
680 (Pdb) step
681 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
682 -> return None
683 (Pdb) step
684 --Return--
685 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
686 -> return None
687 (Pdb) step
688 --Return--
689 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
690 -> mod.foo_pony(callback)
691 (Pdb) step
Georg Brandl9fa2e022009-09-16 16:40:45 +0000692 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
693 -> pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000694 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000695 """
Georg Brandl243ad662009-05-05 09:00:19 +0000696
697
Georg Brandl3f940892010-07-30 10:29:19 +0000698def test_pdb_continue_in_bottomframe():
699 """Test that "continue" and "next" work properly in bottom frame (issue #5294).
700
701 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700702 ... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
Georg Brandl3f940892010-07-30 10:29:19 +0000703 ... inst.set_trace()
704 ... inst.botframe = sys._getframe() # hackery to get the right botframe
705 ... print(1)
706 ... print(2)
707 ... print(3)
708 ... print(4)
709
Georg Brandl7410dd12010-07-30 12:01:20 +0000710 >>> with PdbTestInput([ # doctest: +ELLIPSIS
Georg Brandl3f940892010-07-30 10:29:19 +0000711 ... 'next',
712 ... 'break 7',
713 ... 'continue',
714 ... 'next',
715 ... 'continue',
716 ... 'continue',
717 ... ]):
718 ... test_function()
719 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
720 -> inst.botframe = sys._getframe() # hackery to get the right botframe
721 (Pdb) next
722 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
723 -> print(1)
724 (Pdb) break 7
Georg Brandl7410dd12010-07-30 12:01:20 +0000725 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
Georg Brandl3f940892010-07-30 10:29:19 +0000726 (Pdb) continue
727 1
728 2
729 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
730 -> print(3)
731 (Pdb) next
732 3
733 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
734 -> print(4)
735 (Pdb) continue
736 4
737 """
738
739
Georg Brandl46b9afc2010-07-30 09:14:20 +0000740def pdb_invoke(method, arg):
741 """Run pdb.method(arg)."""
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700742 getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
Georg Brandl46b9afc2010-07-30 09:14:20 +0000743
744
745def test_pdb_run_with_incorrect_argument():
746 """Testing run and runeval with incorrect first argument.
747
748 >>> pti = PdbTestInput(['continue',])
749 >>> with pti:
750 ... pdb_invoke('run', lambda x: x)
751 Traceback (most recent call last):
752 TypeError: exec() arg 1 must be a string, bytes or code object
753
754 >>> with pti:
755 ... pdb_invoke('runeval', lambda x: x)
756 Traceback (most recent call last):
757 TypeError: eval() arg 1 must be a string, bytes or code object
758 """
759
760
761def test_pdb_run_with_code_object():
762 """Testing run and runeval with code object as a first argument.
763
Georg Brandle1e8df12010-07-31 08:14:16 +0000764 >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
Georg Brandl46b9afc2010-07-30 09:14:20 +0000765 ... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
Georg Brandle1e8df12010-07-31 08:14:16 +0000766 > <string>(1)<module>()...
Georg Brandl46b9afc2010-07-30 09:14:20 +0000767 (Pdb) step
768 --Return--
769 > <string>(1)<module>()->None
770 (Pdb) x
771 1
772 (Pdb) continue
773
774 >>> with PdbTestInput(['x', 'continue']):
775 ... x=0
776 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
777 > <string>(1)<module>()->None
778 (Pdb) x
779 1
780 (Pdb) continue
781 """
782
Guido van Rossum8820c232013-11-21 11:30:06 -0800783def test_next_until_return_at_return_event():
784 """Test that pdb stops after a next/until/return issued at a return debug event.
785
786 >>> def test_function_2():
787 ... x = 1
788 ... x = 2
789
790 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700791 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800792 ... test_function_2()
793 ... test_function_2()
794 ... test_function_2()
795 ... end = 1
796
Irit Katrielad442a62021-04-02 17:15:21 +0100797 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -0800798 >>> with PdbTestInput(['break test_function_2',
799 ... 'continue',
800 ... 'return',
801 ... 'next',
802 ... 'continue',
803 ... 'return',
804 ... 'until',
805 ... 'continue',
806 ... 'return',
807 ... 'return',
808 ... 'continue']):
809 ... test_function()
810 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
811 -> test_function_2()
812 (Pdb) break test_function_2
813 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
814 (Pdb) continue
815 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
816 -> x = 1
817 (Pdb) return
818 --Return--
819 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
820 -> x = 2
821 (Pdb) next
822 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
823 -> test_function_2()
824 (Pdb) continue
825 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
826 -> x = 1
827 (Pdb) return
828 --Return--
829 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
830 -> x = 2
831 (Pdb) until
832 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
833 -> test_function_2()
834 (Pdb) continue
835 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
836 -> x = 1
837 (Pdb) return
838 --Return--
839 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
840 -> x = 2
841 (Pdb) return
842 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
843 -> end = 1
844 (Pdb) continue
845 """
846
847def test_pdb_next_command_for_generator():
848 """Testing skip unwindng stack on yield for generators for "next" command
849
850 >>> def test_gen():
851 ... yield 0
852 ... return 1
853 ... yield 2
854
855 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700856 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800857 ... it = test_gen()
858 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300859 ... if next(it) != 0:
860 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800861 ... next(it)
862 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300863 ... if ex.value != 1:
864 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800865 ... print("finished")
866
867 >>> with PdbTestInput(['step',
868 ... 'step',
869 ... 'step',
870 ... 'next',
871 ... 'next',
872 ... 'step',
873 ... 'step',
874 ... 'continue']):
875 ... test_function()
876 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
877 -> it = test_gen()
878 (Pdb) step
879 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
880 -> try:
881 (Pdb) step
882 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300883 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -0800884 (Pdb) step
885 --Call--
886 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
887 -> def test_gen():
888 (Pdb) next
889 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
890 -> yield 0
891 (Pdb) next
892 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
893 -> return 1
894 (Pdb) step
895 --Return--
896 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
897 -> return 1
898 (Pdb) step
899 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300900 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -0800901 -> next(it)
902 (Pdb) continue
903 finished
904 """
905
Pablo Galindo46877022018-01-29 00:25:05 +0000906def test_pdb_next_command_for_coroutine():
907 """Testing skip unwindng stack on yield for coroutines for "next" command
908
909 >>> import asyncio
910
911 >>> async def test_coro():
912 ... await asyncio.sleep(0)
913 ... await asyncio.sleep(0)
914 ... await asyncio.sleep(0)
915
916 >>> async def test_main():
917 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
918 ... await test_coro()
919
920 >>> def test_function():
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000921 ... loop = asyncio.new_event_loop()
Pablo Galindo46877022018-01-29 00:25:05 +0000922 ... loop.run_until_complete(test_main())
923 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700924 ... asyncio.set_event_loop_policy(None)
Pablo Galindo46877022018-01-29 00:25:05 +0000925 ... print("finished")
926
927 >>> with PdbTestInput(['step',
928 ... 'step',
929 ... 'next',
930 ... 'next',
931 ... 'next',
932 ... 'step',
933 ... 'continue']):
934 ... test_function()
935 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
936 -> await test_coro()
937 (Pdb) step
938 --Call--
939 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
940 -> async def test_coro():
941 (Pdb) step
942 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
943 -> await asyncio.sleep(0)
944 (Pdb) next
945 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
946 -> await asyncio.sleep(0)
947 (Pdb) next
948 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
949 -> await asyncio.sleep(0)
950 (Pdb) next
951 Internal StopIteration
952 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
953 -> await test_coro()
954 (Pdb) step
955 --Return--
956 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
957 -> await test_coro()
958 (Pdb) continue
959 finished
960 """
961
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500962def test_pdb_next_command_for_asyncgen():
963 """Testing skip unwindng stack on yield for coroutines for "next" command
964
965 >>> import asyncio
966
967 >>> async def agen():
968 ... yield 1
969 ... await asyncio.sleep(0)
970 ... yield 2
971
972 >>> async def test_coro():
973 ... async for x in agen():
974 ... print(x)
975
976 >>> async def test_main():
977 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
978 ... await test_coro()
979
980 >>> def test_function():
981 ... loop = asyncio.new_event_loop()
982 ... loop.run_until_complete(test_main())
983 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700984 ... asyncio.set_event_loop_policy(None)
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500985 ... print("finished")
986
987 >>> with PdbTestInput(['step',
988 ... 'step',
989 ... 'next',
990 ... 'next',
991 ... 'step',
992 ... 'next',
993 ... 'continue']):
994 ... test_function()
995 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
996 -> await test_coro()
997 (Pdb) step
998 --Call--
999 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
1000 -> async def test_coro():
1001 (Pdb) step
1002 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
1003 -> async for x in agen():
1004 (Pdb) next
1005 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
1006 -> print(x)
1007 (Pdb) next
1008 1
1009 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
1010 -> async for x in agen():
1011 (Pdb) step
1012 --Call--
1013 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
1014 -> yield 1
1015 (Pdb) next
1016 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
1017 -> await asyncio.sleep(0)
1018 (Pdb) continue
1019 2
1020 finished
1021 """
1022
Guido van Rossum8820c232013-11-21 11:30:06 -08001023def test_pdb_return_command_for_generator():
1024 """Testing no unwindng stack on yield for generators
1025 for "return" command
1026
1027 >>> def test_gen():
1028 ... yield 0
1029 ... return 1
1030 ... yield 2
1031
1032 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001033 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001034 ... it = test_gen()
1035 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001036 ... if next(it) != 0:
1037 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001038 ... next(it)
1039 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001040 ... if ex.value != 1:
1041 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001042 ... print("finished")
1043
1044 >>> with PdbTestInput(['step',
1045 ... 'step',
1046 ... 'step',
1047 ... 'return',
1048 ... 'step',
1049 ... 'step',
1050 ... 'continue']):
1051 ... test_function()
1052 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
1053 -> it = test_gen()
1054 (Pdb) step
1055 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
1056 -> try:
1057 (Pdb) step
1058 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001059 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -08001060 (Pdb) step
1061 --Call--
1062 > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
1063 -> def test_gen():
1064 (Pdb) return
1065 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001066 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001067 -> next(it)
1068 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001069 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001070 -> except StopIteration as ex:
1071 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001072 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
1073 -> if ex.value != 1:
Guido van Rossum8820c232013-11-21 11:30:06 -08001074 (Pdb) continue
1075 finished
1076 """
1077
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001078def test_pdb_return_command_for_coroutine():
1079 """Testing no unwindng stack on yield for coroutines for "return" command
1080
1081 >>> import asyncio
1082
1083 >>> async def test_coro():
1084 ... await asyncio.sleep(0)
1085 ... await asyncio.sleep(0)
1086 ... await asyncio.sleep(0)
1087
1088 >>> async def test_main():
1089 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1090 ... await test_coro()
1091
1092 >>> def test_function():
1093 ... loop = asyncio.new_event_loop()
1094 ... loop.run_until_complete(test_main())
1095 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001096 ... asyncio.set_event_loop_policy(None)
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001097 ... print("finished")
1098
1099 >>> with PdbTestInput(['step',
1100 ... 'step',
1101 ... 'next',
1102 ... 'continue']):
1103 ... test_function()
1104 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
1105 -> await test_coro()
1106 (Pdb) step
1107 --Call--
1108 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
1109 -> async def test_coro():
1110 (Pdb) step
1111 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
1112 -> await asyncio.sleep(0)
1113 (Pdb) next
1114 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
1115 -> await asyncio.sleep(0)
1116 (Pdb) continue
1117 finished
1118 """
1119
Guido van Rossum8820c232013-11-21 11:30:06 -08001120def test_pdb_until_command_for_generator():
1121 """Testing no unwindng stack on yield for generators
Min ho Kimc4cacc82019-07-31 08:16:13 +10001122 for "until" command if target breakpoint is not reached
Guido van Rossum8820c232013-11-21 11:30:06 -08001123
1124 >>> def test_gen():
1125 ... yield 0
1126 ... yield 1
1127 ... yield 2
1128
1129 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001130 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001131 ... for i in test_gen():
1132 ... print(i)
1133 ... print("finished")
1134
1135 >>> with PdbTestInput(['step',
1136 ... 'until 4',
1137 ... 'step',
1138 ... 'step',
1139 ... 'continue']):
1140 ... test_function()
1141 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
1142 -> for i in test_gen():
1143 (Pdb) step
1144 --Call--
1145 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
1146 -> def test_gen():
1147 (Pdb) until 4
1148 0
1149 1
1150 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
1151 -> yield 2
1152 (Pdb) step
1153 --Return--
1154 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
1155 -> yield 2
1156 (Pdb) step
1157 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
1158 -> print(i)
1159 (Pdb) continue
1160 2
1161 finished
1162 """
1163
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001164def test_pdb_until_command_for_coroutine():
1165 """Testing no unwindng stack for coroutines
Min ho Kimc4cacc82019-07-31 08:16:13 +10001166 for "until" command if target breakpoint is not reached
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001167
1168 >>> import asyncio
1169
1170 >>> async def test_coro():
1171 ... print(0)
1172 ... await asyncio.sleep(0)
1173 ... print(1)
1174 ... await asyncio.sleep(0)
1175 ... print(2)
1176 ... await asyncio.sleep(0)
1177 ... print(3)
1178
1179 >>> async def test_main():
1180 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1181 ... await test_coro()
1182
1183 >>> def test_function():
1184 ... loop = asyncio.new_event_loop()
1185 ... loop.run_until_complete(test_main())
1186 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001187 ... asyncio.set_event_loop_policy(None)
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001188 ... print("finished")
1189
1190 >>> with PdbTestInput(['step',
1191 ... 'until 8',
1192 ... 'continue']):
1193 ... test_function()
1194 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
1195 -> await test_coro()
1196 (Pdb) step
1197 --Call--
1198 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
1199 -> async def test_coro():
1200 (Pdb) until 8
1201 0
1202 1
1203 2
1204 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
1205 -> print(3)
1206 (Pdb) continue
1207 3
1208 finished
1209 """
1210
Guido van Rossum8820c232013-11-21 11:30:06 -08001211def test_pdb_next_command_in_generator_for_loop():
Martin Panter46f50722016-05-26 05:35:26 +00001212 """The next command on returning from a generator controlled by a for loop.
Guido van Rossum8820c232013-11-21 11:30:06 -08001213
1214 >>> def test_gen():
1215 ... yield 0
1216 ... return 1
1217
1218 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001219 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001220 ... for i in test_gen():
1221 ... print('value', i)
1222 ... x = 123
1223
Irit Katriel21b02b52021-04-28 11:38:29 +01001224 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -08001225 >>> with PdbTestInput(['break test_gen',
1226 ... 'continue',
1227 ... 'next',
1228 ... 'next',
1229 ... 'next',
1230 ... 'continue']):
1231 ... test_function()
1232 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1233 -> for i in test_gen():
1234 (Pdb) break test_gen
Irit Katrielad442a62021-04-02 17:15:21 +01001235 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 -08001236 (Pdb) continue
1237 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1238 -> yield 0
1239 (Pdb) next
1240 value 0
1241 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1242 -> return 1
1243 (Pdb) next
1244 Internal StopIteration: 1
1245 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1246 -> for i in test_gen():
1247 (Pdb) next
1248 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1249 -> x = 123
1250 (Pdb) continue
1251 """
1252
1253def test_pdb_next_command_subiterator():
1254 """The next command in a generator with a subiterator.
1255
1256 >>> def test_subgenerator():
1257 ... yield 0
1258 ... return 1
1259
1260 >>> def test_gen():
1261 ... x = yield from test_subgenerator()
1262 ... return x
1263
1264 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001265 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001266 ... for i in test_gen():
1267 ... print('value', i)
1268 ... x = 123
1269
1270 >>> with PdbTestInput(['step',
1271 ... 'step',
1272 ... 'next',
1273 ... 'next',
1274 ... 'next',
1275 ... 'continue']):
1276 ... test_function()
1277 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1278 -> for i in test_gen():
1279 (Pdb) step
1280 --Call--
1281 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1282 -> def test_gen():
1283 (Pdb) step
1284 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1285 -> x = yield from test_subgenerator()
1286 (Pdb) next
1287 value 0
1288 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1289 -> return x
1290 (Pdb) next
1291 Internal StopIteration: 1
1292 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1293 -> for i in test_gen():
1294 (Pdb) next
1295 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1296 -> x = 123
1297 (Pdb) continue
1298 """
1299
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001300def test_pdb_issue_20766():
1301 """Test for reference leaks when the SIGINT handler is set.
1302
1303 >>> def test_function():
1304 ... i = 1
1305 ... while i <= 2:
1306 ... sess = pdb.Pdb()
1307 ... sess.set_trace(sys._getframe())
1308 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1309 ... i += 1
1310
Irit Katrielad442a62021-04-02 17:15:21 +01001311 >>> reset_Breakpoint()
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001312 >>> with PdbTestInput(['continue',
1313 ... 'continue']):
1314 ... test_function()
1315 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1316 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1317 (Pdb) continue
1318 pdb 1: <built-in function default_int_handler>
1319 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
1320 -> sess.set_trace(sys._getframe())
1321 (Pdb) continue
1322 pdb 2: <built-in function default_int_handler>
1323 """
Georg Brandl46b9afc2010-07-30 09:14:20 +00001324
Georg Brandl6cccb862010-07-30 14:16:43 +00001325
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001326class PdbTestCase(unittest.TestCase):
1327 def tearDown(self):
Hai Shi604bba12020-08-04 23:51:43 +08001328 os_helper.unlink(os_helper.TESTFN)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001329
1330 def _run_pdb(self, pdb_args, commands):
Hai Shi604bba12020-08-04 23:51:43 +08001331 self.addCleanup(os_helper.rmtree, '__pycache__')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001332 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1333 with subprocess.Popen(
1334 cmd,
1335 stdout=subprocess.PIPE,
1336 stdin=subprocess.PIPE,
1337 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001338 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001339 ) as proc:
1340 stdout, stderr = proc.communicate(str.encode(commands))
1341 stdout = stdout and bytes.decode(stdout)
1342 stderr = stderr and bytes.decode(stderr)
1343 return stdout, stderr
1344
1345 def run_pdb_script(self, script, commands):
Senthil Kumaran42d70812012-05-01 10:07:49 +08001346 """Run 'script' lines with pdb and the pdb 'commands'."""
1347 filename = 'main.py'
1348 with open(filename, 'w') as f:
1349 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001350 self.addCleanup(os_helper.unlink, filename)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001351 return self._run_pdb([filename], commands)
1352
1353 def run_pdb_module(self, script, commands):
1354 """Runs the script code as part of a module"""
1355 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001356 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001357 main_file = self.module_name + '/__main__.py'
1358 init_file = self.module_name + '/__init__.py'
1359 os.mkdir(self.module_name)
1360 with open(init_file, 'w') as f:
1361 pass
1362 with open(main_file, 'w') as f:
1363 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001364 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001365 return self._run_pdb(['-m', self.module_name], commands)
Senthil Kumaran42d70812012-05-01 10:07:49 +08001366
Georg Brandl6e220552013-10-13 20:51:47 +02001367 def _assert_find_function(self, file_content, func_name, expected):
Hai Shi604bba12020-08-04 23:51:43 +08001368 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6e220552013-10-13 20:51:47 +02001369 f.write(file_content)
1370
1371 expected = None if not expected else (
Hai Shi604bba12020-08-04 23:51:43 +08001372 expected[0], os_helper.TESTFN, expected[1])
Georg Brandl6e220552013-10-13 20:51:47 +02001373 self.assertEqual(
Hai Shi604bba12020-08-04 23:51:43 +08001374 expected, pdb.find_function(func_name, os_helper.TESTFN))
Georg Brandl6e220552013-10-13 20:51:47 +02001375
1376 def test_find_function_empty_file(self):
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001377 self._assert_find_function(b'', 'foo', None)
Georg Brandl6e220552013-10-13 20:51:47 +02001378
1379 def test_find_function_found(self):
1380 self._assert_find_function(
1381 """\
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001382def foo():
1383 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001384
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001385def bœr():
1386 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001387
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001388def quux():
1389 pass
1390""".encode(),
1391 'bœr',
1392 ('bœr', 4),
1393 )
1394
1395 def test_find_function_found_with_encoding_cookie(self):
1396 self._assert_find_function(
1397 """\
1398# coding: iso-8859-15
1399def foo():
1400 pass
1401
1402def bœr():
1403 pass
1404
1405def quux():
1406 pass
1407""".encode('iso-8859-15'),
1408 'bœr',
1409 ('bœr', 5),
1410 )
1411
1412 def test_find_function_found_with_bom(self):
1413 self._assert_find_function(
1414 codecs.BOM_UTF8 + """\
1415def bœr():
1416 pass
1417""".encode(),
1418 'bœr',
1419 ('bœr', 1),
Georg Brandl6e220552013-10-13 20:51:47 +02001420 )
1421
Georg Brandl6cccb862010-07-30 14:16:43 +00001422 def test_issue7964(self):
1423 # open the file as binary so we can force \r\n newline
Hai Shi604bba12020-08-04 23:51:43 +08001424 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6cccb862010-07-30 14:16:43 +00001425 f.write(b'print("testing my pdb")\r\n')
Hai Shi604bba12020-08-04 23:51:43 +08001426 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
Georg Brandl6cccb862010-07-30 14:16:43 +00001427 proc = subprocess.Popen(cmd,
1428 stdout=subprocess.PIPE,
1429 stdin=subprocess.PIPE,
1430 stderr=subprocess.STDOUT,
1431 )
Brian Curtin994ad6c2010-11-05 15:38:47 +00001432 self.addCleanup(proc.stdout.close)
Georg Brandl6cccb862010-07-30 14:16:43 +00001433 stdout, stderr = proc.communicate(b'quit\n')
1434 self.assertNotIn(b'SyntaxError', stdout,
1435 "Got a syntax error running test script under PDB")
1436
Senthil Kumaran42d70812012-05-01 10:07:49 +08001437 def test_issue13183(self):
1438 script = """
1439 from bar import bar
1440
1441 def foo():
1442 bar()
1443
1444 def nope():
1445 pass
1446
1447 def foobar():
1448 foo()
1449 nope()
1450
1451 foobar()
1452 """
1453 commands = """
1454 from bar import bar
1455 break bar
1456 continue
1457 step
1458 step
1459 quit
1460 """
1461 bar = """
1462 def bar():
Senthil Kumarancb172042012-05-02 08:00:22 +08001463 pass
Senthil Kumaran42d70812012-05-01 10:07:49 +08001464 """
1465 with open('bar.py', 'w') as f:
1466 f.write(textwrap.dedent(bar))
Hai Shi604bba12020-08-04 23:51:43 +08001467 self.addCleanup(os_helper.unlink, 'bar.py')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001468 stdout, stderr = self.run_pdb_script(script, commands)
Georg Brandl4bde9ca2012-05-01 09:21:16 +02001469 self.assertTrue(
1470 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1471 'Fail to step into the caller after a return')
Senthil Kumaran42d70812012-05-01 10:07:49 +08001472
Daniel Hahler9139f922019-04-01 23:59:50 +02001473 def test_issue13120(self):
1474 # Invoking "continue" on a non-main thread triggered an exception
1475 # inside signal.signal.
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001476
Hai Shi604bba12020-08-04 23:51:43 +08001477 with open(os_helper.TESTFN, 'wb') as f:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001478 f.write(textwrap.dedent("""
1479 import threading
1480 import pdb
1481
1482 def start_pdb():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001483 pdb.Pdb(readrc=False).set_trace()
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001484 x = 1
1485 y = 1
1486
1487 t = threading.Thread(target=start_pdb)
1488 t.start()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001489 cmd = [sys.executable, '-u', os_helper.TESTFN]
Andrew Svetlov539ee5d2012-12-04 21:08:28 +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'}
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001495 )
1496 self.addCleanup(proc.stdout.close)
1497 stdout, stderr = proc.communicate(b'cont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001498 self.assertNotIn(b'Error', stdout,
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001499 "Got an error running test script under PDB")
1500
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001501 def test_issue36250(self):
1502
Hai Shi604bba12020-08-04 23:51:43 +08001503 with open(os_helper.TESTFN, 'wb') as f:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001504 f.write(textwrap.dedent("""
1505 import threading
1506 import pdb
1507
1508 evt = threading.Event()
1509
1510 def start_pdb():
1511 evt.wait()
1512 pdb.Pdb(readrc=False).set_trace()
1513
1514 t = threading.Thread(target=start_pdb)
1515 t.start()
1516 pdb.Pdb(readrc=False).set_trace()
1517 evt.set()
1518 t.join()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001519 cmd = [sys.executable, '-u', os_helper.TESTFN]
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001520 proc = subprocess.Popen(cmd,
1521 stdout=subprocess.PIPE,
1522 stdin=subprocess.PIPE,
1523 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001524 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001525 )
1526 self.addCleanup(proc.stdout.close)
1527 stdout, stderr = proc.communicate(b'cont\ncont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001528 self.assertNotIn(b'Error', stdout,
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001529 "Got an error running test script under PDB")
1530
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001531 def test_issue16180(self):
1532 # A syntax error in the debuggee.
1533 script = "def f: pass\n"
1534 commands = ''
1535 expected = "SyntaxError:"
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001536 stdout, stderr = self.run_pdb_script(script, commands)
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001537 self.assertIn(expected, stdout,
1538 '\n\nExpected:\n{}\nGot:\n{}\n'
1539 'Fail to handle a syntax error in the debuggee.'
1540 .format(expected, stdout))
1541
Irit Katriel652bfde2021-04-01 16:25:59 +01001542 def test_issue26053(self):
1543 # run command of pdb prompt echoes the correct args
1544 script = "print('hello')"
1545 commands = """
1546 continue
1547 run a b c
1548 run d e f
1549 quit
1550 """
1551 stdout, stderr = self.run_pdb_script(script, commands)
Irit Katrielbd4ab8e2021-04-01 20:05:51 +01001552 res = '\n'.join([x.strip() for x in stdout.splitlines()])
1553 self.assertRegex(res, "Restarting .* with arguments:\na b c")
1554 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001555
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001556 def test_readrc_kwarg(self):
Victor Stinner11ea0442016-09-09 22:56:54 -07001557 script = textwrap.dedent("""
1558 import pdb; pdb.Pdb(readrc=False).set_trace()
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001559
Victor Stinner11ea0442016-09-09 22:56:54 -07001560 print('hello')
1561 """)
Victor Stinner11ea0442016-09-09 22:56:54 -07001562
Victor Stinnerbc626262016-09-09 23:22:09 -07001563 save_home = os.environ.pop('HOME', None)
1564 try:
Hai Shi604bba12020-08-04 23:51:43 +08001565 with os_helper.temp_cwd():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001566 with open('.pdbrc', 'w') as f:
1567 f.write("invalid\n")
1568
1569 with open('main.py', 'w') as f:
1570 f.write(script)
1571
1572 cmd = [sys.executable, 'main.py']
1573 proc = subprocess.Popen(
1574 cmd,
1575 stdout=subprocess.PIPE,
1576 stdin=subprocess.PIPE,
1577 stderr=subprocess.PIPE,
1578 )
Victor Stinnerbc626262016-09-09 23:22:09 -07001579 with proc:
1580 stdout, stderr = proc.communicate(b'q\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001581 self.assertNotIn(b"NameError: name 'invalid' is not defined",
1582 stdout)
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001583
1584 finally:
Victor Stinner11ea0442016-09-09 22:56:54 -07001585 if save_home is not None:
1586 os.environ['HOME'] = save_home
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001587
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001588 def test_readrc_homedir(self):
1589 save_home = os.environ.pop("HOME", None)
Hai Shi604bba12020-08-04 23:51:43 +08001590 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001591 rc_path = os.path.join(temp_dir, ".pdbrc")
1592 os.path.expanduser.return_value = rc_path
1593 try:
1594 with open(rc_path, "w") as f:
1595 f.write("invalid")
1596 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1597 finally:
1598 if save_home is not None:
1599 os.environ["HOME"] = save_home
1600
Barry Warsaw35425d62017-09-22 12:29:42 -04001601 def test_header(self):
1602 stdout = StringIO()
1603 header = 'Nobody expects... blah, blah, blah'
1604 with ExitStack() as resources:
1605 resources.enter_context(patch('sys.stdout', stdout))
1606 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1607 pdb.set_trace(header=header)
1608 self.assertEqual(stdout.getvalue(), header + '\n')
1609
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001610 def test_run_module(self):
1611 script = """print("SUCCESS")"""
1612 commands = """
1613 continue
1614 quit
1615 """
1616 stdout, stderr = self.run_pdb_module(script, commands)
1617 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1618
1619 def test_module_is_run_as_main(self):
1620 script = """
1621 if __name__ == '__main__':
1622 print("SUCCESS")
1623 """
1624 commands = """
1625 continue
1626 quit
1627 """
1628 stdout, stderr = self.run_pdb_module(script, commands)
1629 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1630
1631 def test_breakpoint(self):
1632 script = """
1633 if __name__ == '__main__':
1634 pass
1635 print("SUCCESS")
1636 pass
1637 """
1638 commands = """
1639 b 3
1640 quit
1641 """
1642 stdout, stderr = self.run_pdb_module(script, commands)
1643 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1644 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1645
1646 def test_run_pdb_with_pdb(self):
1647 commands = """
1648 c
1649 quit
1650 """
1651 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001652 self.assertIn(
1653 pdb._usage,
1654 stdout.replace('\r', '') # remove \r for windows
1655 )
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001656
1657 def test_module_without_a_main(self):
1658 module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001659 os_helper.rmtree(module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001660 init_file = module_name + '/__init__.py'
1661 os.mkdir(module_name)
1662 with open(init_file, 'w') as f:
1663 pass
Hai Shi604bba12020-08-04 23:51:43 +08001664 self.addCleanup(os_helper.rmtree, module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001665 stdout, stderr = self._run_pdb(['-m', module_name], "")
1666 self.assertIn("ImportError: No module named t_main.__main__",
1667 stdout.splitlines())
1668
1669 def test_blocks_at_first_code_line(self):
1670 script = """
1671 #This is a comment, on line 2
1672
1673 print("SUCCESS")
1674 """
1675 commands = """
1676 quit
1677 """
1678 stdout, stderr = self.run_pdb_module(script, commands)
1679 self.assertTrue(any("__main__.py(4)<module>()"
1680 in l for l in stdout.splitlines()), stdout)
1681
1682 def test_relative_imports(self):
1683 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001684 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001685 main_file = self.module_name + '/__main__.py'
1686 init_file = self.module_name + '/__init__.py'
1687 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001688 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001689 os.mkdir(self.module_name)
1690 with open(init_file, 'w') as f:
1691 f.write(textwrap.dedent("""
1692 top_var = "VAR from top"
1693 """))
1694 with open(main_file, 'w') as f:
1695 f.write(textwrap.dedent("""
1696 from . import top_var
1697 from .module import var
1698 from . import module
1699 pass # We'll stop here and print the vars
1700 """))
1701 with open(module_file, 'w') as f:
1702 f.write(textwrap.dedent("""
1703 var = "VAR from module"
1704 var2 = "second var"
1705 """))
1706 commands = """
1707 b 5
1708 c
1709 p top_var
1710 p var
1711 p module.var2
1712 quit
1713 """
1714 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
Mario Corchero38bfa842018-02-03 06:40:11 +00001715 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001716 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1717 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Georg Brandl6cccb862010-07-30 14:16:43 +00001718
Mario Corchero38bfa842018-02-03 06:40:11 +00001719 def test_relative_imports_on_plain_module(self):
1720 # Validates running a plain module. See bpo32691
1721 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001722 os_helper.rmtree(self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001723 main_file = self.module_name + '/runme.py'
1724 init_file = self.module_name + '/__init__.py'
1725 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001726 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001727 os.mkdir(self.module_name)
1728 with open(init_file, 'w') as f:
1729 f.write(textwrap.dedent("""
1730 top_var = "VAR from top"
1731 """))
1732 with open(main_file, 'w') as f:
1733 f.write(textwrap.dedent("""
1734 from . import module
1735 pass # We'll stop here and print the vars
1736 """))
1737 with open(module_file, 'w') as f:
1738 f.write(textwrap.dedent("""
1739 var = "VAR from module"
1740 """))
1741 commands = """
1742 b 3
1743 c
1744 p module.var
1745 quit
1746 """
1747 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1748 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1749
Daniel Hahler3e936432019-03-12 04:29:04 +01001750 def test_errors_in_command(self):
1751 commands = "\n".join([
1752 'print(',
1753 'debug print(',
1754 'debug doesnotexist',
1755 'c',
1756 ])
Mark Shannon877df852020-11-12 09:43:29 +00001757 stdout, _ = self.run_pdb_script('pass', commands + '\n')
Daniel Hahler3e936432019-03-12 04:29:04 +01001758
Daniel Hahler43277052019-02-15 21:52:53 +01001759 self.assertEqual(stdout.splitlines()[1:], [
Mark Shannon877df852020-11-12 09:43:29 +00001760 '-> pass',
Pablo Galindod6d63712021-01-19 23:59:33 +00001761 '(Pdb) *** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001762
1763 '(Pdb) ENTERING RECURSIVE DEBUGGER',
Pablo Galindod6d63712021-01-19 23:59:33 +00001764 '*** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001765 'LEAVING RECURSIVE DEBUGGER',
1766
1767 '(Pdb) ENTERING RECURSIVE DEBUGGER',
1768 '> <string>(1)<module>()',
1769 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1770 'LEAVING RECURSIVE DEBUGGER',
Daniel Hahler43277052019-02-15 21:52:53 +01001771 '(Pdb) ',
1772 ])
Georg Brandl6cccb862010-07-30 14:16:43 +00001773
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001774
1775 def test_issue42384(self):
1776 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1777 script = textwrap.dedent("""
1778 import sys
1779 print('sys.path[0] is', sys.path[0])
1780 """)
1781 commands = 'c\nq'
1782
1783 with os_helper.temp_cwd() as cwd:
1784 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1785
1786 stdout, stderr = self.run_pdb_script(script, commands)
1787
1788 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1789
1790 @os_helper.skip_unless_symlink
1791 def test_issue42384_symlink(self):
1792 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1793 script = textwrap.dedent("""
1794 import sys
1795 print('sys.path[0] is', sys.path[0])
1796 """)
1797 commands = 'c\nq'
1798
1799 with os_helper.temp_cwd() as cwd:
1800 cwd = os.path.realpath(cwd)
1801 dir_one = os.path.join(cwd, 'dir_one')
1802 dir_two = os.path.join(cwd, 'dir_two')
1803 expected = f'(Pdb) sys.path[0] is {dir_one}'
1804
1805 os.mkdir(dir_one)
1806 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1807 f.write(script)
1808 os.mkdir(dir_two)
1809 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1810
1811 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1812
1813 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1814
Andrey Bienkowski501d4a52021-01-25 21:08:01 +00001815 def test_issue42383(self):
1816 with os_helper.temp_cwd() as cwd:
1817 with open('foo.py', 'w') as f:
1818 s = textwrap.dedent("""
1819 print('The correct file was executed')
1820
1821 import os
1822 os.chdir("subdir")
1823 """)
1824 f.write(s)
1825
1826 subdir = os.path.join(cwd, 'subdir')
1827 os.mkdir(subdir)
1828 os.mkdir(os.path.join(subdir, 'subdir'))
1829 wrong_file = os.path.join(subdir, 'foo.py')
1830
1831 with open(wrong_file, 'w') as f:
1832 f.write('print("The wrong file was executed")')
1833
1834 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
1835 expected = '(Pdb) The correct file was executed'
1836 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
1837
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001838
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001839class ChecklineTests(unittest.TestCase):
1840 def setUp(self):
1841 linecache.clearcache() # Pdb.checkline() uses linecache.getline()
1842
1843 def tearDown(self):
1844 os_helper.unlink(os_helper.TESTFN)
1845
1846 def test_checkline_before_debugging(self):
1847 with open(os_helper.TESTFN, "w") as f:
1848 f.write("print(123)")
1849 db = pdb.Pdb()
1850 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1851
1852 def test_checkline_after_reset(self):
1853 with open(os_helper.TESTFN, "w") as f:
1854 f.write("print(123)")
1855 db = pdb.Pdb()
1856 db.reset()
1857 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1858
1859 def test_checkline_is_not_executable(self):
1860 with open(os_helper.TESTFN, "w") as f:
1861 # Test for comments, docstrings and empty lines
1862 s = textwrap.dedent("""
1863 # Comment
1864 \"\"\" docstring \"\"\"
1865 ''' docstring '''
1866
1867 """)
1868 f.write(s)
1869 db = pdb.Pdb()
1870 num_lines = len(s.splitlines()) + 2 # Test for EOF
1871 for lineno in range(num_lines):
1872 self.assertFalse(db.checkline(os_helper.TESTFN, lineno))
1873
1874
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001875def load_tests(*args):
Georg Brandl243ad662009-05-05 09:00:19 +00001876 from test import test_pdb
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001877 suites = [
1878 unittest.makeSuite(PdbTestCase),
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001879 unittest.makeSuite(ChecklineTests),
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001880 doctest.DocTestSuite(test_pdb)
1881 ]
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001882 return unittest.TestSuite(suites)
Georg Brandl243ad662009-05-05 09:00:19 +00001883
1884
1885if __name__ == '__main__':
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001886 unittest.main()