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