Debian Codegraph @

Lib/test/test_pdb.py

raw
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 import zipapp
14
15 from contextlib import ExitStack, redirect_stdout
16 from io import StringIO
17 from test import support
18 from test.support import force_not_colorized, os_helper
19 from test.support.import_helper import import_module
20 from test.support.pty_helper import run_pty, FakeInput
21 from unittest.mock import patch
22
23 # gh-114275: WASI fails to run asyncio tests, similar skip than test_asyncio.
24 SKIP_ASYNCIO_TESTS = (not support.has_socket_support)
25
26
27 class PdbTestInput(object):
28 """Context manager that makes testing Pdb in doctests easier."""
29
30 def __init__(self, input):
31 self.input = input
32
33 def __enter__(self):
34 self.real_stdin = sys.stdin
35 sys.stdin = FakeInput(self.input)
36 self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
37
38 def __exit__(self, *exc):
39 sys.stdin = self.real_stdin
40 if self.orig_trace:
41 sys.settrace(self.orig_trace)
42
43
44 def test_pdb_displayhook():
45 """This tests the custom displayhook for pdb.
46
47 >>> def test_function(foo, bar):
48 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
49
50 >>> with PdbTestInput([
51 ... 'foo',
52 ... 'bar',
53 ... 'for i in range(5): print(i)',
54 ... 'continue',
55 ... ]):
56 ... test_function(1, None)
57 > <doctest test.test_pdb.test_pdb_displayhook[0]>(2)test_function()
58 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
59 (Pdb) foo
60 1
61 (Pdb) bar
62 (Pdb) for i in range(5): print(i)
63 0
64 1
65 2
66 3
67 4
68 (Pdb) continue
69 """
70
71
72 def test_pdb_basic_commands():
73 """Test the basic commands of pdb.
74
75 >>> def test_function_2(foo, bar='default'):
76 ... print(foo)
77 ... for i in range(5):
78 ... print(i)
79 ... print(bar)
80 ... for i in range(10):
81 ... never_executed
82 ... print('after for')
83 ... print('...')
84 ... return foo.upper()
85
86 >>> def test_function3(arg=None, *, kwonly=None):
87 ... pass
88
89 >>> def test_function4(a, b, c, /):
90 ... pass
91
92 >>> def test_function():
93 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
94 ... ret = test_function_2('baz')
95 ... test_function3(kwonly=True)
96 ... test_function4(1, 2, 3)
97 ... print(ret)
98
99 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
100 ... 'step', # go to line ret = test_function_2('baz')
101 ... 'step', # entering the function call
102 ... 'args', # display function args
103 ... 'list', # list function source
104 ... 'bt', # display backtrace
105 ... 'up', # step up to test_function()
106 ... 'down', # step down to test_function_2() again
107 ... 'next', # stepping to print(foo)
108 ... 'next', # stepping to the for loop
109 ... 'step', # stepping into the for loop
110 ... 'until', # continuing until out of the for loop
111 ... 'next', # executing the print(bar)
112 ... 'jump 8', # jump over second for loop
113 ... 'return', # return out of function
114 ... 'retval', # display return value
115 ... 'next', # step to test_function3()
116 ... 'step', # stepping into test_function3()
117 ... 'args', # display function args
118 ... 'return', # return out of function
119 ... 'next', # step to test_function4()
120 ... 'step', # stepping to test_function4()
121 ... 'args', # display function args
122 ... 'continue',
123 ... ]):
124 ... test_function()
125 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(2)test_function()
126 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
127 (Pdb) step
128 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
129 -> ret = test_function_2('baz')
130 (Pdb) step
131 --Call--
132 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
133 -> def test_function_2(foo, bar='default'):
134 (Pdb) args
135 foo = 'baz'
136 bar = 'default'
137 (Pdb) list
138 1 -> def test_function_2(foo, bar='default'):
139 2 print(foo)
140 3 for i in range(5):
141 4 print(i)
142 5 print(bar)
143 6 for i in range(10):
144 7 never_executed
145 8 print('after for')
146 9 print('...')
147 10 return foo.upper()
148 [EOF]
149 (Pdb) bt
150 ...
151 <doctest test.test_pdb.test_pdb_basic_commands[4]>(26)<module>()
152 -> test_function()
153 <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
154 -> ret = test_function_2('baz')
155 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
156 -> def test_function_2(foo, bar='default'):
157 (Pdb) up
158 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
159 -> ret = test_function_2('baz')
160 (Pdb) down
161 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
162 -> def test_function_2(foo, bar='default'):
163 (Pdb) next
164 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
165 -> print(foo)
166 (Pdb) next
167 baz
168 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
169 -> for i in range(5):
170 (Pdb) step
171 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
172 -> print(i)
173 (Pdb) until
174 0
175 1
176 2
177 3
178 4
179 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
180 -> print(bar)
181 (Pdb) next
182 default
183 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
184 -> for i in range(10):
185 (Pdb) jump 8
186 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
187 -> print('after for')
188 (Pdb) return
189 after for
190 ...
191 --Return--
192 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
193 -> return foo.upper()
194 (Pdb) retval
195 'BAZ'
196 (Pdb) next
197 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(4)test_function()
198 -> test_function3(kwonly=True)
199 (Pdb) step
200 --Call--
201 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(1)test_function3()
202 -> def test_function3(arg=None, *, kwonly=None):
203 (Pdb) args
204 arg = None
205 kwonly = True
206 (Pdb) return
207 --Return--
208 > <doctest test.test_pdb.test_pdb_basic_commands[1]>(2)test_function3()->None
209 -> pass
210 (Pdb) next
211 > <doctest test.test_pdb.test_pdb_basic_commands[3]>(5)test_function()
212 -> test_function4(1, 2, 3)
213 (Pdb) step
214 --Call--
215 > <doctest test.test_pdb.test_pdb_basic_commands[2]>(1)test_function4()
216 -> def test_function4(a, b, c, /):
217 (Pdb) args
218 a = 1
219 b = 2
220 c = 3
221 (Pdb) continue
222 BAZ
223 """
224
225 def reset_Breakpoint():
226 import bdb
227 bdb.Breakpoint.clearBreakpoints()
228
229 def test_pdb_breakpoint_commands():
230 """Test basic commands related to breakpoints.
231
232 >>> def test_function():
233 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
234 ... print(1)
235 ... print(2)
236 ... print(3)
237 ... print(4)
238
239 First, need to clear bdb state that might be left over from previous tests.
240 Otherwise, the new breakpoints might get assigned different numbers.
241
242 >>> reset_Breakpoint()
243
244 Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because
245 the breakpoint list outputs a tab for the "stop only" and "ignore next"
246 lines, which we don't want to put in here.
247
248 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
249 ... 'break 3',
250 ... 'break 4, +',
251 ... 'disable 1',
252 ... 'ignore 1 10',
253 ... 'condition 1 1 < 2',
254 ... 'condition 1 1 <',
255 ... 'break 4',
256 ... 'break 4',
257 ... 'break',
258 ... 'clear 3',
259 ... 'break',
260 ... 'condition 1',
261 ... 'enable 1',
262 ... 'clear 1',
263 ... 'commands 2',
264 ... 'p "42"',
265 ... 'print("42", 7*6)', # Issue 18764 (not about breakpoints)
266 ... 'end',
267 ... 'continue', # will stop at breakpoint 2 (line 4)
268 ... 'clear', # clear all!
269 ... 'y',
270 ... 'tbreak 5',
271 ... 'continue', # will stop at temporary breakpoint
272 ... 'break', # make sure breakpoint is gone
273 ... 'commands 10', # out of range
274 ... 'commands a', # display help
275 ... 'commands 4', # already deleted
276 ... 'break 6, undefined', # condition causing `NameError` during evaluation
277 ... 'continue', # will stop, ignoring runtime error
278 ... 'continue',
279 ... ]):
280 ... test_function()
281 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(2)test_function()
282 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
283 (Pdb) break 3
284 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
285 (Pdb) break 4, +
286 *** Invalid condition +: SyntaxError: invalid syntax
287 (Pdb) disable 1
288 Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
289 (Pdb) ignore 1 10
290 Will ignore next 10 crossings of breakpoint 1.
291 (Pdb) condition 1 1 < 2
292 New condition set for breakpoint 1.
293 (Pdb) condition 1 1 <
294 *** Invalid condition 1 <: SyntaxError: invalid syntax
295 (Pdb) break 4
296 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
297 (Pdb) break 4
298 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
299 (Pdb) break
300 Num Type Disp Enb Where
301 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
302 stop only if 1 < 2
303 ignore next 10 hits
304 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
305 3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
306 (Pdb) clear 3
307 Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
308 (Pdb) break
309 Num Type Disp Enb Where
310 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
311 stop only if 1 < 2
312 ignore next 10 hits
313 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
314 (Pdb) condition 1
315 Breakpoint 1 is now unconditional.
316 (Pdb) enable 1
317 Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
318 (Pdb) clear 1
319 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
320 (Pdb) commands 2
321 (com) p "42"
322 (com) print("42", 7*6)
323 (com) end
324 (Pdb) continue
325 1
326 '42'
327 42 42
328 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
329 -> print(2)
330 (Pdb) clear
331 Clear all breaks? y
332 Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
333 (Pdb) tbreak 5
334 Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
335 (Pdb) continue
336 2
337 Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
338 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
339 -> print(3)
340 (Pdb) break
341 (Pdb) commands 10
342 *** cannot set commands: Breakpoint number 10 out of range
343 (Pdb) commands a
344 *** Invalid argument: a
345 Usage: (Pdb) commands [bpnumber]
346 (com) ...
347 (com) end
348 (Pdb)
349 (Pdb) commands 4
350 *** cannot set commands: Breakpoint 4 already deleted
351 (Pdb) break 6, undefined
352 Breakpoint 5 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:6
353 (Pdb) continue
354 3
355 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(6)test_function()
356 -> print(4)
357 (Pdb) continue
358 4
359 """
360
361 def test_pdb_breakpoint_on_annotated_function_def():
362 """Test breakpoints on function definitions with annotation.
363
364 >>> def foo[T]():
365 ... return 0
366
367 >>> def bar() -> int:
368 ... return 0
369
370 >>> def foobar[T]() -> int:
371 ... return 0
372
373 >>> reset_Breakpoint()
374
375 >>> def test_function():
376 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
377 ... pass
378
379 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
380 ... 'break foo',
381 ... 'break bar',
382 ... 'break foobar',
383 ... 'continue',
384 ... ]):
385 ... test_function()
386 > <doctest test.test_pdb.test_pdb_breakpoint_on_annotated_function_def[4]>(2)test_function()
387 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
388 (Pdb) break foo
389 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_on_annotated_function_def[0]>:2
390 (Pdb) break bar
391 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_on_annotated_function_def[1]>:2
392 (Pdb) break foobar
393 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_on_annotated_function_def[2]>:2
394 (Pdb) continue
395 """
396
397 def test_pdb_breakpoint_with_filename():
398 """Breakpoints with filename:lineno
399
400 >>> def test_function():
401 ... # inspect_fodder2 is a great module as the line number is stable
402 ... from test.test_inspect import inspect_fodder2 as mod2
403 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
404 ... mod2.func88()
405 ... mod2.func114()
406 ... # Be a good citizen and clean up the mess
407 ... reset_Breakpoint()
408
409 First, need to clear bdb state that might be left over from previous tests.
410 Otherwise, the new breakpoints might get assigned different numbers.
411
412 >>> reset_Breakpoint()
413
414 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
415 ... 'break test.test_inspect.inspect_fodder2:90',
416 ... 'continue', # will stop at func88
417 ... 'break test/test_inspect/inspect_fodder2.py:115',
418 ... 'continue', # will stop at func114
419 ... 'continue',
420 ... ]):
421 ... test_function()
422 > <doctest test.test_pdb.test_pdb_breakpoint_with_filename[0]>(4)test_function()
423 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
424 (Pdb) break test.test_inspect.inspect_fodder2:90
425 Breakpoint 1 at ...inspect_fodder2.py:90
426 (Pdb) continue
427 > ...inspect_fodder2.py(90)func88()
428 -> return 90
429 (Pdb) break test/test_inspect/inspect_fodder2.py:115
430 Breakpoint 2 at ...inspect_fodder2.py:115
431 (Pdb) continue
432 > ...inspect_fodder2.py(115)func114()
433 -> return 115
434 (Pdb) continue
435 """
436
437 def test_pdb_breakpoints_preserved_across_interactive_sessions():
438 """Breakpoints are remembered between interactive sessions
439
440 >>> reset_Breakpoint()
441 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
442 ... 'import test.test_pdb',
443 ... 'break test.test_pdb.do_something',
444 ... 'break test.test_pdb.do_nothing',
445 ... 'break',
446 ... 'continue',
447 ... ]):
448 ... pdb.run('print()')
449 > <string>(1)<module>()...
450 (Pdb) import test.test_pdb
451 (Pdb) break test.test_pdb.do_something
452 Breakpoint 1 at ...test_pdb.py:...
453 (Pdb) break test.test_pdb.do_nothing
454 Breakpoint 2 at ...test_pdb.py:...
455 (Pdb) break
456 Num Type Disp Enb Where
457 1 breakpoint keep yes at ...test_pdb.py:...
458 2 breakpoint keep yes at ...test_pdb.py:...
459 (Pdb) continue
460
461 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
462 ... 'break',
463 ... 'break pdb.find_function',
464 ... 'break',
465 ... 'clear 1',
466 ... 'continue',
467 ... ]):
468 ... pdb.run('print()')
469 > <string>(1)<module>()...
470 (Pdb) break
471 Num Type Disp Enb Where
472 1 breakpoint keep yes at ...test_pdb.py:...
473 2 breakpoint keep yes at ...test_pdb.py:...
474 (Pdb) break pdb.find_function
475 Breakpoint 3 at ...pdb.py:...
476 (Pdb) break
477 Num Type Disp Enb Where
478 1 breakpoint keep yes at ...test_pdb.py:...
479 2 breakpoint keep yes at ...test_pdb.py:...
480 3 breakpoint keep yes at ...pdb.py:...
481 (Pdb) clear 1
482 Deleted breakpoint 1 at ...test_pdb.py:...
483 (Pdb) continue
484
485 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
486 ... 'break',
487 ... 'clear 2',
488 ... 'clear 3',
489 ... 'continue',
490 ... ]):
491 ... pdb.run('print()')
492 > <string>(1)<module>()...
493 (Pdb) break
494 Num Type Disp Enb Where
495 2 breakpoint keep yes at ...test_pdb.py:...
496 3 breakpoint keep yes at ...pdb.py:...
497 (Pdb) clear 2
498 Deleted breakpoint 2 at ...test_pdb.py:...
499 (Pdb) clear 3
500 Deleted breakpoint 3 at ...pdb.py:...
501 (Pdb) continue
502 """
503
504 def test_pdb_pp_repr_exc():
505 """Test that do_p/do_pp do not swallow exceptions.
506
507 >>> class BadRepr:
508 ... def __repr__(self):
509 ... raise Exception('repr_exc')
510 >>> obj = BadRepr()
511
512 >>> def test_function():
513 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
514
515 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
516 ... 'p obj',
517 ... 'pp obj',
518 ... 'continue',
519 ... ]):
520 ... test_function()
521 > <doctest test.test_pdb.test_pdb_pp_repr_exc[2]>(2)test_function()
522 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
523 (Pdb) p obj
524 *** Exception: repr_exc
525 (Pdb) pp obj
526 *** Exception: repr_exc
527 (Pdb) continue
528 """
529
530 def test_pdb_empty_line():
531 """Test that empty line repeats the last command.
532
533 >>> def test_function():
534 ... x = 1
535 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
536 ... y = 2
537
538 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
539 ... 'p x',
540 ... '', # Should repeat p x
541 ... 'n ;; p 0 ;; p x', # Fill cmdqueue with multiple commands
542 ... '', # Should still repeat p x
543 ... 'continue',
544 ... ]):
545 ... test_function()
546 > <doctest test.test_pdb.test_pdb_empty_line[0]>(3)test_function()
547 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
548 (Pdb) p x
549 1
550 (Pdb)
551 1
552 (Pdb) n ;; p 0 ;; p x
553 0
554 1
555 > <doctest test.test_pdb.test_pdb_empty_line[0]>(4)test_function()
556 -> y = 2
557 (Pdb)
558 1
559 (Pdb) continue
560 """
561
562 def do_nothing():
563 pass
564
565 def do_something():
566 print(42)
567
568 def test_list_commands():
569 """Test the list and source commands of pdb.
570
571 >>> def test_function_2(foo):
572 ... import test.test_pdb
573 ... test.test_pdb.do_nothing()
574 ... 'some...'
575 ... 'more...'
576 ... 'code...'
577 ... 'to...'
578 ... 'make...'
579 ... 'a...'
580 ... 'long...'
581 ... 'listing...'
582 ... 'useful...'
583 ... '...'
584 ... '...'
585 ... return foo
586
587 >>> def test_function():
588 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
589 ... ret = test_function_2('baz')
590
591 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
592 ... 'step', # go to the test function line
593 ... 'list', # list first function
594 ... 'step', # step into second function
595 ... 'list', # list second function
596 ... 'list', # continue listing to EOF
597 ... 'list 1,3', # list specific lines
598 ... 'list x', # invalid argument
599 ... 'next', # step to import
600 ... 'next', # step over import
601 ... 'step', # step into do_nothing
602 ... 'longlist', # list all lines
603 ... 'source do_something', # list all lines of function
604 ... 'source fooxxx', # something that doesn't exit
605 ... 'continue',
606 ... ]):
607 ... test_function()
608 > <doctest test.test_pdb.test_list_commands[1]>(2)test_function()
609 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
610 (Pdb) step
611 > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
612 -> ret = test_function_2('baz')
613 (Pdb) list
614 1 def test_function():
615 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
616 3 -> ret = test_function_2('baz')
617 [EOF]
618 (Pdb) step
619 --Call--
620 > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
621 -> def test_function_2(foo):
622 (Pdb) list
623 1 -> def test_function_2(foo):
624 2 import test.test_pdb
625 3 test.test_pdb.do_nothing()
626 4 'some...'
627 5 'more...'
628 6 'code...'
629 7 'to...'
630 8 'make...'
631 9 'a...'
632 10 'long...'
633 11 'listing...'
634 (Pdb) list
635 12 'useful...'
636 13 '...'
637 14 '...'
638 15 return foo
639 [EOF]
640 (Pdb) list 1,3
641 1 -> def test_function_2(foo):
642 2 import test.test_pdb
643 3 test.test_pdb.do_nothing()
644 (Pdb) list x
645 *** ...
646 (Pdb) next
647 > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
648 -> import test.test_pdb
649 (Pdb) next
650 > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
651 -> test.test_pdb.do_nothing()
652 (Pdb) step
653 --Call--
654 > ...test_pdb.py(...)do_nothing()
655 -> def do_nothing():
656 (Pdb) longlist
657 ... -> def do_nothing():
658 ... pass
659 (Pdb) source do_something
660 ... def do_something():
661 ... print(42)
662 (Pdb) source fooxxx
663 *** ...
664 (Pdb) continue
665 """
666
667 def test_pdb_whatis_command():
668 """Test the whatis command
669
670 >>> myvar = (1,2)
671 >>> def myfunc():
672 ... pass
673
674 >>> class MyClass:
675 ... def mymethod(self):
676 ... pass
677
678 >>> def test_function():
679 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
680
681 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
682 ... 'whatis myvar',
683 ... 'whatis myfunc',
684 ... 'whatis MyClass',
685 ... 'whatis MyClass()',
686 ... 'whatis MyClass.mymethod',
687 ... 'whatis MyClass().mymethod',
688 ... 'continue',
689 ... ]):
690 ... test_function()
691 > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()
692 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
693 (Pdb) whatis myvar
694 <class 'tuple'>
695 (Pdb) whatis myfunc
696 Function myfunc
697 (Pdb) whatis MyClass
698 Class test.test_pdb.MyClass
699 (Pdb) whatis MyClass()
700 <class 'test.test_pdb.MyClass'>
701 (Pdb) whatis MyClass.mymethod
702 Function mymethod
703 (Pdb) whatis MyClass().mymethod
704 Method mymethod
705 (Pdb) continue
706 """
707
708 def test_pdb_display_command():
709 """Test display command
710
711 >>> def test_function():
712 ... a = 0
713 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
714 ... a = 1
715 ... a = 2
716 ... a = 3
717 ... a = 4
718
719 >>> with PdbTestInput([ # doctest: +ELLIPSIS
720 ... 's',
721 ... 'display +',
722 ... 'display',
723 ... 'display a',
724 ... 'n',
725 ... 'display',
726 ... 'undisplay a',
727 ... 'n',
728 ... 'display a',
729 ... 'undisplay',
730 ... 'display a < 1',
731 ... 'n',
732 ... 'display undefined',
733 ... 'continue',
734 ... ]):
735 ... test_function()
736 > <doctest test.test_pdb.test_pdb_display_command[0]>(3)test_function()
737 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
738 (Pdb) s
739 > <doctest test.test_pdb.test_pdb_display_command[0]>(4)test_function()
740 -> a = 1
741 (Pdb) display +
742 *** Unable to display +: SyntaxError: invalid syntax
743 (Pdb) display
744 No expression is being displayed
745 (Pdb) display a
746 display a: 0
747 (Pdb) n
748 > <doctest test.test_pdb.test_pdb_display_command[0]>(5)test_function()
749 -> a = 2
750 display a: 1 [old: 0]
751 (Pdb) display
752 Currently displaying:
753 a: 1
754 (Pdb) undisplay a
755 (Pdb) n
756 > <doctest test.test_pdb.test_pdb_display_command[0]>(6)test_function()
757 -> a = 3
758 (Pdb) display a
759 display a: 2
760 (Pdb) undisplay
761 (Pdb) display a < 1
762 display a < 1: False
763 (Pdb) n
764 > <doctest test.test_pdb.test_pdb_display_command[0]>(7)test_function()
765 -> a = 4
766 (Pdb) display undefined
767 display undefined: ** raised NameError: name 'undefined' is not defined **
768 (Pdb) continue
769 """
770
771 def test_pdb_alias_command():
772 """Test alias command
773
774 >>> class A:
775 ... def __init__(self):
776 ... self.attr1 = 10
777 ... self.attr2 = 'str'
778 ... def method(self):
779 ... pass
780
781 >>> def test_function():
782 ... o = A()
783 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
784 ... o.method()
785
786 >>> with PdbTestInput([ # doctest: +ELLIPSIS
787 ... 's',
788 ... 'alias pi',
789 ... 'alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")',
790 ... 'alias ps pi self',
791 ... 'alias ps',
792 ... 'pi o',
793 ... 's',
794 ... 'ps',
795 ... 'alias myp p %2',
796 ... 'alias myp',
797 ... 'alias myp p %1',
798 ... 'myp',
799 ... 'myp 1',
800 ... 'myp 1 2',
801 ... 'alias repeat_second_arg p "%* %2"',
802 ... 'repeat_second_arg 1 2 3',
803 ... 'continue',
804 ... ]):
805 ... test_function()
806 > <doctest test.test_pdb.test_pdb_alias_command[1]>(3)test_function()
807 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
808 (Pdb) s
809 > <doctest test.test_pdb.test_pdb_alias_command[1]>(4)test_function()
810 -> o.method()
811 (Pdb) alias pi
812 *** Unknown alias 'pi'
813 (Pdb) alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
814 (Pdb) alias ps pi self
815 (Pdb) alias ps
816 ps = pi self
817 (Pdb) pi o
818 o.attr1 = 10
819 o.attr2 = str
820 (Pdb) s
821 --Call--
822 > <doctest test.test_pdb.test_pdb_alias_command[0]>(5)method()
823 -> def method(self):
824 (Pdb) ps
825 self.attr1 = 10
826 self.attr2 = str
827 (Pdb) alias myp p %2
828 *** Replaceable parameters must be consecutive
829 (Pdb) alias myp
830 *** Unknown alias 'myp'
831 (Pdb) alias myp p %1
832 (Pdb) myp
833 *** Not enough arguments for alias 'myp'
834 (Pdb) myp 1
835 1
836 (Pdb) myp 1 2
837 *** Too many arguments for alias 'myp'
838 (Pdb) alias repeat_second_arg p "%* %2"
839 (Pdb) repeat_second_arg 1 2 3
840 '1 2 3 2'
841 (Pdb) continue
842 """
843
844 def test_pdb_where_command():
845 """Test where command
846
847 >>> def g():
848 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
849
850 >>> def f():
851 ... g();
852
853 >>> def test_function():
854 ... f()
855
856 >>> with PdbTestInput([ # doctest: +ELLIPSIS
857 ... 'w',
858 ... 'where',
859 ... 'u',
860 ... 'w',
861 ... 'continue',
862 ... ]):
863 ... test_function()
864 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()
865 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
866 (Pdb) w
867 ...
868 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
869 -> test_function()
870 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
871 -> f()
872 <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
873 -> g();
874 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()
875 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
876 (Pdb) where
877 ...
878 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
879 -> test_function()
880 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
881 -> f()
882 <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
883 -> g();
884 > <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()
885 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
886 (Pdb) u
887 > <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
888 -> g();
889 (Pdb) w
890 ...
891 <doctest test.test_pdb.test_pdb_where_command[3]>(8)<module>()
892 -> test_function()
893 <doctest test.test_pdb.test_pdb_where_command[2]>(2)test_function()
894 -> f()
895 > <doctest test.test_pdb.test_pdb_where_command[1]>(2)f()
896 -> g();
897 <doctest test.test_pdb.test_pdb_where_command[0]>(2)g()
898 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
899 (Pdb) continue
900 """
901
902
903 # skip this test if sys.flags.no_site = True;
904 # exit() isn't defined unless there's a site module.
905 if not sys.flags.no_site:
906 def test_pdb_interact_command():
907 """Test interact command
908
909 >>> g = 0
910 >>> dict_g = {}
911
912 >>> def test_function():
913 ... x = 1
914 ... lst_local = []
915 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
916
917 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
918 ... 'interact',
919 ... 'x',
920 ... 'g',
921 ... 'x = 2',
922 ... 'g = 3',
923 ... 'dict_g["a"] = True',
924 ... 'lst_local.append(x)',
925 ... 'exit()',
926 ... 'p x',
927 ... 'p g',
928 ... 'p dict_g',
929 ... 'p lst_local',
930 ... 'continue',
931 ... ]):
932 ... test_function()
933 > <doctest test.test_pdb.test_pdb_interact_command[2]>(4)test_function()
934 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
935 (Pdb) interact
936 *pdb interact start*
937 ... x
938 1
939 ... g
940 0
941 ... x = 2
942 ... g = 3
943 ... dict_g["a"] = True
944 ... lst_local.append(x)
945 ... exit()
946 *exit from pdb interact command*
947 (Pdb) p x
948 1
949 (Pdb) p g
950 0
951 (Pdb) p dict_g
952 {'a': True}
953 (Pdb) p lst_local
954 [2]
955 (Pdb) continue
956 """
957
958 def test_convenience_variables():
959 """Test convenience variables
960
961 >>> def util_function():
962 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
963 ... try:
964 ... raise Exception('test')
965 ... except:
966 ... pass
967 ... return 1
968
969 >>> def test_function():
970 ... util_function()
971
972 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
973 ... 'step', # Step to try statement
974 ... '$_frame.f_lineno', # Check frame convenience variable
975 ... '$ _frame', # This should be a syntax error
976 ... '$a = 10', # Set a convenience variable
977 ... '$a', # Print its value
978 ... 'p "$a"', # Print the string $a
979 ... 'p $a + 2', # Do some calculation
980 ... 'p f"$a = {$a}"', # Make sure $ in string is not converted and f-string works
981 ... 'u', # Switch frame
982 ... '$_frame.f_lineno', # Make sure the frame changed
983 ... '$a', # Make sure the value persists
984 ... 'd', # Go back to the original frame
985 ... 'next',
986 ... '$a', # The value should be gone
987 ... 'next',
988 ... '$_exception', # Check exception convenience variable
989 ... 'next',
990 ... '$_exception', # Exception should be gone
991 ... 'return',
992 ... '$_retval', # Check return convenience variable
993 ... 'continue',
994 ... ]):
995 ... test_function()
996 > <doctest test.test_pdb.test_convenience_variables[0]>(2)util_function()
997 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
998 (Pdb) step
999 > <doctest test.test_pdb.test_convenience_variables[0]>(3)util_function()
1000 -> try:
1001 (Pdb) $_frame.f_lineno
1002 3
1003 (Pdb) $ _frame
1004 *** SyntaxError: invalid syntax
1005 (Pdb) $a = 10
1006 (Pdb) $a
1007 10
1008 (Pdb) p "$a"
1009 '$a'
1010 (Pdb) p $a + 2
1011 12
1012 (Pdb) p f"$a = {$a}"
1013 '$a = 10'
1014 (Pdb) u
1015 > <doctest test.test_pdb.test_convenience_variables[1]>(2)test_function()
1016 -> util_function()
1017 (Pdb) $_frame.f_lineno
1018 2
1019 (Pdb) $a
1020 10
1021 (Pdb) d
1022 > <doctest test.test_pdb.test_convenience_variables[0]>(3)util_function()
1023 -> try:
1024 (Pdb) next
1025 > <doctest test.test_pdb.test_convenience_variables[0]>(4)util_function()
1026 -> raise Exception('test')
1027 (Pdb) $a
1028 *** KeyError: 'a'
1029 (Pdb) next
1030 Exception: test
1031 > <doctest test.test_pdb.test_convenience_variables[0]>(4)util_function()
1032 -> raise Exception('test')
1033 (Pdb) $_exception
1034 Exception('test')
1035 (Pdb) next
1036 > <doctest test.test_pdb.test_convenience_variables[0]>(5)util_function()
1037 -> except:
1038 (Pdb) $_exception
1039 *** KeyError: '_exception'
1040 (Pdb) return
1041 --Return--
1042 > <doctest test.test_pdb.test_convenience_variables[0]>(7)util_function()->1
1043 -> return 1
1044 (Pdb) $_retval
1045 1
1046 (Pdb) continue
1047 """
1048
1049
1050 def test_post_mortem_chained():
1051 """Test post mortem traceback debugging of chained exception
1052
1053 >>> def test_function_2():
1054 ... try:
1055 ... 1/0
1056 ... finally:
1057 ... print('Exception!')
1058
1059 >>> def test_function_reraise():
1060 ... try:
1061 ... test_function_2()
1062 ... except ZeroDivisionError as e:
1063 ... raise ZeroDivisionError('reraised') from e
1064
1065 >>> def test_function():
1066 ... import pdb;
1067 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1068 ... try:
1069 ... test_function_reraise()
1070 ... except Exception as e:
1071 ... pdb._post_mortem(e, instance)
1072
1073 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1074 ... 'exceptions',
1075 ... 'exceptions 0',
1076 ... '$_exception',
1077 ... 'up',
1078 ... 'down',
1079 ... 'exceptions 1',
1080 ... '$_exception',
1081 ... 'up',
1082 ... 'down',
1083 ... 'exceptions -1',
1084 ... 'exceptions 3',
1085 ... 'up',
1086 ... 'exit',
1087 ... ]):
1088 ... try:
1089 ... test_function()
1090 ... except ZeroDivisionError:
1091 ... print('Correctly reraised.')
1092 Exception!
1093 > <doctest test.test_pdb.test_post_mortem_chained[1]>(5)test_function_reraise()
1094 -> raise ZeroDivisionError('reraised') from e
1095 (Pdb) exceptions
1096 0 ZeroDivisionError('division by zero')
1097 > 1 ZeroDivisionError('reraised')
1098 (Pdb) exceptions 0
1099 > <doctest test.test_pdb.test_post_mortem_chained[0]>(3)test_function_2()
1100 -> 1/0
1101 (Pdb) $_exception
1102 ZeroDivisionError('division by zero')
1103 (Pdb) up
1104 > <doctest test.test_pdb.test_post_mortem_chained[1]>(3)test_function_reraise()
1105 -> test_function_2()
1106 (Pdb) down
1107 > <doctest test.test_pdb.test_post_mortem_chained[0]>(3)test_function_2()
1108 -> 1/0
1109 (Pdb) exceptions 1
1110 > <doctest test.test_pdb.test_post_mortem_chained[1]>(5)test_function_reraise()
1111 -> raise ZeroDivisionError('reraised') from e
1112 (Pdb) $_exception
1113 ZeroDivisionError('reraised')
1114 (Pdb) up
1115 > <doctest test.test_pdb.test_post_mortem_chained[2]>(5)test_function()
1116 -> test_function_reraise()
1117 (Pdb) down
1118 > <doctest test.test_pdb.test_post_mortem_chained[1]>(5)test_function_reraise()
1119 -> raise ZeroDivisionError('reraised') from e
1120 (Pdb) exceptions -1
1121 *** No exception with that number
1122 (Pdb) exceptions 3
1123 *** No exception with that number
1124 (Pdb) up
1125 > <doctest test.test_pdb.test_post_mortem_chained[2]>(5)test_function()
1126 -> test_function_reraise()
1127 (Pdb) exit
1128 """
1129
1130
1131 def test_post_mortem_cause_no_context():
1132 """Test post mortem traceback debugging of chained exception
1133
1134 >>> def make_exc_with_stack(type_, *content, from_=None):
1135 ... try:
1136 ... raise type_(*content) from from_
1137 ... except Exception as out:
1138 ... return out
1139 ...
1140
1141 >>> def main():
1142 ... try:
1143 ... raise ValueError('Context Not Shown')
1144 ... except Exception as e1:
1145 ... raise ValueError("With Cause") from make_exc_with_stack(TypeError,'The Cause')
1146
1147 >>> def test_function():
1148 ... import pdb;
1149 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1150 ... try:
1151 ... main()
1152 ... except Exception as e:
1153 ... pdb._post_mortem(e, instance)
1154
1155 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1156 ... 'exceptions',
1157 ... 'exceptions 0',
1158 ... 'exceptions 1',
1159 ... 'up',
1160 ... 'down',
1161 ... 'exit',
1162 ... ]):
1163 ... try:
1164 ... test_function()
1165 ... except ValueError:
1166 ... print('Ok.')
1167 > <doctest test.test_pdb.test_post_mortem_cause_no_context[1]>(5)main()
1168 -> raise ValueError("With Cause") from make_exc_with_stack(TypeError,'The Cause')
1169 (Pdb) exceptions
1170 0 TypeError('The Cause')
1171 > 1 ValueError('With Cause')
1172 (Pdb) exceptions 0
1173 > <doctest test.test_pdb.test_post_mortem_cause_no_context[0]>(3)make_exc_with_stack()
1174 -> raise type_(*content) from from_
1175 (Pdb) exceptions 1
1176 > <doctest test.test_pdb.test_post_mortem_cause_no_context[1]>(5)main()
1177 -> raise ValueError("With Cause") from make_exc_with_stack(TypeError,'The Cause')
1178 (Pdb) up
1179 > <doctest test.test_pdb.test_post_mortem_cause_no_context[2]>(5)test_function()
1180 -> main()
1181 (Pdb) down
1182 > <doctest test.test_pdb.test_post_mortem_cause_no_context[1]>(5)main()
1183 -> raise ValueError("With Cause") from make_exc_with_stack(TypeError,'The Cause')
1184 (Pdb) exit"""
1185
1186
1187 def test_post_mortem_context_of_the_cause():
1188 """Test post mortem traceback debugging of chained exception
1189
1190
1191 >>> def main():
1192 ... try:
1193 ... raise TypeError('Context of the cause')
1194 ... except Exception as e1:
1195 ... try:
1196 ... raise ValueError('Root Cause')
1197 ... except Exception as e2:
1198 ... ex = e2
1199 ... raise ValueError("With Cause, and cause has context") from ex
1200
1201 >>> def test_function():
1202 ... import pdb;
1203 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1204 ... try:
1205 ... main()
1206 ... except Exception as e:
1207 ... pdb._post_mortem(e, instance)
1208
1209 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1210 ... 'exceptions',
1211 ... 'exceptions 2',
1212 ... 'up',
1213 ... 'down',
1214 ... 'exceptions 3',
1215 ... 'up',
1216 ... 'down',
1217 ... 'exceptions 4',
1218 ... 'up',
1219 ... 'down',
1220 ... 'exit',
1221 ... ]):
1222 ... try:
1223 ... test_function()
1224 ... except ValueError:
1225 ... print('Correctly reraised.')
1226 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[0]>(9)main()
1227 -> raise ValueError("With Cause, and cause has context") from ex
1228 (Pdb) exceptions
1229 0 TypeError('Context of the cause')
1230 1 ValueError('Root Cause')
1231 > 2 ValueError('With Cause, and cause has context')
1232 (Pdb) exceptions 2
1233 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[0]>(9)main()
1234 -> raise ValueError("With Cause, and cause has context") from ex
1235 (Pdb) up
1236 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[1]>(5)test_function()
1237 -> main()
1238 (Pdb) down
1239 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[0]>(9)main()
1240 -> raise ValueError("With Cause, and cause has context") from ex
1241 (Pdb) exceptions 3
1242 *** No exception with that number
1243 (Pdb) up
1244 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[1]>(5)test_function()
1245 -> main()
1246 (Pdb) down
1247 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[0]>(9)main()
1248 -> raise ValueError("With Cause, and cause has context") from ex
1249 (Pdb) exceptions 4
1250 *** No exception with that number
1251 (Pdb) up
1252 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[1]>(5)test_function()
1253 -> main()
1254 (Pdb) down
1255 > <doctest test.test_pdb.test_post_mortem_context_of_the_cause[0]>(9)main()
1256 -> raise ValueError("With Cause, and cause has context") from ex
1257 (Pdb) exit
1258 """
1259
1260
1261 def test_post_mortem_from_none():
1262 """Test post mortem traceback debugging of chained exception
1263
1264 In particular that cause from None (which sets __supress_context__ to True)
1265 does not show context.
1266
1267
1268 >>> def main():
1269 ... try:
1270 ... raise TypeError('Context of the cause')
1271 ... except Exception as e1:
1272 ... raise ValueError("With Cause, and cause has context") from None
1273
1274 >>> def test_function():
1275 ... import pdb;
1276 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1277 ... try:
1278 ... main()
1279 ... except Exception as e:
1280 ... pdb._post_mortem(e, instance)
1281
1282 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1283 ... 'exceptions',
1284 ... 'exit',
1285 ... ]):
1286 ... try:
1287 ... test_function()
1288 ... except ValueError:
1289 ... print('Correctly reraised.')
1290 > <doctest test.test_pdb.test_post_mortem_from_none[0]>(5)main()
1291 -> raise ValueError("With Cause, and cause has context") from None
1292 (Pdb) exceptions
1293 > 0 ValueError('With Cause, and cause has context')
1294 (Pdb) exit
1295 """
1296
1297
1298 def test_post_mortem_from_no_stack():
1299 """Test post mortem traceback debugging of chained exception
1300
1301 especially when one exception has no stack.
1302
1303 >>> def main():
1304 ... raise Exception() from Exception()
1305
1306
1307 >>> def test_function():
1308 ... import pdb;
1309 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1310 ... try:
1311 ... main()
1312 ... except Exception as e:
1313 ... pdb._post_mortem(e, instance)
1314
1315 >>> with PdbTestInput( # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1316 ... ["exceptions",
1317 ... "exceptions 0",
1318 ... "exit"],
1319 ... ):
1320 ... try:
1321 ... test_function()
1322 ... except ValueError:
1323 ... print('Correctly reraised.')
1324 > <doctest test.test_pdb.test_post_mortem_from_no_stack[0]>(2)main()
1325 -> raise Exception() from Exception()
1326 (Pdb) exceptions
1327 - Exception()
1328 > 1 Exception()
1329 (Pdb) exceptions 0
1330 *** This exception does not have a traceback, cannot jump to it
1331 (Pdb) exit
1332 """
1333
1334
1335 def test_post_mortem_single_no_stack():
1336 """Test post mortem called when origin exception has no stack
1337
1338
1339 >>> def test_function():
1340 ... import pdb;
1341 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1342 ... import sys
1343 ... sys.last_exc = Exception()
1344 ... pdb._post_mortem(sys.last_exc, instance)
1345
1346 >>> with PdbTestInput( # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1347 ... []
1348 ... ):
1349 ... try:
1350 ... test_function()
1351 ... except ValueError as e:
1352 ... print(e)
1353 A valid traceback must be passed if no exception is being handled
1354 """
1355
1356 def test_post_mortem_complex():
1357 """Test post mortem traceback debugging of chained exception
1358
1359 Test with simple and complex cycles, exception groups,...
1360
1361 >>> def make_ex_with_stack(type_, *content, from_=None):
1362 ... try:
1363 ... raise type_(*content) from from_
1364 ... except Exception as out:
1365 ... return out
1366 ...
1367
1368 >>> def cycle():
1369 ... try:
1370 ... raise ValueError("Cycle Leaf")
1371 ... except Exception as e:
1372 ... raise e from e
1373 ...
1374
1375 >>> def tri_cycle():
1376 ... a = make_ex_with_stack(ValueError, "Cycle1")
1377 ... b = make_ex_with_stack(ValueError, "Cycle2")
1378 ... c = make_ex_with_stack(ValueError, "Cycle3")
1379 ...
1380 ... a.__cause__ = b
1381 ... b.__cause__ = c
1382 ...
1383 ... raise c from a
1384 ...
1385
1386 >>> def cause():
1387 ... try:
1388 ... raise ValueError("Cause Leaf")
1389 ... except Exception as e:
1390 ... raise e
1391 ...
1392
1393 >>> def context(n=10):
1394 ... try:
1395 ... raise ValueError(f"Context Leaf {n}")
1396 ... except Exception as e:
1397 ... if n == 0:
1398 ... raise ValueError(f"With Context {n}") from e
1399 ... else:
1400 ... context(n - 1)
1401 ...
1402
1403 >>> def main():
1404 ... try:
1405 ... cycle()
1406 ... except Exception as e1:
1407 ... try:
1408 ... tri_cycle()
1409 ... except Exception as e2:
1410 ... ex = e2
1411 ... raise ValueError("With Context and With Cause") from ex
1412
1413
1414 >>> def test_function():
1415 ... import pdb;
1416 ... instance = pdb.Pdb(nosigint=True, readrc=False)
1417 ... try:
1418 ... main()
1419 ... except Exception as e:
1420 ... pdb._post_mortem(e, instance)
1421
1422 >>> with PdbTestInput( # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1423 ... ["exceptions",
1424 ... "exceptions 0",
1425 ... "exceptions 1",
1426 ... "exceptions 2",
1427 ... "exceptions 3",
1428 ... "exit"],
1429 ... ):
1430 ... try:
1431 ... test_function()
1432 ... except ValueError:
1433 ... print('Correctly reraised.')
1434 > <doctest test.test_pdb.test_post_mortem_complex[5]>(9)main()
1435 -> raise ValueError("With Context and With Cause") from ex
1436 (Pdb) exceptions
1437 0 ValueError('Cycle2')
1438 1 ValueError('Cycle1')
1439 2 ValueError('Cycle3')
1440 > 3 ValueError('With Context and With Cause')
1441 (Pdb) exceptions 0
1442 > <doctest test.test_pdb.test_post_mortem_complex[0]>(3)make_ex_with_stack()
1443 -> raise type_(*content) from from_
1444 (Pdb) exceptions 1
1445 > <doctest test.test_pdb.test_post_mortem_complex[0]>(3)make_ex_with_stack()
1446 -> raise type_(*content) from from_
1447 (Pdb) exceptions 2
1448 > <doctest test.test_pdb.test_post_mortem_complex[0]>(3)make_ex_with_stack()
1449 -> raise type_(*content) from from_
1450 (Pdb) exceptions 3
1451 > <doctest test.test_pdb.test_post_mortem_complex[5]>(9)main()
1452 -> raise ValueError("With Context and With Cause") from ex
1453 (Pdb) exit
1454 """
1455
1456
1457 def test_post_mortem():
1458 """Test post mortem traceback debugging.
1459
1460 >>> def test_function_2():
1461 ... try:
1462 ... 1/0
1463 ... finally:
1464 ... print('Exception!')
1465
1466 >>> def test_function():
1467 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1468 ... test_function_2()
1469 ... print('Not reached.')
1470
1471 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1472 ... 'step', # step to test_function_2() line
1473 ... 'next', # step over exception-raising call
1474 ... 'bt', # get a backtrace
1475 ... 'list', # list code of test_function()
1476 ... 'down', # step into test_function_2()
1477 ... 'list', # list code of test_function_2()
1478 ... 'continue',
1479 ... ]):
1480 ... try:
1481 ... test_function()
1482 ... except ZeroDivisionError:
1483 ... print('Correctly reraised.')
1484 > <doctest test.test_pdb.test_post_mortem[1]>(2)test_function()
1485 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1486 (Pdb) step
1487 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
1488 -> test_function_2()
1489 (Pdb) next
1490 Exception!
1491 ZeroDivisionError: division by zero
1492 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
1493 -> test_function_2()
1494 (Pdb) bt
1495 ...
1496 <doctest test.test_pdb.test_post_mortem[2]>(11)<module>()
1497 -> test_function()
1498 > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
1499 -> test_function_2()
1500 <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
1501 -> 1/0
1502 (Pdb) list
1503 1 def test_function():
1504 2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1505 3 -> test_function_2()
1506 4 print('Not reached.')
1507 [EOF]
1508 (Pdb) down
1509 > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
1510 -> 1/0
1511 (Pdb) list
1512 1 def test_function_2():
1513 2 try:
1514 3 >> 1/0
1515 4 finally:
1516 5 -> print('Exception!')
1517 [EOF]
1518 (Pdb) continue
1519 Correctly reraised.
1520 """
1521
1522
1523 def test_pdb_return_to_different_file():
1524 """When pdb returns to a different file, it should not skip if f_trace is
1525 not already set
1526
1527 >>> import pprint
1528
1529 >>> class A:
1530 ... def __repr__(self):
1531 ... return 'A'
1532
1533 >>> def test_function():
1534 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1535 ... pprint.pprint(A())
1536
1537 >>> reset_Breakpoint()
1538 >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1539 ... 'b A.__repr__',
1540 ... 'continue',
1541 ... 'return',
1542 ... 'next',
1543 ... 'return',
1544 ... 'return',
1545 ... 'continue',
1546 ... ]):
1547 ... test_function()
1548 > <doctest test.test_pdb.test_pdb_return_to_different_file[2]>(2)test_function()
1549 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1550 (Pdb) b A.__repr__
1551 Breakpoint 1 at <doctest test.test_pdb.test_pdb_return_to_different_file[1]>:3
1552 (Pdb) continue
1553 > <doctest test.test_pdb.test_pdb_return_to_different_file[1]>(3)__repr__()
1554 -> return 'A'
1555 (Pdb) return
1556 --Return--
1557 > <doctest test.test_pdb.test_pdb_return_to_different_file[1]>(3)__repr__()->'A'
1558 -> return 'A'
1559 (Pdb) next
1560 > ...pprint.py..._safe_repr()
1561 -> return rep,...
1562 (Pdb) return
1563 --Return--
1564 > ...pprint.py..._safe_repr()->('A'...)
1565 -> return rep,...
1566 (Pdb) return
1567 --Return--
1568 > ...pprint.py...format()->('A'...)
1569 -> return...
1570 (Pdb) continue
1571 A
1572 """
1573
1574
1575 def test_pdb_skip_modules():
1576 """This illustrates the simple case of module skipping.
1577
1578 >>> def skip_module():
1579 ... import string
1580 ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
1581 ... string.capwords('FOO')
1582
1583 >>> with PdbTestInput([
1584 ... 'step',
1585 ... 'step',
1586 ... 'continue',
1587 ... ]):
1588 ... skip_module()
1589 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(3)skip_module()
1590 -> import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
1591 (Pdb) step
1592 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
1593 -> string.capwords('FOO')
1594 (Pdb) step
1595 --Return--
1596 > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
1597 -> string.capwords('FOO')
1598 (Pdb) continue
1599 """
1600
1601 def test_pdb_invalid_arg():
1602 """This tests pdb commands that have invalid arguments
1603
1604 >>> def test_function():
1605 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1606
1607 >>> with PdbTestInput([
1608 ... 'a = 3',
1609 ... 'll 4',
1610 ... 'step 1',
1611 ... 'continue'
1612 ... ]):
1613 ... test_function()
1614 > <doctest test.test_pdb.test_pdb_invalid_arg[0]>(2)test_function()
1615 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1616 (Pdb) a = 3
1617 *** Invalid argument: = 3
1618 Usage: a(rgs)
1619 (Pdb) ll 4
1620 *** Invalid argument: 4
1621 Usage: ll | longlist
1622 (Pdb) step 1
1623 *** Invalid argument: 1
1624 Usage: s(tep)
1625 (Pdb) continue
1626 """
1627
1628
1629 # Module for testing skipping of module that makes a callback
1630 mod = types.ModuleType('module_to_skip')
1631 exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
1632
1633
1634 def test_pdb_skip_modules_with_callback():
1635 """This illustrates skipping of modules that call into other code.
1636
1637 >>> def skip_module():
1638 ... def callback():
1639 ... return None
1640 ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
1641 ... mod.foo_pony(callback)
1642
1643 >>> with PdbTestInput([
1644 ... 'step',
1645 ... 'step',
1646 ... 'step',
1647 ... 'step',
1648 ... 'step',
1649 ... 'step',
1650 ... 'continue',
1651 ... ]):
1652 ... skip_module()
1653 ... pass # provides something to "step" to
1654 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(4)skip_module()
1655 -> import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
1656 (Pdb) step
1657 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
1658 -> mod.foo_pony(callback)
1659 (Pdb) step
1660 --Call--
1661 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
1662 -> def callback():
1663 (Pdb) step
1664 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
1665 -> return None
1666 (Pdb) step
1667 --Return--
1668 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
1669 -> return None
1670 (Pdb) step
1671 --Return--
1672 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
1673 -> mod.foo_pony(callback)
1674 (Pdb) step
1675 > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(11)<module>()
1676 -> pass # provides something to "step" to
1677 (Pdb) continue
1678 """
1679
1680
1681 def test_pdb_continue_in_bottomframe():
1682 """Test that "continue" and "next" work properly in bottom frame (issue #5294).
1683
1684 >>> def test_function():
1685 ... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
1686 ... inst.set_trace()
1687 ... inst.botframe = sys._getframe() # hackery to get the right botframe
1688 ... print(1)
1689 ... print(2)
1690 ... print(3)
1691 ... print(4)
1692
1693 >>> with PdbTestInput([ # doctest: +ELLIPSIS
1694 ... 'step',
1695 ... 'next',
1696 ... 'break 7',
1697 ... 'continue',
1698 ... 'next',
1699 ... 'continue',
1700 ... 'continue',
1701 ... ]):
1702 ... test_function()
1703 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(3)test_function()
1704 -> inst.set_trace()
1705 (Pdb) step
1706 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
1707 -> inst.botframe = sys._getframe() # hackery to get the right botframe
1708 (Pdb) next
1709 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
1710 -> print(1)
1711 (Pdb) break 7
1712 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
1713 (Pdb) continue
1714 1
1715 2
1716 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
1717 -> print(3)
1718 (Pdb) next
1719 3
1720 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
1721 -> print(4)
1722 (Pdb) continue
1723 4
1724 """
1725
1726
1727 def pdb_invoke(method, arg):
1728 """Run pdb.method(arg)."""
1729 getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
1730
1731
1732 def test_pdb_run_with_incorrect_argument():
1733 """Testing run and runeval with incorrect first argument.
1734
1735 >>> pti = PdbTestInput(['continue',])
1736 >>> with pti:
1737 ... pdb_invoke('run', lambda x: x)
1738 Traceback (most recent call last):
1739 TypeError: exec() arg 1 must be a string, bytes or code object
1740
1741 >>> with pti:
1742 ... pdb_invoke('runeval', lambda x: x)
1743 Traceback (most recent call last):
1744 TypeError: eval() arg 1 must be a string, bytes or code object
1745 """
1746
1747
1748 def test_pdb_run_with_code_object():
1749 """Testing run and runeval with code object as a first argument.
1750
1751 >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
1752 ... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
1753 > <string>(1)<module>()...
1754 (Pdb) step
1755 --Return--
1756 > <string>(1)<module>()->None
1757 (Pdb) x
1758 1
1759 (Pdb) continue
1760
1761 >>> with PdbTestInput(['x', 'continue']):
1762 ... x=0
1763 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
1764 > <string>(1)<module>()->None
1765 (Pdb) x
1766 1
1767 (Pdb) continue
1768 """
1769
1770 def test_next_until_return_at_return_event():
1771 """Test that pdb stops after a next/until/return issued at a return debug event.
1772
1773 >>> def test_function_2():
1774 ... x = 1
1775 ... x = 2
1776
1777 >>> def test_function():
1778 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1779 ... test_function_2()
1780 ... test_function_2()
1781 ... test_function_2()
1782 ... end = 1
1783
1784 >>> reset_Breakpoint()
1785 >>> with PdbTestInput(['break test_function_2',
1786 ... 'continue',
1787 ... 'return',
1788 ... 'next',
1789 ... 'continue',
1790 ... 'return',
1791 ... 'until',
1792 ... 'continue',
1793 ... 'return',
1794 ... 'return',
1795 ... 'continue']):
1796 ... test_function()
1797 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(2)test_function()
1798 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1799 (Pdb) break test_function_2
1800 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:2
1801 (Pdb) continue
1802 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
1803 -> x = 1
1804 (Pdb) return
1805 --Return--
1806 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
1807 -> x = 2
1808 (Pdb) next
1809 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
1810 -> test_function_2()
1811 (Pdb) continue
1812 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
1813 -> x = 1
1814 (Pdb) return
1815 --Return--
1816 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
1817 -> x = 2
1818 (Pdb) until
1819 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
1820 -> test_function_2()
1821 (Pdb) continue
1822 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
1823 -> x = 1
1824 (Pdb) return
1825 --Return--
1826 > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
1827 -> x = 2
1828 (Pdb) return
1829 > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
1830 -> end = 1
1831 (Pdb) continue
1832 """
1833
1834 def test_pdb_next_command_for_generator():
1835 """Testing skip unwindng stack on yield for generators for "next" command
1836
1837 >>> def test_gen():
1838 ... yield 0
1839 ... return 1
1840 ... yield 2
1841
1842 >>> def test_function():
1843 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1844 ... it = test_gen()
1845 ... try:
1846 ... if next(it) != 0:
1847 ... raise AssertionError
1848 ... next(it)
1849 ... except StopIteration as ex:
1850 ... if ex.value != 1:
1851 ... raise AssertionError
1852 ... print("finished")
1853
1854 >>> with PdbTestInput(['step',
1855 ... 'step',
1856 ... 'step',
1857 ... 'step',
1858 ... 'next',
1859 ... 'next',
1860 ... 'step',
1861 ... 'step',
1862 ... 'continue']):
1863 ... test_function()
1864 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(2)test_function()
1865 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1866 (Pdb) step
1867 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
1868 -> it = test_gen()
1869 (Pdb) step
1870 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
1871 -> try:
1872 (Pdb) step
1873 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
1874 -> if next(it) != 0:
1875 (Pdb) step
1876 --Call--
1877 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
1878 -> def test_gen():
1879 (Pdb) next
1880 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
1881 -> yield 0
1882 (Pdb) next
1883 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
1884 -> return 1
1885 (Pdb) step
1886 --Return--
1887 > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
1888 -> return 1
1889 (Pdb) step
1890 StopIteration: 1
1891 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
1892 -> next(it)
1893 (Pdb) continue
1894 finished
1895 """
1896
1897 if not SKIP_ASYNCIO_TESTS:
1898 def test_pdb_next_command_for_coroutine():
1899 """Testing skip unwindng stack on yield for coroutines for "next" command
1900
1901 >>> import asyncio
1902
1903 >>> async def test_coro():
1904 ... await asyncio.sleep(0)
1905 ... await asyncio.sleep(0)
1906 ... await asyncio.sleep(0)
1907
1908 >>> async def test_main():
1909 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1910 ... await test_coro()
1911
1912 >>> def test_function():
1913 ... loop = asyncio.new_event_loop()
1914 ... loop.run_until_complete(test_main())
1915 ... loop.close()
1916 ... asyncio.set_event_loop_policy(None)
1917 ... print("finished")
1918
1919 >>> with PdbTestInput(['step',
1920 ... 'step',
1921 ... 'step',
1922 ... 'next',
1923 ... 'next',
1924 ... 'next',
1925 ... 'step',
1926 ... 'continue']):
1927 ... test_function()
1928 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(2)test_main()
1929 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1930 (Pdb) step
1931 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
1932 -> await test_coro()
1933 (Pdb) step
1934 --Call--
1935 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
1936 -> async def test_coro():
1937 (Pdb) step
1938 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
1939 -> await asyncio.sleep(0)
1940 (Pdb) next
1941 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
1942 -> await asyncio.sleep(0)
1943 (Pdb) next
1944 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
1945 -> await asyncio.sleep(0)
1946 (Pdb) next
1947 Internal StopIteration
1948 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
1949 -> await test_coro()
1950 (Pdb) step
1951 --Return--
1952 > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
1953 -> await test_coro()
1954 (Pdb) continue
1955 finished
1956 """
1957
1958 def test_pdb_next_command_for_asyncgen():
1959 """Testing skip unwindng stack on yield for coroutines for "next" command
1960
1961 >>> import asyncio
1962
1963 >>> async def agen():
1964 ... yield 1
1965 ... await asyncio.sleep(0)
1966 ... yield 2
1967
1968 >>> async def test_coro():
1969 ... async for x in agen():
1970 ... print(x)
1971
1972 >>> async def test_main():
1973 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1974 ... await test_coro()
1975
1976 >>> def test_function():
1977 ... loop = asyncio.new_event_loop()
1978 ... loop.run_until_complete(test_main())
1979 ... loop.close()
1980 ... asyncio.set_event_loop_policy(None)
1981 ... print("finished")
1982
1983 >>> with PdbTestInput(['step',
1984 ... 'step',
1985 ... 'step',
1986 ... 'next',
1987 ... 'next',
1988 ... 'step',
1989 ... 'next',
1990 ... 'continue']):
1991 ... test_function()
1992 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(2)test_main()
1993 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1994 (Pdb) step
1995 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
1996 -> await test_coro()
1997 (Pdb) step
1998 --Call--
1999 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
2000 -> async def test_coro():
2001 (Pdb) step
2002 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
2003 -> async for x in agen():
2004 (Pdb) next
2005 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
2006 -> print(x)
2007 (Pdb) next
2008 1
2009 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
2010 -> async for x in agen():
2011 (Pdb) step
2012 --Call--
2013 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
2014 -> yield 1
2015 (Pdb) next
2016 > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
2017 -> await asyncio.sleep(0)
2018 (Pdb) continue
2019 2
2020 finished
2021 """
2022
2023 def test_pdb_return_command_for_generator():
2024 """Testing no unwindng stack on yield for generators
2025 for "return" command
2026
2027 >>> def test_gen():
2028 ... yield 0
2029 ... return 1
2030 ... yield 2
2031
2032 >>> def test_function():
2033 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2034 ... it = test_gen()
2035 ... try:
2036 ... if next(it) != 0:
2037 ... raise AssertionError
2038 ... next(it)
2039 ... except StopIteration as ex:
2040 ... if ex.value != 1:
2041 ... raise AssertionError
2042 ... print("finished")
2043
2044 >>> with PdbTestInput(['step',
2045 ... 'step',
2046 ... 'step',
2047 ... 'step',
2048 ... 'return',
2049 ... 'step',
2050 ... 'step',
2051 ... 'continue']):
2052 ... test_function()
2053 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(2)test_function()
2054 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2055 (Pdb) step
2056 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
2057 -> it = test_gen()
2058 (Pdb) step
2059 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
2060 -> try:
2061 (Pdb) step
2062 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
2063 -> if next(it) != 0:
2064 (Pdb) step
2065 --Call--
2066 > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
2067 -> def test_gen():
2068 (Pdb) return
2069 StopIteration: 1
2070 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
2071 -> next(it)
2072 (Pdb) step
2073 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
2074 -> except StopIteration as ex:
2075 (Pdb) step
2076 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
2077 -> if ex.value != 1:
2078 (Pdb) continue
2079 finished
2080 """
2081
2082 if not SKIP_ASYNCIO_TESTS:
2083 def test_pdb_return_command_for_coroutine():
2084 """Testing no unwindng stack on yield for coroutines for "return" command
2085
2086 >>> import asyncio
2087
2088 >>> async def test_coro():
2089 ... await asyncio.sleep(0)
2090 ... await asyncio.sleep(0)
2091 ... await asyncio.sleep(0)
2092
2093 >>> async def test_main():
2094 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2095 ... await test_coro()
2096
2097 >>> def test_function():
2098 ... loop = asyncio.new_event_loop()
2099 ... loop.run_until_complete(test_main())
2100 ... loop.close()
2101 ... asyncio.set_event_loop_policy(None)
2102 ... print("finished")
2103
2104 >>> with PdbTestInput(['step',
2105 ... 'step',
2106 ... 'step',
2107 ... 'next',
2108 ... 'continue']):
2109 ... test_function()
2110 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(2)test_main()
2111 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2112 (Pdb) step
2113 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
2114 -> await test_coro()
2115 (Pdb) step
2116 --Call--
2117 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
2118 -> async def test_coro():
2119 (Pdb) step
2120 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
2121 -> await asyncio.sleep(0)
2122 (Pdb) next
2123 > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
2124 -> await asyncio.sleep(0)
2125 (Pdb) continue
2126 finished
2127 """
2128
2129 def test_pdb_until_command_for_generator():
2130 """Testing no unwindng stack on yield for generators
2131 for "until" command if target breakpoint is not reached
2132
2133 >>> def test_gen():
2134 ... yield 0
2135 ... yield 1
2136 ... yield 2
2137
2138 >>> def test_function():
2139 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2140 ... for i in test_gen():
2141 ... print(i)
2142 ... print("finished")
2143
2144 >>> with PdbTestInput(['step',
2145 ... 'step',
2146 ... 'until 4',
2147 ... 'step',
2148 ... 'step',
2149 ... 'continue']):
2150 ... test_function()
2151 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(2)test_function()
2152 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2153 (Pdb) step
2154 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
2155 -> for i in test_gen():
2156 (Pdb) step
2157 --Call--
2158 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
2159 -> def test_gen():
2160 (Pdb) until 4
2161 0
2162 1
2163 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
2164 -> yield 2
2165 (Pdb) step
2166 --Return--
2167 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
2168 -> yield 2
2169 (Pdb) step
2170 > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
2171 -> print(i)
2172 (Pdb) continue
2173 2
2174 finished
2175 """
2176
2177 if not SKIP_ASYNCIO_TESTS:
2178 def test_pdb_until_command_for_coroutine():
2179 """Testing no unwindng stack for coroutines
2180 for "until" command if target breakpoint is not reached
2181
2182 >>> import asyncio
2183
2184 >>> async def test_coro():
2185 ... print(0)
2186 ... await asyncio.sleep(0)
2187 ... print(1)
2188 ... await asyncio.sleep(0)
2189 ... print(2)
2190 ... await asyncio.sleep(0)
2191 ... print(3)
2192
2193 >>> async def test_main():
2194 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2195 ... await test_coro()
2196
2197 >>> def test_function():
2198 ... loop = asyncio.new_event_loop()
2199 ... loop.run_until_complete(test_main())
2200 ... loop.close()
2201 ... asyncio.set_event_loop_policy(None)
2202 ... print("finished")
2203
2204 >>> with PdbTestInput(['step',
2205 ... 'step',
2206 ... 'until 8',
2207 ... 'continue']):
2208 ... test_function()
2209 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(2)test_main()
2210 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2211 (Pdb) step
2212 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
2213 -> await test_coro()
2214 (Pdb) step
2215 --Call--
2216 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
2217 -> async def test_coro():
2218 (Pdb) until 8
2219 0
2220 1
2221 2
2222 > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
2223 -> print(3)
2224 (Pdb) continue
2225 3
2226 finished
2227 """
2228
2229 def test_pdb_next_command_in_generator_for_loop():
2230 """The next command on returning from a generator controlled by a for loop.
2231
2232 >>> def test_gen():
2233 ... yield 0
2234 ... return 1
2235
2236 >>> def test_function():
2237 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2238 ... for i in test_gen():
2239 ... print('value', i)
2240 ... x = 123
2241
2242 >>> reset_Breakpoint()
2243 >>> with PdbTestInput(['break test_gen',
2244 ... 'continue',
2245 ... 'next',
2246 ... 'next',
2247 ... 'next',
2248 ... 'continue']):
2249 ... test_function()
2250 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(2)test_function()
2251 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2252 (Pdb) break test_gen
2253 Breakpoint 1 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:2
2254 (Pdb) continue
2255 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
2256 -> yield 0
2257 (Pdb) next
2258 value 0
2259 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
2260 -> return 1
2261 (Pdb) next
2262 Internal StopIteration: 1
2263 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
2264 -> for i in test_gen():
2265 (Pdb) next
2266 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
2267 -> x = 123
2268 (Pdb) continue
2269 """
2270
2271 def test_pdb_next_command_subiterator():
2272 """The next command in a generator with a subiterator.
2273
2274 >>> def test_subgenerator():
2275 ... yield 0
2276 ... return 1
2277
2278 >>> def test_gen():
2279 ... x = yield from test_subgenerator()
2280 ... return x
2281
2282 >>> def test_function():
2283 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2284 ... for i in test_gen():
2285 ... print('value', i)
2286 ... x = 123
2287
2288 >>> with PdbTestInput(['step',
2289 ... 'step',
2290 ... 'step',
2291 ... 'next',
2292 ... 'next',
2293 ... 'next',
2294 ... 'continue']):
2295 ... test_function()
2296 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(2)test_function()
2297 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2298 (Pdb) step
2299 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
2300 -> for i in test_gen():
2301 (Pdb) step
2302 --Call--
2303 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
2304 -> def test_gen():
2305 (Pdb) step
2306 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
2307 -> x = yield from test_subgenerator()
2308 (Pdb) next
2309 value 0
2310 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
2311 -> return x
2312 (Pdb) next
2313 Internal StopIteration: 1
2314 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
2315 -> for i in test_gen():
2316 (Pdb) next
2317 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
2318 -> x = 123
2319 (Pdb) continue
2320 """
2321
2322 def test_pdb_multiline_statement():
2323 """Test for multiline statement
2324
2325 >>> def test_function():
2326 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2327
2328 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2329 ... 'def f(x):',
2330 ... ' return x * 2',
2331 ... '',
2332 ... 'val = 2',
2333 ... 'if val > 0:',
2334 ... ' val = f(val)',
2335 ... '',
2336 ... '', # empty line should repeat the multi-line statement
2337 ... 'val',
2338 ... 'c'
2339 ... ]):
2340 ... test_function()
2341 > <doctest test.test_pdb.test_pdb_multiline_statement[0]>(2)test_function()
2342 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2343 (Pdb) def f(x):
2344 ... return x * 2
2345 ...
2346 (Pdb) val = 2
2347 (Pdb) if val > 0:
2348 ... val = f(val)
2349 ...
2350 (Pdb)
2351 (Pdb) val
2352 8
2353 (Pdb) c
2354 """
2355
2356 def test_pdb_closure():
2357 """Test for all expressions/statements that involve closure
2358
2359 >>> k = 0
2360 >>> g = 1
2361 >>> def test_function():
2362 ... x = 2
2363 ... g = 3
2364 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2365
2366 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2367 ... 'k',
2368 ... 'g',
2369 ... 'y = y',
2370 ... 'global g; g',
2371 ... 'global g; (lambda: g)()',
2372 ... '(lambda: x)()',
2373 ... '(lambda: g)()',
2374 ... 'lst = [n for n in range(10) if (n % x) == 0]',
2375 ... 'lst',
2376 ... 'sum(n for n in lst if n > x)',
2377 ... 'x = 1; raise Exception()',
2378 ... 'x',
2379 ... 'def f():',
2380 ... ' return x',
2381 ... '',
2382 ... 'f()',
2383 ... 'c'
2384 ... ]):
2385 ... test_function()
2386 > <doctest test.test_pdb.test_pdb_closure[2]>(4)test_function()
2387 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2388 (Pdb) k
2389 0
2390 (Pdb) g
2391 3
2392 (Pdb) y = y
2393 *** NameError: name 'y' is not defined
2394 (Pdb) global g; g
2395 1
2396 (Pdb) global g; (lambda: g)()
2397 1
2398 (Pdb) (lambda: x)()
2399 2
2400 (Pdb) (lambda: g)()
2401 3
2402 (Pdb) lst = [n for n in range(10) if (n % x) == 0]
2403 (Pdb) lst
2404 [0, 2, 4, 6, 8]
2405 (Pdb) sum(n for n in lst if n > x)
2406 18
2407 (Pdb) x = 1; raise Exception()
2408 *** Exception
2409 (Pdb) x
2410 1
2411 (Pdb) def f():
2412 ... return x
2413 ...
2414 (Pdb) f()
2415 1
2416 (Pdb) c
2417 """
2418
2419 def test_pdb_show_attribute_and_item():
2420 """Test for expressions with command prefix
2421
2422 >>> def test_function():
2423 ... n = lambda x: x
2424 ... c = {"a": 1}
2425 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2426
2427 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2428 ... 'c["a"]',
2429 ... 'c.get("a")',
2430 ... 'n(1)',
2431 ... 'j=1',
2432 ... 'j+1',
2433 ... 'r"a"',
2434 ... 'next(iter([1]))',
2435 ... 'list((0, 1))',
2436 ... 'c'
2437 ... ]):
2438 ... test_function()
2439 > <doctest test.test_pdb.test_pdb_show_attribute_and_item[0]>(4)test_function()
2440 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2441 (Pdb) c["a"]
2442 1
2443 (Pdb) c.get("a")
2444 1
2445 (Pdb) n(1)
2446 1
2447 (Pdb) j=1
2448 (Pdb) j+1
2449 2
2450 (Pdb) r"a"
2451 'a'
2452 (Pdb) next(iter([1]))
2453 1
2454 (Pdb) list((0, 1))
2455 [0, 1]
2456 (Pdb) c
2457 """
2458
2459 def test_pdb_issue_20766():
2460 """Test for reference leaks when the SIGINT handler is set.
2461
2462 >>> def test_function():
2463 ... i = 1
2464 ... while i <= 2:
2465 ... sess = pdb.Pdb()
2466 ... sess.set_trace(sys._getframe())
2467 ... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
2468 ... i += 1
2469
2470 >>> reset_Breakpoint()
2471 >>> with PdbTestInput(['continue',
2472 ... 'continue']):
2473 ... test_function()
2474 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
2475 -> sess.set_trace(sys._getframe())
2476 (Pdb) continue
2477 pdb 1: <built-in function default_int_handler>
2478 > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
2479 -> sess.set_trace(sys._getframe())
2480 (Pdb) continue
2481 pdb 2: <built-in function default_int_handler>
2482 """
2483
2484 def test_pdb_issue_43318():
2485 """echo breakpoints cleared with filename:lineno
2486
2487 >>> def test_function():
2488 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2489 ... print(1)
2490 ... print(2)
2491 ... print(3)
2492 ... print(4)
2493 >>> reset_Breakpoint()
2494 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2495 ... 'break 3',
2496 ... 'clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3',
2497 ... 'continue'
2498 ... ]):
2499 ... test_function()
2500 > <doctest test.test_pdb.test_pdb_issue_43318[0]>(2)test_function()
2501 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2502 (Pdb) break 3
2503 Breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
2504 (Pdb) clear <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
2505 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_issue_43318[0]>:3
2506 (Pdb) continue
2507 1
2508 2
2509 3
2510 4
2511 """
2512
2513 def test_pdb_issue_gh_91742():
2514 """See GH-91742
2515
2516 >>> def test_function():
2517 ... __author__ = "pi"
2518 ... __version__ = "3.14"
2519 ...
2520 ... def about():
2521 ... '''About'''
2522 ... print(f"Author: {__author__!r}",
2523 ... f"Version: {__version__!r}",
2524 ... sep=" ")
2525 ...
2526 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2527 ... about()
2528
2529
2530 >>> reset_Breakpoint()
2531 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2532 ... 'step',
2533 ... 'step',
2534 ... 'next',
2535 ... 'next',
2536 ... 'jump 5',
2537 ... 'continue'
2538 ... ]):
2539 ... test_function()
2540 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(11)test_function()
2541 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2542 (Pdb) step
2543 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(12)test_function()
2544 -> about()
2545 (Pdb) step
2546 --Call--
2547 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(5)about()
2548 -> def about():
2549 (Pdb) next
2550 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(7)about()
2551 -> print(f"Author: {__author__!r}",
2552 (Pdb) next
2553 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(8)about()
2554 -> f"Version: {__version__!r}",
2555 (Pdb) jump 5
2556 > <doctest test.test_pdb.test_pdb_issue_gh_91742[0]>(5)about()
2557 -> def about():
2558 (Pdb) continue
2559 Author: 'pi' Version: '3.14'
2560 """
2561
2562 def test_pdb_issue_gh_94215():
2563 """See GH-94215
2564
2565 Check that frame_setlineno() does not leak references.
2566
2567 >>> def test_function():
2568 ... def func():
2569 ... def inner(v): pass
2570 ... inner(
2571 ... 42
2572 ... )
2573 ...
2574 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2575 ... func()
2576
2577 >>> reset_Breakpoint()
2578 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2579 ... 'step',
2580 ... 'step',
2581 ... 'next',
2582 ... 'next',
2583 ... 'jump 3',
2584 ... 'next',
2585 ... 'next',
2586 ... 'jump 3',
2587 ... 'next',
2588 ... 'next',
2589 ... 'jump 3',
2590 ... 'continue'
2591 ... ]):
2592 ... test_function()
2593 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(8)test_function()
2594 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2595 (Pdb) step
2596 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(9)test_function()
2597 -> func()
2598 (Pdb) step
2599 --Call--
2600 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(2)func()
2601 -> def func():
2602 (Pdb) next
2603 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
2604 -> def inner(v): pass
2605 (Pdb) next
2606 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
2607 -> inner(
2608 (Pdb) jump 3
2609 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
2610 -> def inner(v): pass
2611 (Pdb) next
2612 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
2613 -> inner(
2614 (Pdb) next
2615 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(5)func()
2616 -> 42
2617 (Pdb) jump 3
2618 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
2619 -> def inner(v): pass
2620 (Pdb) next
2621 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(4)func()
2622 -> inner(
2623 (Pdb) next
2624 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(5)func()
2625 -> 42
2626 (Pdb) jump 3
2627 > <doctest test.test_pdb.test_pdb_issue_gh_94215[0]>(3)func()
2628 -> def inner(v): pass
2629 (Pdb) continue
2630 """
2631
2632 def test_pdb_issue_gh_101673():
2633 """See GH-101673
2634
2635 Make sure ll won't revert local variable assignment
2636
2637 >>> def test_function():
2638 ... a = 1
2639 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2640
2641 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2642 ... '!a = 2',
2643 ... 'll',
2644 ... 'p a',
2645 ... 'continue'
2646 ... ]):
2647 ... test_function()
2648 > <doctest test.test_pdb.test_pdb_issue_gh_101673[0]>(3)test_function()
2649 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2650 (Pdb) !a = 2
2651 (Pdb) ll
2652 1 def test_function():
2653 2 a = 1
2654 3 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2655 (Pdb) p a
2656 2
2657 (Pdb) continue
2658 """
2659
2660 def test_pdb_issue_gh_103225():
2661 """See GH-103225
2662
2663 Make sure longlist uses 1-based line numbers in frames that correspond to a module
2664
2665 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2666 ... 'longlist',
2667 ... 'continue'
2668 ... ]):
2669 ... a = 1
2670 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2671 ... b = 2
2672 > <doctest test.test_pdb.test_pdb_issue_gh_103225[0]>(6)<module>()
2673 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2674 (Pdb) longlist
2675 1 with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2676 2 'longlist',
2677 3 'continue'
2678 4 ]):
2679 5 a = 1
2680 6 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2681 7 b = 2
2682 (Pdb) continue
2683 """
2684
2685 def test_pdb_issue_gh_101517():
2686 """See GH-101517
2687
2688 Make sure pdb doesn't crash when the exception is caught in a try/except* block
2689
2690 >>> def test_function():
2691 ... try:
2692 ... raise KeyError
2693 ... except* Exception as e:
2694 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2695
2696 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2697 ... 'continue'
2698 ... ]):
2699 ... test_function()
2700 > <doctest test.test_pdb.test_pdb_issue_gh_101517[0]>(5)test_function()
2701 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2702 (Pdb) continue
2703 """
2704
2705 def test_pdb_issue_gh_108976():
2706 """See GH-108976
2707 Make sure setting f_trace_opcodes = True won't crash pdb
2708 >>> def test_function():
2709 ... import sys
2710 ... sys._getframe().f_trace_opcodes = True
2711 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2712 ... a = 1
2713 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2714 ... 'continue'
2715 ... ]):
2716 ... test_function()
2717 > <doctest test.test_pdb.test_pdb_issue_gh_108976[0]>(4)test_function()
2718 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2719 (Pdb) continue
2720 """
2721
2722 def test_pdb_issue_gh_127321():
2723 """See GH-127321
2724 breakpoint() should stop at a opcode that has a line number
2725 >>> def test_function():
2726 ... import pdb; pdb_instance = pdb.Pdb(nosigint=True, readrc=False)
2727 ... [1, 2] and pdb_instance.set_trace()
2728 ... a = 1
2729 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2730 ... 'continue'
2731 ... ]):
2732 ... test_function()
2733 > <doctest test.test_pdb.test_pdb_issue_gh_127321[0]>(4)test_function()
2734 -> a = 1
2735 (Pdb) continue
2736 """
2737
2738
2739 def test_pdb_issue_gh_136057():
2740 """See GH-136057
2741 "step" and "next" commands should be able to get over list comprehensions
2742 >>> def test_function():
2743 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2744 ... lst = [i for i in range(10)]
2745 ... for i in lst: pass
2746
2747 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2748 ... 'next',
2749 ... 'next',
2750 ... 'step',
2751 ... 'continue',
2752 ... ]):
2753 ... test_function()
2754 > <doctest test.test_pdb.test_pdb_issue_gh_136057[0]>(2)test_function()
2755 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2756 (Pdb) next
2757 > <doctest test.test_pdb.test_pdb_issue_gh_136057[0]>(3)test_function()
2758 -> lst = [i for i in range(10)]
2759 (Pdb) next
2760 > <doctest test.test_pdb.test_pdb_issue_gh_136057[0]>(4)test_function()
2761 -> for i in lst: pass
2762 (Pdb) step
2763 --Return--
2764 > <doctest test.test_pdb.test_pdb_issue_gh_136057[0]>(4)test_function()->None
2765 -> for i in lst: pass
2766 (Pdb) continue
2767 """
2768
2769
2770 def test_pdb_issue_gh_80731():
2771 """See GH-80731
2772
2773 pdb should correctly print exception info if in an except block.
2774
2775 >>> with PdbTestInput([ # doctest: +ELLIPSIS
2776 ... 'import sys',
2777 ... 'sys.exc_info()',
2778 ... 'continue'
2779 ... ]):
2780 ... try:
2781 ... raise ValueError('Correct')
2782 ... except ValueError:
2783 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2784 > <doctest test.test_pdb.test_pdb_issue_gh_80731[0]>(9)<module>()
2785 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2786 (Pdb) import sys
2787 (Pdb) sys.exc_info()
2788 (<class 'ValueError'>, ValueError('Correct'), <traceback object at ...>)
2789 (Pdb) continue
2790 """
2791
2792
2793 def test_pdb_ambiguous_statements():
2794 """See GH-104301
2795
2796 Make sure that ambiguous statements prefixed by '!' are properly disambiguated
2797
2798 >>> with PdbTestInput([
2799 ... 's', # step to the print line
2800 ... '! n = 42', # disambiguated statement: reassign the name n
2801 ... 'n', # advance the debugger into the print()
2802 ... 'continue'
2803 ... ]):
2804 ... n = -1
2805 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2806 ... print(f"The value of n is {n}")
2807 > <doctest test.test_pdb.test_pdb_ambiguous_statements[0]>(8)<module>()
2808 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2809 (Pdb) s
2810 > <doctest test.test_pdb.test_pdb_ambiguous_statements[0]>(9)<module>()
2811 -> print(f"The value of n is {n}")
2812 (Pdb) ! n = 42
2813 (Pdb) n
2814 The value of n is 42
2815 > <doctest test.test_pdb.test_pdb_ambiguous_statements[0]>(1)<module>()
2816 -> with PdbTestInput([
2817 (Pdb) continue
2818 """
2819
2820 def test_pdb_f_trace_lines():
2821 """GH-80675
2822
2823 pdb should work even if f_trace_lines is set to False on some frames.
2824
2825 >>> reset_Breakpoint()
2826
2827 >>> def test_function():
2828 ... import sys
2829 ... frame = sys._getframe()
2830 ... frame.f_trace_lines = False
2831 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2832 ... if frame.f_trace_lines != False:
2833 ... print("f_trace_lines is not reset after continue!")
2834
2835 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2836 ... 'continue'
2837 ... ]):
2838 ... test_function()
2839 > <doctest test.test_pdb.test_pdb_f_trace_lines[1]>(5)test_function()
2840 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2841 (Pdb) continue
2842 """
2843
2844 def test_pdb_frame_refleak():
2845 """
2846 pdb should not leak reference to frames
2847
2848 >>> def frame_leaker(container):
2849 ... import sys
2850 ... container.append(sys._getframe())
2851 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2852 ... pass
2853
2854 >>> def test_function():
2855 ... import gc
2856 ... container = []
2857 ... frame_leaker(container) # c
2858 ... print(len(gc.get_referrers(container[0])))
2859 ... container = []
2860 ... frame_leaker(container) # n c
2861 ... print(len(gc.get_referrers(container[0])))
2862 ... container = []
2863 ... frame_leaker(container) # r c
2864 ... print(len(gc.get_referrers(container[0])))
2865
2866 >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2867 ... 'continue',
2868 ... 'next',
2869 ... 'continue',
2870 ... 'return',
2871 ... 'continue',
2872 ... ]):
2873 ... test_function()
2874 > <doctest test.test_pdb.test_pdb_frame_refleak[0]>(4)frame_leaker()
2875 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2876 (Pdb) continue
2877 1
2878 > <doctest test.test_pdb.test_pdb_frame_refleak[0]>(4)frame_leaker()
2879 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2880 (Pdb) next
2881 > <doctest test.test_pdb.test_pdb_frame_refleak[0]>(5)frame_leaker()
2882 -> pass
2883 (Pdb) continue
2884 1
2885 > <doctest test.test_pdb.test_pdb_frame_refleak[0]>(4)frame_leaker()
2886 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2887 (Pdb) return
2888 --Return--
2889 > <doctest test.test_pdb.test_pdb_frame_refleak[0]>(5)frame_leaker()->None
2890 -> pass
2891 (Pdb) continue
2892 1
2893 """
2894
2895 def test_pdb_function_break():
2896 """Testing the line number of break on function
2897
2898 >>> def foo(): pass
2899
2900 >>> def bar():
2901 ...
2902 ... pass
2903
2904 >>> def boo():
2905 ... # comments
2906 ... global x
2907 ... x = 1
2908
2909 >>> def gen():
2910 ... yield 42
2911
2912 >>> def test_function():
2913 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2914
2915 >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
2916 ... 'break foo',
2917 ... 'break bar',
2918 ... 'break boo',
2919 ... 'break gen',
2920 ... 'continue'
2921 ... ]):
2922 ... test_function()
2923 > <doctest test.test_pdb.test_pdb_function_break[4]>(2)test_function()
2924 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2925 (Pdb) break foo
2926 Breakpoint ... at <doctest test.test_pdb.test_pdb_function_break[0]>:1
2927 (Pdb) break bar
2928 Breakpoint ... at <doctest test.test_pdb.test_pdb_function_break[1]>:3
2929 (Pdb) break boo
2930 Breakpoint ... at <doctest test.test_pdb.test_pdb_function_break[2]>:4
2931 (Pdb) break gen
2932 Breakpoint ... at <doctest test.test_pdb.test_pdb_function_break[3]>:2
2933 (Pdb) continue
2934 """
2935
2936 def test_pdb_issue_gh_65052():
2937 """See GH-65052
2938
2939 args, retval and display should not crash if the object is not displayable
2940 >>> class A:
2941 ... def __new__(cls):
2942 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2943 ... return object.__new__(cls)
2944 ... def __init__(self):
2945 ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2946 ... self.a = 1
2947 ... def __repr__(self):
2948 ... return self.a
2949
2950 >>> def test_function():
2951 ... A()
2952 >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
2953 ... 's',
2954 ... 's',
2955 ... 'retval',
2956 ... 'continue',
2957 ... 'args',
2958 ... 'display self',
2959 ... 'display',
2960 ... 'continue',
2961 ... ]):
2962 ... test_function()
2963 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(3)__new__()
2964 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2965 (Pdb) s
2966 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(4)__new__()
2967 -> return object.__new__(cls)
2968 (Pdb) s
2969 --Return--
2970 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(4)__new__()-><A instance at ...>
2971 -> return object.__new__(cls)
2972 (Pdb) retval
2973 *** repr(retval) failed: AttributeError: 'A' object has no attribute 'a' ***
2974 (Pdb) continue
2975 > <doctest test.test_pdb.test_pdb_issue_gh_65052[0]>(6)__init__()
2976 -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
2977 (Pdb) args
2978 self = *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
2979 (Pdb) display self
2980 display self: *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
2981 (Pdb) display
2982 Currently displaying:
2983 self: *** repr(self) failed: AttributeError: 'A' object has no attribute 'a' ***
2984 (Pdb) continue
2985 """
2986
2987
2988 @support.requires_subprocess()
2989 class PdbTestCase(unittest.TestCase):
2990 def tearDown(self):
2991 os_helper.unlink(os_helper.TESTFN)
2992
2993 @unittest.skipIf(sys.flags.safe_path,
2994 'PYTHONSAFEPATH changes default sys.path')
2995 def _run_pdb(self, pdb_args, commands,
2996 expected_returncode=0,
2997 extra_env=None):
2998 self.addCleanup(os_helper.rmtree, '__pycache__')
2999 cmd = [sys.executable, '-m', 'pdb'] + pdb_args
3000 if extra_env is not None:
3001 env = os.environ | extra_env
3002 else:
3003 env = os.environ
3004 with subprocess.Popen(
3005 cmd,
3006 stdout=subprocess.PIPE,
3007 stdin=subprocess.PIPE,
3008 stderr=subprocess.PIPE,
3009 env = {**env, 'PYTHONIOENCODING': 'utf-8'}
3010 ) as proc:
3011 stdout, stderr = proc.communicate(str.encode(commands))
3012 stdout = bytes.decode(stdout) if isinstance(stdout, bytes) else stdout
3013 stderr = bytes.decode(stderr) if isinstance(stderr, bytes) else stderr
3014 self.assertEqual(
3015 proc.returncode,
3016 expected_returncode,
3017 f"Unexpected return code\nstdout: {stdout}\nstderr: {stderr}"
3018 )
3019 return stdout, stderr
3020
3021 def run_pdb_script(self, script, commands,
3022 expected_returncode=0,
3023 extra_env=None,
3024 script_args=None,
3025 pdbrc=None,
3026 remove_home=False):
3027 """Run 'script' lines with pdb and the pdb 'commands'."""
3028 filename = 'main.py'
3029 with open(filename, 'w') as f:
3030 f.write(textwrap.dedent(script))
3031
3032 if pdbrc is not None:
3033 with open('.pdbrc', 'w') as f:
3034 f.write(textwrap.dedent(pdbrc))
3035 self.addCleanup(os_helper.unlink, '.pdbrc')
3036 self.addCleanup(os_helper.unlink, filename)
3037
3038 homesave = None
3039 if remove_home:
3040 homesave = os.environ.pop('HOME', None)
3041 try:
3042 if script_args is None:
3043 script_args = []
3044 stdout, stderr = self._run_pdb([filename] + script_args, commands, expected_returncode, extra_env)
3045 finally:
3046 if homesave is not None:
3047 os.environ['HOME'] = homesave
3048 return stdout, stderr
3049
3050 def run_pdb_module(self, script, commands):
3051 """Runs the script code as part of a module"""
3052 self.module_name = 't_main'
3053 os_helper.rmtree(self.module_name)
3054 main_file = self.module_name + '/__main__.py'
3055 init_file = self.module_name + '/__init__.py'
3056 os.mkdir(self.module_name)
3057 with open(init_file, 'w') as f:
3058 pass
3059 with open(main_file, 'w') as f:
3060 f.write(textwrap.dedent(script))
3061 self.addCleanup(os_helper.rmtree, self.module_name)
3062 return self._run_pdb(['-m', self.module_name], commands)
3063
3064 def _assert_find_function(self, file_content, func_name, expected):
3065 with open(os_helper.TESTFN, 'wb') as f:
3066 f.write(file_content)
3067
3068 expected = None if not expected else (
3069 expected[0], os_helper.TESTFN, expected[1])
3070 self.assertEqual(
3071 expected, pdb.find_function(func_name, os_helper.TESTFN))
3072
3073 def _fd_dir_for_pipe_targets(self):
3074 """Return a directory exposing live file descriptors, if any."""
3075 return self._proc_fd_dir() or self._dev_fd_dir()
3076
3077 def _proc_fd_dir(self):
3078 """Return /proc-backed fd dir when it can be used for pipes."""
3079 # GH-142836: Opening /proc/self/fd entries for pipes raises EACCES on
3080 # Solaris, so prefer other mechanisms there.
3081 if sys.platform.startswith("sunos"):
3082 return None
3083
3084 proc_fd = "/proc/self/fd"
3085 if os.path.isdir(proc_fd) and os.path.exists(os.path.join(proc_fd, '0')):
3086 return proc_fd
3087 return None
3088
3089 def _dev_fd_dir(self):
3090 """Return /dev-backed fd dir when usable."""
3091 dev_fd = "/dev/fd"
3092 if os.path.isdir(dev_fd) and os.path.exists(os.path.join(dev_fd, '0')):
3093 if sys.platform.startswith("freebsd"):
3094 try:
3095 if os.stat("/dev").st_dev == os.stat(dev_fd).st_dev:
3096 return None
3097 except FileNotFoundError:
3098 return None
3099 return dev_fd
3100 return None
3101
3102 def test_find_function_empty_file(self):
3103 self._assert_find_function(b'', 'foo', None)
3104
3105 def test_find_function_found(self):
3106 self._assert_find_function(
3107 """\
3108 def foo():
3109 pass
3110
3111 def bœr():
3112 pass
3113
3114 def quux():
3115 pass
3116 """.encode(),
3117 'bœr',
3118 ('bœr', 5),
3119 )
3120
3121 def test_find_function_found_with_encoding_cookie(self):
3122 self._assert_find_function(
3123 """\
3124 # coding: iso-8859-15
3125 def foo():
3126 pass
3127
3128 def bœr():
3129 pass
3130
3131 def quux():
3132 pass
3133 """.encode('iso-8859-15'),
3134 'bœr',
3135 ('bœr', 6),
3136 )
3137
3138 def test_find_function_found_with_bom(self):
3139 self._assert_find_function(
3140 codecs.BOM_UTF8 + """\
3141 def bœr():
3142 pass
3143 """.encode(),
3144 'bœr',
3145 ('bœr', 2),
3146 )
3147
3148 def test_spec(self):
3149 # Test that __main__.__spec__ is set to None when running a script
3150 script = """
3151 import __main__
3152 print(__main__.__spec__)
3153 """
3154
3155 commands = "continue"
3156
3157 stdout, _ = self.run_pdb_script(script, commands)
3158 self.assertIn('None', stdout)
3159
3160 def test_script_target_anonymous_pipe(self):
3161 """
3162 _ScriptTarget doesn't fail on an anonymous pipe.
3163
3164 GH-142315
3165 """
3166 fd_dir = self._fd_dir_for_pipe_targets()
3167 if fd_dir is None:
3168 self.skipTest('anonymous pipe targets require /proc/self/fd or /dev/fd')
3169
3170 read_fd, write_fd = os.pipe()
3171
3172 def safe_close(fd):
3173 try:
3174 os.close(fd)
3175 except OSError:
3176 pass
3177
3178 self.addCleanup(safe_close, read_fd)
3179 self.addCleanup(safe_close, write_fd)
3180
3181 pipe_path = os.path.join(fd_dir, str(read_fd))
3182 if not os.path.exists(pipe_path):
3183 self.skipTest('fd directory does not expose anonymous pipes')
3184
3185 script_source = 'marker = "via_pipe"\n'
3186 os.write(write_fd, script_source.encode('utf-8'))
3187 os.close(write_fd)
3188
3189 original_path0 = sys.path[0]
3190 self.addCleanup(sys.path.__setitem__, 0, original_path0)
3191
3192 target = pdb._ScriptTarget(pipe_path)
3193 code_text = target.code
3194 namespace = target.namespace
3195 exec(code_text, namespace)
3196
3197 self.assertEqual(namespace['marker'], 'via_pipe')
3198 self.assertEqual(namespace['__file__'], target.filename)
3199 self.assertIsNone(namespace['__spec__'])
3200
3201 def test_find_function_first_executable_line(self):
3202 code = textwrap.dedent("""\
3203 def foo(): pass
3204
3205 def bar():
3206 pass # line 4
3207
3208 def baz():
3209 # comment
3210 pass # line 8
3211
3212 def mul():
3213 # code on multiple lines
3214 code = compile( # line 12
3215 'def f()',
3216 '<string>',
3217 'exec',
3218 )
3219 """).encode()
3220
3221 self._assert_find_function(code, 'foo', ('foo', 1))
3222 self._assert_find_function(code, 'bar', ('bar', 4))
3223 self._assert_find_function(code, 'baz', ('baz', 8))
3224 self._assert_find_function(code, 'mul', ('mul', 12))
3225
3226 def test_issue7964(self):
3227 # open the file as binary so we can force \r\n newline
3228 with open(os_helper.TESTFN, 'wb') as f:
3229 f.write(b'print("testing my pdb")\r\n')
3230 cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
3231 proc = subprocess.Popen(cmd,
3232 stdout=subprocess.PIPE,
3233 stdin=subprocess.PIPE,
3234 stderr=subprocess.PIPE,
3235 )
3236 self.addCleanup(proc.stdout.close)
3237 stdout, stderr = proc.communicate(b'quit\n')
3238 self.assertNotIn(b'SyntaxError', stdout,
3239 "Got a syntax error running test script under PDB")
3240
3241 def test_issue46434(self):
3242 # Temporarily patch in an extra help command which doesn't have a
3243 # docstring to emulate what happens in an embeddable distribution
3244 script = """
3245 def do_testcmdwithnodocs(self, arg):
3246 pass
3247
3248 import pdb
3249 pdb.Pdb.do_testcmdwithnodocs = do_testcmdwithnodocs
3250 """
3251 commands = """
3252 continue
3253 help testcmdwithnodocs
3254 """
3255 stdout, stderr = self.run_pdb_script(script, commands)
3256 output = (stdout or '') + (stderr or '')
3257 self.assertNotIn('AttributeError', output,
3258 'Calling help on a command with no docs should be handled gracefully')
3259 self.assertIn("*** No help for 'testcmdwithnodocs'; __doc__ string missing", output,
3260 'Calling help on a command with no docs should print an error')
3261
3262 def test_issue13183(self):
3263 script = """
3264 from bar import bar
3265
3266 def foo():
3267 bar()
3268
3269 def nope():
3270 pass
3271
3272 def foobar():
3273 foo()
3274 nope()
3275
3276 foobar()
3277 """
3278 commands = """
3279 from bar import bar
3280 break bar
3281 continue
3282 step
3283 step
3284 quit
3285 """
3286 bar = """
3287 def bar():
3288 pass
3289 """
3290 with open('bar.py', 'w') as f:
3291 f.write(textwrap.dedent(bar))
3292 self.addCleanup(os_helper.unlink, 'bar.py')
3293 stdout, stderr = self.run_pdb_script(script, commands)
3294 self.assertTrue(
3295 any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
3296 'Fail to step into the caller after a return')
3297
3298 def test_issue13120(self):
3299 # Invoking "continue" on a non-main thread triggered an exception
3300 # inside signal.signal.
3301
3302 with open(os_helper.TESTFN, 'wb') as f:
3303 f.write(textwrap.dedent("""
3304 import threading
3305 import pdb
3306
3307 def start_pdb():
3308 pdb.Pdb(readrc=False).set_trace()
3309 x = 1
3310 y = 1
3311
3312 t = threading.Thread(target=start_pdb)
3313 t.start()""").encode('ascii'))
3314 cmd = [sys.executable, '-u', os_helper.TESTFN]
3315 proc = subprocess.Popen(cmd,
3316 stdout=subprocess.PIPE,
3317 stdin=subprocess.PIPE,
3318 stderr=subprocess.PIPE,
3319 env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
3320 )
3321 self.addCleanup(proc.stdout.close)
3322 stdout, stderr = proc.communicate(b'cont\n')
3323 self.assertNotIn(b'Error', stdout,
3324 "Got an error running test script under PDB")
3325
3326 def test_issue36250(self):
3327
3328 with open(os_helper.TESTFN, 'wb') as f:
3329 f.write(textwrap.dedent("""
3330 import threading
3331 import pdb
3332
3333 evt = threading.Event()
3334
3335 def start_pdb():
3336 evt.wait()
3337 pdb.Pdb(readrc=False).set_trace()
3338
3339 t = threading.Thread(target=start_pdb)
3340 t.start()
3341 pdb.Pdb(readrc=False).set_trace()
3342 evt.set()
3343 t.join()""").encode('ascii'))
3344 cmd = [sys.executable, '-u', os_helper.TESTFN]
3345 proc = subprocess.Popen(cmd,
3346 stdout=subprocess.PIPE,
3347 stdin=subprocess.PIPE,
3348 stderr=subprocess.PIPE,
3349 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
3350 )
3351 self.addCleanup(proc.stdout.close)
3352 stdout, stderr = proc.communicate(b'cont\ncont\n')
3353 self.assertNotIn(b'Error', stdout,
3354 "Got an error running test script under PDB")
3355
3356 @force_not_colorized
3357 def test_issue16180(self):
3358 # A syntax error in the debuggee.
3359 script = "def f: pass\n"
3360 commands = ''
3361 expected = "SyntaxError:"
3362 stdout, stderr = self.run_pdb_script(
3363 script, commands
3364 )
3365 self.assertIn(expected, stderr,
3366 '\n\nExpected:\n{}\nGot:\n{}\n'
3367 'Fail to handle a syntax error in the debuggee.'
3368 .format(expected, stderr))
3369
3370 @force_not_colorized
3371 def test_issue84583(self):
3372 # A syntax error from ast.literal_eval should not make pdb exit.
3373 script = "import ast; ast.literal_eval('')\n"
3374 commands = """
3375 continue
3376 where
3377 quit
3378 """
3379 stdout, stderr = self.run_pdb_script(script, commands)
3380 # The code should appear 3 times in the stdout/stderr:
3381 # 1. when pdb starts (stdout)
3382 # 2. when the exception is raised, in trackback (stderr)
3383 # 3. in where command (stdout)
3384 self.assertEqual(stdout.count("ast.literal_eval('')"), 2)
3385 self.assertEqual(stderr.count("ast.literal_eval('')"), 1)
3386
3387 def test_issue26053(self):
3388 # run command of pdb prompt echoes the correct args
3389 script = "print('hello')"
3390 commands = """
3391 continue
3392 run a b c
3393 run d e f
3394 quit
3395 """
3396 stdout, stderr = self.run_pdb_script(script, commands)
3397 res = '\n'.join([x.strip() for x in stdout.splitlines()])
3398 self.assertRegex(res, "Restarting .* with arguments:\na b c")
3399 self.assertRegex(res, "Restarting .* with arguments:\nd e f")
3400
3401 def test_issue58956(self):
3402 # Set a breakpoint in a function that already exists on the call stack
3403 # should enable the trace function for the frame.
3404 script = """
3405 import bar
3406 def foo():
3407 ret = bar.bar()
3408 pass
3409 foo()
3410 """
3411 commands = """
3412 b bar.bar
3413 c
3414 b main.py:5
3415 c
3416 p ret
3417 quit
3418 """
3419 bar = """
3420 def bar():
3421 return 42
3422 """
3423 with open('bar.py', 'w') as f:
3424 f.write(textwrap.dedent(bar))
3425 self.addCleanup(os_helper.unlink, 'bar.py')
3426 stdout, stderr = self.run_pdb_script(script, commands)
3427 lines = stdout.splitlines()
3428 self.assertIn('-> pass', lines)
3429 self.assertIn('(Pdb) 42', lines)
3430
3431 def test_step_into_botframe(self):
3432 # gh-125422
3433 # pdb should not be able to step into the botframe (bdb.py)
3434 script = "x = 1"
3435 commands = """
3436 step
3437 step
3438 step
3439 quit
3440 """
3441 stdout, _ = self.run_pdb_script(script, commands)
3442 self.assertIn("The program finished", stdout)
3443 self.assertNotIn("bdb.py", stdout)
3444
3445 def test_pdbrc_basic(self):
3446 script = textwrap.dedent("""
3447 a = 1
3448 b = 2
3449 """)
3450
3451 pdbrc = textwrap.dedent("""
3452 # Comments should be fine
3453 n
3454 p f"{a+8=}"
3455 """)
3456
3457 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
3458 self.assertNotIn("SyntaxError", stdout)
3459 self.assertIn("a+8=9", stdout)
3460
3461 def test_pdbrc_empty_line(self):
3462 """Test that empty lines in .pdbrc are ignored."""
3463
3464 script = textwrap.dedent("""
3465 a = 1
3466 b = 2
3467 c = 3
3468 """)
3469
3470 pdbrc = textwrap.dedent("""
3471 n
3472
3473 """)
3474
3475 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
3476 self.assertIn("b = 2", stdout)
3477 self.assertNotIn("c = 3", stdout)
3478
3479 def test_pdbrc_alias(self):
3480 script = textwrap.dedent("""
3481 class A:
3482 def __init__(self):
3483 self.attr = 1
3484 a = A()
3485 b = 2
3486 """)
3487
3488 pdbrc = textwrap.dedent("""
3489 alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
3490 until 6
3491 pi a
3492 """)
3493
3494 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
3495 self.assertIn("a.attr = 1", stdout)
3496
3497 def test_pdbrc_semicolon(self):
3498 script = textwrap.dedent("""
3499 class A:
3500 def __init__(self):
3501 self.attr = 1
3502 a = A()
3503 b = 2
3504 """)
3505
3506 pdbrc = textwrap.dedent("""
3507 b 5;;c;;n
3508 """)
3509
3510 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
3511 self.assertIn("-> b = 2", stdout)
3512
3513 def test_pdbrc_commands(self):
3514 script = textwrap.dedent("""
3515 class A:
3516 def __init__(self):
3517 self.attr = 1
3518 a = A()
3519 b = 2
3520 """)
3521
3522 pdbrc = textwrap.dedent("""
3523 b 6
3524 commands 1 ;; p a;; end
3525 c
3526 """)
3527
3528 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc=pdbrc, remove_home=True)
3529 self.assertIn("<__main__.A object at", stdout)
3530
3531 def test_readrc_kwarg(self):
3532 script = textwrap.dedent("""
3533 print('hello')
3534 """)
3535
3536 stdout, stderr = self.run_pdb_script(script, 'q\n', pdbrc='invalid', remove_home=True)
3537 self.assertIn("NameError: name 'invalid' is not defined", stdout)
3538
3539 def test_readrc_homedir(self):
3540 save_home = os.environ.pop("HOME", None)
3541 with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
3542 rc_path = os.path.join(temp_dir, ".pdbrc")
3543 os.path.expanduser.return_value = rc_path
3544 try:
3545 with open(rc_path, "w") as f:
3546 f.write("invalid")
3547 self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
3548 finally:
3549 if save_home is not None:
3550 os.environ["HOME"] = save_home
3551
3552 def test_header(self):
3553 stdout = StringIO()
3554 header = 'Nobody expects... blah, blah, blah'
3555 with ExitStack() as resources:
3556 resources.enter_context(patch('sys.stdout', stdout))
3557 resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
3558 pdb.set_trace(header=header)
3559 self.assertEqual(stdout.getvalue(), header + '\n')
3560
3561 def test_run_module(self):
3562 script = """print("SUCCESS")"""
3563 commands = """
3564 continue
3565 quit
3566 """
3567 stdout, stderr = self.run_pdb_module(script, commands)
3568 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
3569
3570 def test_module_is_run_as_main(self):
3571 script = """
3572 if __name__ == '__main__':
3573 print("SUCCESS")
3574 """
3575 commands = """
3576 continue
3577 quit
3578 """
3579 stdout, stderr = self.run_pdb_module(script, commands)
3580 self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
3581
3582 def test_run_module_with_args(self):
3583 commands = """
3584 continue
3585 """
3586 self._run_pdb(["calendar", "-m"], commands, expected_returncode=2)
3587
3588 stdout, _ = self._run_pdb(["-m", "calendar", "1"], commands)
3589 self.assertIn("December", stdout)
3590
3591 stdout, _ = self._run_pdb(["-m", "calendar", "--type", "text"], commands)
3592 self.assertIn("December", stdout)
3593
3594 def test_run_script_with_args(self):
3595 script = """
3596 import sys
3597 print(sys.argv[1:])
3598 """
3599 commands = """
3600 continue
3601 quit
3602 """
3603
3604 stdout, stderr = self.run_pdb_script(script, commands, script_args=["--bar", "foo"])
3605 self.assertIn("['--bar', 'foo']", stdout)
3606
3607 def test_breakpoint(self):
3608 script = """
3609 if __name__ == '__main__':
3610 pass
3611 print("SUCCESS")
3612 pass
3613 """
3614 commands = """
3615 b 3
3616 quit
3617 """
3618 stdout, stderr = self.run_pdb_module(script, commands)
3619 self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
3620 self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
3621
3622 def test_run_pdb_with_pdb(self):
3623 commands = """
3624 c
3625 quit
3626 """
3627 stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
3628 self.assertIn(
3629 pdb._usage,
3630 stdout.replace('\r', '') # remove \r for windows
3631 )
3632
3633 def test_module_without_a_main(self):
3634 module_name = 't_main'
3635 os_helper.rmtree(module_name)
3636 init_file = module_name + '/__init__.py'
3637 os.mkdir(module_name)
3638 with open(init_file, 'w'):
3639 pass
3640 self.addCleanup(os_helper.rmtree, module_name)
3641 stdout, stderr = self._run_pdb(
3642 ['-m', module_name], "", expected_returncode=1
3643 )
3644 self.assertIn("ImportError: No module named t_main.__main__;", stdout)
3645
3646 def test_package_without_a_main(self):
3647 pkg_name = 't_pkg'
3648 module_name = 't_main'
3649 os_helper.rmtree(pkg_name)
3650 modpath = pkg_name + '/' + module_name
3651 os.makedirs(modpath)
3652 with open(modpath + '/__init__.py', 'w'):
3653 pass
3654 self.addCleanup(os_helper.rmtree, pkg_name)
3655 stdout, stderr = self._run_pdb(
3656 ['-m', modpath.replace('/', '.')], "", expected_returncode=1
3657 )
3658 self.assertIn(
3659 "'t_pkg.t_main' is a package and cannot be directly executed",
3660 stdout)
3661
3662 def test_nonexistent_module(self):
3663 assert not os.path.exists(os_helper.TESTFN)
3664 stdout, stderr = self._run_pdb(["-m", os_helper.TESTFN], "", expected_returncode=1)
3665 self.assertIn(f"ImportError: No module named {os_helper.TESTFN}", stdout)
3666
3667 def test_dir_as_script(self):
3668 with os_helper.temp_dir() as temp_dir:
3669 stdout, stderr = self._run_pdb([temp_dir], "", expected_returncode=1)
3670 self.assertIn(f"Error: {temp_dir} is a directory", stdout)
3671
3672 def test_invalid_cmd_line_options(self):
3673 stdout, stderr = self._run_pdb(["-c"], "", expected_returncode=2)
3674 self.assertIn(f"pdb: error: argument -c/--command: expected one argument", stderr.split('\n')[1])
3675 stdout, stderr = self._run_pdb(["--spam", "-m", "pdb"], "", expected_returncode=2)
3676 self.assertIn(f"pdb: error: unrecognized arguments: --spam", stderr.split('\n')[1])
3677
3678 def test_blocks_at_first_code_line(self):
3679 script = """
3680 #This is a comment, on line 2
3681
3682 print("SUCCESS")
3683 """
3684 commands = """
3685 quit
3686 """
3687 stdout, stderr = self.run_pdb_module(script, commands)
3688 self.assertTrue(any("__main__.py(4)<module>()"
3689 in l for l in stdout.splitlines()), stdout)
3690
3691 def test_file_modified_after_execution(self):
3692 script = """
3693 print("hello")
3694 """
3695
3696 # the time.sleep is needed for low-resolution filesystems like HFS+
3697 commands = """
3698 filename = $_frame.f_code.co_filename
3699 f = open(filename, "w")
3700 f.write("print('goodbye')")
3701 import time; time.sleep(1)
3702 f.close()
3703 ll
3704 """
3705
3706 stdout, stderr = self.run_pdb_script(script, commands)
3707 self.assertIn("WARNING:", stdout)
3708 self.assertIn("was edited", stdout)
3709
3710 def test_file_modified_after_execution_with_multiple_instances(self):
3711 # the time.sleep is needed for low-resolution filesystems like HFS+
3712 script = """
3713 import pdb; pdb.Pdb().set_trace()
3714 with open(__file__, "w") as f:
3715 f.write("print('goodbye')\\n" * 5)
3716 import time; time.sleep(1)
3717 import pdb; pdb.Pdb().set_trace()
3718 """
3719
3720 commands = """
3721 continue
3722 continue
3723 """
3724
3725 filename = 'main.py'
3726 with open(filename, 'w') as f:
3727 f.write(textwrap.dedent(script))
3728 self.addCleanup(os_helper.unlink, filename)
3729 self.addCleanup(os_helper.rmtree, '__pycache__')
3730 cmd = [sys.executable, filename]
3731 with subprocess.Popen(
3732 cmd,
3733 stdout=subprocess.PIPE,
3734 stdin=subprocess.PIPE,
3735 stderr=subprocess.PIPE,
3736 env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'},
3737 ) as proc:
3738 stdout, _ = proc.communicate(str.encode(commands))
3739 stdout = stdout and bytes.decode(stdout)
3740
3741 self.assertEqual(proc.returncode, 0)
3742 self.assertIn("WARNING:", stdout)
3743 self.assertIn("was edited", stdout)
3744
3745 def test_file_modified_after_execution_with_restart(self):
3746 script = """
3747 import random
3748 # Any code with a source to step into so this script is not checked
3749 # for changes when it's being changed
3750 random.randint(1, 4)
3751 print("hello")
3752 """
3753
3754 commands = """
3755 ll
3756 n
3757 s
3758 filename = $_frame.f_back.f_code.co_filename
3759 def change_file(content, filename):
3760 with open(filename, "w") as f:
3761 f.write(f"print({content})")
3762
3763 change_file('world', filename)
3764 restart
3765 ll
3766 """
3767
3768 stdout, stderr = self.run_pdb_script(script, commands)
3769 # Make sure the code is running correctly and the file is edited
3770 self.assertIn("hello", stdout)
3771 self.assertIn("world", stdout)
3772 # The file was edited, but restart should clear the state and consider
3773 # the file as up to date
3774 self.assertNotIn("WARNING:", stdout)
3775
3776 def test_post_mortem_restart(self):
3777 script = """
3778 def foo():
3779 raise ValueError("foo")
3780 foo()
3781 """
3782
3783 commands = """
3784 continue
3785 restart
3786 continue
3787 quit
3788 """
3789
3790 stdout, stderr = self.run_pdb_script(script, commands)
3791 self.assertIn("Restarting", stdout)
3792
3793 def test_relative_imports(self):
3794 self.module_name = 't_main'
3795 os_helper.rmtree(self.module_name)
3796 main_file = self.module_name + '/__main__.py'
3797 init_file = self.module_name + '/__init__.py'
3798 module_file = self.module_name + '/module.py'
3799 self.addCleanup(os_helper.rmtree, self.module_name)
3800 os.mkdir(self.module_name)
3801 with open(init_file, 'w') as f:
3802 f.write(textwrap.dedent("""
3803 top_var = "VAR from top"
3804 """))
3805 with open(main_file, 'w') as f:
3806 f.write(textwrap.dedent("""
3807 from . import top_var
3808 from .module import var
3809 from . import module
3810 pass # We'll stop here and print the vars
3811 """))
3812 with open(module_file, 'w') as f:
3813 f.write(textwrap.dedent("""
3814 var = "VAR from module"
3815 var2 = "second var"
3816 """))
3817 commands = """
3818 b 5
3819 c
3820 p top_var
3821 p var
3822 p module.var2
3823 quit
3824 """
3825 stdout, _ = self._run_pdb(['-m', self.module_name], commands)
3826 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
3827 self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
3828 self.assertTrue(any("second var" in l for l in stdout.splitlines()))
3829
3830 def test_relative_imports_on_plain_module(self):
3831 # Validates running a plain module. See bpo32691
3832 self.module_name = 't_main'
3833 os_helper.rmtree(self.module_name)
3834 main_file = self.module_name + '/runme.py'
3835 init_file = self.module_name + '/__init__.py'
3836 module_file = self.module_name + '/module.py'
3837 self.addCleanup(os_helper.rmtree, self.module_name)
3838 os.mkdir(self.module_name)
3839 with open(init_file, 'w') as f:
3840 f.write(textwrap.dedent("""
3841 top_var = "VAR from top"
3842 """))
3843 with open(main_file, 'w') as f:
3844 f.write(textwrap.dedent("""
3845 from . import module
3846 pass # We'll stop here and print the vars
3847 """))
3848 with open(module_file, 'w') as f:
3849 f.write(textwrap.dedent("""
3850 var = "VAR from module"
3851 """))
3852 commands = """
3853 b 3
3854 c
3855 p module.var
3856 quit
3857 """
3858 stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
3859 self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
3860
3861 def test_errors_in_command(self):
3862 commands = "\n".join([
3863 'print(]',
3864 'debug print(',
3865 'debug doesnotexist',
3866 'c',
3867 ])
3868 stdout, _ = self.run_pdb_script('pass', commands + '\n')
3869
3870 self.assertEqual(stdout.splitlines()[1:], [
3871 '-> pass',
3872 "(Pdb) *** SyntaxError: closing parenthesis ']' does not match opening "
3873 "parenthesis '('",
3874
3875 '(Pdb) ENTERING RECURSIVE DEBUGGER',
3876 '*** SyntaxError: \'(\' was never closed',
3877 'LEAVING RECURSIVE DEBUGGER',
3878
3879 '(Pdb) ENTERING RECURSIVE DEBUGGER',
3880 '> <string>(1)<module>()',
3881 "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
3882 'LEAVING RECURSIVE DEBUGGER',
3883 '(Pdb) ',
3884 ])
3885
3886 def test_issue34266(self):
3887 '''do_run handles exceptions from parsing its arg'''
3888 def check(bad_arg, msg):
3889 commands = "\n".join([
3890 f'run {bad_arg}',
3891 'q',
3892 ])
3893 stdout, _ = self.run_pdb_script('pass', commands + '\n')
3894 self.assertEqual(stdout.splitlines()[1:], [
3895 '-> pass',
3896 f'(Pdb) *** Cannot run {bad_arg}: {msg}',
3897 '(Pdb) ',
3898 ])
3899 check('\\', 'No escaped character')
3900 check('"', 'No closing quotation')
3901
3902 def test_issue42384(self):
3903 '''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
3904 script = textwrap.dedent("""
3905 import sys
3906 print('sys.path[0] is', sys.path[0])
3907 """)
3908 commands = 'c\nq'
3909
3910 with os_helper.temp_cwd() as cwd:
3911 expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
3912
3913 stdout, stderr = self.run_pdb_script(script, commands)
3914
3915 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
3916
3917 @os_helper.skip_unless_symlink
3918 def test_issue42384_symlink(self):
3919 '''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
3920 script = textwrap.dedent("""
3921 import sys
3922 print('sys.path[0] is', sys.path[0])
3923 """)
3924 commands = 'c\nq'
3925
3926 with os_helper.temp_cwd() as cwd:
3927 cwd = os.path.realpath(cwd)
3928 dir_one = os.path.join(cwd, 'dir_one')
3929 dir_two = os.path.join(cwd, 'dir_two')
3930 expected = f'(Pdb) sys.path[0] is {dir_one}'
3931
3932 os.mkdir(dir_one)
3933 with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
3934 f.write(script)
3935 os.mkdir(dir_two)
3936 os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
3937
3938 stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
3939
3940 self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
3941
3942 def test_safe_path(self):
3943 """ With safe_path set, pdb should not mangle sys.path[0]"""
3944
3945 script = textwrap.dedent("""
3946 import sys
3947 import random
3948 print('sys.path[0] is', sys.path[0])
3949 """)
3950 commands = 'c\n'
3951
3952
3953 with os_helper.temp_cwd() as cwd:
3954 stdout, _ = self.run_pdb_script(script, commands, extra_env={'PYTHONSAFEPATH': '1'})
3955
3956 unexpected = f'sys.path[0] is {os.path.realpath(cwd)}'
3957 self.assertNotIn(unexpected, stdout)
3958
3959 def test_issue42383(self):
3960 with os_helper.temp_cwd() as cwd:
3961 with open('foo.py', 'w') as f:
3962 s = textwrap.dedent("""
3963 print('The correct file was executed')
3964
3965 import os
3966 os.chdir("subdir")
3967 """)
3968 f.write(s)
3969
3970 subdir = os.path.join(cwd, 'subdir')
3971 os.mkdir(subdir)
3972 os.mkdir(os.path.join(subdir, 'subdir'))
3973 wrong_file = os.path.join(subdir, 'foo.py')
3974
3975 with open(wrong_file, 'w') as f:
3976 f.write('print("The wrong file was executed")')
3977
3978 stdout, stderr = self._run_pdb(['foo.py'], 'c\nc\nq')
3979 expected = '(Pdb) The correct file was executed'
3980 self.assertEqual(stdout.split('\n')[6].rstrip('\r'), expected)
3981
3982 def test_gh_94215_crash(self):
3983 script = """\
3984 def func():
3985 def inner(v): pass
3986 inner(
3987 42
3988 )
3989 func()
3990 """
3991 commands = textwrap.dedent("""
3992 break func
3993 continue
3994 next
3995 next
3996 jump 2
3997 """)
3998 stdout, stderr = self.run_pdb_script(script, commands)
3999 self.assertFalse(stderr)
4000
4001 def test_gh_93696_frozen_list(self):
4002 frozen_src = """
4003 def func():
4004 x = "Sentinel string for gh-93696"
4005 print(x)
4006 """
4007 host_program = """
4008 import os
4009 import sys
4010
4011 def _create_fake_frozen_module():
4012 with open('gh93696.py') as f:
4013 src = f.read()
4014
4015 # this function has a co_filename as if it were in a frozen module
4016 dummy_mod = compile(src, "<frozen gh93696>", "exec")
4017 func_code = dummy_mod.co_consts[0]
4018
4019 mod = type(sys)("gh93696")
4020 mod.func = type(lambda: None)(func_code, mod.__dict__)
4021 mod.__file__ = 'gh93696.py'
4022
4023 return mod
4024
4025 mod = _create_fake_frozen_module()
4026 mod.func()
4027 """
4028 commands = """
4029 break 20
4030 continue
4031 step
4032 list
4033 quit
4034 """
4035 with open('gh93696.py', 'w') as f:
4036 f.write(textwrap.dedent(frozen_src))
4037
4038 with open('gh93696_host.py', 'w') as f:
4039 f.write(textwrap.dedent(host_program))
4040
4041 self.addCleanup(os_helper.unlink, 'gh93696.py')
4042 self.addCleanup(os_helper.unlink, 'gh93696_host.py')
4043 stdout, stderr = self._run_pdb(["gh93696_host.py"], commands)
4044 # verify that pdb found the source of the "frozen" function
4045 self.assertIn('x = "Sentinel string for gh-93696"', stdout, "Sentinel statement not found")
4046
4047 def test_empty_file(self):
4048 script = ''
4049 commands = 'q\n'
4050 # We check that pdb stopped at line 0, but anything reasonable
4051 # is acceptable here, as long as it does not halt
4052 stdout, _ = self.run_pdb_script(script, commands)
4053 self.assertIn('main.py(0)', stdout)
4054 stdout, _ = self.run_pdb_module(script, commands)
4055 self.assertIn('__main__.py(0)', stdout)
4056
4057 def test_non_utf8_encoding(self):
4058 script_dir = os.path.join(os.path.dirname(__file__), 'encoded_modules')
4059 for filename in os.listdir(script_dir):
4060 if filename.endswith(".py"):
4061 self._run_pdb([os.path.join(script_dir, filename)], 'q')
4062
4063 def test_zipapp(self):
4064 with os_helper.temp_dir() as temp_dir:
4065 os.mkdir(os.path.join(temp_dir, 'source'))
4066 script = textwrap.dedent(
4067 """
4068 def f(x):
4069 return x + 1
4070 f(21 + 21)
4071 """
4072 )
4073 with open(os.path.join(temp_dir, 'source', '__main__.py'), 'w') as f:
4074 f.write(script)
4075 zipapp.create_archive(os.path.join(temp_dir, 'source'),
4076 os.path.join(temp_dir, 'zipapp.pyz'))
4077 stdout, _ = self._run_pdb([os.path.join(temp_dir, 'zipapp.pyz')], '\n'.join([
4078 'b f',
4079 'c',
4080 'p x',
4081 'q'
4082 ]))
4083 self.assertIn('42', stdout)
4084 self.assertIn('return x + 1', stdout)
4085
4086 def test_issue_59000(self):
4087 script = """
4088 def foo():
4089 pass
4090
4091 class C:
4092 def foo(self):
4093 pass
4094 """
4095 commands = """
4096 break C.foo
4097 quit
4098 """
4099 stdout, stderr = self.run_pdb_script(script, commands)
4100 self.assertIn("The specified object 'C.foo' is not a function", stdout)
4101
4102
4103 class ChecklineTests(unittest.TestCase):
4104 def setUp(self):
4105 linecache.clearcache() # Pdb.checkline() uses linecache.getline()
4106
4107 def tearDown(self):
4108 os_helper.unlink(os_helper.TESTFN)
4109
4110 def test_checkline_before_debugging(self):
4111 with open(os_helper.TESTFN, "w") as f:
4112 f.write("print(123)")
4113 db = pdb.Pdb()
4114 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
4115
4116 def test_checkline_after_reset(self):
4117 with open(os_helper.TESTFN, "w") as f:
4118 f.write("print(123)")
4119 db = pdb.Pdb()
4120 db.reset()
4121 self.assertEqual(db.checkline(os_helper.TESTFN, 1), 1)
4122
4123 def test_checkline_is_not_executable(self):
4124 # Test for comments, docstrings and empty lines
4125 s = textwrap.dedent("""
4126 # Comment
4127 \"\"\" docstring \"\"\"
4128 ''' docstring '''
4129
4130 """)
4131 with open(os_helper.TESTFN, "w") as f:
4132 f.write(s)
4133 num_lines = len(s.splitlines()) + 2 # Test for EOF
4134 with redirect_stdout(StringIO()):
4135 db = pdb.Pdb()
4136 for lineno in range(num_lines):
4137 self.assertFalse(db.checkline(os_helper.TESTFN, lineno))
4138
4139
4140 @support.requires_subprocess()
4141 class PdbTestReadline(unittest.TestCase):
4142
4143 @classmethod
4144 def setUpClass(cls):
4145 # Ensure that the readline module is loaded
4146 # If this fails, the test is skipped because SkipTest will be raised
4147 readline = import_module('readline')
4148 if readline.backend == "editline":
4149 raise unittest.SkipTest("libedit readline is not supported for pdb")
4150
4151 def test_basic_completion(self):
4152 script = textwrap.dedent("""
4153 import pdb; pdb.Pdb().set_trace()
4154 # Concatenate strings so that the output doesn't appear in the source
4155 print('hello' + '!')
4156 """)
4157
4158 # List everything starting with 'co', there should be multiple matches
4159 # then add ntin and complete 'contin' to 'continue'
4160 input = b"co\t\tntin\t\n"
4161
4162 output = run_pty(script, input)
4163
4164 self.assertIn(b'commands', output)
4165 self.assertIn(b'condition', output)
4166 self.assertIn(b'continue', output)
4167 self.assertIn(b'hello!', output)
4168
4169 def test_expression_completion(self):
4170 script = textwrap.dedent("""
4171 value = "speci"
4172 import pdb; pdb.Pdb().set_trace()
4173 """)
4174
4175 # Complete: value + 'al'
4176 input = b"val\t + 'al'\n"
4177 # Complete: p value + 'es'
4178 input += b"p val\t + 'es'\n"
4179 # Complete: $_frame
4180 input += b"$_fra\t\n"
4181 # Continue
4182 input += b"c\n"
4183
4184 output = run_pty(script, input)
4185
4186 self.assertIn(b'special', output)
4187 self.assertIn(b'species', output)
4188 self.assertIn(b'$_frame', output)
4189
4190 def test_builtin_completion(self):
4191 script = textwrap.dedent("""
4192 value = "speci"
4193 import pdb; pdb.Pdb().set_trace()
4194 """)
4195
4196 # Complete: print(value + 'al')
4197 input = b"pri\tval\t + 'al')\n"
4198
4199 # Continue
4200 input += b"c\n"
4201
4202 output = run_pty(script, input)
4203
4204 self.assertIn(b'special', output)
4205
4206 def test_local_namespace(self):
4207 script = textwrap.dedent("""
4208 def f():
4209 original = "I live Pythin"
4210 import pdb; pdb.Pdb().set_trace()
4211 f()
4212 """)
4213
4214 # Complete: original.replace('i', 'o')
4215 input = b"orig\t.repl\t('i', 'o')\n"
4216
4217 # Continue
4218 input += b"c\n"
4219
4220 output = run_pty(script, input)
4221
4222 self.assertIn(b'I love Python', output)
4223
4224 def test_multiline_completion(self):
4225 script = textwrap.dedent("""
4226 import pdb; pdb.Pdb().set_trace()
4227 """)
4228
4229 input = b"def func():\n"
4230 # Complete: \treturn 40 + 2
4231 input += b"\tret\t 40 + 2\n"
4232 input += b"\n"
4233 # Complete: func()
4234 input += b"fun\t()\n"
4235 input += b"c\n"
4236
4237 output = run_pty(script, input)
4238
4239 self.assertIn(b'42', output)
4240
4241
4242 def load_tests(loader, tests, pattern):
4243 from test import test_pdb
4244 tests.addTest(doctest.DocTestSuite(test_pdb))
4245 return tests
4246
4247
4248 if __name__ == '__main__':
4249 unittest.main()