blob: cd096e7dd56e8de44973f6d6e01cabf899241d04 [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
Georg Brandle59ca2a2010-07-30 17:04:28 +0000394def do_nothing():
395 pass
396
397def do_something():
398 print(42)
399
400def test_list_commands():
401 """Test the list and source commands of pdb.
402
403 >>> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000404 ... import test.test_pdb
405 ... test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000406 ... 'some...'
407 ... 'more...'
408 ... 'code...'
409 ... 'to...'
410 ... 'make...'
411 ... 'a...'
412 ... 'long...'
413 ... 'listing...'
414 ... 'useful...'
415 ... '...'
416 ... '...'
417 ... return foo
418
419 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700420 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000421 ... ret = test_function_2('baz')
422
423 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
424 ... 'list', # list first function
425 ... 'step', # step into second function
426 ... 'list', # list second function
427 ... 'list', # continue listing to EOF
428 ... 'list 1,3', # list specific lines
429 ... 'list x', # invalid argument
430 ... 'next', # step to import
431 ... 'next', # step over import
432 ... 'step', # step into do_nothing
433 ... 'longlist', # list all lines
434 ... 'source do_something', # list all lines of function
Georg Brandlcdf66a92010-07-30 18:15:16 +0000435 ... 'source fooxxx', # something that doesn't exit
Georg Brandle59ca2a2010-07-30 17:04:28 +0000436 ... 'continue',
437 ... ]):
438 ... test_function()
439 > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
440 -> ret = test_function_2('baz')
441 (Pdb) list
442 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700443 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000444 3 -> ret = test_function_2('baz')
445 [EOF]
446 (Pdb) step
447 --Call--
448 > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
449 -> def test_function_2(foo):
450 (Pdb) list
451 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000452 2 import test.test_pdb
453 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000454 4 'some...'
455 5 'more...'
456 6 'code...'
457 7 'to...'
458 8 'make...'
459 9 'a...'
460 10 'long...'
461 11 'listing...'
462 (Pdb) list
463 12 'useful...'
464 13 '...'
465 14 '...'
466 15 return foo
467 [EOF]
468 (Pdb) list 1,3
469 1 -> def test_function_2(foo):
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000470 2 import test.test_pdb
471 3 test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000472 (Pdb) list x
473 *** ...
474 (Pdb) next
475 > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000476 -> import test.test_pdb
Georg Brandle59ca2a2010-07-30 17:04:28 +0000477 (Pdb) next
478 > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
Georg Brandla8fbc6a2010-07-31 11:52:46 +0000479 -> test.test_pdb.do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000480 (Pdb) step
481 --Call--
Georg Brandle1e8df12010-07-31 08:14:16 +0000482 > ...test_pdb.py(...)do_nothing()
Georg Brandle59ca2a2010-07-30 17:04:28 +0000483 -> def do_nothing():
484 (Pdb) longlist
485 ... -> def do_nothing():
486 ... pass
487 (Pdb) source do_something
488 ... def do_something():
489 ... print(42)
Georg Brandlcdf66a92010-07-30 18:15:16 +0000490 (Pdb) source fooxxx
491 *** ...
Georg Brandle59ca2a2010-07-30 17:04:28 +0000492 (Pdb) continue
493 """
494
Irit Katriel022bc752020-08-27 01:51:12 +0100495def test_pdb_whatis_command():
496 """Test the whatis command
497
498 >>> myvar = (1,2)
499 >>> def myfunc():
500 ... pass
501
502 >>> class MyClass:
503 ... def mymethod(self):
504 ... pass
505
506 >>> def test_function():
507 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
508
509 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
510 ... 'whatis myvar',
511 ... 'whatis myfunc',
512 ... 'whatis MyClass',
513 ... 'whatis MyClass()',
514 ... 'whatis MyClass.mymethod',
515 ... 'whatis MyClass().mymethod',
516 ... 'continue',
517 ... ]):
518 ... test_function()
519 --Return--
520 > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()->None
521 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
522 (Pdb) whatis myvar
523 <class 'tuple'>
524 (Pdb) whatis myfunc
525 Function myfunc
526 (Pdb) whatis MyClass
527 Class test.test_pdb.MyClass
528 (Pdb) whatis MyClass()
529 <class 'test.test_pdb.MyClass'>
530 (Pdb) whatis MyClass.mymethod
531 Function mymethod
532 (Pdb) whatis MyClass().mymethod
533 Method mymethod
534 (Pdb) continue
535 """
Georg Brandle59ca2a2010-07-30 17:04:28 +0000536
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000537def test_post_mortem():
538 """Test post mortem traceback debugging.
539
540 >>> def test_function_2():
541 ... try:
542 ... 1/0
543 ... finally:
544 ... print('Exception!')
545
546 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700547 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000548 ... test_function_2()
549 ... print('Not reached.')
550
551 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
552 ... 'next', # step over exception-raising call
553 ... 'bt', # get a backtrace
554 ... 'list', # list code of test_function()
555 ... 'down', # step into test_function_2()
556 ... 'list', # list code of test_function_2()
557 ... 'continue',
558 ... ]):
559 ... try:
560 ... test_function()
561 ... except ZeroDivisionError:
562 ... print('Correctly reraised.')
563 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
564 -> test_function_2()
565 (Pdb) next
566 Exception!
567 ZeroDivisionError: division by zero
568 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
569 -> test_function_2()
570 (Pdb) bt
571 ...
572 <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
573 -> test_function()
574 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
575 -> test_function_2()
576 <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
577 -> 1/0
578 (Pdb) list
579 1 def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700580 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000581 3 -> test_function_2()
582 4 print('Not reached.')
583 [EOF]
584 (Pdb) down
585 > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
586 -> 1/0
587 (Pdb) list
588 1 def test_function_2():
589 2 try:
590 3 >> 1/0
591 4 finally:
592 5 -> print('Exception!')
593 [EOF]
594 (Pdb) continue
595 Correctly reraised.
596 """
597
598
Georg Brandl243ad662009-05-05 09:00:19 +0000599def test_pdb_skip_modules():
600 """This illustrates the simple case of module skipping.
601
602 >>> def skip_module():
603 ... import string
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700604 ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000605 ... string.capwords('FOO')
Georg Brandl243ad662009-05-05 09:00:19 +0000606
Georg Brandl9fa2e022009-09-16 16:40:45 +0000607 >>> with PdbTestInput([
608 ... 'step',
609 ... 'continue',
610 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000611 ... skip_module()
Georg Brandl243ad662009-05-05 09:00:19 +0000612 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
613 -> string.capwords('FOO')
614 (Pdb) step
615 --Return--
616 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
617 -> string.capwords('FOO')
618 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000619 """
Georg Brandl243ad662009-05-05 09:00:19 +0000620
621
622# Module for testing skipping of module that makes a callback
Brett Cannon9529fbf2013-06-15 17:11:25 -0400623mod = types.ModuleType('module_to_skip')
Georg Brandl243ad662009-05-05 09:00:19 +0000624exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
625
626
627def test_pdb_skip_modules_with_callback():
628 """This illustrates skipping of modules that call into other code.
629
630 >>> def skip_module():
631 ... def callback():
632 ... return None
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700633 ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
Georg Brandl243ad662009-05-05 09:00:19 +0000634 ... mod.foo_pony(callback)
Georg Brandl243ad662009-05-05 09:00:19 +0000635
Georg Brandl9fa2e022009-09-16 16:40:45 +0000636 >>> with PdbTestInput([
637 ... 'step',
638 ... 'step',
639 ... 'step',
640 ... 'step',
641 ... 'step',
642 ... 'continue',
643 ... ]):
Georg Brandl243ad662009-05-05 09:00:19 +0000644 ... skip_module()
Georg Brandl9fa2e022009-09-16 16:40:45 +0000645 ... pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000646 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
647 -> mod.foo_pony(callback)
648 (Pdb) step
649 --Call--
650 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
651 -> def callback():
652 (Pdb) step
653 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
654 -> return None
655 (Pdb) step
656 --Return--
657 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
658 -> return None
659 (Pdb) step
660 --Return--
661 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
662 -> mod.foo_pony(callback)
663 (Pdb) step
Georg Brandl9fa2e022009-09-16 16:40:45 +0000664 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
665 -> pass # provides something to "step" to
Georg Brandl243ad662009-05-05 09:00:19 +0000666 (Pdb) continue
Georg Brandl9fa2e022009-09-16 16:40:45 +0000667 """
Georg Brandl243ad662009-05-05 09:00:19 +0000668
669
Georg Brandl3f940892010-07-30 10:29:19 +0000670def test_pdb_continue_in_bottomframe():
671 """Test that "continue" and "next" work properly in bottom frame (issue #5294).
672
673 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700674 ... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
Georg Brandl3f940892010-07-30 10:29:19 +0000675 ... inst.set_trace()
676 ... inst.botframe = sys._getframe() # hackery to get the right botframe
677 ... print(1)
678 ... print(2)
679 ... print(3)
680 ... print(4)
681
Georg Brandl7410dd12010-07-30 12:01:20 +0000682 >>> with PdbTestInput([ # doctest: +ELLIPSIS
Georg Brandl3f940892010-07-30 10:29:19 +0000683 ... 'next',
684 ... 'break 7',
685 ... 'continue',
686 ... 'next',
687 ... 'continue',
688 ... 'continue',
689 ... ]):
690 ... test_function()
691 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
692 -> inst.botframe = sys._getframe() # hackery to get the right botframe
693 (Pdb) next
694 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
695 -> print(1)
696 (Pdb) break 7
Georg Brandl7410dd12010-07-30 12:01:20 +0000697 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
Georg Brandl3f940892010-07-30 10:29:19 +0000698 (Pdb) continue
699 1
700 2
701 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
702 -> print(3)
703 (Pdb) next
704 3
705 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
706 -> print(4)
707 (Pdb) continue
708 4
709 """
710
711
Georg Brandl46b9afc2010-07-30 09:14:20 +0000712def pdb_invoke(method, arg):
713 """Run pdb.method(arg)."""
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700714 getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
Georg Brandl46b9afc2010-07-30 09:14:20 +0000715
716
717def test_pdb_run_with_incorrect_argument():
718 """Testing run and runeval with incorrect first argument.
719
720 >>> pti = PdbTestInput(['continue',])
721 >>> with pti:
722 ... pdb_invoke('run', lambda x: x)
723 Traceback (most recent call last):
724 TypeError: exec() arg 1 must be a string, bytes or code object
725
726 >>> with pti:
727 ... pdb_invoke('runeval', lambda x: x)
728 Traceback (most recent call last):
729 TypeError: eval() arg 1 must be a string, bytes or code object
730 """
731
732
733def test_pdb_run_with_code_object():
734 """Testing run and runeval with code object as a first argument.
735
Georg Brandle1e8df12010-07-31 08:14:16 +0000736 >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
Georg Brandl46b9afc2010-07-30 09:14:20 +0000737 ... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
Georg Brandle1e8df12010-07-31 08:14:16 +0000738 > <string>(1)<module>()...
Georg Brandl46b9afc2010-07-30 09:14:20 +0000739 (Pdb) step
740 --Return--
741 > <string>(1)<module>()->None
742 (Pdb) x
743 1
744 (Pdb) continue
745
746 >>> with PdbTestInput(['x', 'continue']):
747 ... x=0
748 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
749 > <string>(1)<module>()->None
750 (Pdb) x
751 1
752 (Pdb) continue
753 """
754
Guido van Rossum8820c232013-11-21 11:30:06 -0800755def test_next_until_return_at_return_event():
756 """Test that pdb stops after a next/until/return issued at a return debug event.
757
758 >>> def test_function_2():
759 ... x = 1
760 ... x = 2
761
762 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700763 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800764 ... test_function_2()
765 ... test_function_2()
766 ... test_function_2()
767 ... end = 1
768
Irit Katrielad442a62021-04-02 17:15:21 +0100769 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -0800770 >>> with PdbTestInput(['break test_function_2',
771 ... 'continue',
772 ... 'return',
773 ... 'next',
774 ... 'continue',
775 ... 'return',
776 ... 'until',
777 ... 'continue',
778 ... 'return',
779 ... 'return',
780 ... 'continue']):
781 ... test_function()
782 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
783 -> test_function_2()
784 (Pdb) break test_function_2
785 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
786 (Pdb) continue
787 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
788 -> x = 1
789 (Pdb) return
790 --Return--
791 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
792 -> x = 2
793 (Pdb) next
794 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
795 -> test_function_2()
796 (Pdb) continue
797 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
798 -> x = 1
799 (Pdb) return
800 --Return--
801 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
802 -> x = 2
803 (Pdb) until
804 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
805 -> test_function_2()
806 (Pdb) continue
807 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
808 -> x = 1
809 (Pdb) return
810 --Return--
811 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
812 -> x = 2
813 (Pdb) return
814 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
815 -> end = 1
816 (Pdb) continue
817 """
818
819def test_pdb_next_command_for_generator():
820 """Testing skip unwindng stack on yield for generators for "next" command
821
822 >>> def test_gen():
823 ... yield 0
824 ... return 1
825 ... yield 2
826
827 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -0700828 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -0800829 ... it = test_gen()
830 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300831 ... if next(it) != 0:
832 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800833 ... next(it)
834 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300835 ... if ex.value != 1:
836 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -0800837 ... print("finished")
838
839 >>> with PdbTestInput(['step',
840 ... 'step',
841 ... 'step',
842 ... 'next',
843 ... 'next',
844 ... 'step',
845 ... 'step',
846 ... 'continue']):
847 ... test_function()
848 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
849 -> it = test_gen()
850 (Pdb) step
851 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
852 -> try:
853 (Pdb) step
854 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300855 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -0800856 (Pdb) step
857 --Call--
858 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
859 -> def test_gen():
860 (Pdb) next
861 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
862 -> yield 0
863 (Pdb) next
864 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
865 -> return 1
866 (Pdb) step
867 --Return--
868 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
869 -> return 1
870 (Pdb) step
871 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +0300872 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -0800873 -> next(it)
874 (Pdb) continue
875 finished
876 """
877
Pablo Galindo46877022018-01-29 00:25:05 +0000878def test_pdb_next_command_for_coroutine():
879 """Testing skip unwindng stack on yield for coroutines for "next" command
880
881 >>> import asyncio
882
883 >>> async def test_coro():
884 ... await asyncio.sleep(0)
885 ... await asyncio.sleep(0)
886 ... await asyncio.sleep(0)
887
888 >>> async def test_main():
889 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
890 ... await test_coro()
891
892 >>> def test_function():
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000893 ... loop = asyncio.new_event_loop()
Pablo Galindo46877022018-01-29 00:25:05 +0000894 ... loop.run_until_complete(test_main())
895 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700896 ... asyncio.set_event_loop_policy(None)
Pablo Galindo46877022018-01-29 00:25:05 +0000897 ... print("finished")
898
899 >>> with PdbTestInput(['step',
900 ... 'step',
901 ... 'next',
902 ... 'next',
903 ... 'next',
904 ... 'step',
905 ... 'continue']):
906 ... test_function()
907 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
908 -> await test_coro()
909 (Pdb) step
910 --Call--
911 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
912 -> async def test_coro():
913 (Pdb) step
914 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
915 -> await asyncio.sleep(0)
916 (Pdb) next
917 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
918 -> await asyncio.sleep(0)
919 (Pdb) next
920 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
921 -> await asyncio.sleep(0)
922 (Pdb) next
923 Internal StopIteration
924 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
925 -> await test_coro()
926 (Pdb) step
927 --Return--
928 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
929 -> await test_coro()
930 (Pdb) continue
931 finished
932 """
933
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500934def test_pdb_next_command_for_asyncgen():
935 """Testing skip unwindng stack on yield for coroutines for "next" command
936
937 >>> import asyncio
938
939 >>> async def agen():
940 ... yield 1
941 ... await asyncio.sleep(0)
942 ... yield 2
943
944 >>> async def test_coro():
945 ... async for x in agen():
946 ... print(x)
947
948 >>> async def test_main():
949 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
950 ... await test_coro()
951
952 >>> def test_function():
953 ... loop = asyncio.new_event_loop()
954 ... loop.run_until_complete(test_main())
955 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -0700956 ... asyncio.set_event_loop_policy(None)
Yury Selivanov9ee1bf92018-01-28 22:43:46 -0500957 ... print("finished")
958
959 >>> with PdbTestInput(['step',
960 ... 'step',
961 ... 'next',
962 ... 'next',
963 ... 'step',
964 ... 'next',
965 ... 'continue']):
966 ... test_function()
967 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
968 -> await test_coro()
969 (Pdb) step
970 --Call--
971 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
972 -> async def test_coro():
973 (Pdb) step
974 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
975 -> async for x in agen():
976 (Pdb) next
977 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
978 -> print(x)
979 (Pdb) next
980 1
981 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
982 -> async for x in agen():
983 (Pdb) step
984 --Call--
985 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
986 -> yield 1
987 (Pdb) next
988 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
989 -> await asyncio.sleep(0)
990 (Pdb) continue
991 2
992 finished
993 """
994
Guido van Rossum8820c232013-11-21 11:30:06 -0800995def test_pdb_return_command_for_generator():
996 """Testing no unwindng stack on yield for generators
997 for "return" command
998
999 >>> def test_gen():
1000 ... yield 0
1001 ... return 1
1002 ... yield 2
1003
1004 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001005 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001006 ... it = test_gen()
1007 ... try:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001008 ... if next(it) != 0:
1009 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001010 ... next(it)
1011 ... except StopIteration as ex:
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001012 ... if ex.value != 1:
1013 ... raise AssertionError
Guido van Rossum8820c232013-11-21 11:30:06 -08001014 ... print("finished")
1015
1016 >>> with PdbTestInput(['step',
1017 ... 'step',
1018 ... 'step',
1019 ... 'return',
1020 ... 'step',
1021 ... 'step',
1022 ... 'continue']):
1023 ... test_function()
1024 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
1025 -> it = test_gen()
1026 (Pdb) step
1027 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
1028 -> try:
1029 (Pdb) step
1030 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001031 -> if next(it) != 0:
Guido van Rossum8820c232013-11-21 11:30:06 -08001032 (Pdb) step
1033 --Call--
1034 > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
1035 -> def test_gen():
1036 (Pdb) return
1037 StopIteration: 1
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001038 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001039 -> next(it)
1040 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001041 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
Guido van Rossum8820c232013-11-21 11:30:06 -08001042 -> except StopIteration as ex:
1043 (Pdb) step
Serhiy Storchakaa16de5d2015-04-01 16:58:19 +03001044 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
1045 -> if ex.value != 1:
Guido van Rossum8820c232013-11-21 11:30:06 -08001046 (Pdb) continue
1047 finished
1048 """
1049
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001050def test_pdb_return_command_for_coroutine():
1051 """Testing no unwindng stack on yield for coroutines for "return" command
1052
1053 >>> import asyncio
1054
1055 >>> async def test_coro():
1056 ... await asyncio.sleep(0)
1057 ... await asyncio.sleep(0)
1058 ... await asyncio.sleep(0)
1059
1060 >>> async def test_main():
1061 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1062 ... await test_coro()
1063
1064 >>> def test_function():
1065 ... loop = asyncio.new_event_loop()
1066 ... loop.run_until_complete(test_main())
1067 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001068 ... asyncio.set_event_loop_policy(None)
Pablo Galindoc7ab5812018-01-29 01:31:00 +00001069 ... print("finished")
1070
1071 >>> with PdbTestInput(['step',
1072 ... 'step',
1073 ... 'next',
1074 ... 'continue']):
1075 ... test_function()
1076 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
1077 -> await test_coro()
1078 (Pdb) step
1079 --Call--
1080 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
1081 -> async def test_coro():
1082 (Pdb) step
1083 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
1084 -> await asyncio.sleep(0)
1085 (Pdb) next
1086 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
1087 -> await asyncio.sleep(0)
1088 (Pdb) continue
1089 finished
1090 """
1091
Guido van Rossum8820c232013-11-21 11:30:06 -08001092def test_pdb_until_command_for_generator():
1093 """Testing no unwindng stack on yield for generators
Min ho Kimc4cacc82019-07-31 08:16:13 +10001094 for "until" command if target breakpoint is not reached
Guido van Rossum8820c232013-11-21 11:30:06 -08001095
1096 >>> def test_gen():
1097 ... yield 0
1098 ... yield 1
1099 ... yield 2
1100
1101 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001102 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001103 ... for i in test_gen():
1104 ... print(i)
1105 ... print("finished")
1106
1107 >>> with PdbTestInput(['step',
1108 ... 'until 4',
1109 ... 'step',
1110 ... 'step',
1111 ... 'continue']):
1112 ... test_function()
1113 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
1114 -> for i in test_gen():
1115 (Pdb) step
1116 --Call--
1117 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
1118 -> def test_gen():
1119 (Pdb) until 4
1120 0
1121 1
1122 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
1123 -> yield 2
1124 (Pdb) step
1125 --Return--
1126 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
1127 -> yield 2
1128 (Pdb) step
1129 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
1130 -> print(i)
1131 (Pdb) continue
1132 2
1133 finished
1134 """
1135
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001136def test_pdb_until_command_for_coroutine():
1137 """Testing no unwindng stack for coroutines
Min ho Kimc4cacc82019-07-31 08:16:13 +10001138 for "until" command if target breakpoint is not reached
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001139
1140 >>> import asyncio
1141
1142 >>> async def test_coro():
1143 ... print(0)
1144 ... await asyncio.sleep(0)
1145 ... print(1)
1146 ... await asyncio.sleep(0)
1147 ... print(2)
1148 ... await asyncio.sleep(0)
1149 ... print(3)
1150
1151 >>> async def test_main():
1152 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1153 ... await test_coro()
1154
1155 >>> def test_function():
1156 ... loop = asyncio.new_event_loop()
1157 ... loop.run_until_complete(test_main())
1158 ... loop.close()
Brett Cannon8425de42018-06-01 20:34:09 -07001159 ... asyncio.set_event_loop_policy(None)
Andrew Svetlov4f4ef0a2018-01-29 16:17:45 +02001160 ... print("finished")
1161
1162 >>> with PdbTestInput(['step',
1163 ... 'until 8',
1164 ... 'continue']):
1165 ... test_function()
1166 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
1167 -> await test_coro()
1168 (Pdb) step
1169 --Call--
1170 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
1171 -> async def test_coro():
1172 (Pdb) until 8
1173 0
1174 1
1175 2
1176 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
1177 -> print(3)
1178 (Pdb) continue
1179 3
1180 finished
1181 """
1182
Guido van Rossum8820c232013-11-21 11:30:06 -08001183def test_pdb_next_command_in_generator_for_loop():
Martin Panter46f50722016-05-26 05:35:26 +00001184 """The next command on returning from a generator controlled by a for loop.
Guido van Rossum8820c232013-11-21 11:30:06 -08001185
1186 >>> def test_gen():
1187 ... yield 0
1188 ... return 1
1189
1190 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001191 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001192 ... for i in test_gen():
1193 ... print('value', i)
1194 ... x = 123
1195
Irit Katriel21b02b52021-04-28 11:38:29 +01001196 >>> reset_Breakpoint()
Guido van Rossum8820c232013-11-21 11:30:06 -08001197 >>> with PdbTestInput(['break test_gen',
1198 ... 'continue',
1199 ... 'next',
1200 ... 'next',
1201 ... 'next',
1202 ... 'continue']):
1203 ... test_function()
1204 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1205 -> for i in test_gen():
1206 (Pdb) break test_gen
Irit Katrielad442a62021-04-02 17:15:21 +01001207 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 -08001208 (Pdb) continue
1209 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1210 -> yield 0
1211 (Pdb) next
1212 value 0
1213 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1214 -> return 1
1215 (Pdb) next
1216 Internal StopIteration: 1
1217 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1218 -> for i in test_gen():
1219 (Pdb) next
1220 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1221 -> x = 123
1222 (Pdb) continue
1223 """
1224
1225def test_pdb_next_command_subiterator():
1226 """The next command in a generator with a subiterator.
1227
1228 >>> def test_subgenerator():
1229 ... yield 0
1230 ... return 1
1231
1232 >>> def test_gen():
1233 ... x = yield from test_subgenerator()
1234 ... return x
1235
1236 >>> def test_function():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001237 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
Guido van Rossum8820c232013-11-21 11:30:06 -08001238 ... for i in test_gen():
1239 ... print('value', i)
1240 ... x = 123
1241
1242 >>> with PdbTestInput(['step',
1243 ... 'step',
1244 ... 'next',
1245 ... 'next',
1246 ... 'next',
1247 ... 'continue']):
1248 ... test_function()
1249 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1250 -> for i in test_gen():
1251 (Pdb) step
1252 --Call--
1253 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1254 -> def test_gen():
1255 (Pdb) step
1256 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1257 -> x = yield from test_subgenerator()
1258 (Pdb) next
1259 value 0
1260 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1261 -> return x
1262 (Pdb) next
1263 Internal StopIteration: 1
1264 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1265 -> for i in test_gen():
1266 (Pdb) next
1267 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1268 -> x = 123
1269 (Pdb) continue
1270 """
1271
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001272def test_pdb_issue_20766():
1273 """Test for reference leaks when the SIGINT handler is set.
1274
1275 >>> def test_function():
1276 ... i = 1
1277 ... while i <= 2:
1278 ... sess = pdb.Pdb()
1279 ... sess.set_trace(sys._getframe())
1280 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1281 ... i += 1
1282
Irit Katrielad442a62021-04-02 17:15:21 +01001283 >>> reset_Breakpoint()
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001284 >>> with PdbTestInput(['continue',
1285 ... 'continue']):
1286 ... test_function()
1287 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1288 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1289 (Pdb) continue
1290 pdb 1: <built-in function default_int_handler>
1291 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
1292 -> sess.set_trace(sys._getframe())
1293 (Pdb) continue
1294 pdb 2: <built-in function default_int_handler>
1295 """
Georg Brandl46b9afc2010-07-30 09:14:20 +00001296
Georg Brandl6cccb862010-07-30 14:16:43 +00001297
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001298class PdbTestCase(unittest.TestCase):
1299 def tearDown(self):
Hai Shi604bba12020-08-04 23:51:43 +08001300 os_helper.unlink(os_helper.TESTFN)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001301
1302 def _run_pdb(self, pdb_args, commands):
Hai Shi604bba12020-08-04 23:51:43 +08001303 self.addCleanup(os_helper.rmtree, '__pycache__')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001304 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1305 with subprocess.Popen(
1306 cmd,
1307 stdout=subprocess.PIPE,
1308 stdin=subprocess.PIPE,
1309 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001310 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001311 ) as proc:
1312 stdout, stderr = proc.communicate(str.encode(commands))
1313 stdout = stdout and bytes.decode(stdout)
1314 stderr = stderr and bytes.decode(stderr)
1315 return stdout, stderr
1316
1317 def run_pdb_script(self, script, commands):
Senthil Kumaran42d70812012-05-01 10:07:49 +08001318 """Run 'script' lines with pdb and the pdb 'commands'."""
1319 filename = 'main.py'
1320 with open(filename, 'w') as f:
1321 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001322 self.addCleanup(os_helper.unlink, filename)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001323 return self._run_pdb([filename], commands)
1324
1325 def run_pdb_module(self, script, commands):
1326 """Runs the script code as part of a module"""
1327 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001328 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001329 main_file = self.module_name + '/__main__.py'
1330 init_file = self.module_name + '/__init__.py'
1331 os.mkdir(self.module_name)
1332 with open(init_file, 'w') as f:
1333 pass
1334 with open(main_file, 'w') as f:
1335 f.write(textwrap.dedent(script))
Hai Shi604bba12020-08-04 23:51:43 +08001336 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001337 return self._run_pdb(['-m', self.module_name], commands)
Senthil Kumaran42d70812012-05-01 10:07:49 +08001338
Georg Brandl6e220552013-10-13 20:51:47 +02001339 def _assert_find_function(self, file_content, func_name, expected):
Hai Shi604bba12020-08-04 23:51:43 +08001340 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6e220552013-10-13 20:51:47 +02001341 f.write(file_content)
1342
1343 expected = None if not expected else (
Hai Shi604bba12020-08-04 23:51:43 +08001344 expected[0], os_helper.TESTFN, expected[1])
Georg Brandl6e220552013-10-13 20:51:47 +02001345 self.assertEqual(
Hai Shi604bba12020-08-04 23:51:43 +08001346 expected, pdb.find_function(func_name, os_helper.TESTFN))
Georg Brandl6e220552013-10-13 20:51:47 +02001347
1348 def test_find_function_empty_file(self):
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001349 self._assert_find_function(b'', 'foo', None)
Georg Brandl6e220552013-10-13 20:51:47 +02001350
1351 def test_find_function_found(self):
1352 self._assert_find_function(
1353 """\
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001354def foo():
1355 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001356
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001357def bœr():
1358 pass
Georg Brandl6e220552013-10-13 20:51:47 +02001359
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +03001360def quux():
1361 pass
1362""".encode(),
1363 'bœr',
1364 ('bœr', 4),
1365 )
1366
1367 def test_find_function_found_with_encoding_cookie(self):
1368 self._assert_find_function(
1369 """\
1370# coding: iso-8859-15
1371def foo():
1372 pass
1373
1374def bœr():
1375 pass
1376
1377def quux():
1378 pass
1379""".encode('iso-8859-15'),
1380 'bœr',
1381 ('bœr', 5),
1382 )
1383
1384 def test_find_function_found_with_bom(self):
1385 self._assert_find_function(
1386 codecs.BOM_UTF8 + """\
1387def bœr():
1388 pass
1389""".encode(),
1390 'bœr',
1391 ('bœr', 1),
Georg Brandl6e220552013-10-13 20:51:47 +02001392 )
1393
Georg Brandl6cccb862010-07-30 14:16:43 +00001394 def test_issue7964(self):
1395 # open the file as binary so we can force \r\n newline
Hai Shi604bba12020-08-04 23:51:43 +08001396 with open(os_helper.TESTFN, 'wb') as f:
Georg Brandl6cccb862010-07-30 14:16:43 +00001397 f.write(b'print("testing my pdb")\r\n')
Hai Shi604bba12020-08-04 23:51:43 +08001398 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
Georg Brandl6cccb862010-07-30 14:16:43 +00001399 proc = subprocess.Popen(cmd,
1400 stdout=subprocess.PIPE,
1401 stdin=subprocess.PIPE,
1402 stderr=subprocess.STDOUT,
1403 )
Brian Curtin994ad6c2010-11-05 15:38:47 +00001404 self.addCleanup(proc.stdout.close)
Georg Brandl6cccb862010-07-30 14:16:43 +00001405 stdout, stderr = proc.communicate(b'quit\n')
1406 self.assertNotIn(b'SyntaxError', stdout,
1407 "Got a syntax error running test script under PDB")
1408
Senthil Kumaran42d70812012-05-01 10:07:49 +08001409 def test_issue13183(self):
1410 script = """
1411 from bar import bar
1412
1413 def foo():
1414 bar()
1415
1416 def nope():
1417 pass
1418
1419 def foobar():
1420 foo()
1421 nope()
1422
1423 foobar()
1424 """
1425 commands = """
1426 from bar import bar
1427 break bar
1428 continue
1429 step
1430 step
1431 quit
1432 """
1433 bar = """
1434 def bar():
Senthil Kumarancb172042012-05-02 08:00:22 +08001435 pass
Senthil Kumaran42d70812012-05-01 10:07:49 +08001436 """
1437 with open('bar.py', 'w') as f:
1438 f.write(textwrap.dedent(bar))
Hai Shi604bba12020-08-04 23:51:43 +08001439 self.addCleanup(os_helper.unlink, 'bar.py')
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001440 stdout, stderr = self.run_pdb_script(script, commands)
Georg Brandl4bde9ca2012-05-01 09:21:16 +02001441 self.assertTrue(
1442 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1443 'Fail to step into the caller after a return')
Senthil Kumaran42d70812012-05-01 10:07:49 +08001444
Daniel Hahler9139f922019-04-01 23:59:50 +02001445 def test_issue13120(self):
1446 # Invoking "continue" on a non-main thread triggered an exception
1447 # inside signal.signal.
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001448
Hai Shi604bba12020-08-04 23:51:43 +08001449 with open(os_helper.TESTFN, 'wb') as f:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001450 f.write(textwrap.dedent("""
1451 import threading
1452 import pdb
1453
1454 def start_pdb():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001455 pdb.Pdb(readrc=False).set_trace()
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001456 x = 1
1457 y = 1
1458
1459 t = threading.Thread(target=start_pdb)
1460 t.start()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001461 cmd = [sys.executable, '-u', os_helper.TESTFN]
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001462 proc = subprocess.Popen(cmd,
1463 stdout=subprocess.PIPE,
1464 stdin=subprocess.PIPE,
1465 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001466 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001467 )
1468 self.addCleanup(proc.stdout.close)
1469 stdout, stderr = proc.communicate(b'cont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001470 self.assertNotIn(b'Error', stdout,
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001471 "Got an error running test script under PDB")
1472
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001473 def test_issue36250(self):
1474
Hai Shi604bba12020-08-04 23:51:43 +08001475 with open(os_helper.TESTFN, 'wb') as f:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001476 f.write(textwrap.dedent("""
1477 import threading
1478 import pdb
1479
1480 evt = threading.Event()
1481
1482 def start_pdb():
1483 evt.wait()
1484 pdb.Pdb(readrc=False).set_trace()
1485
1486 t = threading.Thread(target=start_pdb)
1487 t.start()
1488 pdb.Pdb(readrc=False).set_trace()
1489 evt.set()
1490 t.join()""").encode('ascii'))
Hai Shi604bba12020-08-04 23:51:43 +08001491 cmd = [sys.executable, '-u', os_helper.TESTFN]
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001492 proc = subprocess.Popen(cmd,
1493 stdout=subprocess.PIPE,
1494 stdin=subprocess.PIPE,
1495 stderr=subprocess.STDOUT,
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001496 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001497 )
1498 self.addCleanup(proc.stdout.close)
1499 stdout, stderr = proc.communicate(b'cont\ncont\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001500 self.assertNotIn(b'Error', stdout,
Daniel Hahler8d64bfa2019-09-09 12:45:58 +02001501 "Got an error running test script under PDB")
1502
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001503 def test_issue16180(self):
1504 # A syntax error in the debuggee.
1505 script = "def f: pass\n"
1506 commands = ''
1507 expected = "SyntaxError:"
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001508 stdout, stderr = self.run_pdb_script(script, commands)
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001509 self.assertIn(expected, stdout,
1510 '\n\nExpected:\n{}\nGot:\n{}\n'
1511 'Fail to handle a syntax error in the debuggee.'
1512 .format(expected, stdout))
1513
Irit Katriel652bfde2021-04-01 16:25:59 +01001514 def test_issue26053(self):
1515 # run command of pdb prompt echoes the correct args
1516 script = "print('hello')"
1517 commands = """
1518 continue
1519 run a b c
1520 run d e f
1521 quit
1522 """
1523 stdout, stderr = self.run_pdb_script(script, commands)
Irit Katrielbd4ab8e2021-04-01 20:05:51 +01001524 res = '\n'.join([x.strip() for x in stdout.splitlines()])
1525 self.assertRegex(res, "Restarting .* with arguments:\na b c")
1526 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001527
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001528 def test_readrc_kwarg(self):
Victor Stinner11ea0442016-09-09 22:56:54 -07001529 script = textwrap.dedent("""
1530 import pdb; pdb.Pdb(readrc=False).set_trace()
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001531
Victor Stinner11ea0442016-09-09 22:56:54 -07001532 print('hello')
1533 """)
Victor Stinner11ea0442016-09-09 22:56:54 -07001534
Victor Stinnerbc626262016-09-09 23:22:09 -07001535 save_home = os.environ.pop('HOME', None)
1536 try:
Hai Shi604bba12020-08-04 23:51:43 +08001537 with os_helper.temp_cwd():
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001538 with open('.pdbrc', 'w') as f:
1539 f.write("invalid\n")
1540
1541 with open('main.py', 'w') as f:
1542 f.write(script)
1543
1544 cmd = [sys.executable, 'main.py']
1545 proc = subprocess.Popen(
1546 cmd,
1547 stdout=subprocess.PIPE,
1548 stdin=subprocess.PIPE,
1549 stderr=subprocess.PIPE,
1550 )
Victor Stinnerbc626262016-09-09 23:22:09 -07001551 with proc:
1552 stdout, stderr = proc.communicate(b'q\n')
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001553 self.assertNotIn(b"NameError: name 'invalid' is not defined",
1554 stdout)
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001555
1556 finally:
Victor Stinner11ea0442016-09-09 22:56:54 -07001557 if save_home is not None:
1558 os.environ['HOME'] = save_home
Łukasz Langa2eb6eca2016-09-09 22:21:17 -07001559
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001560 def test_readrc_homedir(self):
1561 save_home = os.environ.pop("HOME", None)
Hai Shi604bba12020-08-04 23:51:43 +08001562 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
Timothy Hopper7ea9a852019-08-02 18:20:14 -04001563 rc_path = os.path.join(temp_dir, ".pdbrc")
1564 os.path.expanduser.return_value = rc_path
1565 try:
1566 with open(rc_path, "w") as f:
1567 f.write("invalid")
1568 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1569 finally:
1570 if save_home is not None:
1571 os.environ["HOME"] = save_home
1572
Barry Warsaw35425d62017-09-22 12:29:42 -04001573 def test_header(self):
1574 stdout = StringIO()
1575 header = 'Nobody expects... blah, blah, blah'
1576 with ExitStack() as resources:
1577 resources.enter_context(patch('sys.stdout', stdout))
1578 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1579 pdb.set_trace(header=header)
1580 self.assertEqual(stdout.getvalue(), header + '\n')
1581
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001582 def test_run_module(self):
1583 script = """print("SUCCESS")"""
1584 commands = """
1585 continue
1586 quit
1587 """
1588 stdout, stderr = self.run_pdb_module(script, commands)
1589 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1590
1591 def test_module_is_run_as_main(self):
1592 script = """
1593 if __name__ == '__main__':
1594 print("SUCCESS")
1595 """
1596 commands = """
1597 continue
1598 quit
1599 """
1600 stdout, stderr = self.run_pdb_module(script, commands)
1601 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1602
1603 def test_breakpoint(self):
1604 script = """
1605 if __name__ == '__main__':
1606 pass
1607 print("SUCCESS")
1608 pass
1609 """
1610 commands = """
1611 b 3
1612 quit
1613 """
1614 stdout, stderr = self.run_pdb_module(script, commands)
1615 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1616 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1617
1618 def test_run_pdb_with_pdb(self):
1619 commands = """
1620 c
1621 quit
1622 """
1623 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001624 self.assertIn(
1625 pdb._usage,
1626 stdout.replace('\r', '') # remove \r for windows
1627 )
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001628
1629 def test_module_without_a_main(self):
1630 module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001631 os_helper.rmtree(module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001632 init_file = module_name + '/__init__.py'
1633 os.mkdir(module_name)
1634 with open(init_file, 'w') as f:
1635 pass
Hai Shi604bba12020-08-04 23:51:43 +08001636 self.addCleanup(os_helper.rmtree, module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001637 stdout, stderr = self._run_pdb(['-m', module_name], "")
1638 self.assertIn("ImportError: No module named t_main.__main__",
1639 stdout.splitlines())
1640
1641 def test_blocks_at_first_code_line(self):
1642 script = """
1643 #This is a comment, on line 2
1644
1645 print("SUCCESS")
1646 """
1647 commands = """
1648 quit
1649 """
1650 stdout, stderr = self.run_pdb_module(script, commands)
1651 self.assertTrue(any("__main__.py(4)<module>()"
1652 in l for l in stdout.splitlines()), stdout)
1653
1654 def test_relative_imports(self):
1655 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001656 os_helper.rmtree(self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001657 main_file = self.module_name + '/__main__.py'
1658 init_file = self.module_name + '/__init__.py'
1659 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001660 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001661 os.mkdir(self.module_name)
1662 with open(init_file, 'w') as f:
1663 f.write(textwrap.dedent("""
1664 top_var = "VAR from top"
1665 """))
1666 with open(main_file, 'w') as f:
1667 f.write(textwrap.dedent("""
1668 from . import top_var
1669 from .module import var
1670 from . import module
1671 pass # We'll stop here and print the vars
1672 """))
1673 with open(module_file, 'w') as f:
1674 f.write(textwrap.dedent("""
1675 var = "VAR from module"
1676 var2 = "second var"
1677 """))
1678 commands = """
1679 b 5
1680 c
1681 p top_var
1682 p var
1683 p module.var2
1684 quit
1685 """
1686 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
Mario Corchero38bfa842018-02-03 06:40:11 +00001687 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001688 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1689 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Georg Brandl6cccb862010-07-30 14:16:43 +00001690
Mario Corchero38bfa842018-02-03 06:40:11 +00001691 def test_relative_imports_on_plain_module(self):
1692 # Validates running a plain module. See bpo32691
1693 self.module_name = 't_main'
Hai Shi604bba12020-08-04 23:51:43 +08001694 os_helper.rmtree(self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001695 main_file = self.module_name + '/runme.py'
1696 init_file = self.module_name + '/__init__.py'
1697 module_file = self.module_name + '/module.py'
Hai Shi604bba12020-08-04 23:51:43 +08001698 self.addCleanup(os_helper.rmtree, self.module_name)
Mario Corchero38bfa842018-02-03 06:40:11 +00001699 os.mkdir(self.module_name)
1700 with open(init_file, 'w') as f:
1701 f.write(textwrap.dedent("""
1702 top_var = "VAR from top"
1703 """))
1704 with open(main_file, 'w') as f:
1705 f.write(textwrap.dedent("""
1706 from . import module
1707 pass # We'll stop here and print the vars
1708 """))
1709 with open(module_file, 'w') as f:
1710 f.write(textwrap.dedent("""
1711 var = "VAR from module"
1712 """))
1713 commands = """
1714 b 3
1715 c
1716 p module.var
1717 quit
1718 """
1719 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1720 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1721
Daniel Hahler3e936432019-03-12 04:29:04 +01001722 def test_errors_in_command(self):
1723 commands = "\n".join([
1724 'print(',
1725 'debug print(',
1726 'debug doesnotexist',
1727 'c',
1728 ])
Mark Shannon877df852020-11-12 09:43:29 +00001729 stdout, _ = self.run_pdb_script('pass', commands + '\n')
Daniel Hahler3e936432019-03-12 04:29:04 +01001730
Daniel Hahler43277052019-02-15 21:52:53 +01001731 self.assertEqual(stdout.splitlines()[1:], [
Mark Shannon877df852020-11-12 09:43:29 +00001732 '-> pass',
Pablo Galindod6d63712021-01-19 23:59:33 +00001733 '(Pdb) *** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001734
1735 '(Pdb) ENTERING RECURSIVE DEBUGGER',
Pablo Galindod6d63712021-01-19 23:59:33 +00001736 '*** SyntaxError: \'(\' was never closed',
Daniel Hahler3e936432019-03-12 04:29:04 +01001737 'LEAVING RECURSIVE DEBUGGER',
1738
1739 '(Pdb) ENTERING RECURSIVE DEBUGGER',
1740 '> <string>(1)<module>()',
1741 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1742 'LEAVING RECURSIVE DEBUGGER',
Daniel Hahler43277052019-02-15 21:52:53 +01001743 '(Pdb) ',
1744 ])
Georg Brandl6cccb862010-07-30 14:16:43 +00001745
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001746
1747 def test_issue42384(self):
1748 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1749 script = textwrap.dedent("""
1750 import sys
1751 print('sys.path[0] is', sys.path[0])
1752 """)
1753 commands = 'c\nq'
1754
1755 with os_helper.temp_cwd() as cwd:
1756 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1757
1758 stdout, stderr = self.run_pdb_script(script, commands)
1759
1760 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1761
1762 @os_helper.skip_unless_symlink
1763 def test_issue42384_symlink(self):
1764 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1765 script = textwrap.dedent("""
1766 import sys
1767 print('sys.path[0] is', sys.path[0])
1768 """)
1769 commands = 'c\nq'
1770
1771 with os_helper.temp_cwd() as cwd:
1772 cwd = os.path.realpath(cwd)
1773 dir_one = os.path.join(cwd, 'dir_one')
1774 dir_two = os.path.join(cwd, 'dir_two')
1775 expected = f'(Pdb) sys.path[0] is {dir_one}'
1776
1777 os.mkdir(dir_one)
1778 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1779 f.write(script)
1780 os.mkdir(dir_two)
1781 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1782
1783 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1784
1785 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1786
Andrey Bienkowski501d4a52021-01-25 21:08:01 +00001787 def test_issue42383(self):
1788 with os_helper.temp_cwd() as cwd:
1789 with open('foo.py', 'w') as f:
1790 s = textwrap.dedent("""
1791 print('The correct file was executed')
1792
1793 import os
1794 os.chdir("subdir")
1795 """)
1796 f.write(s)
1797
1798 subdir = os.path.join(cwd, 'subdir')
1799 os.mkdir(subdir)
1800 os.mkdir(os.path.join(subdir, 'subdir'))
1801 wrong_file = os.path.join(subdir, 'foo.py')
1802
1803 with open(wrong_file, 'w') as f:
1804 f.write('print("The wrong file was executed")')
1805
1806 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
1807 expected = '(Pdb) The correct file was executed'
1808 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
1809
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001810
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001811class ChecklineTests(unittest.TestCase):
1812 def setUp(self):
1813 linecache.clearcache() # Pdb.checkline() uses linecache.getline()
1814
1815 def tearDown(self):
1816 os_helper.unlink(os_helper.TESTFN)
1817
1818 def test_checkline_before_debugging(self):
1819 with open(os_helper.TESTFN, "w") as f:
1820 f.write("print(123)")
1821 db = pdb.Pdb()
1822 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1823
1824 def test_checkline_after_reset(self):
1825 with open(os_helper.TESTFN, "w") as f:
1826 f.write("print(123)")
1827 db = pdb.Pdb()
1828 db.reset()
1829 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
1830
1831 def test_checkline_is_not_executable(self):
1832 with open(os_helper.TESTFN, "w") as f:
1833 # Test for comments, docstrings and empty lines
1834 s = textwrap.dedent("""
1835 # Comment
1836 \"\"\" docstring \"\"\"
1837 ''' docstring '''
1838
1839 """)
1840 f.write(s)
1841 db = pdb.Pdb()
1842 num_lines = len(s.splitlines()) + 2 # Test for EOF
1843 for lineno in range(num_lines):
1844 self.assertFalse(db.checkline(os_helper.TESTFN, lineno))
1845
1846
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001847def load_tests(*args):
Georg Brandl243ad662009-05-05 09:00:19 +00001848 from test import test_pdb
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001849 suites = [
1850 unittest.makeSuite(PdbTestCase),
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -07001851 unittest.makeSuite(ChecklineTests),
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001852 doctest.DocTestSuite(test_pdb)
1853 ]
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001854 return unittest.TestSuite(suites)
Georg Brandl243ad662009-05-05 09:00:19 +00001855
1856
1857if __name__ == '__main__':
Andrew Svetlovf0efea02013-03-18 10:09:50 -07001858 unittest.main()