Debian Codegraph @

lib-python/3/test/test_pdb.py

raw symbols SCIP
1 # A test suite for pdb; not very comprehensive at the moment.
2
3 import doctest
4 import os
5 import pdb
6 import sys
7 import types
8 import codecs
9 import unittest
10 import subprocess
11 import textwrap
12 import linecache
13
14 from contextlib import ExitStack, redirect_stdout
15 from io import StringIO
16 from test import support
17 from test.support import os_helper
18 from test.support.import_helper import import_module
19 from test.support.pty_helper import run_pty, FakeInput
20 from unittest.mock import patch
21
22 # gh-114275: WASI fails to run asyncio tests, similar skip than test_asyncio.
23 SKIP_ASYNCIO_TESTS = (not support.has_socket_support)
24
25
26 class PdbTestInput(object):
27 """Context manager that makes testing Pdb in doctests easier."""
28
29 def __init__(self, input):
30 self.input = input
31
32 def __enter__(self):
33 self.real_stdin = sys.stdin
34 sys.stdin = FakeInput(self.input)
35 self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
36
37 def __exit__(self, *exc):
38 sys.stdin = self.real_stdin
39 if self.orig_trace:
40 sys.settrace(self.orig_trace)
41
42
43 def test_pdb_displayhook():
44 """This tests the custom displayhook for pdb.
45
46 >>> def test_function(foo, bar):
47 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
48 ... pass
49
50 >>> with PdbTestInput([
51 ... 'foo',
52 ... 'bar',
53 ... 'for i in range(5): print(i)',
54 ... 'continue',
55 ... ]):
56 ... test_function(1, None)
57 > <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function()
58 -> pass
59 (Pdb) foo
60 1
61 (Pdb) bar
62 (Pdb) for i in range(5): print(i)
63 0
64 1
65 2
66 3
67 4
68 (Pdb) continue
69 """
70
71
72 def test_pdb_basic_commands():
73 """Test the basic commands of pdb.
74
75 >>> def test_function_2(foo, bar='default'):
76 ... print(foo)
77 ... for i in range(5):
78 ... print(i)
79 ... print(bar)
80 ... for i in range(10):
81 ... never_executed
82 ... print('after for')
83 ... print('...')
84 ... return foo.upper()
85
86 >>> def test_function3(arg=None, *, kwonly=None):
87 ... pass
88
89 >>> def test_function4(a, b, c, /):
90 ... pass
91
92 >>> def test_function():
93 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
94 ... ret = test_function_2('baz')
95 ... test_function3(kwonly=True)
96 ... test_function4(1, 2, 3)
97 ... print(ret)
98
99 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
100 ... 'step', # entering the function call
101 ... 'args', # display function args
102 ... 'list', # list function source
103 ... 'bt', # display backtrace
104 ... 'up', # step up to test_function()
105 ... 'down', # step down to test_function_2() again
106 ... 'next', # stepping to print(foo)
107 ... 'next', # stepping to the for loop
108 ... 'step', # stepping into the for loop
109 ... 'until', # continuing until out of the for loop
110 ... 'next', # executing the print(bar)
111 ... 'jump 8', # jump over second for loop
112 ... 'return', # return out of function
113 ... 'retval', # display return value
114 ... 'next', # step to test_function3()
115 ... 'step', # stepping into test_function3()
116 ... 'args', # display function args
117 ... 'return', # return out of function
118 ... 'next', # step to test_function4()
119 ... 'step', # stepping to test_function4()
120 ... 'args', # display function args
121 ... 'continue',
122 ... ]):
123 ... test_function()
124 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
125 -> ret = test_function_2('baz')
126 (Pdb) step
127 --Call--
128 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
129 -> def test_function_2(foo, bar='default'):
130 (Pdb) args
131 foo = 'baz'
132 bar = 'default'
133 (Pdb) list
134 1 -> def test_function_2(foo, bar='default'):
135 2 print(foo)
136 3 for i in range(5):
137 4 print(i)
138 5 print(bar)
139 6 for i in range(10):
140 7 never_executed
141 8 print('after for')
142 9 print('...')
143 10 return foo.upper()
144 [EOF]
145 (Pdb) bt
146 ...
147 <doctest test.test_pdb.test_pdb_basic_commands[4]>(25)<module>()
148 -> test_function()
149 <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
150 -> ret = test_function_2('baz')
151 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
152 -> def test_function_2(foo, bar='default'):
153 (Pdb) up
154 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
155 -> ret = test_function_2('baz')
156 (Pdb) down
157 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
158 -> def test_function_2(foo, bar='default'):
159 (Pdb) next
160 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
161 -> print(foo)
162 (Pdb) next
163 baz
164 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
165 -> for i in range(5):
166 (Pdb) step
167 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
168 -> print(i)
169 (Pdb) until
170 0
171 1
172 2
173 3
174 4
175 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
176 -> print(bar)
177 (Pdb) next
178 default
179 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
180 -> for i in range(10):
181 (Pdb) jump 8
182 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
183 -> print('after for')
184 (Pdb) return
185 after for
186 ...
187 --Return--
188 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
189 -> return foo.upper()
190 (Pdb) retval
191 'BAZ'
192 (Pdb) next
193 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(4)test_function()
194 -> test_function3(kwonly=True)
195 (Pdb) step
196 --Call--
197 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(1)test_function3()
198 -> def test_function3(arg=None, *, kwonly=None):
199 (Pdb) args
200 arg = None
201 kwonly = True
202 (Pdb) return
203 --Return--
204 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(2)test_function3()->None
205 -> pass
206 (Pdb) next
207 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(5)test_function()
208 -> test_function4(1, 2, 3)
209 (Pdb) step
210 --Call--
211 > <doctest test.test_pdb.test_pdb_basic_commands[2]>(1)test_function4()
212 -> def test_function4(a, b, c, /):
213 (Pdb) args
214 a = 1
215 b = 2
216 c = 3
217 (Pdb) continue
218 BAZ
219 """
220
221 def reset_Breakpoint():
222 import bdb
223 bdb.Breakpoint.clearBreakpoints()
224
225 def test_pdb_breakpoint_commands():
226 """Test basic commands related to breakpoints.
227
228 >>> def test_function():
229 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
230 ... print(1)
231 ... print(2)
232 ... print(3)
233 ... print(4)
234
235 First, need to clear bdb state that might be left over from previous tests.
236 Otherwise, the new breakpoints might get assigned different numbers.
237
238 >>> reset_Breakpoint()
239
240 Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because
241 the breakpoint list outputs a tab for the "stop only" and "ignore next"
242 lines, which we don't want to put in here.
243
244 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
245 ... 'break 3',
246 ... 'disable 1',
247 ... 'ignore 1 10',
248 ... 'condition 1 1 < 2',
249 ... 'break 4',
250 ... 'break 4',
251 ... 'break',
252 ... 'clear 3',
253 ... 'break',
254 ... 'condition 1',
255 ... 'enable 1',
256 ... 'clear 1',
257 ... 'commands 2',
258 ... 'p "42"',
259 ... 'print("42", 7*6)', # Issue 18764 (not about breakpoints)
260 ... 'end',
261 ... 'continue', # will stop at breakpoint 2 (line 4)
262 ... 'clear', # clear all!
263 ... 'y',
264 ... 'tbreak 5',
265 ... 'continue', # will stop at temporary breakpoint
266 ... 'break', # make sure breakpoint is gone
267 ... 'commands 10', # out of range
268 ... 'commands a', # display help
269 ... 'commands 4', # already deleted
270 ... 'continue',
271 ... ]):
272 ... test_function()
273 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
274 -> print(1)
275 (Pdb) break 3
276 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
277 (Pdb) disable 1
278 Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
279 (Pdb) ignore 1 10
280 Will ignore next 10 crossings of breakpoint 1.
281 (Pdb) condition 1 1 < 2
282 New condition set for breakpoint 1.
283 (Pdb) break 4
284 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
285 (Pdb) break 4
286 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
287 (Pdb) break
288 Num Type Disp Enb Where
289 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
290 stop only if 1 < 2
291 ignore next 10 hits
292 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
293 3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
294 (Pdb) clear 3
295 Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
296 (Pdb) break
297 Num Type Disp Enb Where
298 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
299 stop only if 1 < 2
300 ignore next 10 hits
301 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
302 (Pdb) condition 1
303 Breakpoint 1 is now unconditional.
304 (Pdb) enable 1
305 Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
306 (Pdb) clear 1
307 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
308 (Pdb) commands 2
309 (com) p "42"
310 (com) print("42", 7*6)
311 (com) end
312 (Pdb) continue
313 1
314 '42'
315 42 42
316 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
317 -> print(2)
318 (Pdb) clear
319 Clear all breaks? y
320 Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
321 (Pdb) tbreak 5
322 Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
323 (Pdb) continue
324 2
325 Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
326 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
327 -> print(3)
328 (Pdb) break
329 (Pdb) commands 10
330 *** cannot set commands: Breakpoint number 10 out of range
331 (Pdb) commands a
332 *** Usage: commands [bnum]
333 ...
334 end
335 (Pdb) commands 4
336 *** cannot set commands: Breakpoint 4 already deleted
337 (Pdb) continue
338 3
339 4
340 """
341
342 def test_pdb_breakpoints_preserved_across_interactive_sessions():
343 """Breakpoints are remembered between interactive sessions
344
345 >>> reset_Breakpoint()
346 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
347 ... 'import test.test_pdb',
348 ... 'break test.test_pdb.do_something',
349 ... 'break test.test_pdb.do_nothing',
350 ... 'break',
351 ... 'continue',
352 ... ]):
353 ... pdb.run('print()')
354 > <string>(1)<module>()...
355 (Pdb) import test.test_pdb
356 (Pdb) break test.test_pdb.do_something
357 Breakpoint 1 at ...test_pdb.py:...
358 (Pdb) break test.test_pdb.do_nothing
359 Breakpoint 2 at ...test_pdb.py:...
360 (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) continue
365
366 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
367 ... 'break',
368 ... 'break pdb.find_function',
369 ... 'break',
370 ... 'clear 1',
371 ... 'continue',
372 ... ]):
373 ... pdb.run('print()')
374 > <string>(1)<module>()...
375 (Pdb) break
376 Num Type Disp Enb Where
377 1 breakpoint keep yes at ...test_pdb.py:...
378 2 breakpoint keep yes at ...test_pdb.py:...
379 (Pdb) break pdb.find_function
380 Breakpoint 3 at ...pdb.py:97
381 (Pdb) break
382 Num Type Disp Enb Where
383 1 breakpoint keep yes at ...test_pdb.py:...
384 2 breakpoint keep yes at ...test_pdb.py:...
385 3 breakpoint keep yes at ...pdb.py:...
386 (Pdb) clear 1
387 Deleted breakpoint 1 at ...test_pdb.py:...
388 (Pdb) continue
389
390 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
391 ... 'break',
392 ... 'clear 2',
393 ... 'clear 3',
394 ... 'continue',
395 ... ]):
396 ... pdb.run('print()')
397 > <string>(1)<module>()...
398 (Pdb) break
399 Num Type Disp Enb Where
400 2 breakpoint keep yes at ...test_pdb.py:...
401 3 breakpoint keep yes at ...pdb.py:...
402 (Pdb) clear 2
403 Deleted breakpoint 2 at ...test_pdb.py:...
404 (Pdb) clear 3
405 Deleted breakpoint 3 at ...pdb.py:...
406 (Pdb) continue
407 """
408
409 def test_pdb_pp_repr_exc():
410 """Test that do_p/do_pp do not swallow exceptions.
411
412 >>> class BadRepr:
413 ... def __repr__(self):
414 ... raise Exception('repr_exc')
415 >>> obj = BadRepr()
416
417 >>> def test_function():
418 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
419
420 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
421 ... 'p obj',
422 ... 'pp obj',
423 ... 'continue',
424 ... ]):
425 ... test_function()
426 --Return--
427 > <doctest test.test_pdb.test_pdb_pp_repr_exc[2]>(2)test_function()->None
428 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
429 (Pdb) p obj
430 *** Exception: repr_exc
431 (Pdb) pp obj
432 *** Exception: repr_exc
433 (Pdb) continue
434 """
435
436
437 def do_nothing():
438 pass
439
440 def do_something():
441 print(42)
442
443 def test_list_commands():
444 """Test the list and source commands of pdb.
445
446 >>> def test_function_2(foo):
447 ... import test.test_pdb
448 ... test.test_pdb.do_nothing()
449 ... 'some...'
450 ... 'more...'
451 ... 'code...'
452 ... 'to...'
453 ... 'make...'
454 ... 'a...'
455 ... 'long...'
456 ... 'listing...'
457 ... 'useful...'
458 ... '...'
459 ... '...'
460 ... return foo
461
462 >>> def test_function():
463 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
464 ... ret = test_function_2('baz')
465
466 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
467 ... 'list', # list first function
468 ... 'step', # step into second function
469 ... 'list', # list second function
470 ... 'list', # continue listing to EOF
471 ... 'list 1,3', # list specific lines
472 ... 'list x', # invalid argument
473 ... 'next', # step to import
474 ... 'next', # step over import
475 ... 'step', # step into do_nothing
476 ... 'longlist', # list all lines
477 ... 'source do_something', # list all lines of function
478 ... 'source fooxxx', # something that doesn't exit
479 ... 'continue',
480 ... ]):
481 ... test_function()
482 > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
483 -> ret = test_function_2('baz')
484 (Pdb) list
485 1 def test_function():
486 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
487 3 -> ret = test_function_2('baz')
488 [EOF]
489 (Pdb) step
490 --Call--
491 > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
492 -> def test_function_2(foo):
493 (Pdb) list
494 1 -> def test_function_2(foo):
495 2 import test.test_pdb
496 3 test.test_pdb.do_nothing()
497 4 'some...'
498 5 'more...'
499 6 'code...'
500 7 'to...'
501 8 'make...'
502 9 'a...'
503 10 'long...'
504 11 'listing...'
505 (Pdb) list
506 12 'useful...'
507 13 '...'
508 14 '...'
509 15 return foo
510 [EOF]
511 (Pdb) list 1,3
512 1 -> def test_function_2(foo):
513 2 import test.test_pdb
514 3 test.test_pdb.do_nothing()
515 (Pdb) list x
516 *** ...
517 (Pdb) next
518 > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
519 -> import test.test_pdb
520 (Pdb) next
521 > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
522 -> test.test_pdb.do_nothing()
523 (Pdb) step
524 --Call--
525 > ...test_pdb.py(...)do_nothing()
526 -> def do_nothing():
527 (Pdb) longlist
528 ... -> def do_nothing():
529 ... pass
530 (Pdb) source do_something
531 ... def do_something():
532 ... print(42)
533 (Pdb) source fooxxx
534 *** ...
535 (Pdb) continue
536 """
537
538 def test_pdb_whatis_command():
539 """Test the whatis command
540
541 >>> myvar = (1,2)
542 >>> def myfunc():
543 ... pass
544
545 >>> class MyClass:
546 ... def mymethod(self):
547 ... pass
548
549 >>> def test_function():
550 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
551
552 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
553 ... 'whatis myvar',
554 ... 'whatis myfunc',
555 ... 'whatis MyClass',
556 ... 'whatis MyClass()',
557 ... 'whatis MyClass.mymethod',
558 ... 'whatis MyClass().mymethod',
559 ... 'continue',
560 ... ]):
561 ... test_function()
562 --Return--
563 > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()->None
564 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
565 (Pdb) whatis myvar
566 <class 'tuple'>
567 (Pdb) whatis myfunc
568 Function myfunc
569 (Pdb) whatis MyClass
570 Class test.test_pdb.MyClass
571 (Pdb) whatis MyClass()
572 <class 'test.test_pdb.MyClass'>
573 (Pdb) whatis MyClass.mymethod
574 Function mymethod
575 (Pdb) whatis MyClass().mymethod
576 Method mymethod
577 (Pdb) continue
578 """
579
580 def test_pdb_display_command():
581 """Test display command
582
583 >>> def test_function():
584 ... a = 0
585 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
586 ... a = 1
587 ... a = 2
588 ... a = 3
589 ... a = 4
590
591 >>> with PdbTestInput([ # doctest: +ELLIPSIS
592 ... 'display a',
593 ... 'n',
594 ... 'display',
595 ... 'undisplay a',
596 ... 'n',
597 ... 'display a',
598 ... 'undisplay',
599 ... 'display a < 1',
600 ... 'n',
601 ... 'continue',
602 ... ]):
603 ... test_function()
604 > <doctest test.test_pdb.test_pdb_display_command[0]>(4)test_function()
605 -> a = 1
606 (Pdb) display a
607 display a: 0
608 (Pdb) n
609 > <doctest test.test_pdb.test_pdb_display_command[0]>(5)test_function()
610 -> a = 2
611 display a: 1 [old: 0]
612 (Pdb) display
613 Currently displaying:
614 a: 1
615 (Pdb) undisplay a
616 (Pdb) n
617 > <doctest test.test_pdb.test_pdb_display_command[0]>(6)test_function()
618 -> a = 3
619 (Pdb) display a
620 display a: 2
621 (Pdb) undisplay
622 (Pdb) display a < 1
623 display a < 1: False
624 (Pdb) n
625 > <doctest test.test_pdb.test_pdb_display_command[0]>(7)test_function()
626 -> a = 4
627 (Pdb) continue
628 """
629
630 def test_pdb_alias_command():
631 """Test alias command
632
633 >>> class A:
634 ... def __init__(self):
635 ... self.attr1 = 10
636 ... self.attr2 = 'str'
637 ... def method(self):
638 ... pass
639
640 >>> def test_function():
641 ... o = A()
642 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
643 ... o.method()
644
645 >>> with PdbTestInput([ # doctest: +ELLIPSIS
646 ... 'alias pi',
647 ... 'alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")',
648 ... 'alias ps pi self',
649 ... 'alias ps',
650 ... 'pi o',
651 ... 's',
652 ... 'ps',
653 ... 'continue',
654 ... ]):
655 ... test_function()
656 > <doctest test.test_pdb.test_pdb_alias_command[1]>(4)test_function()
657 -> o.method()
658 (Pdb) alias pi
659 *** Unknown alias 'pi'
660 (Pdb) alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
661 (Pdb) alias ps pi self
662 (Pdb) alias ps
663 ps = pi self
664 (Pdb) pi o
665 o.attr1 = 10
666 o.attr2 = str
667 (Pdb) s
668 --Call--
669 > <doctest test.test_pdb.test_pdb_alias_command[0]>(5)method()
670 -> def method(self):
671 (Pdb) ps
672 self.attr1 = 10
673 self.attr2 = str
674 (Pdb) continue
675 """
676
677 def test_pdb_where_command():
678 """Test where command
679
680 >>> def g():
681 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
682
683 >>> def f():
684 ... g();
685
686 >>> def test_function():
687 ... f()
688
689 >>> with PdbTestInput([ # doctest: +ELLIPSIS
690 ... 'w',
691 ... 'where',
692 ... 'u',
693 ... 'w',
694 ... 'continue',
695 ... ]):
696 ... test_function()
697 --Return--
698 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()->None
699 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
700 (Pdb) w
701 ...
702 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
703 -> test_function()
704 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
705 -> f()
706 <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
707 -> g();
708 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()->None
709 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
710 (Pdb) where
711 ...
712 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
713 -> test_function()
714 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
715 -> f()
716 <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
717 -> g();
718 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()->None
719 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
720 (Pdb) u
721 > <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
722 -> g();
723 (Pdb) w
724 ...
725 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
726 -> test_function()
727 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
728 -> f()
729 > <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
730 -> g();
731 <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()->None
732 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
733 (Pdb) continue
734 """
735
736 def test_post_mortem():
737 """Test post mortem traceback debugging.
738
739 >>> def test_function_2():
740 ... try:
741 ... 1/0
742 ... finally:
743 ... print('Exception!')
744
745 >>> def test_function():
746 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
747 ... test_function_2()
748 ... print('Not reached.')
749
750 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
751 ... 'next', # step over exception-raising call
752 ... 'bt', # get a backtrace
753 ... 'list', # list code of test_function()
754 ... 'down', # step into test_function_2()
755 ... 'list', # list code of test_function_2()
756 ... 'continue',
757 ... ]):
758 ... try:
759 ... test_function()
760 ... except ZeroDivisionError:
761 ... print('Correctly reraised.')
762 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
763 -> test_function_2()
764 (Pdb) next
765 Exception!
766 ZeroDivisionError: division by zero
767 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
768 -> test_function_2()
769 (Pdb) bt
770 ...
771 <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
772 -> test_function()
773 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
774 -> test_function_2()
775 <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
776 -> 1/0
777 (Pdb) list
778 1 def test_function():
779 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
780 3 -> test_function_2()
781 4 print('Not reached.')
782 [EOF]
783 (Pdb) down
784 > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
785 -> 1/0
786 (Pdb) list
787 1 def test_function_2():
788 2 try:
789 3 >> 1/0
790 4 finally:
791 5 -> print('Exception!')
792 [EOF]
793 (Pdb) continue
794 Correctly reraised.
795 """
796
797
798 def test_pdb_skip_modules():
799 """This illustrates the simple case of module skipping.
800
801 >>> def skip_module():
802 ... import string
803 ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
804 ... string.capwords('FOO')
805
806 >>> with PdbTestInput([
807 ... 'step',
808 ... 'continue',
809 ... ]):
810 ... skip_module()
811 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
812 -> string.capwords('FOO')
813 (Pdb) step
814 --Return--
815 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
816 -> string.capwords('FOO')
817 (Pdb) continue
818 """
819
820
821 # Module for testing skipping of module that makes a callback
822 mod = types.ModuleType('module_to_skip')
823 exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
824
825
826 def test_pdb_skip_modules_with_callback():
827 """This illustrates skipping of modules that call into other code.
828
829 >>> def skip_module():
830 ... def callback():
831 ... return None
832 ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
833 ... mod.foo_pony(callback)
834
835 >>> with PdbTestInput([
836 ... 'step',
837 ... 'step',
838 ... 'step',
839 ... 'step',
840 ... 'step',
841 ... 'continue',
842 ... ]):
843 ... skip_module()
844 ... pass # provides something to "step" to
845 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
846 -> mod.foo_pony(callback)
847 (Pdb) step
848 --Call--
849 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
850 -> def callback():
851 (Pdb) step
852 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
853 -> return None
854 (Pdb) step
855 --Return--
856 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
857 -> return None
858 (Pdb) step
859 --Return--
860 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
861 -> mod.foo_pony(callback)
862 (Pdb) step
863 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
864 -> pass # provides something to "step" to
865 (Pdb) continue
866 """
867
868
869 def test_pdb_continue_in_bottomframe():
870 """Test that "continue" and "next" work properly in bottom frame (issue #5294).
871
872 >>> def test_function():
873 ... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
874 ... inst.set_trace()
875 ... inst.botframe = sys._getframe() # hackery to get the right botframe
876 ... print(1)
877 ... print(2)
878 ... print(3)
879 ... print(4)
880
881 >>> with PdbTestInput([ # doctest: +ELLIPSIS
882 ... 'next',
883 ... 'break 7',
884 ... 'continue',
885 ... 'next',
886 ... 'continue',
887 ... 'continue',
888 ... ]):
889 ... test_function()
890 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
891 -> inst.botframe = sys._getframe() # hackery to get the right botframe
892 (Pdb) next
893 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
894 -> print(1)
895 (Pdb) break 7
896 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
897 (Pdb) continue
898 1
899 2
900 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
901 -> print(3)
902 (Pdb) next
903 3
904 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
905 -> print(4)
906 (Pdb) continue
907 4
908 """
909
910
911 def pdb_invoke(method, arg):
912 """Run pdb.method(arg)."""
913 getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
914
915
916 def test_pdb_run_with_incorrect_argument():
917 """Testing run and runeval with incorrect first argument.
918
919 >>> pti = PdbTestInput(['continue',])
920 >>> with pti:
921 ... pdb_invoke('run', lambda x: x)
922 Traceback (most recent call last):
923 TypeError: exec() arg 1 must be a string, bytes or code object
924
925 >>> with pti:
926 ... pdb_invoke('runeval', lambda x: x)
927 Traceback (most recent call last):
928 TypeError: eval() arg 1 must be a string, bytes or code object
929 """
930
931
932 def test_pdb_run_with_code_object():
933 """Testing run and runeval with code object as a first argument.
934
935 >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
936 ... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
937 > <string>(1)<module>()...
938 (Pdb) step
939 --Return--
940 > <string>(1)<module>()->None
941 (Pdb) x
942 1
943 (Pdb) continue
944
945 >>> with PdbTestInput(['x', 'continue']):
946 ... x=0
947 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
948 > <string>(1)<module>()->None
949 (Pdb) x
950 1
951 (Pdb) continue
952 """
953
954 def test_next_until_return_at_return_event():
955 """Test that pdb stops after a next/until/return issued at a return debug event.
956
957 >>> def test_function_2():
958 ... x = 1
959 ... x = 2
960
961 >>> def test_function():
962 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
963 ... test_function_2()
964 ... test_function_2()
965 ... test_function_2()
966 ... end = 1
967
968 >>> reset_Breakpoint()
969 >>> with PdbTestInput(['break test_function_2',
970 ... 'continue',
971 ... 'return',
972 ... 'next',
973 ... 'continue',
974 ... 'return',
975 ... 'until',
976 ... 'continue',
977 ... 'return',
978 ... 'return',
979 ... 'continue']):
980 ... test_function()
981 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
982 -> test_function_2()
983 (Pdb) break test_function_2
984 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
985 (Pdb) continue
986 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
987 -> x = 1
988 (Pdb) return
989 --Return--
990 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
991 -> x = 2
992 (Pdb) next
993 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
994 -> test_function_2()
995 (Pdb) continue
996 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
997 -> x = 1
998 (Pdb) return
999 --Return--
1000 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
1001 -> x = 2
1002 (Pdb) until
1003 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
1004 -> test_function_2()
1005 (Pdb) continue
1006 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
1007 -> x = 1
1008 (Pdb) return
1009 --Return--
1010 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
1011 -> x = 2
1012 (Pdb) return
1013 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
1014 -> end = 1
1015 (Pdb) continue
1016 """
1017
1018 def test_pdb_next_command_for_generator():
1019 """Testing skip unwindng stack on yield for generators for "next" command
1020
1021 >>> def test_gen():
1022 ... yield 0
1023 ... return 1
1024 ... yield 2
1025
1026 >>> def test_function():
1027 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1028 ... it = test_gen()
1029 ... try:
1030 ... if next(it) != 0:
1031 ... raise AssertionError
1032 ... next(it)
1033 ... except StopIteration as ex:
1034 ... if ex.value != 1:
1035 ... raise AssertionError
1036 ... print("finished")
1037
1038 >>> with PdbTestInput(['step',
1039 ... 'step',
1040 ... 'step',
1041 ... 'next',
1042 ... 'next',
1043 ... 'step',
1044 ... 'step',
1045 ... 'continue']):
1046 ... test_function()
1047 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
1048 -> it = test_gen()
1049 (Pdb) step
1050 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
1051 -> try:
1052 (Pdb) step
1053 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
1054 -> if next(it) != 0:
1055 (Pdb) step
1056 --Call--
1057 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
1058 -> def test_gen():
1059 (Pdb) next
1060 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
1061 -> yield 0
1062 (Pdb) next
1063 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
1064 -> return 1
1065 (Pdb) step
1066 --Return--
1067 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
1068 -> return 1
1069 (Pdb) step
1070 StopIteration: 1
1071 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
1072 -> next(it)
1073 (Pdb) continue
1074 finished
1075 """
1076
1077 if not SKIP_ASYNCIO_TESTS:
1078 def test_pdb_next_command_for_coroutine():
1079 """Testing skip unwindng stack on yield for coroutines for "next" 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()
1096 ... asyncio.set_event_loop_policy(None)
1097 ... print("finished")
1098
1099 >>> with PdbTestInput(['step',
1100 ... 'step',
1101 ... 'next',
1102 ... 'next',
1103 ... 'next',
1104 ... 'step',
1105 ... 'continue']):
1106 ... test_function()
1107 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
1108 -> await test_coro()
1109 (Pdb) step
1110 --Call--
1111 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
1112 -> async def test_coro():
1113 (Pdb) step
1114 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
1115 -> await asyncio.sleep(0)
1116 (Pdb) next
1117 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
1118 -> await asyncio.sleep(0)
1119 (Pdb) next
1120 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
1121 -> await asyncio.sleep(0)
1122 (Pdb) next
1123 Internal StopIteration
1124 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
1125 -> await test_coro()
1126 (Pdb) step
1127 --Return--
1128 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
1129 -> await test_coro()
1130 (Pdb) continue
1131 finished
1132 """
1133
1134 def test_pdb_next_command_for_asyncgen():
1135 """Testing skip unwindng stack on yield for coroutines for "next" command
1136
1137 >>> import asyncio
1138
1139 >>> async def agen():
1140 ... yield 1
1141 ... await asyncio.sleep(0)
1142 ... yield 2
1143
1144 >>> async def test_coro():
1145 ... async for x in agen():
1146 ... print(x)
1147
1148 >>> async def test_main():
1149 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1150 ... await test_coro()
1151
1152 >>> def test_function():
1153 ... loop = asyncio.new_event_loop()
1154 ... loop.run_until_complete(test_main())
1155 ... loop.close()
1156 ... asyncio.set_event_loop_policy(None)
1157 ... print("finished")
1158
1159 >>> with PdbTestInput(['step',
1160 ... 'step',
1161 ... 'next',
1162 ... 'next',
1163 ... 'step',
1164 ... 'next',
1165 ... 'continue']):
1166 ... test_function()
1167 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
1168 -> await test_coro()
1169 (Pdb) step
1170 --Call--
1171 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
1172 -> async def test_coro():
1173 (Pdb) step
1174 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
1175 -> async for x in agen():
1176 (Pdb) next
1177 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
1178 -> print(x)
1179 (Pdb) next
1180 1
1181 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
1182 -> async for x in agen():
1183 (Pdb) step
1184 --Call--
1185 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
1186 -> yield 1
1187 (Pdb) next
1188 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
1189 -> await asyncio.sleep(0)
1190 (Pdb) continue
1191 2
1192 finished
1193 """
1194
1195 def test_pdb_return_command_for_generator():
1196 """Testing no unwindng stack on yield for generators
1197 for "return" command
1198
1199 >>> def test_gen():
1200 ... yield 0
1201 ... return 1
1202 ... yield 2
1203
1204 >>> def test_function():
1205 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1206 ... it = test_gen()
1207 ... try:
1208 ... if next(it) != 0:
1209 ... raise AssertionError
1210 ... next(it)
1211 ... except StopIteration as ex:
1212 ... if ex.value != 1:
1213 ... raise AssertionError
1214 ... print("finished")
1215
1216 >>> with PdbTestInput(['step',
1217 ... 'step',
1218 ... 'step',
1219 ... 'return',
1220 ... 'step',
1221 ... 'step',
1222 ... 'continue']):
1223 ... test_function()
1224 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
1225 -> it = test_gen()
1226 (Pdb) step
1227 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
1228 -> try:
1229 (Pdb) step
1230 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
1231 -> if next(it) != 0:
1232 (Pdb) step
1233 --Call--
1234 > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
1235 -> def test_gen():
1236 (Pdb) return
1237 StopIteration: 1
1238 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
1239 -> next(it)
1240 (Pdb) step
1241 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
1242 -> except StopIteration as ex:
1243 (Pdb) step
1244 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
1245 -> if ex.value != 1:
1246 (Pdb) continue
1247 finished
1248 """
1249
1250 if not SKIP_ASYNCIO_TESTS:
1251 def test_pdb_return_command_for_coroutine():
1252 """Testing no unwindng stack on yield for coroutines for "return" command
1253
1254 >>> import asyncio
1255
1256 >>> async def test_coro():
1257 ... await asyncio.sleep(0)
1258 ... await asyncio.sleep(0)
1259 ... await asyncio.sleep(0)
1260
1261 >>> async def test_main():
1262 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1263 ... await test_coro()
1264
1265 >>> def test_function():
1266 ... loop = asyncio.new_event_loop()
1267 ... loop.run_until_complete(test_main())
1268 ... loop.close()
1269 ... asyncio.set_event_loop_policy(None)
1270 ... print("finished")
1271
1272 >>> with PdbTestInput(['step',
1273 ... 'step',
1274 ... 'next',
1275 ... 'continue']):
1276 ... test_function()
1277 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
1278 -> await test_coro()
1279 (Pdb) step
1280 --Call--
1281 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
1282 -> async def test_coro():
1283 (Pdb) step
1284 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
1285 -> await asyncio.sleep(0)
1286 (Pdb) next
1287 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
1288 -> await asyncio.sleep(0)
1289 (Pdb) continue
1290 finished
1291 """
1292
1293 def test_pdb_until_command_for_generator():
1294 """Testing no unwindng stack on yield for generators
1295 for "until" command if target breakpoint is not reached
1296
1297 >>> def test_gen():
1298 ... yield 0
1299 ... yield 1
1300 ... yield 2
1301
1302 >>> def test_function():
1303 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1304 ... for i in test_gen():
1305 ... print(i)
1306 ... print("finished")
1307
1308 >>> with PdbTestInput(['step',
1309 ... 'until 4',
1310 ... 'step',
1311 ... 'step',
1312 ... 'continue']):
1313 ... test_function()
1314 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
1315 -> for i in test_gen():
1316 (Pdb) step
1317 --Call--
1318 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
1319 -> def test_gen():
1320 (Pdb) until 4
1321 0
1322 1
1323 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
1324 -> yield 2
1325 (Pdb) step
1326 --Return--
1327 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
1328 -> yield 2
1329 (Pdb) step
1330 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
1331 -> print(i)
1332 (Pdb) continue
1333 2
1334 finished
1335 """
1336
1337 if not SKIP_ASYNCIO_TESTS:
1338 def test_pdb_until_command_for_coroutine():
1339 """Testing no unwindng stack for coroutines
1340 for "until" command if target breakpoint is not reached
1341
1342 >>> import asyncio
1343
1344 >>> async def test_coro():
1345 ... print(0)
1346 ... await asyncio.sleep(0)
1347 ... print(1)
1348 ... await asyncio.sleep(0)
1349 ... print(2)
1350 ... await asyncio.sleep(0)
1351 ... print(3)
1352
1353 >>> async def test_main():
1354 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1355 ... await test_coro()
1356
1357 >>> def test_function():
1358 ... loop = asyncio.new_event_loop()
1359 ... loop.run_until_complete(test_main())
1360 ... loop.close()
1361 ... asyncio.set_event_loop_policy(None)
1362 ... print("finished")
1363
1364 >>> with PdbTestInput(['step',
1365 ... 'until 8',
1366 ... 'continue']):
1367 ... test_function()
1368 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
1369 -> await test_coro()
1370 (Pdb) step
1371 --Call--
1372 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
1373 -> async def test_coro():
1374 (Pdb) until 8
1375 0
1376 1
1377 2
1378 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
1379 -> print(3)
1380 (Pdb) continue
1381 3
1382 finished
1383 """
1384
1385 def test_pdb_next_command_in_generator_for_loop():
1386 """The next command on returning from a generator controlled by a for loop.
1387
1388 >>> def test_gen():
1389 ... yield 0
1390 ... return 1
1391
1392 >>> def test_function():
1393 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1394 ... for i in test_gen():
1395 ... print('value', i)
1396 ... x = 123
1397
1398 >>> reset_Breakpoint()
1399 >>> with PdbTestInput(['break test_gen',
1400 ... 'continue',
1401 ... 'next',
1402 ... 'next',
1403 ... 'next',
1404 ... 'continue']):
1405 ... test_function()
1406 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1407 -> for i in test_gen():
1408 (Pdb) break test_gen
1409 Breakpoint 1 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:1
1410 (Pdb) continue
1411 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1412 -> yield 0
1413 (Pdb) next
1414 value 0
1415 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1416 -> return 1
1417 (Pdb) next
1418 Internal StopIteration: 1
1419 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1420 -> for i in test_gen():
1421 (Pdb) next
1422 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1423 -> x = 123
1424 (Pdb) continue
1425 """
1426
1427 def test_pdb_next_command_subiterator():
1428 """The next command in a generator with a subiterator.
1429
1430 >>> def test_subgenerator():
1431 ... yield 0
1432 ... return 1
1433
1434 >>> def test_gen():
1435 ... x = yield from test_subgenerator()
1436 ... return x
1437
1438 >>> def test_function():
1439 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1440 ... for i in test_gen():
1441 ... print('value', i)
1442 ... x = 123
1443
1444 >>> with PdbTestInput(['step',
1445 ... 'step',
1446 ... 'next',
1447 ... 'next',
1448 ... 'next',
1449 ... 'continue']):
1450 ... test_function()
1451 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1452 -> for i in test_gen():
1453 (Pdb) step
1454 --Call--
1455 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1456 -> def test_gen():
1457 (Pdb) step
1458 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1459 -> x = yield from test_subgenerator()
1460 (Pdb) next
1461 value 0
1462 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1463 -> return x
1464 (Pdb) next
1465 Internal StopIteration: 1
1466 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1467 -> for i in test_gen():
1468 (Pdb) next
1469 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1470 -> x = 123
1471 (Pdb) continue
1472 """
1473
1474 def test_pdb_issue_20766():
1475 pass
1476
1477
1478 if sys.implementation.name != 'pypy':
1479 __test__ = {"test_pdb_issue_20766": """Test for reference leaks when the SIGINT handler is set.
1480
1481 Note a fix for PyPy: on CPython, the two iterations through the loop
1482 don't stop at the same line each time. Actually, if the loop
1483 iterates more than twice, we have a behavior of period two(!). This
1484 is due to very internal behavior that could be classified as a bug
1485 and that PyPy doesn't emulating exactly.
1486
1487 >>> def test_function():
1488 ... i = 1
1489 ... while i <= 2:
1490 ... sess = pdb.Pdb()
1491 ... sess.set_trace(sys._getframe())
1492 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1493 ... i += 1
1494
1495 >>> reset_Breakpoint()
1496 >>> with PdbTestInput(['continue',
1497 ... 'continue']):
1498 ... test_function()
1499 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1500 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1501 (Pdb) continue
1502 pdb 1: <built-in function default_int_handler>
1503 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1504 -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1505 (Pdb) continue
1506 pdb 2: <built-in function default_int_handler>
1507 """}
1508
1509 def test_pdb_issue_43318():
1510 """echo breakpoints cleared with filename:lineno
1511
1512 >>> def test_function():
1513 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1514 ... print(1)
1515 ... print(2)
1516 ... print(3)
1517 ... print(4)
1518 >>> reset_Breakpoint()
1519 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1520 ... 'break 3',
1521 ... 'clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3',
1522 ... 'continue'
1523 ... ]):
1524 ... test_function()
1525 > <doctest test.test_pdb.test_pdb_issue_43318[0]>(3)test_function()
1526 -> print(1)
1527 (Pdb) break 3
1528 Breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1529 (Pdb) clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1530 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
1531 (Pdb) continue
1532 1
1533 2
1534 3
1535 4
1536 """
1537
1538 def test_pdb_issue_gh_91742():
1539 """See GH-91742
1540
1541 >>> def test_function():
1542 ... __author__ = "pi"
1543 ... __version__ = "3.14"
1544 ...
1545 ... def about():
1546 ... '''About'''
1547 ... print(f"Author: {__author__!r}",
1548 ... f"Version: {__version__!r}",
1549 ... sep=" ")
1550 ...
1551 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1552 ... about()
1553
1554
1555 >>> reset_Breakpoint()
1556 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1557 ... 'step',
1558 ... 'next',
1559 ... 'next',
1560 ... 'jump 5',
1561 ... 'continue'
1562 ... ]):
1563 ... test_function()
1564 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(12)test_function()
1565 -> about()
1566 (Pdb) step
1567 --Call--
1568 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(5)about()
1569 -> def about():
1570 (Pdb) next
1571 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(7)about()
1572 -> print(f"Author: {__author__!r}",
1573 (Pdb) next
1574 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(8)about()
1575 -> f"Version: {__version__!r}",
1576 (Pdb) jump 5
1577 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(5)about()
1578 -> def about():
1579 (Pdb) continue
1580 Author: 'pi' Version: '3.14'
1581 """
1582
1583 def test_pdb_issue_gh_94215():
1584 """See GH-94215
1585
1586 Check that frame_setlineno() does not leak references.
1587
1588 >>> def test_function():
1589 ... def func():
1590 ... def inner(v): pass
1591 ... inner(
1592 ... 42
1593 ... )
1594 ...
1595 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1596 ... func()
1597
1598 >>> reset_Breakpoint()
1599 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1600 ... 'step',
1601 ... 'next',
1602 ... 'next',
1603 ... 'jump 3',
1604 ... 'next',
1605 ... 'next',
1606 ... 'jump 3',
1607 ... 'next',
1608 ... 'next',
1609 ... 'jump 3',
1610 ... 'continue'
1611 ... ]):
1612 ... test_function()
1613 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(9)test_function()
1614 -> func()
1615 (Pdb) step
1616 --Call--
1617 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(2)func()
1618 -> def func():
1619 (Pdb) next
1620 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
1621 -> def inner(v): pass
1622 (Pdb) next
1623 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
1624 -> inner(
1625 (Pdb) jump 3
1626 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
1627 -> def inner(v): pass
1628 (Pdb) next
1629 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
1630 -> inner(
1631 (Pdb) next
1632 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(5)func()
1633 -> 42
1634 (Pdb) jump 3
1635 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
1636 -> def inner(v): pass
1637 (Pdb) next
1638 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
1639 -> inner(
1640 (Pdb) next
1641 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(5)func()
1642 -> 42
1643 (Pdb) jump 3
1644 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
1645 -> def inner(v): pass
1646 (Pdb) continue
1647 """
1648
1649 def test_pdb_issue_gh_101673():
1650 """See GH-101673
1651
1652 Make sure ll won't revert local variable assignment
1653
1654 >>> def test_function():
1655 ... a = 1
1656 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1657
1658 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1659 ... '!a = 2',
1660 ... 'll',
1661 ... 'p a',
1662 ... 'continue'
1663 ... ]):
1664 ... test_function()
1665 --Return--
1666 > <doctest test.test_pdb.test_pdb_issue_gh_101673[0]>(3)test_function()->None
1667 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1668 (Pdb) !a = 2
1669 (Pdb) ll
1670 1 def test_function():
1671 2 a = 1
1672 3 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1673 (Pdb) p a
1674 2
1675 (Pdb) continue
1676 """
1677
1678 def test_pdb_issue_gh_101517():
1679 """See GH-101517
1680
1681 Make sure pdb doesn't crash when the exception is caught in a try/except* block
1682
1683 >>> def test_function():
1684 ... try:
1685 ... raise KeyError
1686 ... except* Exception as e:
1687 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1688
1689 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1690 ... 'continue'
1691 ... ]):
1692 ... test_function()
1693 > <doctest test.test_pdb.test_pdb_issue_gh_101517[0]>(4)test_function()
1694 -> except* Exception as e:
1695 (Pdb) continue
1696 """
1697
1698 def test_pdb_issue_gh_103225():
1699 """See GH-103225
1700
1701 Make sure longlist uses 1-based line numbers in frames that correspond to a module
1702
1703 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1704 ... 'longlist',
1705 ... 'continue'
1706 ... ]):
1707 ... a = 1
1708 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1709 ... b = 2
1710 > <doctest test.test_pdb.test_pdb_issue_gh_103225[0]>(7)<module>()
1711 -> b = 2
1712 (Pdb) longlist
1713 1 with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
1714 2 'longlist',
1715 3 'continue'
1716 4 ]):
1717 5 a = 1
1718 6 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1719 7 -> b = 2
1720 (Pdb) continue
1721 """
1722
1723 def test_pdb_issue_gh_65052():
1724 """See GH-65052
1725
1726 args, retval and display should not crash if the object is not displayable
1727 >>> class A:
1728 ... def __new__(cls):
1729 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1730 ... return object.__new__(cls)
1731 ... def __init__(self):
1732 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1733 ... self.a = 1
1734 ... def __repr__(self):
1735 ... return self.a
1736
1737 >>> def test_function():
1738 ... A()
1739 >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
1740 ... 's',
1741 ... 'retval',
1742 ... 'continue',
1743 ... 'args',
1744 ... 'display self',
1745 ... 'display',
1746 ... 'continue',
1747 ... ]):
1748 ... test_function()
1749 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(4)__new__()
1750 -> return object.__new__(cls)
1751 (Pdb) s
1752 --Return--
1753 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(4)__new__()-><A instance at ...>
1754 -> return object.__new__(cls)
1755 (Pdb) retval
1756 *** repr(retval) failed: AttributeError: 'A' object has no attribute 'a' ***
1757 (Pdb) continue
1758 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(7)__init__()
1759 -> self.a = 1
1760 (Pdb) args
1761 self = *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
1762 (Pdb) display self
1763 display self: *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
1764 (Pdb) display
1765 Currently displaying:
1766 self: *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
1767 (Pdb) continue
1768 """
1769
1770
1771 @support.requires_subprocess()
1772 class PdbTestCase(unittest.TestCase):
1773 def tearDown(self):
1774 os_helper.unlink(os_helper.TESTFN)
1775
1776 @unittest.skipIf(sys.flags.safe_path,
1777 'PYTHONSAFEPATH changes default sys.path')
1778 def _run_pdb(self, pdb_args, commands, expected_returncode=0):
1779 self.addCleanup(os_helper.rmtree, '__pycache__')
1780 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1781 with subprocess.Popen(
1782 cmd,
1783 stdout=subprocess.PIPE,
1784 stdin=subprocess.PIPE,
1785 stderr=subprocess.STDOUT,
1786 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
1787 ) as proc:
1788 stdout, stderr = proc.communicate(str.encode(commands))
1789 stdout = stdout and bytes.decode(stdout)
1790 stderr = stderr and bytes.decode(stderr)
1791 self.assertEqual(
1792 proc.returncode,
1793 expected_returncode,
1794 f"Unexpected return code\nstdout: {stdout}\nstderr: {stderr}"
1795 )
1796 return stdout, stderr
1797
1798 def run_pdb_script(self, script, commands,
1799 expected_returncode=0,
1800 pdbrc=None,
1801 remove_home=False):
1802 """Run 'script' lines with pdb and the pdb 'commands'."""
1803 filename = 'main.py'
1804 with open(filename, 'w') as f:
1805 f.write(textwrap.dedent(script))
1806
1807 if pdbrc is not None:
1808 with open('.pdbrc', 'w') as f:
1809 f.write(textwrap.dedent(pdbrc))
1810 self.addCleanup(os_helper.unlink, '.pdbrc')
1811 self.addCleanup(os_helper.unlink, filename)
1812
1813 homesave = None
1814 if remove_home:
1815 homesave = os.environ.pop('HOME', None)
1816 try:
1817 stdout, stderr = self._run_pdb([filename], commands, expected_returncode)
1818 finally:
1819 if homesave is not None:
1820 os.environ['HOME'] = homesave
1821 return stdout, stderr
1822
1823 def run_pdb_module(self, script, commands):
1824 """Runs the script code as part of a module"""
1825 self.module_name = 't_main'
1826 os_helper.rmtree(self.module_name)
1827 main_file = self.module_name + '/__main__.py'
1828 init_file = self.module_name + '/__init__.py'
1829 os.mkdir(self.module_name)
1830 with open(init_file, 'w') as f:
1831 pass
1832 with open(main_file, 'w') as f:
1833 f.write(textwrap.dedent(script))
1834 self.addCleanup(os_helper.rmtree, self.module_name)
1835 return self._run_pdb(['-m', self.module_name], commands)
1836
1837 def _assert_find_function(self, file_content, func_name, expected):
1838 with open(os_helper.TESTFN, 'wb') as f:
1839 f.write(file_content)
1840
1841 expected = None if not expected else (
1842 expected[0], os_helper.TESTFN, expected[1])
1843 self.assertEqual(
1844 expected, pdb.find_function(func_name, os_helper.TESTFN))
1845
1846 def test_find_function_empty_file(self):
1847 self._assert_find_function(b'', 'foo', None)
1848
1849 def test_find_function_found(self):
1850 self._assert_find_function(
1851 """\
1852 def foo():
1853 pass
1854
1855 def bœr():
1856 pass
1857
1858 def quux():
1859 pass
1860 """.encode(),
1861 'bœr',
1862 ('bœr', 4),
1863 )
1864
1865 def test_find_function_found_with_encoding_cookie(self):
1866 self._assert_find_function(
1867 """\
1868 # coding: iso-8859-15
1869 def foo():
1870 pass
1871
1872 def bœr():
1873 pass
1874
1875 def quux():
1876 pass
1877 """.encode('iso-8859-15'),
1878 'bœr',
1879 ('bœr', 5),
1880 )
1881
1882 def test_find_function_found_with_bom(self):
1883 self._assert_find_function(
1884 codecs.BOM_UTF8 + """\
1885 def bœr():
1886 pass
1887 """.encode(),
1888 'bœr',
1889 ('bœr', 1),
1890 )
1891
1892 def test_spec(self):
1893 # Test that __main__.__spec__ is set to None when running a script
1894 script = """
1895 import __main__
1896 print(__main__.__spec__)
1897 """
1898
1899 commands = "continue"
1900
1901 stdout, _ = self.run_pdb_script(script, commands)
1902 self.assertIn('None', stdout)
1903
1904 def test_issue7964(self):
1905 # open the file as binary so we can force \r\n newline
1906 with open(os_helper.TESTFN, 'wb') as f:
1907 f.write(b'print("testing my pdb")\r\n')
1908 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
1909 proc = subprocess.Popen(cmd,
1910 stdout=subprocess.PIPE,
1911 stdin=subprocess.PIPE,
1912 stderr=subprocess.STDOUT,
1913 )
1914 self.addCleanup(proc.stdout.close)
1915 stdout, stderr = proc.communicate(b'quit\n')
1916 self.assertNotIn(b'SyntaxError', stdout,
1917 "Got a syntax error running test script under PDB")
1918
1919 def test_issue46434(self):
1920 # Temporarily patch in an extra help command which doesn't have a
1921 # docstring to emulate what happens in an embeddable distribution
1922 script = """
1923 def do_testcmdwithnodocs(self, arg):
1924 pass
1925
1926 import pdb
1927 pdb.Pdb.do_testcmdwithnodocs = do_testcmdwithnodocs
1928 """
1929 commands = """
1930 continue
1931 help testcmdwithnodocs
1932 """
1933 stdout, stderr = self.run_pdb_script(script, commands)
1934 output = (stdout or '') + (stderr or '')
1935 self.assertNotIn('AttributeError', output,
1936 'Calling help on a command with no docs should be handled gracefully')
1937 self.assertIn("*** No help for 'testcmdwithnodocs'; __doc__ string missing", output,
1938 'Calling help on a command with no docs should print an error')
1939
1940 def test_issue13183(self):
1941 script = """
1942 from bar import bar
1943
1944 def foo():
1945 bar()
1946
1947 def nope():
1948 pass
1949
1950 def foobar():
1951 foo()
1952 nope()
1953
1954 foobar()
1955 """
1956 commands = """
1957 from bar import bar
1958 break bar
1959 continue
1960 step
1961 step
1962 quit
1963 """
1964 bar = """
1965 def bar():
1966 pass
1967 """
1968 with open('bar.py', 'w') as f:
1969 f.write(textwrap.dedent(bar))
1970 self.addCleanup(os_helper.unlink, 'bar.py')
1971 stdout, stderr = self.run_pdb_script(script, commands)
1972 self.assertTrue(
1973 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1974 'Fail to step into the caller after a return')
1975
1976 def test_issue13120(self):
1977 # Invoking "continue" on a non-main thread triggered an exception
1978 # inside signal.signal.
1979
1980 with open(os_helper.TESTFN, 'wb') as f:
1981 f.write(textwrap.dedent("""
1982 import threading
1983 import pdb
1984
1985 def start_pdb():
1986 pdb.Pdb(readrc=False).set_trace()
1987 x = 1
1988 y = 1
1989
1990 t = threading.Thread(target=start_pdb)
1991 t.start()""").encode('ascii'))
1992 cmd = [sys.executable, '-u', os_helper.TESTFN]
1993 proc = subprocess.Popen(cmd,
1994 stdout=subprocess.PIPE,
1995 stdin=subprocess.PIPE,
1996 stderr=subprocess.STDOUT,
1997 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
1998 )
1999 self.addCleanup(proc.stdout.close)
2000 stdout, stderr = proc.communicate(b'cont\n')
2001 self.assertNotIn(b'Error', stdout,
2002 "Got an error running test script under PDB")
2003
2004 def test_issue36250(self):
2005
2006 with open(os_helper.TESTFN, 'wb') as f:
2007 f.write(textwrap.dedent("""
2008 import threading
2009 import pdb
2010
2011 evt = threading.Event()
2012
2013 def start_pdb():
2014 evt.wait()
2015 pdb.Pdb(readrc=False).set_trace()
2016
2017 t = threading.Thread(target=start_pdb)
2018 t.start()
2019 pdb.Pdb(readrc=False).set_trace()
2020 evt.set()
2021 t.join()""").encode('ascii'))
2022 cmd = [sys.executable, '-u', os_helper.TESTFN]
2023 proc = subprocess.Popen(cmd,
2024 stdout=subprocess.PIPE,
2025 stdin=subprocess.PIPE,
2026 stderr=subprocess.STDOUT,
2027 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
2028 )
2029 self.addCleanup(proc.stdout.close)
2030 stdout, stderr = proc.communicate(b'cont\ncont\n')
2031 self.assertNotIn(b'Error', stdout,
2032 "Got an error running test script under PDB")
2033
2034 def test_issue16180(self):
2035 # A syntax error in the debuggee.
2036 script = "def f: pass\n"
2037 commands = ''
2038 expected = "SyntaxError:"
2039 stdout, stderr = self.run_pdb_script(
2040 script, commands, expected_returncode=1
2041 )
2042 self.assertIn(expected, stdout,
2043 '\n\nExpected:\n{}\nGot:\n{}\n'
2044 'Fail to handle a syntax error in the debuggee.'
2045 .format(expected, stdout))
2046
2047 def test_issue26053(self):
2048 # run command of pdb prompt echoes the correct args
2049 script = "print('hello')"
2050 commands = """
2051 continue
2052 run a b c
2053 run d e f
2054 quit
2055 """
2056 stdout, stderr = self.run_pdb_script(script, commands)
2057 res = '\n'.join([x.strip() for x in stdout.splitlines()])
2058 self.assertRegex(res, "Restarting .* with arguments:\na b c")
2059 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
2060
2061 def test_pdbrc_basic(self):
2062 script = textwrap.dedent("""
2063 a = 1
2064 b = 2
2065 """)
2066
2067 pdbrc = textwrap.dedent("""
2068 # Comments should be fine
2069 n
2070 p f"{a+8=}"
2071 """)
2072
2073 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
2074 self.assertNotIn("SyntaxError", stdout)
2075 self.assertIn("a+8=9", stdout)
2076
2077 def test_pdbrc_empty_line(self):
2078 """Test that empty lines in .pdbrc are ignored."""
2079
2080 script = textwrap.dedent("""
2081 a = 1
2082 b = 2
2083 c = 3
2084 """)
2085
2086 pdbrc = textwrap.dedent("""
2087 n
2088
2089 """)
2090
2091 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
2092 self.assertIn("b = 2", stdout)
2093 self.assertNotIn("c = 3", stdout)
2094
2095 def test_pdbrc_alias(self):
2096 script = textwrap.dedent("""
2097 class A:
2098 def __init__(self):
2099 self.attr = 1
2100 a = A()
2101 b = 2
2102 """)
2103
2104 pdbrc = textwrap.dedent("""
2105 alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
2106 until 6
2107 pi a
2108 """)
2109
2110 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
2111 self.assertIn("a.attr = 1", stdout)
2112
2113 def test_pdbrc_semicolon(self):
2114 script = textwrap.dedent("""
2115 class A:
2116 def __init__(self):
2117 self.attr = 1
2118 a = A()
2119 b = 2
2120 """)
2121
2122 pdbrc = textwrap.dedent("""
2123 b 5;;c;;n
2124 """)
2125
2126 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
2127 self.assertIn("-> b = 2", stdout)
2128
2129 def test_pdbrc_commands(self):
2130 script = textwrap.dedent("""
2131 class A:
2132 def __init__(self):
2133 self.attr = 1
2134 a = A()
2135 b = 2
2136 """)
2137
2138 pdbrc = textwrap.dedent("""
2139 b 6
2140 commands 1 ;; p a;; end
2141 c
2142 """)
2143
2144 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
2145 self.assertIn("<__main__.A object at", stdout)
2146
2147 def test_readrc_kwarg(self):
2148 script = textwrap.dedent("""
2149 print('hello')
2150 """)
2151
2152 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc='invalid', remove_home=True)
2153 self.assertIn("NameError: name 'invalid' is not defined", stdout)
2154
2155 def test_readrc_homedir(self):
2156 save_home = os.environ.pop("HOME", None)
2157 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
2158 rc_path = os.path.join(temp_dir, ".pdbrc")
2159 os.path.expanduser.return_value = rc_path
2160 try:
2161 with open(rc_path, "w") as f:
2162 f.write("invalid")
2163 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
2164 finally:
2165 if save_home is not None:
2166 os.environ["HOME"] = save_home
2167
2168 def test_header(self):
2169 stdout = StringIO()
2170 header = 'Nobody expects... blah, blah, blah'
2171 with ExitStack() as resources:
2172 resources.enter_context(patch('sys.stdout', stdout))
2173 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
2174 pdb.set_trace(header=header)
2175 self.assertEqual(stdout.getvalue(), header + '\n')
2176
2177 def test_run_module(self):
2178 script = """print("SUCCESS")"""
2179 commands = """
2180 continue
2181 quit
2182 """
2183 stdout, stderr = self.run_pdb_module(script, commands)
2184 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
2185
2186 def test_module_is_run_as_main(self):
2187 script = """
2188 if __name__ == '__main__':
2189 print("SUCCESS")
2190 """
2191 commands = """
2192 continue
2193 quit
2194 """
2195 stdout, stderr = self.run_pdb_module(script, commands)
2196 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
2197
2198 def test_breakpoint(self):
2199 script = """
2200 if __name__ == '__main__':
2201 pass
2202 print("SUCCESS")
2203 pass
2204 """
2205 commands = """
2206 b 3
2207 quit
2208 """
2209 stdout, stderr = self.run_pdb_module(script, commands)
2210 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
2211 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
2212
2213 def test_run_pdb_with_pdb(self):
2214 commands = """
2215 c
2216 quit
2217 """
2218 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
2219 self.assertIn(
2220 pdb._usage,
2221 stdout.replace('\r', '') # remove \r for windows
2222 )
2223
2224 def test_module_without_a_main(self):
2225 module_name = 't_main'
2226 os_helper.rmtree(module_name)
2227 init_file = module_name + '/__init__.py'
2228 os.mkdir(module_name)
2229 with open(init_file, 'w'):
2230 pass
2231 self.addCleanup(os_helper.rmtree, module_name)
2232 stdout, stderr = self._run_pdb(
2233 ['-m', module_name], "", expected_returncode=1
2234 )
2235 self.assertIn("ImportError: No module named t_main.__main__;", stdout)
2236
2237 def test_package_without_a_main(self):
2238 pkg_name = 't_pkg'
2239 module_name = 't_main'
2240 os_helper.rmtree(pkg_name)
2241 modpath = pkg_name + '/' + module_name
2242 os.makedirs(modpath)
2243 with open(modpath + '/__init__.py', 'w'):
2244 pass
2245 self.addCleanup(os_helper.rmtree, pkg_name)
2246 stdout, stderr = self._run_pdb(
2247 ['-m', modpath.replace('/', '.')], "", expected_returncode=1
2248 )
2249 self.assertIn(
2250 "'t_pkg.t_main' is a package and cannot be directly executed",
2251 stdout)
2252
2253 def test_nonexistent_module(self):
2254 assert not os.path.exists(os_helper.TESTFN)
2255 stdout, stderr = self._run_pdb(["-m", os_helper.TESTFN], "", expected_returncode=1)
2256 self.assertIn(f"ImportError: No module named {os_helper.TESTFN}", stdout)
2257
2258 def test_dir_as_script(self):
2259 with os_helper.temp_dir() as temp_dir:
2260 stdout, stderr = self._run_pdb([temp_dir], "", expected_returncode=1)
2261 self.assertIn(f"Error: {temp_dir} is a directory", stdout)
2262
2263 def test_invalid_cmd_line_options(self):
2264 stdout, stderr = self._run_pdb(["-c"], "", expected_returncode=1)
2265 self.assertIn(f"Error: option -c requires argument", stdout)
2266 stdout, stderr = self._run_pdb(["--spam"], "", expected_returncode=1)
2267 self.assertIn(f"Error: option --spam not recognized", stdout)
2268
2269 def test_blocks_at_first_code_line(self):
2270 script = """
2271 #This is a comment, on line 2
2272
2273 print("SUCCESS")
2274 """
2275 commands = """
2276 quit
2277 """
2278 stdout, stderr = self.run_pdb_module(script, commands)
2279 self.assertTrue(any("__main__.py(4)<module>()"
2280 in l for l in stdout.splitlines()), stdout)
2281
2282 def test_relative_imports(self):
2283 self.module_name = 't_main'
2284 os_helper.rmtree(self.module_name)
2285 main_file = self.module_name + '/__main__.py'
2286 init_file = self.module_name + '/__init__.py'
2287 module_file = self.module_name + '/module.py'
2288 self.addCleanup(os_helper.rmtree, self.module_name)
2289 os.mkdir(self.module_name)
2290 with open(init_file, 'w') as f:
2291 f.write(textwrap.dedent("""
2292 top_var = "VAR from top"
2293 """))
2294 with open(main_file, 'w') as f:
2295 f.write(textwrap.dedent("""
2296 from . import top_var
2297 from .module import var
2298 from . import module
2299 pass # We'll stop here and print the vars
2300 """))
2301 with open(module_file, 'w') as f:
2302 f.write(textwrap.dedent("""
2303 var = "VAR from module"
2304 var2 = "second var"
2305 """))
2306 commands = """
2307 b 5
2308 c
2309 p top_var
2310 p var
2311 p module.var2
2312 quit
2313 """
2314 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
2315 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
2316 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
2317 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
2318
2319 def test_relative_imports_on_plain_module(self):
2320 # Validates running a plain module. See bpo32691
2321 self.module_name = 't_main'
2322 os_helper.rmtree(self.module_name)
2323 main_file = self.module_name + '/runme.py'
2324 init_file = self.module_name + '/__init__.py'
2325 module_file = self.module_name + '/module.py'
2326 self.addCleanup(os_helper.rmtree, self.module_name)
2327 os.mkdir(self.module_name)
2328 with open(init_file, 'w') as f:
2329 f.write(textwrap.dedent("""
2330 top_var = "VAR from top"
2331 """))
2332 with open(main_file, 'w') as f:
2333 f.write(textwrap.dedent("""
2334 from . import module
2335 pass # We'll stop here and print the vars
2336 """))
2337 with open(module_file, 'w') as f:
2338 f.write(textwrap.dedent("""
2339 var = "VAR from module"
2340 """))
2341 commands = """
2342 b 3
2343 c
2344 p module.var
2345 quit
2346 """
2347 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
2348 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
2349
2350 def test_errors_in_command(self):
2351 commands = "\n".join([
2352 'print(',
2353 'debug print(',
2354 'debug doesnotexist',
2355 'c',
2356 ])
2357 stdout, _ = self.run_pdb_script('pass', commands + '\n')
2358
2359 self.assertEqual(stdout.splitlines()[1:], [
2360 '-> pass',
2361 '(Pdb) *** SyntaxError: \'(\' was never closed',
2362
2363 '(Pdb) ENTERING RECURSIVE DEBUGGER',
2364 '*** SyntaxError: \'(\' was never closed',
2365 'LEAVING RECURSIVE DEBUGGER',
2366
2367 '(Pdb) ENTERING RECURSIVE DEBUGGER',
2368 '> <string>(1)<module>()',
2369 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
2370 'LEAVING RECURSIVE DEBUGGER',
2371 '(Pdb) ',
2372 ])
2373
2374 def test_issue34266(self):
2375 '''do_run handles exceptions from parsing its arg'''
2376 def check(bad_arg, msg):
2377 commands = "\n".join([
2378 f'run {bad_arg}',
2379 'q',
2380 ])
2381 stdout, _ = self.run_pdb_script('pass', commands + '\n')
2382 self.assertEqual(stdout.splitlines()[1:], [
2383 '-> pass',
2384 f'(Pdb) *** Cannot run {bad_arg}: {msg}',
2385 '(Pdb) ',
2386 ])
2387 check('\\', 'No escaped character')
2388 check('"', 'No closing quotation')
2389
2390 def test_issue42384(self):
2391 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
2392 script = textwrap.dedent("""
2393 import sys
2394 print('sys.path[0] is', sys.path[0])
2395 """)
2396 commands = 'c\nq'
2397
2398 with os_helper.temp_cwd() as cwd:
2399 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
2400
2401 stdout, stderr = self.run_pdb_script(script, commands)
2402
2403 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
2404
2405 @os_helper.skip_unless_symlink
2406 def test_issue42384_symlink(self):
2407 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
2408 script = textwrap.dedent("""
2409 import sys
2410 print('sys.path[0] is', sys.path[0])
2411 """)
2412 commands = 'c\nq'
2413
2414 with os_helper.temp_cwd() as cwd:
2415 cwd = os.path.realpath(cwd)
2416 dir_one = os.path.join(cwd, 'dir_one')
2417 dir_two = os.path.join(cwd, 'dir_two')
2418 expected = f'(Pdb) sys.path[0] is {dir_one}'
2419
2420 os.mkdir(dir_one)
2421 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
2422 f.write(script)
2423 os.mkdir(dir_two)
2424 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
2425
2426 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
2427
2428 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
2429
2430 def test_issue42383(self):
2431 with os_helper.temp_cwd() as cwd:
2432 with open('foo.py', 'w') as f:
2433 s = textwrap.dedent("""
2434 print('The correct file was executed')
2435
2436 import os
2437 os.chdir("subdir")
2438 """)
2439 f.write(s)
2440
2441 subdir = os.path.join(cwd, 'subdir')
2442 os.mkdir(subdir)
2443 os.mkdir(os.path.join(subdir, 'subdir'))
2444 wrong_file = os.path.join(subdir, 'foo.py')
2445
2446 with open(wrong_file, 'w') as f:
2447 f.write('print("The wrong file was executed")')
2448
2449 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
2450 expected = '(Pdb) The correct file was executed'
2451 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
2452
2453 def test_gh_94215_crash(self):
2454 script = """\
2455 def func():
2456 def inner(v): pass
2457 inner(
2458 42
2459 )
2460 func()
2461 """
2462 commands = textwrap.dedent("""
2463 break func
2464 continue
2465 next
2466 next
2467 jump 2
2468 """)
2469 stdout, stderr = self.run_pdb_script(script, commands)
2470 self.assertFalse(stderr)
2471
2472 def test_gh_93696_frozen_list(self):
2473 frozen_src = """
2474 def func():
2475 x = "Sentinel string for gh-93696"
2476 print(x)
2477 """
2478 host_program = """
2479 import os
2480 import sys
2481
2482 def _create_fake_frozen_module():
2483 with open('gh93696.py') as f:
2484 src = f.read()
2485
2486 # this function has a co_filename as if it were in a frozen module
2487 dummy_mod = compile(src, "<frozen gh93696>", "exec")
2488 func_code = dummy_mod.co_consts[0]
2489
2490 mod = type(sys)("gh93696")
2491 mod.func = type(lambda: None)(func_code, mod.__dict__)
2492 mod.__file__ = 'gh93696.py'
2493
2494 return mod
2495
2496 mod = _create_fake_frozen_module()
2497 mod.func()
2498 """
2499 commands = """
2500 break 20
2501 continue
2502 step
2503 list
2504 quit
2505 """
2506 with open('gh93696.py', 'w') as f:
2507 f.write(textwrap.dedent(frozen_src))
2508
2509 with open('gh93696_host.py', 'w') as f:
2510 f.write(textwrap.dedent(host_program))
2511
2512 self.addCleanup(os_helper.unlink, 'gh93696.py')
2513 self.addCleanup(os_helper.unlink, 'gh93696_host.py')
2514 stdout, stderr = self._run_pdb(["gh93696_host.py"], commands)
2515 # verify that pdb found the source of the "frozen" function
2516 self.assertIn('x = "Sentinel string for gh-93696"', stdout, "Sentinel statement not found")
2517
2518 def test_non_utf8_encoding(self):
2519 script_dir = os.path.join(os.path.dirname(__file__), 'encoded_modules')
2520 for filename in os.listdir(script_dir):
2521 if filename.endswith(".py"):
2522 self._run_pdb([os.path.join(script_dir, filename)], 'q')
2523
2524 class ChecklineTests(unittest.TestCase):
2525 def setUp(self):
2526 linecache.clearcache() # Pdb.checkline() uses linecache.getline()
2527
2528 def tearDown(self):
2529 os_helper.unlink(os_helper.TESTFN)
2530
2531 def test_checkline_before_debugging(self):
2532 with open(os_helper.TESTFN, "w") as f:
2533 f.write("print(123)")
2534 db = pdb.Pdb()
2535 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
2536
2537 def test_checkline_after_reset(self):
2538 with open(os_helper.TESTFN, "w") as f:
2539 f.write("print(123)")
2540 db = pdb.Pdb()
2541 db.reset()
2542 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
2543
2544 def test_checkline_is_not_executable(self):
2545 # Test for comments, docstrings and empty lines
2546 s = textwrap.dedent("""
2547 # Comment
2548 \"\"\" docstring \"\"\"
2549 ''' docstring '''
2550
2551 """)
2552 with open(os_helper.TESTFN, "w") as f:
2553 f.write(s)
2554 num_lines = len(s.splitlines()) + 2 # Test for EOF
2555 with redirect_stdout(StringIO()):
2556 db = pdb.Pdb()
2557 for lineno in range(num_lines):
2558 self.assertFalse(db.checkline(os_helper.TESTFN, lineno))
2559
2560
2561 @support.requires_subprocess()
2562 class PdbTestReadline(unittest.TestCase):
2563 def setUpClass():
2564 # Ensure that the readline module is loaded
2565 # If this fails, the test is skipped because SkipTest will be raised
2566 readline = import_module('readline')
2567 if readline.__doc__ and "libedit" in readline.__doc__:
2568 raise unittest.SkipTest("libedit readline is not supported for pdb")
2569
2570 def test_basic_completion(self):
2571 script = textwrap.dedent("""
2572 import pdb; pdb.Pdb().set_trace()
2573 # Concatenate strings so that the output doesn't appear in the source
2574 print('hello' + '!')
2575 """)
2576
2577 # List everything starting with 'co', there should be multiple matches
2578 # then add ntin and complete 'contin' to 'continue'
2579 input = b"co\t\tntin\t\n"
2580
2581 output = run_pty(script, input)
2582
2583 self.assertIn(b'commands', output)
2584 self.assertIn(b'condition', output)
2585 self.assertIn(b'continue', output)
2586 self.assertIn(b'hello!', output)
2587
2588
2589 def load_tests(loader, tests, pattern):
2590 from test import test_pdb
2591 tests.addTest(doctest.DocTestSuite(test_pdb))
2592 return tests
2593
2594
2595 if __name__ == '__main__':
2596 unittest.main()