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
12
13from contextlib import ExitStack
14from io import StringIO
15from test import support
16# This little helper class is essential for testing pdb under doctest.
17from test.test_doctest import _FakeInput
18from unittest.mock import patch
19
20
21class PdbTestInput(object):
22    """Context manager that makes testing Pdb in doctests easier."""
23
24    def __init__(self, input):
25        self.input = input
26
27    def __enter__(self):
28        self.real_stdin = sys.stdin
29        sys.stdin = _FakeInput(self.input)
30        self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
31
32    def __exit__(self, *exc):
33        sys.stdin = self.real_stdin
34        if self.orig_trace:
35            sys.settrace(self.orig_trace)
36
37
38def test_pdb_displayhook():
39    """This tests the custom displayhook for pdb.
40
41    >>> def test_function(foo, bar):
42    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
43    ...     pass
44
45    >>> with PdbTestInput([
46    ...     'foo',
47    ...     'bar',
48    ...     'for i in range(5): print(i)',
49    ...     'continue',
50    ... ]):
51    ...     test_function(1, None)
52    > <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function()
53    -> pass
54    (Pdb) foo
55    1
56    (Pdb) bar
57    (Pdb) for i in range(5): print(i)
58    0
59    1
60    2
61    3
62    4
63    (Pdb) continue
64    """
65
66
67def test_pdb_basic_commands():
68    """Test the basic commands of pdb.
69
70    >>> def test_function_2(foo, bar='default'):
71    ...     print(foo)
72    ...     for i in range(5):
73    ...         print(i)
74    ...     print(bar)
75    ...     for i in range(10):
76    ...         never_executed
77    ...     print('after for')
78    ...     print('...')
79    ...     return foo.upper()
80
81    >>> def test_function3(arg=None, *, kwonly=None):
82    ...     pass
83
84    >>> def test_function4(a, b, c, /):
85    ...     pass
86
87    >>> def test_function():
88    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
89    ...     ret = test_function_2('baz')
90    ...     test_function3(kwonly=True)
91    ...     test_function4(1, 2, 3)
92    ...     print(ret)
93
94    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
95    ...     'step',       # entering the function call
96    ...     'args',       # display function args
97    ...     'list',       # list function source
98    ...     'bt',         # display backtrace
99    ...     'up',         # step up to test_function()
100    ...     'down',       # step down to test_function_2() again
101    ...     'next',       # stepping to print(foo)
102    ...     'next',       # stepping to the for loop
103    ...     'step',       # stepping into the for loop
104    ...     'until',      # continuing until out of the for loop
105    ...     'next',       # executing the print(bar)
106    ...     'jump 8',     # jump over second for loop
107    ...     'return',     # return out of function
108    ...     'retval',     # display return value
109    ...     'next',       # step to test_function3()
110    ...     'step',       # stepping into test_function3()
111    ...     'args',       # display function args
112    ...     'return',     # return out of function
113    ...     'next',       # step to test_function4()
114    ...     'step',       # stepping to test_function4()
115    ...     'args',       # display function args
116    ...     'continue',
117    ... ]):
118    ...    test_function()
119    > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
120    -> ret = test_function_2('baz')
121    (Pdb) step
122    --Call--
123    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
124    -> def test_function_2(foo, bar='default'):
125    (Pdb) args
126    foo = 'baz'
127    bar = 'default'
128    (Pdb) list
129      1  ->     def test_function_2(foo, bar='default'):
130      2             print(foo)
131      3             for i in range(5):
132      4                 print(i)
133      5             print(bar)
134      6             for i in range(10):
135      7                 never_executed
136      8             print('after for')
137      9             print('...')
138     10             return foo.upper()
139    [EOF]
140    (Pdb) bt
141    ...
142      <doctest test.test_pdb.test_pdb_basic_commands[4]>(25)<module>()
143    -> test_function()
144      <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
145    -> ret = test_function_2('baz')
146    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
147    -> def test_function_2(foo, bar='default'):
148    (Pdb) up
149    > <doctest test.test_pdb.test_pdb_basic_commands[3]>(3)test_function()
150    -> ret = test_function_2('baz')
151    (Pdb) down
152    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
153    -> def test_function_2(foo, bar='default'):
154    (Pdb) next
155    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
156    -> print(foo)
157    (Pdb) next
158    baz
159    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
160    -> for i in range(5):
161    (Pdb) step
162    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
163    -> print(i)
164    (Pdb) until
165    0
166    1
167    2
168    3
169    4
170    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
171    -> print(bar)
172    (Pdb) next
173    default
174    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
175    -> for i in range(10):
176    (Pdb) jump 8
177    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
178    -> print('after for')
179    (Pdb) return
180    after for
181    ...
182    --Return--
183    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
184    -> return foo.upper()
185    (Pdb) retval
186    'BAZ'
187    (Pdb) next
188    > <doctest test.test_pdb.test_pdb_basic_commands[3]>(4)test_function()
189    -> test_function3(kwonly=True)
190    (Pdb) step
191    --Call--
192    > <doctest test.test_pdb.test_pdb_basic_commands[1]>(1)test_function3()
193    -> def test_function3(arg=None, *, kwonly=None):
194    (Pdb) args
195    arg = None
196    kwonly = True
197    (Pdb) return
198    --Return--
199    > <doctest test.test_pdb.test_pdb_basic_commands[1]>(2)test_function3()->None
200    -> pass
201    (Pdb) next
202    > <doctest test.test_pdb.test_pdb_basic_commands[3]>(5)test_function()
203    -> test_function4(1, 2, 3)
204    (Pdb) step
205    --Call--
206    > <doctest test.test_pdb.test_pdb_basic_commands[2]>(1)test_function4()
207    -> def test_function4(a, b, c, /):
208    (Pdb) args
209    a = 1
210    b = 2
211    c = 3
212    (Pdb) continue
213    BAZ
214    """
215
216
217def test_pdb_breakpoint_commands():
218    """Test basic commands related to breakpoints.
219
220    >>> def test_function():
221    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
222    ...     print(1)
223    ...     print(2)
224    ...     print(3)
225    ...     print(4)
226
227    First, need to clear bdb state that might be left over from previous tests.
228    Otherwise, the new breakpoints might get assigned different numbers.
229
230    >>> from bdb import Breakpoint
231    >>> Breakpoint.next = 1
232    >>> Breakpoint.bplist = {}
233    >>> Breakpoint.bpbynumber = [None]
234
235    Now test the breakpoint commands.  NORMALIZE_WHITESPACE is needed because
236    the breakpoint list outputs a tab for the "stop only" and "ignore next"
237    lines, which we don't want to put in here.
238
239    >>> with PdbTestInput([  # doctest: +NORMALIZE_WHITESPACE
240    ...     'break 3',
241    ...     'disable 1',
242    ...     'ignore 1 10',
243    ...     'condition 1 1 < 2',
244    ...     'break 4',
245    ...     'break 4',
246    ...     'break',
247    ...     'clear 3',
248    ...     'break',
249    ...     'condition 1',
250    ...     'enable 1',
251    ...     'clear 1',
252    ...     'commands 2',
253    ...     'p "42"',
254    ...     'print("42", 7*6)',     # Issue 18764 (not about breakpoints)
255    ...     'end',
256    ...     'continue',  # will stop at breakpoint 2 (line 4)
257    ...     'clear',     # clear all!
258    ...     'y',
259    ...     'tbreak 5',
260    ...     'continue',  # will stop at temporary breakpoint
261    ...     'break',     # make sure breakpoint is gone
262    ...     'continue',
263    ... ]):
264    ...    test_function()
265    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
266    -> print(1)
267    (Pdb) break 3
268    Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
269    (Pdb) disable 1
270    Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
271    (Pdb) ignore 1 10
272    Will ignore next 10 crossings of breakpoint 1.
273    (Pdb) condition 1 1 < 2
274    New condition set for breakpoint 1.
275    (Pdb) break 4
276    Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
277    (Pdb) break 4
278    Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
279    (Pdb) break
280    Num Type         Disp Enb   Where
281    1   breakpoint   keep no    at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
282            stop only if 1 < 2
283            ignore next 10 hits
284    2   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
285    3   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
286    (Pdb) clear 3
287    Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
288    (Pdb) break
289    Num Type         Disp Enb   Where
290    1   breakpoint   keep no    at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
291            stop only if 1 < 2
292            ignore next 10 hits
293    2   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
294    (Pdb) condition 1
295    Breakpoint 1 is now unconditional.
296    (Pdb) enable 1
297    Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
298    (Pdb) clear 1
299    Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
300    (Pdb) commands 2
301    (com) p "42"
302    (com) print("42", 7*6)
303    (com) end
304    (Pdb) continue
305    1
306    '42'
307    42 42
308    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
309    -> print(2)
310    (Pdb) clear
311    Clear all breaks? y
312    Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
313    (Pdb) tbreak 5
314    Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
315    (Pdb) continue
316    2
317    Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
318    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
319    -> print(3)
320    (Pdb) break
321    (Pdb) continue
322    3
323    4
324    """
325
326
327def do_nothing():
328    pass
329
330def do_something():
331    print(42)
332
333def test_list_commands():
334    """Test the list and source commands of pdb.
335
336    >>> def test_function_2(foo):
337    ...     import test.test_pdb
338    ...     test.test_pdb.do_nothing()
339    ...     'some...'
340    ...     'more...'
341    ...     'code...'
342    ...     'to...'
343    ...     'make...'
344    ...     'a...'
345    ...     'long...'
346    ...     'listing...'
347    ...     'useful...'
348    ...     '...'
349    ...     '...'
350    ...     return foo
351
352    >>> def test_function():
353    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
354    ...     ret = test_function_2('baz')
355
356    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
357    ...     'list',      # list first function
358    ...     'step',      # step into second function
359    ...     'list',      # list second function
360    ...     'list',      # continue listing to EOF
361    ...     'list 1,3',  # list specific lines
362    ...     'list x',    # invalid argument
363    ...     'next',      # step to import
364    ...     'next',      # step over import
365    ...     'step',      # step into do_nothing
366    ...     'longlist',  # list all lines
367    ...     'source do_something',  # list all lines of function
368    ...     'source fooxxx',        # something that doesn't exit
369    ...     'continue',
370    ... ]):
371    ...    test_function()
372    > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
373    -> ret = test_function_2('baz')
374    (Pdb) list
375      1         def test_function():
376      2             import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
377      3  ->         ret = test_function_2('baz')
378    [EOF]
379    (Pdb) step
380    --Call--
381    > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
382    -> def test_function_2(foo):
383    (Pdb) list
384      1  ->     def test_function_2(foo):
385      2             import test.test_pdb
386      3             test.test_pdb.do_nothing()
387      4             'some...'
388      5             'more...'
389      6             'code...'
390      7             'to...'
391      8             'make...'
392      9             'a...'
393     10             'long...'
394     11             'listing...'
395    (Pdb) list
396     12             'useful...'
397     13             '...'
398     14             '...'
399     15             return foo
400    [EOF]
401    (Pdb) list 1,3
402      1  ->     def test_function_2(foo):
403      2             import test.test_pdb
404      3             test.test_pdb.do_nothing()
405    (Pdb) list x
406    *** ...
407    (Pdb) next
408    > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
409    -> import test.test_pdb
410    (Pdb) next
411    > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
412    -> test.test_pdb.do_nothing()
413    (Pdb) step
414    --Call--
415    > ...test_pdb.py(...)do_nothing()
416    -> def do_nothing():
417    (Pdb) longlist
418    ...  ->     def do_nothing():
419    ...             pass
420    (Pdb) source do_something
421    ...         def do_something():
422    ...             print(42)
423    (Pdb) source fooxxx
424    *** ...
425    (Pdb) continue
426    """
427
428def test_pdb_whatis_command():
429    """Test the whatis command
430
431    >>> myvar = (1,2)
432    >>> def myfunc():
433    ...     pass
434
435    >>> class MyClass:
436    ...    def mymethod(self):
437    ...        pass
438
439    >>> def test_function():
440    ...   import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
441
442    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
443    ...    'whatis myvar',
444    ...    'whatis myfunc',
445    ...    'whatis MyClass',
446    ...    'whatis MyClass()',
447    ...    'whatis MyClass.mymethod',
448    ...    'whatis MyClass().mymethod',
449    ...    'continue',
450    ... ]):
451    ...    test_function()
452    --Return--
453    > <doctest test.test_pdb.test_pdb_whatis_command[3]>(2)test_function()->None
454    -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
455    (Pdb) whatis myvar
456    <class 'tuple'>
457    (Pdb) whatis myfunc
458    Function myfunc
459    (Pdb) whatis MyClass
460    Class test.test_pdb.MyClass
461    (Pdb) whatis MyClass()
462    <class 'test.test_pdb.MyClass'>
463    (Pdb) whatis MyClass.mymethod
464    Function mymethod
465    (Pdb) whatis MyClass().mymethod
466    Method mymethod
467    (Pdb) continue
468    """
469
470def test_post_mortem():
471    """Test post mortem traceback debugging.
472
473    >>> def test_function_2():
474    ...     try:
475    ...         1/0
476    ...     finally:
477    ...         print('Exception!')
478
479    >>> def test_function():
480    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
481    ...     test_function_2()
482    ...     print('Not reached.')
483
484    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
485    ...     'next',      # step over exception-raising call
486    ...     'bt',        # get a backtrace
487    ...     'list',      # list code of test_function()
488    ...     'down',      # step into test_function_2()
489    ...     'list',      # list code of test_function_2()
490    ...     'continue',
491    ... ]):
492    ...    try:
493    ...        test_function()
494    ...    except ZeroDivisionError:
495    ...        print('Correctly reraised.')
496    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
497    -> test_function_2()
498    (Pdb) next
499    Exception!
500    ZeroDivisionError: division by zero
501    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
502    -> test_function_2()
503    (Pdb) bt
504    ...
505      <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
506    -> test_function()
507    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
508    -> test_function_2()
509      <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
510    -> 1/0
511    (Pdb) list
512      1         def test_function():
513      2             import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
514      3  ->         test_function_2()
515      4             print('Not reached.')
516    [EOF]
517    (Pdb) down
518    > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
519    -> 1/0
520    (Pdb) list
521      1         def test_function_2():
522      2             try:
523      3  >>             1/0
524      4             finally:
525      5  ->             print('Exception!')
526    [EOF]
527    (Pdb) continue
528    Correctly reraised.
529    """
530
531
532def test_pdb_skip_modules():
533    """This illustrates the simple case of module skipping.
534
535    >>> def skip_module():
536    ...     import string
537    ...     import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
538    ...     string.capwords('FOO')
539
540    >>> with PdbTestInput([
541    ...     'step',
542    ...     'continue',
543    ... ]):
544    ...     skip_module()
545    > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
546    -> string.capwords('FOO')
547    (Pdb) step
548    --Return--
549    > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
550    -> string.capwords('FOO')
551    (Pdb) continue
552    """
553
554
555# Module for testing skipping of module that makes a callback
556mod = types.ModuleType('module_to_skip')
557exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
558
559
560def test_pdb_skip_modules_with_callback():
561    """This illustrates skipping of modules that call into other code.
562
563    >>> def skip_module():
564    ...     def callback():
565    ...         return None
566    ...     import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
567    ...     mod.foo_pony(callback)
568
569    >>> with PdbTestInput([
570    ...     'step',
571    ...     'step',
572    ...     'step',
573    ...     'step',
574    ...     'step',
575    ...     'continue',
576    ... ]):
577    ...     skip_module()
578    ...     pass  # provides something to "step" to
579    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
580    -> mod.foo_pony(callback)
581    (Pdb) step
582    --Call--
583    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
584    -> def callback():
585    (Pdb) step
586    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
587    -> return None
588    (Pdb) step
589    --Return--
590    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
591    -> return None
592    (Pdb) step
593    --Return--
594    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
595    -> mod.foo_pony(callback)
596    (Pdb) step
597    > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
598    -> pass  # provides something to "step" to
599    (Pdb) continue
600    """
601
602
603def test_pdb_continue_in_bottomframe():
604    """Test that "continue" and "next" work properly in bottom frame (issue #5294).
605
606    >>> def test_function():
607    ...     import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
608    ...     inst.set_trace()
609    ...     inst.botframe = sys._getframe()  # hackery to get the right botframe
610    ...     print(1)
611    ...     print(2)
612    ...     print(3)
613    ...     print(4)
614
615    >>> with PdbTestInput([  # doctest: +ELLIPSIS
616    ...     'next',
617    ...     'break 7',
618    ...     'continue',
619    ...     'next',
620    ...     'continue',
621    ...     'continue',
622    ... ]):
623    ...    test_function()
624    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
625    -> inst.botframe = sys._getframe()  # hackery to get the right botframe
626    (Pdb) next
627    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
628    -> print(1)
629    (Pdb) break 7
630    Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
631    (Pdb) continue
632    1
633    2
634    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
635    -> print(3)
636    (Pdb) next
637    3
638    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
639    -> print(4)
640    (Pdb) continue
641    4
642    """
643
644
645def pdb_invoke(method, arg):
646    """Run pdb.method(arg)."""
647    getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
648
649
650def test_pdb_run_with_incorrect_argument():
651    """Testing run and runeval with incorrect first argument.
652
653    >>> pti = PdbTestInput(['continue',])
654    >>> with pti:
655    ...     pdb_invoke('run', lambda x: x)
656    Traceback (most recent call last):
657    TypeError: exec() arg 1 must be a string, bytes or code object
658
659    >>> with pti:
660    ...     pdb_invoke('runeval', lambda x: x)
661    Traceback (most recent call last):
662    TypeError: eval() arg 1 must be a string, bytes or code object
663    """
664
665
666def test_pdb_run_with_code_object():
667    """Testing run and runeval with code object as a first argument.
668
669    >>> with PdbTestInput(['step','x', 'continue']):  # doctest: +ELLIPSIS
670    ...     pdb_invoke('run', compile('x=1', '<string>', 'exec'))
671    > <string>(1)<module>()...
672    (Pdb) step
673    --Return--
674    > <string>(1)<module>()->None
675    (Pdb) x
676    1
677    (Pdb) continue
678
679    >>> with PdbTestInput(['x', 'continue']):
680    ...     x=0
681    ...     pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
682    > <string>(1)<module>()->None
683    (Pdb) x
684    1
685    (Pdb) continue
686    """
687
688def test_next_until_return_at_return_event():
689    """Test that pdb stops after a next/until/return issued at a return debug event.
690
691    >>> def test_function_2():
692    ...     x = 1
693    ...     x = 2
694
695    >>> def test_function():
696    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
697    ...     test_function_2()
698    ...     test_function_2()
699    ...     test_function_2()
700    ...     end = 1
701
702    >>> from bdb import Breakpoint
703    >>> Breakpoint.next = 1
704    >>> with PdbTestInput(['break test_function_2',
705    ...                    'continue',
706    ...                    'return',
707    ...                    'next',
708    ...                    'continue',
709    ...                    'return',
710    ...                    'until',
711    ...                    'continue',
712    ...                    'return',
713    ...                    'return',
714    ...                    'continue']):
715    ...     test_function()
716    > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
717    -> test_function_2()
718    (Pdb) break test_function_2
719    Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
720    (Pdb) continue
721    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
722    -> x = 1
723    (Pdb) return
724    --Return--
725    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
726    -> x = 2
727    (Pdb) next
728    > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
729    -> test_function_2()
730    (Pdb) continue
731    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
732    -> x = 1
733    (Pdb) return
734    --Return--
735    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
736    -> x = 2
737    (Pdb) until
738    > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
739    -> test_function_2()
740    (Pdb) continue
741    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
742    -> x = 1
743    (Pdb) return
744    --Return--
745    > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
746    -> x = 2
747    (Pdb) return
748    > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
749    -> end = 1
750    (Pdb) continue
751    """
752
753def test_pdb_next_command_for_generator():
754    """Testing skip unwindng stack on yield for generators for "next" command
755
756    >>> def test_gen():
757    ...     yield 0
758    ...     return 1
759    ...     yield 2
760
761    >>> def test_function():
762    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
763    ...     it = test_gen()
764    ...     try:
765    ...         if next(it) != 0:
766    ...             raise AssertionError
767    ...         next(it)
768    ...     except StopIteration as ex:
769    ...         if ex.value != 1:
770    ...             raise AssertionError
771    ...     print("finished")
772
773    >>> with PdbTestInput(['step',
774    ...                    'step',
775    ...                    'step',
776    ...                    'next',
777    ...                    'next',
778    ...                    'step',
779    ...                    'step',
780    ...                    'continue']):
781    ...     test_function()
782    > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
783    -> it = test_gen()
784    (Pdb) step
785    > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
786    -> try:
787    (Pdb) step
788    > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
789    -> if next(it) != 0:
790    (Pdb) step
791    --Call--
792    > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
793    -> def test_gen():
794    (Pdb) next
795    > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
796    -> yield 0
797    (Pdb) next
798    > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
799    -> return 1
800    (Pdb) step
801    --Return--
802    > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
803    -> return 1
804    (Pdb) step
805    StopIteration: 1
806    > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
807    -> next(it)
808    (Pdb) continue
809    finished
810    """
811
812def test_pdb_next_command_for_coroutine():
813    """Testing skip unwindng stack on yield for coroutines for "next" command
814
815    >>> import asyncio
816
817    >>> async def test_coro():
818    ...     await asyncio.sleep(0)
819    ...     await asyncio.sleep(0)
820    ...     await asyncio.sleep(0)
821
822    >>> async def test_main():
823    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
824    ...     await test_coro()
825
826    >>> def test_function():
827    ...     loop = asyncio.new_event_loop()
828    ...     loop.run_until_complete(test_main())
829    ...     loop.close()
830    ...     asyncio.set_event_loop_policy(None)
831    ...     print("finished")
832
833    >>> with PdbTestInput(['step',
834    ...                    'step',
835    ...                    'next',
836    ...                    'next',
837    ...                    'next',
838    ...                    'step',
839    ...                    'continue']):
840    ...     test_function()
841    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
842    -> await test_coro()
843    (Pdb) step
844    --Call--
845    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
846    -> async def test_coro():
847    (Pdb) step
848    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
849    -> await asyncio.sleep(0)
850    (Pdb) next
851    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
852    -> await asyncio.sleep(0)
853    (Pdb) next
854    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
855    -> await asyncio.sleep(0)
856    (Pdb) next
857    Internal StopIteration
858    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
859    -> await test_coro()
860    (Pdb) step
861    --Return--
862    > <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
863    -> await test_coro()
864    (Pdb) continue
865    finished
866    """
867
868def test_pdb_next_command_for_asyncgen():
869    """Testing skip unwindng stack on yield for coroutines for "next" command
870
871    >>> import asyncio
872
873    >>> async def agen():
874    ...     yield 1
875    ...     await asyncio.sleep(0)
876    ...     yield 2
877
878    >>> async def test_coro():
879    ...     async for x in agen():
880    ...         print(x)
881
882    >>> async def test_main():
883    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
884    ...     await test_coro()
885
886    >>> def test_function():
887    ...     loop = asyncio.new_event_loop()
888    ...     loop.run_until_complete(test_main())
889    ...     loop.close()
890    ...     asyncio.set_event_loop_policy(None)
891    ...     print("finished")
892
893    >>> with PdbTestInput(['step',
894    ...                    'step',
895    ...                    'next',
896    ...                    'next',
897    ...                    'step',
898    ...                    'next',
899    ...                    'continue']):
900    ...     test_function()
901    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
902    -> await test_coro()
903    (Pdb) step
904    --Call--
905    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
906    -> async def test_coro():
907    (Pdb) step
908    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
909    -> async for x in agen():
910    (Pdb) next
911    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
912    -> print(x)
913    (Pdb) next
914    1
915    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
916    -> async for x in agen():
917    (Pdb) step
918    --Call--
919    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
920    -> yield 1
921    (Pdb) next
922    > <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
923    -> await asyncio.sleep(0)
924    (Pdb) continue
925    2
926    finished
927    """
928
929def test_pdb_return_command_for_generator():
930    """Testing no unwindng stack on yield for generators
931       for "return" command
932
933    >>> def test_gen():
934    ...     yield 0
935    ...     return 1
936    ...     yield 2
937
938    >>> def test_function():
939    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
940    ...     it = test_gen()
941    ...     try:
942    ...         if next(it) != 0:
943    ...             raise AssertionError
944    ...         next(it)
945    ...     except StopIteration as ex:
946    ...         if ex.value != 1:
947    ...             raise AssertionError
948    ...     print("finished")
949
950    >>> with PdbTestInput(['step',
951    ...                    'step',
952    ...                    'step',
953    ...                    'return',
954    ...                    'step',
955    ...                    'step',
956    ...                    'continue']):
957    ...     test_function()
958    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
959    -> it = test_gen()
960    (Pdb) step
961    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
962    -> try:
963    (Pdb) step
964    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
965    -> if next(it) != 0:
966    (Pdb) step
967    --Call--
968    > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
969    -> def test_gen():
970    (Pdb) return
971    StopIteration: 1
972    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
973    -> next(it)
974    (Pdb) step
975    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
976    -> except StopIteration as ex:
977    (Pdb) step
978    > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
979    -> if ex.value != 1:
980    (Pdb) continue
981    finished
982    """
983
984def test_pdb_return_command_for_coroutine():
985    """Testing no unwindng stack on yield for coroutines for "return" command
986
987    >>> import asyncio
988
989    >>> async def test_coro():
990    ...     await asyncio.sleep(0)
991    ...     await asyncio.sleep(0)
992    ...     await asyncio.sleep(0)
993
994    >>> async def test_main():
995    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
996    ...     await test_coro()
997
998    >>> def test_function():
999    ...     loop = asyncio.new_event_loop()
1000    ...     loop.run_until_complete(test_main())
1001    ...     loop.close()
1002    ...     asyncio.set_event_loop_policy(None)
1003    ...     print("finished")
1004
1005    >>> with PdbTestInput(['step',
1006    ...                    'step',
1007    ...                    'next',
1008    ...                    'continue']):
1009    ...     test_function()
1010    > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
1011    -> await test_coro()
1012    (Pdb) step
1013    --Call--
1014    > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
1015    -> async def test_coro():
1016    (Pdb) step
1017    > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
1018    -> await asyncio.sleep(0)
1019    (Pdb) next
1020    > <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
1021    -> await asyncio.sleep(0)
1022    (Pdb) continue
1023    finished
1024    """
1025
1026def test_pdb_until_command_for_generator():
1027    """Testing no unwindng stack on yield for generators
1028       for "until" command if target breakpoint is not reached
1029
1030    >>> def test_gen():
1031    ...     yield 0
1032    ...     yield 1
1033    ...     yield 2
1034
1035    >>> def test_function():
1036    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1037    ...     for i in test_gen():
1038    ...         print(i)
1039    ...     print("finished")
1040
1041    >>> with PdbTestInput(['step',
1042    ...                    'until 4',
1043    ...                    'step',
1044    ...                    'step',
1045    ...                    'continue']):
1046    ...     test_function()
1047    > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
1048    -> for i in test_gen():
1049    (Pdb) step
1050    --Call--
1051    > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
1052    -> def test_gen():
1053    (Pdb) until 4
1054    0
1055    1
1056    > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
1057    -> yield 2
1058    (Pdb) step
1059    --Return--
1060    > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
1061    -> yield 2
1062    (Pdb) step
1063    > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
1064    -> print(i)
1065    (Pdb) continue
1066    2
1067    finished
1068    """
1069
1070def test_pdb_until_command_for_coroutine():
1071    """Testing no unwindng stack for coroutines
1072       for "until" command if target breakpoint is not reached
1073
1074    >>> import asyncio
1075
1076    >>> async def test_coro():
1077    ...     print(0)
1078    ...     await asyncio.sleep(0)
1079    ...     print(1)
1080    ...     await asyncio.sleep(0)
1081    ...     print(2)
1082    ...     await asyncio.sleep(0)
1083    ...     print(3)
1084
1085    >>> async def test_main():
1086    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1087    ...     await test_coro()
1088
1089    >>> def test_function():
1090    ...     loop = asyncio.new_event_loop()
1091    ...     loop.run_until_complete(test_main())
1092    ...     loop.close()
1093    ...     asyncio.set_event_loop_policy(None)
1094    ...     print("finished")
1095
1096    >>> with PdbTestInput(['step',
1097    ...                    'until 8',
1098    ...                    'continue']):
1099    ...     test_function()
1100    > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
1101    -> await test_coro()
1102    (Pdb) step
1103    --Call--
1104    > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
1105    -> async def test_coro():
1106    (Pdb) until 8
1107    0
1108    1
1109    2
1110    > <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
1111    -> print(3)
1112    (Pdb) continue
1113    3
1114    finished
1115    """
1116
1117def test_pdb_next_command_in_generator_for_loop():
1118    """The next command on returning from a generator controlled by a for loop.
1119
1120    >>> def test_gen():
1121    ...     yield 0
1122    ...     return 1
1123
1124    >>> def test_function():
1125    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1126    ...     for i in test_gen():
1127    ...         print('value', i)
1128    ...     x = 123
1129
1130    >>> with PdbTestInput(['break test_gen',
1131    ...                    'continue',
1132    ...                    'next',
1133    ...                    'next',
1134    ...                    'next',
1135    ...                    'continue']):
1136    ...     test_function()
1137    > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1138    -> for i in test_gen():
1139    (Pdb) break test_gen
1140    Breakpoint 6 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:1
1141    (Pdb) continue
1142    > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
1143    -> yield 0
1144    (Pdb) next
1145    value 0
1146    > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
1147    -> return 1
1148    (Pdb) next
1149    Internal StopIteration: 1
1150    > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
1151    -> for i in test_gen():
1152    (Pdb) next
1153    > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
1154    -> x = 123
1155    (Pdb) continue
1156    """
1157
1158def test_pdb_next_command_subiterator():
1159    """The next command in a generator with a subiterator.
1160
1161    >>> def test_subgenerator():
1162    ...     yield 0
1163    ...     return 1
1164
1165    >>> def test_gen():
1166    ...     x = yield from test_subgenerator()
1167    ...     return x
1168
1169    >>> def test_function():
1170    ...     import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
1171    ...     for i in test_gen():
1172    ...         print('value', i)
1173    ...     x = 123
1174
1175    >>> with PdbTestInput(['step',
1176    ...                    'step',
1177    ...                    'next',
1178    ...                    'next',
1179    ...                    'next',
1180    ...                    'continue']):
1181    ...     test_function()
1182    > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1183    -> for i in test_gen():
1184    (Pdb) step
1185    --Call--
1186    > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
1187    -> def test_gen():
1188    (Pdb) step
1189    > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
1190    -> x = yield from test_subgenerator()
1191    (Pdb) next
1192    value 0
1193    > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
1194    -> return x
1195    (Pdb) next
1196    Internal StopIteration: 1
1197    > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
1198    -> for i in test_gen():
1199    (Pdb) next
1200    > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
1201    -> x = 123
1202    (Pdb) continue
1203    """
1204
1205def test_pdb_issue_20766():
1206    """Test for reference leaks when the SIGINT handler is set.
1207
1208    >>> def test_function():
1209    ...     i = 1
1210    ...     while i <= 2:
1211    ...         sess = pdb.Pdb()
1212    ...         sess.set_trace(sys._getframe())
1213    ...         print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1214    ...         i += 1
1215
1216    >>> with PdbTestInput(['continue',
1217    ...                    'continue']):
1218    ...     test_function()
1219    > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
1220    -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
1221    (Pdb) continue
1222    pdb 1: <built-in function default_int_handler>
1223    > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
1224    -> sess.set_trace(sys._getframe())
1225    (Pdb) continue
1226    pdb 2: <built-in function default_int_handler>
1227    """
1228
1229
1230class PdbTestCase(unittest.TestCase):
1231    def tearDown(self):
1232        support.unlink(support.TESTFN)
1233
1234    def _run_pdb(self, pdb_args, commands):
1235        self.addCleanup(support.rmtree, '__pycache__')
1236        cmd = [sys.executable, '-m', 'pdb'] + pdb_args
1237        with subprocess.Popen(
1238                cmd,
1239                stdout=subprocess.PIPE,
1240                stdin=subprocess.PIPE,
1241                stderr=subprocess.STDOUT,
1242                env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
1243        ) as proc:
1244            stdout, stderr = proc.communicate(str.encode(commands))
1245        stdout = stdout and bytes.decode(stdout)
1246        stderr = stderr and bytes.decode(stderr)
1247        return stdout, stderr
1248
1249    def run_pdb_script(self, script, commands):
1250        """Run 'script' lines with pdb and the pdb 'commands'."""
1251        filename = 'main.py'
1252        with open(filename, 'w') as f:
1253            f.write(textwrap.dedent(script))
1254        self.addCleanup(support.unlink, filename)
1255        return self._run_pdb([filename], commands)
1256
1257    def run_pdb_module(self, script, commands):
1258        """Runs the script code as part of a module"""
1259        self.module_name = 't_main'
1260        support.rmtree(self.module_name)
1261        main_file = self.module_name + '/__main__.py'
1262        init_file = self.module_name + '/__init__.py'
1263        os.mkdir(self.module_name)
1264        with open(init_file, 'w') as f:
1265            pass
1266        with open(main_file, 'w') as f:
1267            f.write(textwrap.dedent(script))
1268        self.addCleanup(support.rmtree, self.module_name)
1269        return self._run_pdb(['-m', self.module_name], commands)
1270
1271    def _assert_find_function(self, file_content, func_name, expected):
1272        with open(support.TESTFN, 'wb') as f:
1273            f.write(file_content)
1274
1275        expected = None if not expected else (
1276            expected[0], support.TESTFN, expected[1])
1277        self.assertEqual(
1278            expected, pdb.find_function(func_name, support.TESTFN))
1279
1280    def test_find_function_empty_file(self):
1281        self._assert_find_function(b'', 'foo', None)
1282
1283    def test_find_function_found(self):
1284        self._assert_find_function(
1285            """\
1286def foo():
1287    pass
1288
1289def bœr():
1290    pass
1291
1292def quux():
1293    pass
1294""".encode(),
1295            'bœr',
1296            ('bœr', 4),
1297        )
1298
1299    def test_find_function_found_with_encoding_cookie(self):
1300        self._assert_find_function(
1301            """\
1302# coding: iso-8859-15
1303def foo():
1304    pass
1305
1306def bœr():
1307    pass
1308
1309def quux():
1310    pass
1311""".encode('iso-8859-15'),
1312            'bœr',
1313            ('bœr', 5),
1314        )
1315
1316    def test_find_function_found_with_bom(self):
1317        self._assert_find_function(
1318            codecs.BOM_UTF8 + """\
1319def bœr():
1320    pass
1321""".encode(),
1322            'bœr',
1323            ('bœr', 1),
1324        )
1325
1326    def test_issue7964(self):
1327        # open the file as binary so we can force \r\n newline
1328        with open(support.TESTFN, 'wb') as f:
1329            f.write(b'print("testing my pdb")\r\n')
1330        cmd = [sys.executable, '-m', 'pdb', support.TESTFN]
1331        proc = subprocess.Popen(cmd,
1332            stdout=subprocess.PIPE,
1333            stdin=subprocess.PIPE,
1334            stderr=subprocess.STDOUT,
1335            )
1336        self.addCleanup(proc.stdout.close)
1337        stdout, stderr = proc.communicate(b'quit\n')
1338        self.assertNotIn(b'SyntaxError', stdout,
1339                         "Got a syntax error running test script under PDB")
1340
1341    def test_issue13183(self):
1342        script = """
1343            from bar import bar
1344
1345            def foo():
1346                bar()
1347
1348            def nope():
1349                pass
1350
1351            def foobar():
1352                foo()
1353                nope()
1354
1355            foobar()
1356        """
1357        commands = """
1358            from bar import bar
1359            break bar
1360            continue
1361            step
1362            step
1363            quit
1364        """
1365        bar = """
1366            def bar():
1367                pass
1368        """
1369        with open('bar.py', 'w') as f:
1370            f.write(textwrap.dedent(bar))
1371        self.addCleanup(support.unlink, 'bar.py')
1372        stdout, stderr = self.run_pdb_script(script, commands)
1373        self.assertTrue(
1374            any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
1375            'Fail to step into the caller after a return')
1376
1377    def test_issue13120(self):
1378        # Invoking "continue" on a non-main thread triggered an exception
1379        # inside signal.signal.
1380
1381        with open(support.TESTFN, 'wb') as f:
1382            f.write(textwrap.dedent("""
1383                import threading
1384                import pdb
1385
1386                def start_pdb():
1387                    pdb.Pdb(readrc=False).set_trace()
1388                    x = 1
1389                    y = 1
1390
1391                t = threading.Thread(target=start_pdb)
1392                t.start()""").encode('ascii'))
1393        cmd = [sys.executable, '-u', support.TESTFN]
1394        proc = subprocess.Popen(cmd,
1395            stdout=subprocess.PIPE,
1396            stdin=subprocess.PIPE,
1397            stderr=subprocess.STDOUT,
1398            env={**os.environ, 'PYTHONIOENCODING': 'utf-8'}
1399            )
1400        self.addCleanup(proc.stdout.close)
1401        stdout, stderr = proc.communicate(b'cont\n')
1402        self.assertNotIn(b'Error', stdout,
1403                         "Got an error running test script under PDB")
1404
1405    def test_issue36250(self):
1406
1407        with open(support.TESTFN, 'wb') as f:
1408            f.write(textwrap.dedent("""
1409                import threading
1410                import pdb
1411
1412                evt = threading.Event()
1413
1414                def start_pdb():
1415                    evt.wait()
1416                    pdb.Pdb(readrc=False).set_trace()
1417
1418                t = threading.Thread(target=start_pdb)
1419                t.start()
1420                pdb.Pdb(readrc=False).set_trace()
1421                evt.set()
1422                t.join()""").encode('ascii'))
1423        cmd = [sys.executable, '-u', support.TESTFN]
1424        proc = subprocess.Popen(cmd,
1425            stdout=subprocess.PIPE,
1426            stdin=subprocess.PIPE,
1427            stderr=subprocess.STDOUT,
1428            env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
1429            )
1430        self.addCleanup(proc.stdout.close)
1431        stdout, stderr = proc.communicate(b'cont\ncont\n')
1432        self.assertNotIn(b'Error', stdout,
1433                         "Got an error running test script under PDB")
1434
1435    def test_issue16180(self):
1436        # A syntax error in the debuggee.
1437        script = "def f: pass\n"
1438        commands = ''
1439        expected = "SyntaxError:"
1440        stdout, stderr = self.run_pdb_script(script, commands)
1441        self.assertIn(expected, stdout,
1442            '\n\nExpected:\n{}\nGot:\n{}\n'
1443            'Fail to handle a syntax error in the debuggee.'
1444            .format(expected, stdout))
1445
1446
1447    def test_readrc_kwarg(self):
1448        script = textwrap.dedent("""
1449            import pdb; pdb.Pdb(readrc=False).set_trace()
1450
1451            print('hello')
1452        """)
1453
1454        save_home = os.environ.pop('HOME', None)
1455        try:
1456            with support.temp_cwd():
1457                with open('.pdbrc', 'w') as f:
1458                    f.write("invalid\n")
1459
1460                with open('main.py', 'w') as f:
1461                    f.write(script)
1462
1463                cmd = [sys.executable, 'main.py']
1464                proc = subprocess.Popen(
1465                    cmd,
1466                    stdout=subprocess.PIPE,
1467                    stdin=subprocess.PIPE,
1468                    stderr=subprocess.PIPE,
1469                )
1470                with proc:
1471                    stdout, stderr = proc.communicate(b'q\n')
1472                    self.assertNotIn(b"NameError: name 'invalid' is not defined",
1473                                  stdout)
1474
1475        finally:
1476            if save_home is not None:
1477                os.environ['HOME'] = save_home
1478
1479    def test_readrc_homedir(self):
1480        save_home = os.environ.pop("HOME", None)
1481        with support.temp_dir() as temp_dir, patch("os.path.expanduser"):
1482            rc_path = os.path.join(temp_dir, ".pdbrc")
1483            os.path.expanduser.return_value = rc_path
1484            try:
1485                with open(rc_path, "w") as f:
1486                    f.write("invalid")
1487                self.assertEqual(pdb.Pdb().rcLines[0], "invalid")
1488            finally:
1489                if save_home is not None:
1490                    os.environ["HOME"] = save_home
1491
1492    def test_header(self):
1493        stdout = StringIO()
1494        header = 'Nobody expects... blah, blah, blah'
1495        with ExitStack() as resources:
1496            resources.enter_context(patch('sys.stdout', stdout))
1497            resources.enter_context(patch.object(pdb.Pdb, 'set_trace'))
1498            pdb.set_trace(header=header)
1499        self.assertEqual(stdout.getvalue(), header + '\n')
1500
1501    def test_run_module(self):
1502        script = """print("SUCCESS")"""
1503        commands = """
1504            continue
1505            quit
1506        """
1507        stdout, stderr = self.run_pdb_module(script, commands)
1508        self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1509
1510    def test_module_is_run_as_main(self):
1511        script = """
1512            if __name__ == '__main__':
1513                print("SUCCESS")
1514        """
1515        commands = """
1516            continue
1517            quit
1518        """
1519        stdout, stderr = self.run_pdb_module(script, commands)
1520        self.assertTrue(any("SUCCESS" in l for l in stdout.splitlines()), stdout)
1521
1522    def test_breakpoint(self):
1523        script = """
1524            if __name__ == '__main__':
1525                pass
1526                print("SUCCESS")
1527                pass
1528        """
1529        commands = """
1530            b 3
1531            quit
1532        """
1533        stdout, stderr = self.run_pdb_module(script, commands)
1534        self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
1535        self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)
1536
1537    def test_run_pdb_with_pdb(self):
1538        commands = """
1539            c
1540            quit
1541        """
1542        stdout, stderr = self._run_pdb(["-m", "pdb"], commands)
1543        self.assertIn(
1544            pdb._usage,
1545            stdout.replace('\r', '')  # remove \r for windows
1546        )
1547
1548    def test_module_without_a_main(self):
1549        module_name = 't_main'
1550        support.rmtree(module_name)
1551        init_file = module_name + '/__init__.py'
1552        os.mkdir(module_name)
1553        with open(init_file, 'w') as f:
1554            pass
1555        self.addCleanup(support.rmtree, module_name)
1556        stdout, stderr = self._run_pdb(['-m', module_name], "")
1557        self.assertIn("ImportError: No module named t_main.__main__",
1558                      stdout.splitlines())
1559
1560    def test_blocks_at_first_code_line(self):
1561        script = """
1562                #This is a comment, on line 2
1563
1564                print("SUCCESS")
1565        """
1566        commands = """
1567            quit
1568        """
1569        stdout, stderr = self.run_pdb_module(script, commands)
1570        self.assertTrue(any("__main__.py(4)<module>()"
1571                            in l for l in stdout.splitlines()), stdout)
1572
1573    def test_relative_imports(self):
1574        self.module_name = 't_main'
1575        support.rmtree(self.module_name)
1576        main_file = self.module_name + '/__main__.py'
1577        init_file = self.module_name + '/__init__.py'
1578        module_file = self.module_name + '/module.py'
1579        self.addCleanup(support.rmtree, self.module_name)
1580        os.mkdir(self.module_name)
1581        with open(init_file, 'w') as f:
1582            f.write(textwrap.dedent("""
1583                top_var = "VAR from top"
1584            """))
1585        with open(main_file, 'w') as f:
1586            f.write(textwrap.dedent("""
1587                from . import top_var
1588                from .module import var
1589                from . import module
1590                pass # We'll stop here and print the vars
1591            """))
1592        with open(module_file, 'w') as f:
1593            f.write(textwrap.dedent("""
1594                var = "VAR from module"
1595                var2 = "second var"
1596            """))
1597        commands = """
1598            b 5
1599            c
1600            p top_var
1601            p var
1602            p module.var2
1603            quit
1604        """
1605        stdout, _ = self._run_pdb(['-m', self.module_name], commands)
1606        self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1607        self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
1608        self.assertTrue(any("second var" in l for l in stdout.splitlines()))
1609
1610    def test_relative_imports_on_plain_module(self):
1611        # Validates running a plain module. See bpo32691
1612        self.module_name = 't_main'
1613        support.rmtree(self.module_name)
1614        main_file = self.module_name + '/runme.py'
1615        init_file = self.module_name + '/__init__.py'
1616        module_file = self.module_name + '/module.py'
1617        self.addCleanup(support.rmtree, self.module_name)
1618        os.mkdir(self.module_name)
1619        with open(init_file, 'w') as f:
1620            f.write(textwrap.dedent("""
1621                top_var = "VAR from top"
1622            """))
1623        with open(main_file, 'w') as f:
1624            f.write(textwrap.dedent("""
1625                from . import module
1626                pass # We'll stop here and print the vars
1627            """))
1628        with open(module_file, 'w') as f:
1629            f.write(textwrap.dedent("""
1630                var = "VAR from module"
1631            """))
1632        commands = """
1633            b 3
1634            c
1635            p module.var
1636            quit
1637        """
1638        stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1639        self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1640
1641    def test_errors_in_command(self):
1642        commands = "\n".join([
1643            'print(',
1644            'debug print(',
1645            'debug doesnotexist',
1646            'c',
1647        ])
1648        stdout, _ = self.run_pdb_script('', commands + '\n')
1649
1650        self.assertEqual(stdout.splitlines()[1:], [
1651            '(Pdb) *** SyntaxError: unexpected EOF while parsing',
1652
1653            '(Pdb) ENTERING RECURSIVE DEBUGGER',
1654            '*** SyntaxError: unexpected EOF while parsing',
1655            'LEAVING RECURSIVE DEBUGGER',
1656
1657            '(Pdb) ENTERING RECURSIVE DEBUGGER',
1658            '> <string>(1)<module>()',
1659            "((Pdb)) *** NameError: name 'doesnotexist' is not defined",
1660            'LEAVING RECURSIVE DEBUGGER',
1661            '(Pdb) ',
1662        ])
1663
1664def load_tests(*args):
1665    from test import test_pdb
1666    suites = [
1667        unittest.makeSuite(PdbTestCase),
1668        doctest.DocTestSuite(test_pdb)
1669    ]
1670    return unittest.TestSuite(suites)
1671
1672
1673if __name__ == '__main__':
1674    unittest.main()
1675