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