blob: a9afca867ca8f79d7cedb2f02609664edb3e17c2 [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>
Mark Shannon9f2c63b2021-07-08 19:21:22 +01001319 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1320 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001321 (Pdb) continue
1322 pdb 2: <built-in function default_int_handler>
1323 """
Georg Brandl46b9afc2010-07-30 09:14:20 +00001324
Miss Islington (bot)9c0180a2021-06-11 09:18:19 -07001325def test_pdb_issue_43318():
1326 """echo breakpoints cleared with filename:lineno
1327
1328 >>> def test_function():
1329 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1330 ... print(1)
1331 ... print(2)
1332 ... print(3)
1333 ... print(4)
1334 >>> reset_Breakpoint()
1335 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1336 ... 'break 3',
1337 ... 'clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3',
1338 ... 'continue'
1339 ... ]):
1340 ... test_function()
1341 > <doctest test.test_pdb.test_pdb_issue_43318[0]>(3)test_function()
1342 -> print(1)
1343 (Pdb) break 3
1344 Breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1345 (Pdb) clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1346 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1347 (Pdb) continue
1348 1
1349 2
1350 3
1351 4
1352 """
1353
Georg Brandl6cccb862010-07-30 14:16:43 +00001354
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001355class PdbTestCase(unittest.TestCase):
1356 def tearDown(self):
Hai Shi604bba12020-08-04 23:51:43 +08001357 os_helper.unlink(os_helper.TESTFN)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001358
1359 def _run_pdb(self, pdb_args, commands):
Hai Shi604bba12020-08-04 23:51:43 +08001360 self.addCleanup(os_helper.rmtree, '__pycache__')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001361 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1362 with subprocess.Popen(
1363 cmd,
1364 stdout=subprocess.PIPE,
1365 stdin=subprocess.PIPE,
1366 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001367 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001368 ) as proc:
1369 stdout, stderr = proc.communicate(str.encode(commands))
1370 stdout = stdout and bytes.decode(stdout)
1371 stderr = stderr and bytes.decode(stderr)
1372 return stdout, stderr
1373
1374 def run_pdb_script(self, script, commands):
Senthil Kumaran42d70812012-05-01 10:07:49 +08001375 """Run 'script' lines with pdb and the pdb 'commands'."""
1376 filename = 'main.py'
1377 with open(filename, 'w') as f:
1378 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001379 self.addCleanup(os_helper.unlink, filename)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001380 return self._run_pdb([filename], commands)
1381
1382 def run_pdb_module(self, script, commands):
1383 """Runs the script code as part of a module"""
1384 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001385 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001386 main_file = self.module_name + '/__main__.py'
1387 init_file = self.module_name + '/__init__.py'
1388 os.mkdir(self.module_name)
1389 with open(init_file, 'w') as f:
1390 pass
1391 with open(main_file, 'w') as f:
1392 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001393 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001394 return self._run_pdb(['-m', self.module_name], commands)
Senthil Kumaran42d70812012-05-01 10:07:49 +08001395
Georg Brandl6e220552013-10-13 20:51:47 +02001396 def _assert_find_function(self, file_content, func_name, expected):
Hai Shi604bba12020-08-04 23:51:43 +08001397 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6e220552013-10-13 20:51:47 +02001398 f.write(file_content)
1399
1400 expected = None if not expected else (
Hai Shi604bba12020-08-04 23:51:43 +08001401 expected[0], os_helper.TESTFN, expected[1])
Georg Brandl6e220552013-10-13 20:51:47 +02001402 self.assertEqual(
Hai Shi604bba12020-08-04 23:51:43 +08001403 expected, pdb.find_function(func_name, os_helper.TESTFN))
Georg Brandl6e220552013-10-13 20:51:47 +02001404
1405 def test_find_function_empty_file(self):
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001406 self._assert_find_function(b'', 'foo', None)
Georg Brandl6e220552013-10-13 20:51:47 +02001407
1408 def test_find_function_found(self):
1409 self._assert_find_function(
1410 """\
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001411def foo():
1412 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001413
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001414def bœr():
1415 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001416
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001417def quux():
1418 pass
1419""".encode(),
1420 'bœr',
1421 ('bœr', 4),
1422 )
1423
1424 def test_find_function_found_with_encoding_cookie(self):
1425 self._assert_find_function(
1426 """\
1427# coding: iso-8859-15
1428def foo():
1429 pass
1430
1431def bœr():
1432 pass
1433
1434def quux():
1435 pass
1436""".encode('iso-8859-15'),
1437 'bœr',
1438 ('bœr', 5),
1439 )
1440
1441 def test_find_function_found_with_bom(self):
1442 self._assert_find_function(
1443 codecs.BOM_UTF8 + """\
1444def bœr():
1445 pass
1446""".encode(),
1447 'bœr',
1448 ('bœr', 1),
Georg Brandl6e220552013-10-13 20:51:47 +02001449 )
1450
Georg Brandl6cccb862010-07-30 14:16:43 +00001451 def test_issue7964(self):
1452 # open the file as binary so we can force \r\n newline
Hai Shi604bba12020-08-04 23:51:43 +08001453 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6cccb862010-07-30 14:16:43 +00001454 f.write(b'print("testing my pdb")\r\n')
Hai Shi604bba12020-08-04 23:51:43 +08001455 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
Georg Brandl6cccb862010-07-30 14:16:43 +00001456 proc = subprocess.Popen(cmd,
1457 stdout=subprocess.PIPE,
1458 stdin=subprocess.PIPE,
1459 stderr=subprocess.STDOUT,
1460 )
Brian Curtin994ad6c2010-11-05 15:38:47 +00001461 self.addCleanup(proc.stdout.close)
Georg Brandl6cccb862010-07-30 14:16:43 +00001462 stdout, stderr = proc.communicate(b'quit\n')
1463 self.assertNotIn(b'SyntaxError', stdout,
1464 "Got a syntax error running test script under PDB")
1465
Senthil Kumaran42d70812012-05-01 10:07:49 +08001466 def test_issue13183(self):
1467 script = """
1468 from bar import bar
1469
1470 def foo():
1471 bar()
1472
1473 def nope():
1474 pass
1475
1476 def foobar():
1477 foo()
1478 nope()
1479
1480 foobar()
1481 """
1482 commands = """
1483 from bar import bar
1484 break bar
1485 continue
1486 step
1487 step
1488 quit
1489 """
1490 bar = """
1491 def bar():
Senthil Kumarancb172042012-05-02 08:00:22 +08001492 pass
Senthil Kumaran42d70812012-05-01 10:07:49 +08001493 """
1494 with open('bar.py', 'w') as f:
1495 f.write(textwrap.dedent(bar))
Hai Shi604bba12020-08-04 23:51:43 +08001496 self.addCleanup(os_helper.unlink, 'bar.py')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001497 stdout, stderr = self.run_pdb_script(script, commands)
Georg Brandl4bde9ca2012-05-01 09:21:16 +02001498 self.assertTrue(
1499 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1500 'Fail to step into the caller after a return')
Senthil Kumaran42d70812012-05-01 10:07:49 +08001501
Daniel Hahler9139f922019-04-01 23:59:50 +02001502 def test_issue13120(self):
1503 # Invoking "continue" on a non-main thread triggered an exception
1504 # inside signal.signal.
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001505
Hai Shi604bba12020-08-04 23:51:43 +08001506 with open(os_helper.TESTFN, 'wb') as f:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001507 f.write(textwrap.dedent("""
1508 import threading
1509 import pdb
1510
1511 def start_pdb():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001512 pdb.Pdb(readrc=False).set_trace()
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001513 x = 1
1514 y = 1
1515
1516 t = threading.Thread(target=start_pdb)
1517 t.start()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001518 cmd = [sys.executable, '-u', os_helper.TESTFN]
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001519 proc = subprocess.Popen(cmd,
1520 stdout=subprocess.PIPE,
1521 stdin=subprocess.PIPE,
1522 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001523 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001524 )
1525 self.addCleanup(proc.stdout.close)
1526 stdout, stderr = proc.communicate(b'cont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001527 self.assertNotIn(b'Error', stdout,
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001528 "Got an error running test script under PDB")
1529
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001530 def test_issue36250(self):
1531
Hai Shi604bba12020-08-04 23:51:43 +08001532 with open(os_helper.TESTFN, 'wb') as f:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001533 f.write(textwrap.dedent("""
1534 import threading
1535 import pdb
1536
1537 evt = threading.Event()
1538
1539 def start_pdb():
1540 evt.wait()
1541 pdb.Pdb(readrc=False).set_trace()
1542
1543 t = threading.Thread(target=start_pdb)
1544 t.start()
1545 pdb.Pdb(readrc=False).set_trace()
1546 evt.set()
1547 t.join()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001548 cmd = [sys.executable, '-u', os_helper.TESTFN]
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001549 proc = subprocess.Popen(cmd,
1550 stdout=subprocess.PIPE,
1551 stdin=subprocess.PIPE,
1552 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001553 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001554 )
1555 self.addCleanup(proc.stdout.close)
1556 stdout, stderr = proc.communicate(b'cont\ncont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001557 self.assertNotIn(b'Error', stdout,
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001558 "Got an error running test script under PDB")
1559
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001560 def test_issue16180(self):
1561 # A syntax error in the debuggee.
1562 script = "def f: pass\n"
1563 commands = ''
1564 expected = "SyntaxError:"
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001565 stdout, stderr = self.run_pdb_script(script, commands)
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001566 self.assertIn(expected, stdout,
1567 '\n\nExpected:\n{}\nGot:\n{}\n'
1568 'Fail to handle a syntax error in the debuggee.'
1569 .format(expected, stdout))
1570
Irit Katriel652bfde2021-04-01 16:25:59 +01001571 def test_issue26053(self):
1572 # run command of pdb prompt echoes the correct args
1573 script = "print('hello')"
1574 commands = """
1575 continue
1576 run a b c
1577 run d e f
1578 quit
1579 """
1580 stdout, stderr = self.run_pdb_script(script, commands)
Irit Katrielbd4ab8e2021-04-01 20:05:51 +01001581 res = '\n'.join([x.strip() for x in stdout.splitlines()])
1582 self.assertRegex(res, "Restarting .* with arguments:\na b c")
1583 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001584
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001585 def test_readrc_kwarg(self):
Victor Stinner11ea0442016-09-09 22:56:54 -07001586 script = textwrap.dedent("""
1587 import pdb; pdb.Pdb(readrc=False).set_trace()
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001588
Victor Stinner11ea0442016-09-09 22:56:54 -07001589 print('hello')
1590 """)
Victor Stinner11ea0442016-09-09 22:56:54 -07001591
Victor Stinnerbc626262016-09-09 23:22:09 -07001592 save_home = os.environ.pop('HOME', None)
1593 try:
Hai Shi604bba12020-08-04 23:51:43 +08001594 with os_helper.temp_cwd():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001595 with open('.pdbrc', 'w') as f:
1596 f.write("invalid\n")
1597
1598 with open('main.py', 'w') as f:
1599 f.write(script)
1600
1601 cmd = [sys.executable, 'main.py']
1602 proc = subprocess.Popen(
1603 cmd,
1604 stdout=subprocess.PIPE,
1605 stdin=subprocess.PIPE,
1606 stderr=subprocess.PIPE,
1607 )
Victor Stinnerbc626262016-09-09 23:22:09 -07001608 with proc:
1609 stdout, stderr = proc.communicate(b'q\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001610 self.assertNotIn(b"NameError: name 'invalid' is not defined",
1611 stdout)
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001612
1613 finally:
Victor Stinner11ea0442016-09-09 22:56:54 -07001614 if save_home is not None:
1615 os.environ['HOME'] = save_home
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001616
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001617 def test_readrc_homedir(self):
1618 save_home = os.environ.pop("HOME", None)
Hai Shi604bba12020-08-04 23:51:43 +08001619 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001620 rc_path = os.path.join(temp_dir, ".pdbrc")
1621 os.path.expanduser.return_value = rc_path
1622 try:
1623 with open(rc_path, "w") as f:
1624 f.write("invalid")
1625 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1626 finally:
1627 if save_home is not None:
1628 os.environ["HOME"] = save_home
1629
Barry Warsaw35425d62017-09-22 12:29:42 -04001630 def test_header(self):
1631 stdout = StringIO()
1632 header = 'Nobody expects... blah, blah, blah'
1633 with ExitStack() as resources:
1634 resources.enter_context(patch('sys.stdout', stdout))
1635 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1636 pdb.set_trace(header=header)
1637 self.assertEqual(stdout.getvalue(), header + '\n')
1638
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001639 def test_run_module(self):
1640 script = """print("SUCCESS")"""
1641 commands = """
1642 continue
1643 quit
1644 """
1645 stdout, stderr = self.run_pdb_module(script, commands)
1646 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1647
1648 def test_module_is_run_as_main(self):
1649 script = """
1650 if __name__ == '__main__':
1651 print("SUCCESS")
1652 """
1653 commands = """
1654 continue
1655 quit
1656 """
1657 stdout, stderr = self.run_pdb_module(script, commands)
1658 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1659
1660 def test_breakpoint(self):
1661 script = """
1662 if __name__ == '__main__':
1663 pass
1664 print("SUCCESS")
1665 pass
1666 """
1667 commands = """
1668 b 3
1669 quit
1670 """
1671 stdout, stderr = self.run_pdb_module(script, commands)
1672 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1673 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1674
1675 def test_run_pdb_with_pdb(self):
1676 commands = """
1677 c
1678 quit
1679 """
1680 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001681 self.assertIn(
1682 pdb._usage,
1683 stdout.replace('\r', '') # remove \r for windows
1684 )
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001685
1686 def test_module_without_a_main(self):
1687 module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001688 os_helper.rmtree(module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001689 init_file = module_name + '/__init__.py'
1690 os.mkdir(module_name)
1691 with open(init_file, 'w') as f:
1692 pass
Hai Shi604bba12020-08-04 23:51:43 +08001693 self.addCleanup(os_helper.rmtree, module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001694 stdout, stderr = self._run_pdb(['-m', module_name], "")
1695 self.assertIn("ImportError: No module named t_main.__main__",
1696 stdout.splitlines())
1697
Jason R. Coombs684eb5c2021-07-28 09:04:38 -04001698 def test_package_without_a_main(self):
1699 pkg_name = 't_pkg'
1700 module_name = 't_main'
1701 os_helper.rmtree(pkg_name)
1702 modpath = pkg_name + '/' + module_name
1703 os.makedirs(modpath)
1704 with open(modpath + '/__init__.py', 'w') as f:
1705 pass
1706 self.addCleanup(os_helper.rmtree, pkg_name)
1707 stdout, stderr = self._run_pdb(['-m', modpath.replace('/', '.')], "")
1708 self.assertIn(
1709 "'t_pkg.t_main' is a package and cannot be directly executed",
1710 stdout)
1711
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001712 def test_blocks_at_first_code_line(self):
1713 script = """
1714 #This is a comment, on line 2
1715
1716 print("SUCCESS")
1717 """
1718 commands = """
1719 quit
1720 """
1721 stdout, stderr = self.run_pdb_module(script, commands)
1722 self.assertTrue(any("__main__.py(4)<module>()"
1723 in l for l in stdout.splitlines()), stdout)
1724
1725 def test_relative_imports(self):
1726 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001727 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001728 main_file = self.module_name + '/__main__.py'
1729 init_file = self.module_name + '/__init__.py'
1730 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001731 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001732 os.mkdir(self.module_name)
1733 with open(init_file, 'w') as f:
1734 f.write(textwrap.dedent("""
1735 top_var = "VAR from top"
1736 """))
1737 with open(main_file, 'w') as f:
1738 f.write(textwrap.dedent("""
1739 from . import top_var
1740 from .module import var
1741 from . import module
1742 pass # We'll stop here and print the vars
1743 """))
1744 with open(module_file, 'w') as f:
1745 f.write(textwrap.dedent("""
1746 var = "VAR from module"
1747 var2 = "second var"
1748 """))
1749 commands = """
1750 b 5
1751 c
1752 p top_var
1753 p var
1754 p module.var2
1755 quit
1756 """
1757 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
Mario Corchero38bfa842018-02-03 06:40:11 +00001758 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001759 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1760 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Georg Brandl6cccb862010-07-30 14:16:43 +00001761
Mario Corchero38bfa842018-02-03 06:40:11 +00001762 def test_relative_imports_on_plain_module(self):
1763 # Validates running a plain module. See bpo32691
1764 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001765 os_helper.rmtree(self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001766 main_file = self.module_name + '/runme.py'
1767 init_file = self.module_name + '/__init__.py'
1768 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001769 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001770 os.mkdir(self.module_name)
1771 with open(init_file, 'w') as f:
1772 f.write(textwrap.dedent("""
1773 top_var = "VAR from top"
1774 """))
1775 with open(main_file, 'w') as f:
1776 f.write(textwrap.dedent("""
1777 from . import module
1778 pass # We'll stop here and print the vars
1779 """))
1780 with open(module_file, 'w') as f:
1781 f.write(textwrap.dedent("""
1782 var = "VAR from module"
1783 """))
1784 commands = """
1785 b 3
1786 c
1787 p module.var
1788 quit
1789 """
1790 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1791 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1792
Daniel Hahler3e936432019-03-12 04:29:04 +01001793 def test_errors_in_command(self):
1794 commands = "\n".join([
1795 'print(',
1796 'debug print(',
1797 'debug doesnotexist',
1798 'c',
1799 ])
Mark Shannon877df852020-11-12 09:43:29 +00001800 stdout, _ = self.run_pdb_script('pass', commands + '\n')
Daniel Hahler3e936432019-03-12 04:29:04 +01001801
Daniel Hahler43277052019-02-15 21:52:53 +01001802 self.assertEqual(stdout.splitlines()[1:], [
Mark Shannon877df852020-11-12 09:43:29 +00001803 '-> pass',
Pablo Galindod6d63712021-01-19 23:59:33 +00001804 '(Pdb) *** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001805
1806 '(Pdb) ENTERING RECURSIVE DEBUGGER',
Pablo Galindod6d63712021-01-19 23:59:33 +00001807 '*** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001808 'LEAVING RECURSIVE DEBUGGER',
1809
1810 '(Pdb) ENTERING RECURSIVE DEBUGGER',
1811 '> <string>(1)<module>()',
1812 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1813 'LEAVING RECURSIVE DEBUGGER',
Daniel Hahler43277052019-02-15 21:52:53 +01001814 '(Pdb) ',
1815 ])
Georg Brandl6cccb862010-07-30 14:16:43 +00001816
Irit Katriel33022f92021-07-03 17:28:46 +01001817 def test_issue34266(self):
1818 '''do_run handles exceptions from parsing its arg'''
1819 def check(bad_arg, msg):
1820 commands = "\n".join([
1821 f'run {bad_arg}',
1822 'q',
1823 ])
1824 stdout, _ = self.run_pdb_script('pass', commands + '\n')
1825 self.assertEqual(stdout.splitlines()[1:], [
1826 '-> pass',
1827 f'(Pdb) *** Cannot run {bad_arg}: {msg}',
1828 '(Pdb) ',
1829 ])
1830 check('\\', 'No escaped character')
1831 check('"', 'No closing quotation')
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001832
1833 def test_issue42384(self):
1834 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1835 script = textwrap.dedent("""
1836 import sys
1837 print('sys.path[0] is', sys.path[0])
1838 """)
1839 commands = 'c\nq'
1840
1841 with os_helper.temp_cwd() as cwd:
1842 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1843
1844 stdout, stderr = self.run_pdb_script(script, commands)
1845
1846 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1847
1848 @os_helper.skip_unless_symlink
1849 def test_issue42384_symlink(self):
1850 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1851 script = textwrap.dedent("""
1852 import sys
1853 print('sys.path[0] is', sys.path[0])
1854 """)
1855 commands = 'c\nq'
1856
1857 with os_helper.temp_cwd() as cwd:
1858 cwd = os.path.realpath(cwd)
1859 dir_one = os.path.join(cwd, 'dir_one')
1860 dir_two = os.path.join(cwd, 'dir_two')
1861 expected = f'(Pdb) sys.path[0] is {dir_one}'
1862
1863 os.mkdir(dir_one)
1864 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1865 f.write(script)
1866 os.mkdir(dir_two)
1867 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1868
1869 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1870
1871 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1872
Andrey Bienkowski501d4a52021-01-25 21:08:01 +00001873 def test_issue42383(self):
1874 with os_helper.temp_cwd() as cwd:
1875 with open('foo.py', 'w') as f:
1876 s = textwrap.dedent("""
1877 print('The correct file was executed')
1878
1879 import os
1880 os.chdir("subdir")
1881 """)
1882 f.write(s)
1883
1884 subdir = os.path.join(cwd, 'subdir')
1885 os.mkdir(subdir)
1886 os.mkdir(os.path.join(subdir, 'subdir'))
1887 wrong_file = os.path.join(subdir, 'foo.py')
1888
1889 with open(wrong_file, 'w') as f:
1890 f.write('print("The wrong file was executed")')
1891
1892 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
1893 expected = '(Pdb) The correct file was executed'
1894 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
1895
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001896
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001897class ChecklineTests(unittest.TestCase):
1898 def setUp(self):
1899 linecache.clearcache() # Pdb.checkline() uses linecache.getline()
1900
1901 def tearDown(self):
1902 os_helper.unlink(os_helper.TESTFN)
1903
1904 def test_checkline_before_debugging(self):
1905 with open(os_helper.TESTFN, "w") as f:
1906 f.write("print(123)")
1907 db = pdb.Pdb()
1908 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1909
1910 def test_checkline_after_reset(self):
1911 with open(os_helper.TESTFN, "w") as f:
1912 f.write("print(123)")
1913 db = pdb.Pdb()
1914 db.reset()
1915 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1916
1917 def test_checkline_is_not_executable(self):
1918 with open(os_helper.TESTFN, "w") as f:
1919 # Test for comments, docstrings and empty lines
1920 s = textwrap.dedent("""
1921 # Comment
1922 \"\"\" docstring \"\"\"
1923 ''' docstring '''
1924
1925 """)
1926 f.write(s)
1927 db = pdb.Pdb()
1928 num_lines = len(s.splitlines()) + 2 # Test for EOF
1929 for lineno in range(num_lines):
1930 self.assertFalse(db.checkline(os_helper.TESTFN, lineno))
1931
1932
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001933def load_tests(*args):
Georg Brandl243ad662009-05-05 09:00:19 +00001934 from test import test_pdb
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001935 suites = [
1936 unittest.makeSuite(PdbTestCase),
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001937 unittest.makeSuite(ChecklineTests),
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001938 doctest.DocTestSuite(test_pdb)
1939 ]
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001940 return unittest.TestSuite(suites)
Georg Brandl243ad662009-05-05 09:00:19 +00001941
1942
1943if __name__ == '__main__':
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001944 unittest.main()