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