test_pdb.py 70 KB

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