test_doctest.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194
  1. """
  2. Test script for doctest.
  3. """
  4. from test import support
  5. from test.support import import_helper
  6. from test.support import os_helper
  7. import doctest
  8. import functools
  9. import os
  10. import sys
  11. import importlib
  12. import importlib.abc
  13. import importlib.util
  14. import unittest
  15. import tempfile
  16. import shutil
  17. import types
  18. import contextlib
  19. if not support.has_subprocess_support:
  20. raise unittest.SkipTest("test_CLI requires subprocess support.")
  21. # NOTE: There are some additional tests relating to interaction with
  22. # zipimport in the test_zipimport_support test module.
  23. # There are also related tests in `test_doctest2` module.
  24. ######################################################################
  25. ## Sample Objects (used by test cases)
  26. ######################################################################
  27. def sample_func(v):
  28. """
  29. Blah blah
  30. >>> print(sample_func(22))
  31. 44
  32. Yee ha!
  33. """
  34. return v+v
  35. class SampleClass:
  36. """
  37. >>> print(1)
  38. 1
  39. >>> # comments get ignored. so are empty PS1 and PS2 prompts:
  40. >>>
  41. ...
  42. Multiline example:
  43. >>> sc = SampleClass(3)
  44. >>> for i in range(10):
  45. ... sc = sc.double()
  46. ... print(' ', sc.get(), sep='', end='')
  47. 6 12 24 48 96 192 384 768 1536 3072
  48. """
  49. def __init__(self, val):
  50. """
  51. >>> print(SampleClass(12).get())
  52. 12
  53. """
  54. self.val = val
  55. def double(self):
  56. """
  57. >>> print(SampleClass(12).double().get())
  58. 24
  59. """
  60. return SampleClass(self.val + self.val)
  61. def get(self):
  62. """
  63. >>> print(SampleClass(-5).get())
  64. -5
  65. """
  66. return self.val
  67. def a_staticmethod(v):
  68. """
  69. >>> print(SampleClass.a_staticmethod(10))
  70. 11
  71. """
  72. return v+1
  73. a_staticmethod = staticmethod(a_staticmethod)
  74. def a_classmethod(cls, v):
  75. """
  76. >>> print(SampleClass.a_classmethod(10))
  77. 12
  78. >>> print(SampleClass(0).a_classmethod(10))
  79. 12
  80. """
  81. return v+2
  82. a_classmethod = classmethod(a_classmethod)
  83. a_property = property(get, doc="""
  84. >>> print(SampleClass(22).a_property)
  85. 22
  86. """)
  87. a_class_attribute = 42
  88. @classmethod
  89. @property
  90. def a_classmethod_property(cls):
  91. """
  92. >>> print(SampleClass.a_classmethod_property)
  93. 42
  94. """
  95. return cls.a_class_attribute
  96. class NestedClass:
  97. """
  98. >>> x = SampleClass.NestedClass(5)
  99. >>> y = x.square()
  100. >>> print(y.get())
  101. 25
  102. """
  103. def __init__(self, val=0):
  104. """
  105. >>> print(SampleClass.NestedClass().get())
  106. 0
  107. """
  108. self.val = val
  109. def square(self):
  110. return SampleClass.NestedClass(self.val*self.val)
  111. def get(self):
  112. return self.val
  113. class SampleNewStyleClass(object):
  114. r"""
  115. >>> print('1\n2\n3')
  116. 1
  117. 2
  118. 3
  119. """
  120. def __init__(self, val):
  121. """
  122. >>> print(SampleNewStyleClass(12).get())
  123. 12
  124. """
  125. self.val = val
  126. def double(self):
  127. """
  128. >>> print(SampleNewStyleClass(12).double().get())
  129. 24
  130. """
  131. return SampleNewStyleClass(self.val + self.val)
  132. def get(self):
  133. """
  134. >>> print(SampleNewStyleClass(-5).get())
  135. -5
  136. """
  137. return self.val
  138. ######################################################################
  139. ## Fake stdin (for testing interactive debugging)
  140. ######################################################################
  141. class _FakeInput:
  142. """
  143. A fake input stream for pdb's interactive debugger. Whenever a
  144. line is read, print it (to simulate the user typing it), and then
  145. return it. The set of lines to return is specified in the
  146. constructor; they should not have trailing newlines.
  147. """
  148. def __init__(self, lines):
  149. self.lines = lines
  150. def readline(self):
  151. line = self.lines.pop(0)
  152. print(line)
  153. return line+'\n'
  154. ######################################################################
  155. ## Test Cases
  156. ######################################################################
  157. def test_Example(): r"""
  158. Unit tests for the `Example` class.
  159. Example is a simple container class that holds:
  160. - `source`: A source string.
  161. - `want`: An expected output string.
  162. - `exc_msg`: An expected exception message string (or None if no
  163. exception is expected).
  164. - `lineno`: A line number (within the docstring).
  165. - `indent`: The example's indentation in the input string.
  166. - `options`: An option dictionary, mapping option flags to True or
  167. False.
  168. These attributes are set by the constructor. `source` and `want` are
  169. required; the other attributes all have default values:
  170. >>> example = doctest.Example('print(1)', '1\n')
  171. >>> (example.source, example.want, example.exc_msg,
  172. ... example.lineno, example.indent, example.options)
  173. ('print(1)\n', '1\n', None, 0, 0, {})
  174. The first three attributes (`source`, `want`, and `exc_msg`) may be
  175. specified positionally; the remaining arguments should be specified as
  176. keyword arguments:
  177. >>> exc_msg = 'IndexError: pop from an empty list'
  178. >>> example = doctest.Example('[].pop()', '', exc_msg,
  179. ... lineno=5, indent=4,
  180. ... options={doctest.ELLIPSIS: True})
  181. >>> (example.source, example.want, example.exc_msg,
  182. ... example.lineno, example.indent, example.options)
  183. ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
  184. The constructor normalizes the `source` string to end in a newline:
  185. Source spans a single line: no terminating newline.
  186. >>> e = doctest.Example('print(1)', '1\n')
  187. >>> e.source, e.want
  188. ('print(1)\n', '1\n')
  189. >>> e = doctest.Example('print(1)\n', '1\n')
  190. >>> e.source, e.want
  191. ('print(1)\n', '1\n')
  192. Source spans multiple lines: require terminating newline.
  193. >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
  194. >>> e.source, e.want
  195. ('print(1);\nprint(2)\n', '1\n2\n')
  196. >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
  197. >>> e.source, e.want
  198. ('print(1);\nprint(2)\n', '1\n2\n')
  199. Empty source string (which should never appear in real examples)
  200. >>> e = doctest.Example('', '')
  201. >>> e.source, e.want
  202. ('\n', '')
  203. The constructor normalizes the `want` string to end in a newline,
  204. unless it's the empty string:
  205. >>> e = doctest.Example('print(1)', '1\n')
  206. >>> e.source, e.want
  207. ('print(1)\n', '1\n')
  208. >>> e = doctest.Example('print(1)', '1')
  209. >>> e.source, e.want
  210. ('print(1)\n', '1\n')
  211. >>> e = doctest.Example('print', '')
  212. >>> e.source, e.want
  213. ('print\n', '')
  214. The constructor normalizes the `exc_msg` string to end in a newline,
  215. unless it's `None`:
  216. Message spans one line
  217. >>> exc_msg = 'IndexError: pop from an empty list'
  218. >>> e = doctest.Example('[].pop()', '', exc_msg)
  219. >>> e.exc_msg
  220. 'IndexError: pop from an empty list\n'
  221. >>> exc_msg = 'IndexError: pop from an empty list\n'
  222. >>> e = doctest.Example('[].pop()', '', exc_msg)
  223. >>> e.exc_msg
  224. 'IndexError: pop from an empty list\n'
  225. Message spans multiple lines
  226. >>> exc_msg = 'ValueError: 1\n 2'
  227. >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
  228. >>> e.exc_msg
  229. 'ValueError: 1\n 2\n'
  230. >>> exc_msg = 'ValueError: 1\n 2\n'
  231. >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
  232. >>> e.exc_msg
  233. 'ValueError: 1\n 2\n'
  234. Empty (but non-None) exception message (which should never appear
  235. in real examples)
  236. >>> exc_msg = ''
  237. >>> e = doctest.Example('raise X()', '', exc_msg)
  238. >>> e.exc_msg
  239. '\n'
  240. Compare `Example`:
  241. >>> example = doctest.Example('print 1', '1\n')
  242. >>> same_example = doctest.Example('print 1', '1\n')
  243. >>> other_example = doctest.Example('print 42', '42\n')
  244. >>> example == same_example
  245. True
  246. >>> example != same_example
  247. False
  248. >>> hash(example) == hash(same_example)
  249. True
  250. >>> example == other_example
  251. False
  252. >>> example != other_example
  253. True
  254. """
  255. def test_DocTest(): r"""
  256. Unit tests for the `DocTest` class.
  257. DocTest is a collection of examples, extracted from a docstring, along
  258. with information about where the docstring comes from (a name,
  259. filename, and line number). The docstring is parsed by the `DocTest`
  260. constructor:
  261. >>> docstring = '''
  262. ... >>> print(12)
  263. ... 12
  264. ...
  265. ... Non-example text.
  266. ...
  267. ... >>> print('another\\example')
  268. ... another
  269. ... example
  270. ... '''
  271. >>> globs = {} # globals to run the test in.
  272. >>> parser = doctest.DocTestParser()
  273. >>> test = parser.get_doctest(docstring, globs, 'some_test',
  274. ... 'some_file', 20)
  275. >>> print(test)
  276. <DocTest some_test from some_file:20 (2 examples)>
  277. >>> len(test.examples)
  278. 2
  279. >>> e1, e2 = test.examples
  280. >>> (e1.source, e1.want, e1.lineno)
  281. ('print(12)\n', '12\n', 1)
  282. >>> (e2.source, e2.want, e2.lineno)
  283. ("print('another\\example')\n", 'another\nexample\n', 6)
  284. Source information (name, filename, and line number) is available as
  285. attributes on the doctest object:
  286. >>> (test.name, test.filename, test.lineno)
  287. ('some_test', 'some_file', 20)
  288. The line number of an example within its containing file is found by
  289. adding the line number of the example and the line number of its
  290. containing test:
  291. >>> test.lineno + e1.lineno
  292. 21
  293. >>> test.lineno + e2.lineno
  294. 26
  295. If the docstring contains inconsistent leading whitespace in the
  296. expected output of an example, then `DocTest` will raise a ValueError:
  297. >>> docstring = r'''
  298. ... >>> print('bad\nindentation')
  299. ... bad
  300. ... indentation
  301. ... '''
  302. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  303. Traceback (most recent call last):
  304. ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
  305. If the docstring contains inconsistent leading whitespace on
  306. continuation lines, then `DocTest` will raise a ValueError:
  307. >>> docstring = r'''
  308. ... >>> print(('bad indentation',
  309. ... ... 2))
  310. ... ('bad', 'indentation')
  311. ... '''
  312. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  313. Traceback (most recent call last):
  314. ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
  315. If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
  316. will raise a ValueError:
  317. >>> docstring = '>>>print(1)\n1'
  318. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  319. Traceback (most recent call last):
  320. ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
  321. If there's no blank space after a PS2 prompt ('...'), then `DocTest`
  322. will raise a ValueError:
  323. >>> docstring = '>>> if 1:\n...print(1)\n1'
  324. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  325. Traceback (most recent call last):
  326. ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
  327. Compare `DocTest`:
  328. >>> docstring = '''
  329. ... >>> print 12
  330. ... 12
  331. ... '''
  332. >>> test = parser.get_doctest(docstring, globs, 'some_test',
  333. ... 'some_test', 20)
  334. >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
  335. ... 'some_test', 20)
  336. >>> test == same_test
  337. True
  338. >>> test != same_test
  339. False
  340. >>> hash(test) == hash(same_test)
  341. True
  342. >>> docstring = '''
  343. ... >>> print 42
  344. ... 42
  345. ... '''
  346. >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
  347. ... 'other_file', 10)
  348. >>> test == other_test
  349. False
  350. >>> test != other_test
  351. True
  352. Compare `DocTestCase`:
  353. >>> DocTestCase = doctest.DocTestCase
  354. >>> test_case = DocTestCase(test)
  355. >>> same_test_case = DocTestCase(same_test)
  356. >>> other_test_case = DocTestCase(other_test)
  357. >>> test_case == same_test_case
  358. True
  359. >>> test_case != same_test_case
  360. False
  361. >>> hash(test_case) == hash(same_test_case)
  362. True
  363. >>> test == other_test_case
  364. False
  365. >>> test != other_test_case
  366. True
  367. """
  368. class test_DocTestFinder:
  369. def basics(): r"""
  370. Unit tests for the `DocTestFinder` class.
  371. DocTestFinder is used to extract DocTests from an object's docstring
  372. and the docstrings of its contained objects. It can be used with
  373. modules, functions, classes, methods, staticmethods, classmethods, and
  374. properties.
  375. Finding Tests in Functions
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. For a function whose docstring contains examples, DocTestFinder.find()
  378. will return a single test (for that function's docstring):
  379. >>> finder = doctest.DocTestFinder()
  380. We'll simulate a __file__ attr that ends in pyc:
  381. >>> import test.test_doctest
  382. >>> old = test.test_doctest.__file__
  383. >>> test.test_doctest.__file__ = 'test_doctest.pyc'
  384. >>> tests = finder.find(sample_func)
  385. >>> print(tests) # doctest: +ELLIPSIS
  386. [<DocTest sample_func from test_doctest.py:34 (1 example)>]
  387. The exact name depends on how test_doctest was invoked, so allow for
  388. leading path components.
  389. >>> tests[0].filename # doctest: +ELLIPSIS
  390. '...test_doctest.py'
  391. >>> test.test_doctest.__file__ = old
  392. >>> e = tests[0].examples[0]
  393. >>> (e.source, e.want, e.lineno)
  394. ('print(sample_func(22))\n', '44\n', 3)
  395. By default, tests are created for objects with no docstring:
  396. >>> def no_docstring(v):
  397. ... pass
  398. >>> finder.find(no_docstring)
  399. []
  400. However, the optional argument `exclude_empty` to the DocTestFinder
  401. constructor can be used to exclude tests for objects with empty
  402. docstrings:
  403. >>> def no_docstring(v):
  404. ... pass
  405. >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
  406. >>> excl_empty_finder.find(no_docstring)
  407. []
  408. If the function has a docstring with no examples, then a test with no
  409. examples is returned. (This lets `DocTestRunner` collect statistics
  410. about which functions have no tests -- but is that useful? And should
  411. an empty test also be created when there's no docstring?)
  412. >>> def no_examples(v):
  413. ... ''' no doctest examples '''
  414. >>> finder.find(no_examples) # doctest: +ELLIPSIS
  415. [<DocTest no_examples from ...:1 (no examples)>]
  416. Finding Tests in Classes
  417. ~~~~~~~~~~~~~~~~~~~~~~~~
  418. For a class, DocTestFinder will create a test for the class's
  419. docstring, and will recursively explore its contents, including
  420. methods, classmethods, staticmethods, properties, and nested classes.
  421. >>> finder = doctest.DocTestFinder()
  422. >>> tests = finder.find(SampleClass)
  423. >>> for t in tests:
  424. ... print('%2s %s' % (len(t.examples), t.name))
  425. 3 SampleClass
  426. 3 SampleClass.NestedClass
  427. 1 SampleClass.NestedClass.__init__
  428. 1 SampleClass.__init__
  429. 2 SampleClass.a_classmethod
  430. 1 SampleClass.a_classmethod_property
  431. 1 SampleClass.a_property
  432. 1 SampleClass.a_staticmethod
  433. 1 SampleClass.double
  434. 1 SampleClass.get
  435. New-style classes are also supported:
  436. >>> tests = finder.find(SampleNewStyleClass)
  437. >>> for t in tests:
  438. ... print('%2s %s' % (len(t.examples), t.name))
  439. 1 SampleNewStyleClass
  440. 1 SampleNewStyleClass.__init__
  441. 1 SampleNewStyleClass.double
  442. 1 SampleNewStyleClass.get
  443. Finding Tests in Modules
  444. ~~~~~~~~~~~~~~~~~~~~~~~~
  445. For a module, DocTestFinder will create a test for the class's
  446. docstring, and will recursively explore its contents, including
  447. functions, classes, and the `__test__` dictionary, if it exists:
  448. >>> # A module
  449. >>> import types
  450. >>> m = types.ModuleType('some_module')
  451. >>> def triple(val):
  452. ... '''
  453. ... >>> print(triple(11))
  454. ... 33
  455. ... '''
  456. ... return val*3
  457. >>> m.__dict__.update({
  458. ... 'sample_func': sample_func,
  459. ... 'SampleClass': SampleClass,
  460. ... '__doc__': '''
  461. ... Module docstring.
  462. ... >>> print('module')
  463. ... module
  464. ... ''',
  465. ... '__test__': {
  466. ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
  467. ... 'c': triple}})
  468. >>> finder = doctest.DocTestFinder()
  469. >>> # Use module=test.test_doctest, to prevent doctest from
  470. >>> # ignoring the objects since they weren't defined in m.
  471. >>> import test.test_doctest
  472. >>> tests = finder.find(m, module=test.test_doctest)
  473. >>> for t in tests:
  474. ... print('%2s %s' % (len(t.examples), t.name))
  475. 1 some_module
  476. 3 some_module.SampleClass
  477. 3 some_module.SampleClass.NestedClass
  478. 1 some_module.SampleClass.NestedClass.__init__
  479. 1 some_module.SampleClass.__init__
  480. 2 some_module.SampleClass.a_classmethod
  481. 1 some_module.SampleClass.a_classmethod_property
  482. 1 some_module.SampleClass.a_property
  483. 1 some_module.SampleClass.a_staticmethod
  484. 1 some_module.SampleClass.double
  485. 1 some_module.SampleClass.get
  486. 1 some_module.__test__.c
  487. 2 some_module.__test__.d
  488. 1 some_module.sample_func
  489. Duplicate Removal
  490. ~~~~~~~~~~~~~~~~~
  491. If a single object is listed twice (under different names), then tests
  492. will only be generated for it once:
  493. >>> from test import doctest_aliases
  494. >>> assert doctest_aliases.TwoNames.f
  495. >>> assert doctest_aliases.TwoNames.g
  496. >>> tests = excl_empty_finder.find(doctest_aliases)
  497. >>> print(len(tests))
  498. 2
  499. >>> print(tests[0].name)
  500. test.doctest_aliases.TwoNames
  501. TwoNames.f and TwoNames.g are bound to the same object.
  502. We can't guess which will be found in doctest's traversal of
  503. TwoNames.__dict__ first, so we have to allow for either.
  504. >>> tests[1].name.split('.')[-1] in ['f', 'g']
  505. True
  506. Empty Tests
  507. ~~~~~~~~~~~
  508. By default, an object with no doctests doesn't create any tests:
  509. >>> tests = doctest.DocTestFinder().find(SampleClass)
  510. >>> for t in tests:
  511. ... print('%2s %s' % (len(t.examples), t.name))
  512. 3 SampleClass
  513. 3 SampleClass.NestedClass
  514. 1 SampleClass.NestedClass.__init__
  515. 1 SampleClass.__init__
  516. 2 SampleClass.a_classmethod
  517. 1 SampleClass.a_classmethod_property
  518. 1 SampleClass.a_property
  519. 1 SampleClass.a_staticmethod
  520. 1 SampleClass.double
  521. 1 SampleClass.get
  522. By default, that excluded objects with no doctests. exclude_empty=False
  523. tells it to include (empty) tests for objects with no doctests. This feature
  524. is really to support backward compatibility in what doctest.master.summarize()
  525. displays.
  526. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
  527. >>> for t in tests:
  528. ... print('%2s %s' % (len(t.examples), t.name))
  529. 3 SampleClass
  530. 3 SampleClass.NestedClass
  531. 1 SampleClass.NestedClass.__init__
  532. 0 SampleClass.NestedClass.get
  533. 0 SampleClass.NestedClass.square
  534. 1 SampleClass.__init__
  535. 2 SampleClass.a_classmethod
  536. 1 SampleClass.a_classmethod_property
  537. 1 SampleClass.a_property
  538. 1 SampleClass.a_staticmethod
  539. 1 SampleClass.double
  540. 1 SampleClass.get
  541. When used with `exclude_empty=False` we are also interested in line numbers
  542. of doctests that are empty.
  543. It used to be broken for quite some time until `bpo-28249`.
  544. >>> from test import doctest_lineno
  545. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(doctest_lineno)
  546. >>> for t in tests:
  547. ... print('%5s %s' % (t.lineno, t.name))
  548. None test.doctest_lineno
  549. 22 test.doctest_lineno.ClassWithDocstring
  550. 30 test.doctest_lineno.ClassWithDoctest
  551. None test.doctest_lineno.ClassWithoutDocstring
  552. None test.doctest_lineno.MethodWrapper
  553. 39 test.doctest_lineno.MethodWrapper.method_with_docstring
  554. 45 test.doctest_lineno.MethodWrapper.method_with_doctest
  555. None test.doctest_lineno.MethodWrapper.method_without_docstring
  556. 4 test.doctest_lineno.func_with_docstring
  557. 12 test.doctest_lineno.func_with_doctest
  558. None test.doctest_lineno.func_without_docstring
  559. Turning off Recursion
  560. ~~~~~~~~~~~~~~~~~~~~~
  561. DocTestFinder can be told not to look for tests in contained objects
  562. using the `recurse` flag:
  563. >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
  564. >>> for t in tests:
  565. ... print('%2s %s' % (len(t.examples), t.name))
  566. 3 SampleClass
  567. Line numbers
  568. ~~~~~~~~~~~~
  569. DocTestFinder finds the line number of each example:
  570. >>> def f(x):
  571. ... '''
  572. ... >>> x = 12
  573. ...
  574. ... some text
  575. ...
  576. ... >>> # examples are not created for comments & bare prompts.
  577. ... >>>
  578. ... ...
  579. ...
  580. ... >>> for x in range(10):
  581. ... ... print(x, end=' ')
  582. ... 0 1 2 3 4 5 6 7 8 9
  583. ... >>> x//2
  584. ... 6
  585. ... '''
  586. >>> test = doctest.DocTestFinder().find(f)[0]
  587. >>> [e.lineno for e in test.examples]
  588. [1, 9, 12]
  589. """
  590. if int.__doc__: # simple check for --without-doc-strings, skip if lacking
  591. def non_Python_modules(): r"""
  592. Finding Doctests in Modules Not Written in Python
  593. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  594. DocTestFinder can also find doctests in most modules not written in Python.
  595. We'll use builtins as an example, since it almost certainly isn't written in
  596. plain ol' Python and is guaranteed to be available.
  597. >>> import builtins
  598. >>> tests = doctest.DocTestFinder().find(builtins)
  599. >>> 825 < len(tests) < 845 # approximate number of objects with docstrings
  600. True
  601. >>> real_tests = [t for t in tests if len(t.examples) > 0]
  602. >>> len(real_tests) # objects that actually have doctests
  603. 14
  604. >>> for t in real_tests:
  605. ... print('{} {}'.format(len(t.examples), t.name))
  606. ...
  607. 1 builtins.bin
  608. 5 builtins.bytearray.hex
  609. 5 builtins.bytes.hex
  610. 3 builtins.float.as_integer_ratio
  611. 2 builtins.float.fromhex
  612. 2 builtins.float.hex
  613. 1 builtins.hex
  614. 1 builtins.int
  615. 3 builtins.int.as_integer_ratio
  616. 2 builtins.int.bit_count
  617. 2 builtins.int.bit_length
  618. 5 builtins.memoryview.hex
  619. 1 builtins.oct
  620. 1 builtins.zip
  621. Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio',
  622. 'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod,
  623. and 'int' is a type.
  624. """
  625. class TestDocTestFinder(unittest.TestCase):
  626. def test_issue35753(self):
  627. # This import of `call` should trigger issue35753 when
  628. # `support.run_doctest` is called due to unwrap failing,
  629. # however with a patched doctest this should succeed.
  630. from unittest.mock import call
  631. dummy_module = types.ModuleType("dummy")
  632. dummy_module.__dict__['inject_call'] = call
  633. try:
  634. support.run_doctest(dummy_module, verbosity=True)
  635. except ValueError as e:
  636. raise support.TestFailed("Doctest unwrap failed") from e
  637. def test_empty_namespace_package(self):
  638. pkg_name = 'doctest_empty_pkg'
  639. with tempfile.TemporaryDirectory() as parent_dir:
  640. pkg_dir = os.path.join(parent_dir, pkg_name)
  641. os.mkdir(pkg_dir)
  642. sys.path.append(parent_dir)
  643. try:
  644. mod = importlib.import_module(pkg_name)
  645. finally:
  646. import_helper.forget(pkg_name)
  647. sys.path.pop()
  648. include_empty_finder = doctest.DocTestFinder(exclude_empty=False)
  649. exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True)
  650. self.assertEqual(len(include_empty_finder.find(mod)), 1)
  651. self.assertEqual(len(exclude_empty_finder.find(mod)), 0)
  652. def test_DocTestParser(): r"""
  653. Unit tests for the `DocTestParser` class.
  654. DocTestParser is used to parse docstrings containing doctest examples.
  655. The `parse` method divides a docstring into examples and intervening
  656. text:
  657. >>> s = '''
  658. ... >>> x, y = 2, 3 # no output expected
  659. ... >>> if 1:
  660. ... ... print(x)
  661. ... ... print(y)
  662. ... 2
  663. ... 3
  664. ...
  665. ... Some text.
  666. ... >>> x+y
  667. ... 5
  668. ... '''
  669. >>> parser = doctest.DocTestParser()
  670. >>> for piece in parser.parse(s):
  671. ... if isinstance(piece, doctest.Example):
  672. ... print('Example:', (piece.source, piece.want, piece.lineno))
  673. ... else:
  674. ... print(' Text:', repr(piece))
  675. Text: '\n'
  676. Example: ('x, y = 2, 3 # no output expected\n', '', 1)
  677. Text: ''
  678. Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
  679. Text: '\nSome text.\n'
  680. Example: ('x+y\n', '5\n', 9)
  681. Text: ''
  682. The `get_examples` method returns just the examples:
  683. >>> for piece in parser.get_examples(s):
  684. ... print((piece.source, piece.want, piece.lineno))
  685. ('x, y = 2, 3 # no output expected\n', '', 1)
  686. ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
  687. ('x+y\n', '5\n', 9)
  688. The `get_doctest` method creates a Test from the examples, along with the
  689. given arguments:
  690. >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
  691. >>> (test.name, test.filename, test.lineno)
  692. ('name', 'filename', 5)
  693. >>> for piece in test.examples:
  694. ... print((piece.source, piece.want, piece.lineno))
  695. ('x, y = 2, 3 # no output expected\n', '', 1)
  696. ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
  697. ('x+y\n', '5\n', 9)
  698. """
  699. class test_DocTestRunner:
  700. def basics(): r"""
  701. Unit tests for the `DocTestRunner` class.
  702. DocTestRunner is used to run DocTest test cases, and to accumulate
  703. statistics. Here's a simple DocTest case we can use:
  704. >>> def f(x):
  705. ... '''
  706. ... >>> x = 12
  707. ... >>> print(x)
  708. ... 12
  709. ... >>> x//2
  710. ... 6
  711. ... '''
  712. >>> test = doctest.DocTestFinder().find(f)[0]
  713. The main DocTestRunner interface is the `run` method, which runs a
  714. given DocTest case in a given namespace (globs). It returns a tuple
  715. `(f,t)`, where `f` is the number of failed tests and `t` is the number
  716. of tried tests.
  717. >>> doctest.DocTestRunner(verbose=False).run(test)
  718. TestResults(failed=0, attempted=3)
  719. If any example produces incorrect output, then the test runner reports
  720. the failure and proceeds to the next example:
  721. >>> def f(x):
  722. ... '''
  723. ... >>> x = 12
  724. ... >>> print(x)
  725. ... 14
  726. ... >>> x//2
  727. ... 6
  728. ... '''
  729. >>> test = doctest.DocTestFinder().find(f)[0]
  730. >>> doctest.DocTestRunner(verbose=True).run(test)
  731. ... # doctest: +ELLIPSIS
  732. Trying:
  733. x = 12
  734. Expecting nothing
  735. ok
  736. Trying:
  737. print(x)
  738. Expecting:
  739. 14
  740. **********************************************************************
  741. File ..., line 4, in f
  742. Failed example:
  743. print(x)
  744. Expected:
  745. 14
  746. Got:
  747. 12
  748. Trying:
  749. x//2
  750. Expecting:
  751. 6
  752. ok
  753. TestResults(failed=1, attempted=3)
  754. """
  755. def verbose_flag(): r"""
  756. The `verbose` flag makes the test runner generate more detailed
  757. output:
  758. >>> def f(x):
  759. ... '''
  760. ... >>> x = 12
  761. ... >>> print(x)
  762. ... 12
  763. ... >>> x//2
  764. ... 6
  765. ... '''
  766. >>> test = doctest.DocTestFinder().find(f)[0]
  767. >>> doctest.DocTestRunner(verbose=True).run(test)
  768. Trying:
  769. x = 12
  770. Expecting nothing
  771. ok
  772. Trying:
  773. print(x)
  774. Expecting:
  775. 12
  776. ok
  777. Trying:
  778. x//2
  779. Expecting:
  780. 6
  781. ok
  782. TestResults(failed=0, attempted=3)
  783. If the `verbose` flag is unspecified, then the output will be verbose
  784. iff `-v` appears in sys.argv:
  785. >>> # Save the real sys.argv list.
  786. >>> old_argv = sys.argv
  787. >>> # If -v does not appear in sys.argv, then output isn't verbose.
  788. >>> sys.argv = ['test']
  789. >>> doctest.DocTestRunner().run(test)
  790. TestResults(failed=0, attempted=3)
  791. >>> # If -v does appear in sys.argv, then output is verbose.
  792. >>> sys.argv = ['test', '-v']
  793. >>> doctest.DocTestRunner().run(test)
  794. Trying:
  795. x = 12
  796. Expecting nothing
  797. ok
  798. Trying:
  799. print(x)
  800. Expecting:
  801. 12
  802. ok
  803. Trying:
  804. x//2
  805. Expecting:
  806. 6
  807. ok
  808. TestResults(failed=0, attempted=3)
  809. >>> # Restore sys.argv
  810. >>> sys.argv = old_argv
  811. In the remaining examples, the test runner's verbosity will be
  812. explicitly set, to ensure that the test behavior is consistent.
  813. """
  814. def exceptions(): r"""
  815. Tests of `DocTestRunner`'s exception handling.
  816. An expected exception is specified with a traceback message. The
  817. lines between the first line and the type/value may be omitted or
  818. replaced with any other string:
  819. >>> def f(x):
  820. ... '''
  821. ... >>> x = 12
  822. ... >>> print(x//0)
  823. ... Traceback (most recent call last):
  824. ... ZeroDivisionError: integer division or modulo by zero
  825. ... '''
  826. >>> test = doctest.DocTestFinder().find(f)[0]
  827. >>> doctest.DocTestRunner(verbose=False).run(test)
  828. TestResults(failed=0, attempted=2)
  829. An example may not generate output before it raises an exception; if
  830. it does, then the traceback message will not be recognized as
  831. signaling an expected exception, so the example will be reported as an
  832. unexpected exception:
  833. >>> def f(x):
  834. ... '''
  835. ... >>> x = 12
  836. ... >>> print('pre-exception output', x//0)
  837. ... pre-exception output
  838. ... Traceback (most recent call last):
  839. ... ZeroDivisionError: integer division or modulo by zero
  840. ... '''
  841. >>> test = doctest.DocTestFinder().find(f)[0]
  842. >>> doctest.DocTestRunner(verbose=False).run(test)
  843. ... # doctest: +ELLIPSIS
  844. **********************************************************************
  845. File ..., line 4, in f
  846. Failed example:
  847. print('pre-exception output', x//0)
  848. Exception raised:
  849. ...
  850. ZeroDivisionError: integer division or modulo by zero
  851. TestResults(failed=1, attempted=2)
  852. Exception messages may contain newlines:
  853. >>> def f(x):
  854. ... r'''
  855. ... >>> raise ValueError('multi\nline\nmessage')
  856. ... Traceback (most recent call last):
  857. ... ValueError: multi
  858. ... line
  859. ... message
  860. ... '''
  861. >>> test = doctest.DocTestFinder().find(f)[0]
  862. >>> doctest.DocTestRunner(verbose=False).run(test)
  863. TestResults(failed=0, attempted=1)
  864. If an exception is expected, but an exception with the wrong type or
  865. message is raised, then it is reported as a failure:
  866. >>> def f(x):
  867. ... r'''
  868. ... >>> raise ValueError('message')
  869. ... Traceback (most recent call last):
  870. ... ValueError: wrong message
  871. ... '''
  872. >>> test = doctest.DocTestFinder().find(f)[0]
  873. >>> doctest.DocTestRunner(verbose=False).run(test)
  874. ... # doctest: +ELLIPSIS
  875. **********************************************************************
  876. File ..., line 3, in f
  877. Failed example:
  878. raise ValueError('message')
  879. Expected:
  880. Traceback (most recent call last):
  881. ValueError: wrong message
  882. Got:
  883. Traceback (most recent call last):
  884. ...
  885. ValueError: message
  886. TestResults(failed=1, attempted=1)
  887. However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
  888. detail:
  889. >>> def f(x):
  890. ... r'''
  891. ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  892. ... Traceback (most recent call last):
  893. ... ValueError: wrong message
  894. ... '''
  895. >>> test = doctest.DocTestFinder().find(f)[0]
  896. >>> doctest.DocTestRunner(verbose=False).run(test)
  897. TestResults(failed=0, attempted=1)
  898. IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
  899. between Python versions. For example, in Python 2.x, the module path of
  900. the exception is not in the output, but this will fail under Python 3:
  901. >>> def f(x):
  902. ... r'''
  903. ... >>> from http.client import HTTPException
  904. ... >>> raise HTTPException('message')
  905. ... Traceback (most recent call last):
  906. ... HTTPException: message
  907. ... '''
  908. >>> test = doctest.DocTestFinder().find(f)[0]
  909. >>> doctest.DocTestRunner(verbose=False).run(test)
  910. ... # doctest: +ELLIPSIS
  911. **********************************************************************
  912. File ..., line 4, in f
  913. Failed example:
  914. raise HTTPException('message')
  915. Expected:
  916. Traceback (most recent call last):
  917. HTTPException: message
  918. Got:
  919. Traceback (most recent call last):
  920. ...
  921. http.client.HTTPException: message
  922. TestResults(failed=1, attempted=2)
  923. But in Python 3 the module path is included, and therefore a test must look
  924. like the following test to succeed in Python 3. But that test will fail under
  925. Python 2.
  926. >>> def f(x):
  927. ... r'''
  928. ... >>> from http.client import HTTPException
  929. ... >>> raise HTTPException('message')
  930. ... Traceback (most recent call last):
  931. ... http.client.HTTPException: message
  932. ... '''
  933. >>> test = doctest.DocTestFinder().find(f)[0]
  934. >>> doctest.DocTestRunner(verbose=False).run(test)
  935. TestResults(failed=0, attempted=2)
  936. However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
  937. (or its unexpected absence) will be ignored:
  938. >>> def f(x):
  939. ... r'''
  940. ... >>> from http.client import HTTPException
  941. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  942. ... Traceback (most recent call last):
  943. ... HTTPException: message
  944. ... '''
  945. >>> test = doctest.DocTestFinder().find(f)[0]
  946. >>> doctest.DocTestRunner(verbose=False).run(test)
  947. TestResults(failed=0, attempted=2)
  948. The module path will be completely ignored, so two different module paths will
  949. still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
  950. be used when exceptions have changed module.
  951. >>> def f(x):
  952. ... r'''
  953. ... >>> from http.client import HTTPException
  954. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  955. ... Traceback (most recent call last):
  956. ... foo.bar.HTTPException: message
  957. ... '''
  958. >>> test = doctest.DocTestFinder().find(f)[0]
  959. >>> doctest.DocTestRunner(verbose=False).run(test)
  960. TestResults(failed=0, attempted=2)
  961. But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
  962. >>> def f(x):
  963. ... r'''
  964. ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  965. ... Traceback (most recent call last):
  966. ... TypeError: wrong type
  967. ... '''
  968. >>> test = doctest.DocTestFinder().find(f)[0]
  969. >>> doctest.DocTestRunner(verbose=False).run(test)
  970. ... # doctest: +ELLIPSIS
  971. **********************************************************************
  972. File ..., line 3, in f
  973. Failed example:
  974. raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  975. Expected:
  976. Traceback (most recent call last):
  977. TypeError: wrong type
  978. Got:
  979. Traceback (most recent call last):
  980. ...
  981. ValueError: message
  982. TestResults(failed=1, attempted=1)
  983. If the exception does not have a message, you can still use
  984. IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
  985. >>> def f(x):
  986. ... r'''
  987. ... >>> from http.client import HTTPException
  988. ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
  989. ... Traceback (most recent call last):
  990. ... foo.bar.HTTPException
  991. ... '''
  992. >>> test = doctest.DocTestFinder().find(f)[0]
  993. >>> doctest.DocTestRunner(verbose=False).run(test)
  994. TestResults(failed=0, attempted=2)
  995. Note that a trailing colon doesn't matter either:
  996. >>> def f(x):
  997. ... r'''
  998. ... >>> from http.client import HTTPException
  999. ... >>> raise HTTPException() #doctest: +IGNORE_EXCEPTION_DETAIL
  1000. ... Traceback (most recent call last):
  1001. ... foo.bar.HTTPException:
  1002. ... '''
  1003. >>> test = doctest.DocTestFinder().find(f)[0]
  1004. >>> doctest.DocTestRunner(verbose=False).run(test)
  1005. TestResults(failed=0, attempted=2)
  1006. If an exception is raised but not expected, then it is reported as an
  1007. unexpected exception:
  1008. >>> def f(x):
  1009. ... r'''
  1010. ... >>> 1//0
  1011. ... 0
  1012. ... '''
  1013. >>> test = doctest.DocTestFinder().find(f)[0]
  1014. >>> doctest.DocTestRunner(verbose=False).run(test)
  1015. ... # doctest: +ELLIPSIS
  1016. **********************************************************************
  1017. File ..., line 3, in f
  1018. Failed example:
  1019. 1//0
  1020. Exception raised:
  1021. Traceback (most recent call last):
  1022. ...
  1023. ZeroDivisionError: integer division or modulo by zero
  1024. TestResults(failed=1, attempted=1)
  1025. """
  1026. def displayhook(): r"""
  1027. Test that changing sys.displayhook doesn't matter for doctest.
  1028. >>> import sys
  1029. >>> orig_displayhook = sys.displayhook
  1030. >>> def my_displayhook(x):
  1031. ... print('hi!')
  1032. >>> sys.displayhook = my_displayhook
  1033. >>> def f():
  1034. ... '''
  1035. ... >>> 3
  1036. ... 3
  1037. ... '''
  1038. >>> test = doctest.DocTestFinder().find(f)[0]
  1039. >>> r = doctest.DocTestRunner(verbose=False).run(test)
  1040. >>> post_displayhook = sys.displayhook
  1041. We need to restore sys.displayhook now, so that we'll be able to test
  1042. results.
  1043. >>> sys.displayhook = orig_displayhook
  1044. Ok, now we can check that everything is ok.
  1045. >>> r
  1046. TestResults(failed=0, attempted=1)
  1047. >>> post_displayhook is my_displayhook
  1048. True
  1049. """
  1050. def optionflags(): r"""
  1051. Tests of `DocTestRunner`'s option flag handling.
  1052. Several option flags can be used to customize the behavior of the test
  1053. runner. These are defined as module constants in doctest, and passed
  1054. to the DocTestRunner constructor (multiple constants should be ORed
  1055. together).
  1056. The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
  1057. and 1/0:
  1058. >>> def f(x):
  1059. ... '>>> True\n1\n'
  1060. >>> # Without the flag:
  1061. >>> test = doctest.DocTestFinder().find(f)[0]
  1062. >>> doctest.DocTestRunner(verbose=False).run(test)
  1063. TestResults(failed=0, attempted=1)
  1064. >>> # With the flag:
  1065. >>> test = doctest.DocTestFinder().find(f)[0]
  1066. >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
  1067. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1068. ... # doctest: +ELLIPSIS
  1069. **********************************************************************
  1070. File ..., line 2, in f
  1071. Failed example:
  1072. True
  1073. Expected:
  1074. 1
  1075. Got:
  1076. True
  1077. TestResults(failed=1, attempted=1)
  1078. The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
  1079. and the '<BLANKLINE>' marker:
  1080. >>> def f(x):
  1081. ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
  1082. >>> # Without the flag:
  1083. >>> test = doctest.DocTestFinder().find(f)[0]
  1084. >>> doctest.DocTestRunner(verbose=False).run(test)
  1085. TestResults(failed=0, attempted=1)
  1086. >>> # With the flag:
  1087. >>> test = doctest.DocTestFinder().find(f)[0]
  1088. >>> flags = doctest.DONT_ACCEPT_BLANKLINE
  1089. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1090. ... # doctest: +ELLIPSIS
  1091. **********************************************************************
  1092. File ..., line 2, in f
  1093. Failed example:
  1094. print("a\n\nb")
  1095. Expected:
  1096. a
  1097. <BLANKLINE>
  1098. b
  1099. Got:
  1100. a
  1101. <BLANKLINE>
  1102. b
  1103. TestResults(failed=1, attempted=1)
  1104. The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
  1105. treated as equal:
  1106. >>> def f(x):
  1107. ... '>>> print(1, 2, 3)\n 1 2\n 3'
  1108. >>> # Without the flag:
  1109. >>> test = doctest.DocTestFinder().find(f)[0]
  1110. >>> doctest.DocTestRunner(verbose=False).run(test)
  1111. ... # doctest: +ELLIPSIS
  1112. **********************************************************************
  1113. File ..., line 2, in f
  1114. Failed example:
  1115. print(1, 2, 3)
  1116. Expected:
  1117. 1 2
  1118. 3
  1119. Got:
  1120. 1 2 3
  1121. TestResults(failed=1, attempted=1)
  1122. >>> # With the flag:
  1123. >>> test = doctest.DocTestFinder().find(f)[0]
  1124. >>> flags = doctest.NORMALIZE_WHITESPACE
  1125. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1126. TestResults(failed=0, attempted=1)
  1127. An example from the docs:
  1128. >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
  1129. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  1130. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
  1131. The ELLIPSIS flag causes ellipsis marker ("...") in the expected
  1132. output to match any substring in the actual output:
  1133. >>> def f(x):
  1134. ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
  1135. >>> # Without the flag:
  1136. >>> test = doctest.DocTestFinder().find(f)[0]
  1137. >>> doctest.DocTestRunner(verbose=False).run(test)
  1138. ... # doctest: +ELLIPSIS
  1139. **********************************************************************
  1140. File ..., line 2, in f
  1141. Failed example:
  1142. print(list(range(15)))
  1143. Expected:
  1144. [0, 1, 2, ..., 14]
  1145. Got:
  1146. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
  1147. TestResults(failed=1, attempted=1)
  1148. >>> # With the flag:
  1149. >>> test = doctest.DocTestFinder().find(f)[0]
  1150. >>> flags = doctest.ELLIPSIS
  1151. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1152. TestResults(failed=0, attempted=1)
  1153. ... also matches nothing:
  1154. >>> if 1:
  1155. ... for i in range(100):
  1156. ... print(i**2, end=' ') #doctest: +ELLIPSIS
  1157. ... print('!')
  1158. 0 1...4...9 16 ... 36 49 64 ... 9801 !
  1159. ... can be surprising; e.g., this test passes:
  1160. >>> if 1: #doctest: +ELLIPSIS
  1161. ... for i in range(20):
  1162. ... print(i, end=' ')
  1163. ... print(20)
  1164. 0 1 2 ...1...2...0
  1165. Examples from the docs:
  1166. >>> print(list(range(20))) # doctest:+ELLIPSIS
  1167. [0, 1, ..., 18, 19]
  1168. >>> print(list(range(20))) # doctest: +ELLIPSIS
  1169. ... # doctest: +NORMALIZE_WHITESPACE
  1170. [0, 1, ..., 18, 19]
  1171. The SKIP flag causes an example to be skipped entirely. I.e., the
  1172. example is not run. It can be useful in contexts where doctest
  1173. examples serve as both documentation and test cases, and an example
  1174. should be included for documentation purposes, but should not be
  1175. checked (e.g., because its output is random, or depends on resources
  1176. which would be unavailable.) The SKIP flag can also be used for
  1177. 'commenting out' broken examples.
  1178. >>> import unavailable_resource # doctest: +SKIP
  1179. >>> unavailable_resource.do_something() # doctest: +SKIP
  1180. >>> unavailable_resource.blow_up() # doctest: +SKIP
  1181. Traceback (most recent call last):
  1182. ...
  1183. UncheckedBlowUpError: Nobody checks me.
  1184. >>> import random
  1185. >>> print(random.random()) # doctest: +SKIP
  1186. 0.721216923889
  1187. The REPORT_UDIFF flag causes failures that involve multi-line expected
  1188. and actual outputs to be displayed using a unified diff:
  1189. >>> def f(x):
  1190. ... r'''
  1191. ... >>> print('\n'.join('abcdefg'))
  1192. ... a
  1193. ... B
  1194. ... c
  1195. ... d
  1196. ... f
  1197. ... g
  1198. ... h
  1199. ... '''
  1200. >>> # Without the flag:
  1201. >>> test = doctest.DocTestFinder().find(f)[0]
  1202. >>> doctest.DocTestRunner(verbose=False).run(test)
  1203. ... # doctest: +ELLIPSIS
  1204. **********************************************************************
  1205. File ..., line 3, in f
  1206. Failed example:
  1207. print('\n'.join('abcdefg'))
  1208. Expected:
  1209. a
  1210. B
  1211. c
  1212. d
  1213. f
  1214. g
  1215. h
  1216. Got:
  1217. a
  1218. b
  1219. c
  1220. d
  1221. e
  1222. f
  1223. g
  1224. TestResults(failed=1, attempted=1)
  1225. >>> # With the flag:
  1226. >>> test = doctest.DocTestFinder().find(f)[0]
  1227. >>> flags = doctest.REPORT_UDIFF
  1228. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1229. ... # doctest: +ELLIPSIS
  1230. **********************************************************************
  1231. File ..., line 3, in f
  1232. Failed example:
  1233. print('\n'.join('abcdefg'))
  1234. Differences (unified diff with -expected +actual):
  1235. @@ -1,7 +1,7 @@
  1236. a
  1237. -B
  1238. +b
  1239. c
  1240. d
  1241. +e
  1242. f
  1243. g
  1244. -h
  1245. TestResults(failed=1, attempted=1)
  1246. The REPORT_CDIFF flag causes failures that involve multi-line expected
  1247. and actual outputs to be displayed using a context diff:
  1248. >>> # Reuse f() from the REPORT_UDIFF example, above.
  1249. >>> test = doctest.DocTestFinder().find(f)[0]
  1250. >>> flags = doctest.REPORT_CDIFF
  1251. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1252. ... # doctest: +ELLIPSIS
  1253. **********************************************************************
  1254. File ..., line 3, in f
  1255. Failed example:
  1256. print('\n'.join('abcdefg'))
  1257. Differences (context diff with expected followed by actual):
  1258. ***************
  1259. *** 1,7 ****
  1260. a
  1261. ! B
  1262. c
  1263. d
  1264. f
  1265. g
  1266. - h
  1267. --- 1,7 ----
  1268. a
  1269. ! b
  1270. c
  1271. d
  1272. + e
  1273. f
  1274. g
  1275. TestResults(failed=1, attempted=1)
  1276. The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
  1277. used by the popular ndiff.py utility. This does intraline difference
  1278. marking, as well as interline differences.
  1279. >>> def f(x):
  1280. ... r'''
  1281. ... >>> print("a b c d e f g h i j k l m")
  1282. ... a b c d e f g h i j k 1 m
  1283. ... '''
  1284. >>> test = doctest.DocTestFinder().find(f)[0]
  1285. >>> flags = doctest.REPORT_NDIFF
  1286. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1287. ... # doctest: +ELLIPSIS
  1288. **********************************************************************
  1289. File ..., line 3, in f
  1290. Failed example:
  1291. print("a b c d e f g h i j k l m")
  1292. Differences (ndiff with -expected +actual):
  1293. - a b c d e f g h i j k 1 m
  1294. ? ^
  1295. + a b c d e f g h i j k l m
  1296. ? + ++ ^
  1297. TestResults(failed=1, attempted=1)
  1298. The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
  1299. failing example:
  1300. >>> def f(x):
  1301. ... r'''
  1302. ... >>> print(1) # first success
  1303. ... 1
  1304. ... >>> print(2) # first failure
  1305. ... 200
  1306. ... >>> print(3) # second failure
  1307. ... 300
  1308. ... >>> print(4) # second success
  1309. ... 4
  1310. ... >>> print(5) # third failure
  1311. ... 500
  1312. ... '''
  1313. >>> test = doctest.DocTestFinder().find(f)[0]
  1314. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1315. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1316. ... # doctest: +ELLIPSIS
  1317. **********************************************************************
  1318. File ..., line 5, in f
  1319. Failed example:
  1320. print(2) # first failure
  1321. Expected:
  1322. 200
  1323. Got:
  1324. 2
  1325. TestResults(failed=3, attempted=5)
  1326. However, output from `report_start` is not suppressed:
  1327. >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
  1328. ... # doctest: +ELLIPSIS
  1329. Trying:
  1330. print(1) # first success
  1331. Expecting:
  1332. 1
  1333. ok
  1334. Trying:
  1335. print(2) # first failure
  1336. Expecting:
  1337. 200
  1338. **********************************************************************
  1339. File ..., line 5, in f
  1340. Failed example:
  1341. print(2) # first failure
  1342. Expected:
  1343. 200
  1344. Got:
  1345. 2
  1346. TestResults(failed=3, attempted=5)
  1347. The FAIL_FAST flag causes the runner to exit after the first failing example,
  1348. so subsequent examples are not even attempted:
  1349. >>> flags = doctest.FAIL_FAST
  1350. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1351. ... # doctest: +ELLIPSIS
  1352. **********************************************************************
  1353. File ..., line 5, in f
  1354. Failed example:
  1355. print(2) # first failure
  1356. Expected:
  1357. 200
  1358. Got:
  1359. 2
  1360. TestResults(failed=1, attempted=2)
  1361. Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
  1362. FAIL_FAST only:
  1363. >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
  1364. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1365. ... # doctest: +ELLIPSIS
  1366. **********************************************************************
  1367. File ..., line 5, in f
  1368. Failed example:
  1369. print(2) # first failure
  1370. Expected:
  1371. 200
  1372. Got:
  1373. 2
  1374. TestResults(failed=1, attempted=2)
  1375. For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
  1376. exceptions count as failures:
  1377. >>> def f(x):
  1378. ... r'''
  1379. ... >>> print(1) # first success
  1380. ... 1
  1381. ... >>> raise ValueError(2) # first failure
  1382. ... 200
  1383. ... >>> print(3) # second failure
  1384. ... 300
  1385. ... >>> print(4) # second success
  1386. ... 4
  1387. ... >>> print(5) # third failure
  1388. ... 500
  1389. ... '''
  1390. >>> test = doctest.DocTestFinder().find(f)[0]
  1391. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1392. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1393. ... # doctest: +ELLIPSIS
  1394. **********************************************************************
  1395. File ..., line 5, in f
  1396. Failed example:
  1397. raise ValueError(2) # first failure
  1398. Exception raised:
  1399. ...
  1400. ValueError: 2
  1401. TestResults(failed=3, attempted=5)
  1402. >>> flags = doctest.FAIL_FAST
  1403. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1404. ... # doctest: +ELLIPSIS
  1405. **********************************************************************
  1406. File ..., line 5, in f
  1407. Failed example:
  1408. raise ValueError(2) # first failure
  1409. Exception raised:
  1410. ...
  1411. ValueError: 2
  1412. TestResults(failed=1, attempted=2)
  1413. New option flags can also be registered, via register_optionflag(). Here
  1414. we reach into doctest's internals a bit.
  1415. >>> unlikely = "UNLIKELY_OPTION_NAME"
  1416. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1417. False
  1418. >>> new_flag_value = doctest.register_optionflag(unlikely)
  1419. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1420. True
  1421. Before 2.4.4/2.5, registering a name more than once erroneously created
  1422. more than one flag value. Here we verify that's fixed:
  1423. >>> redundant_flag_value = doctest.register_optionflag(unlikely)
  1424. >>> redundant_flag_value == new_flag_value
  1425. True
  1426. Clean up.
  1427. >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
  1428. """
  1429. def option_directives(): r"""
  1430. Tests of `DocTestRunner`'s option directive mechanism.
  1431. Option directives can be used to turn option flags on or off for a
  1432. single example. To turn an option on for an example, follow that
  1433. example with a comment of the form ``# doctest: +OPTION``:
  1434. >>> def f(x): r'''
  1435. ... >>> print(list(range(10))) # should fail: no ellipsis
  1436. ... [0, 1, ..., 9]
  1437. ...
  1438. ... >>> print(list(range(10))) # doctest: +ELLIPSIS
  1439. ... [0, 1, ..., 9]
  1440. ... '''
  1441. >>> test = doctest.DocTestFinder().find(f)[0]
  1442. >>> doctest.DocTestRunner(verbose=False).run(test)
  1443. ... # doctest: +ELLIPSIS
  1444. **********************************************************************
  1445. File ..., line 2, in f
  1446. Failed example:
  1447. print(list(range(10))) # should fail: no ellipsis
  1448. Expected:
  1449. [0, 1, ..., 9]
  1450. Got:
  1451. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1452. TestResults(failed=1, attempted=2)
  1453. To turn an option off for an example, follow that example with a
  1454. comment of the form ``# doctest: -OPTION``:
  1455. >>> def f(x): r'''
  1456. ... >>> print(list(range(10)))
  1457. ... [0, 1, ..., 9]
  1458. ...
  1459. ... >>> # should fail: no ellipsis
  1460. ... >>> print(list(range(10))) # doctest: -ELLIPSIS
  1461. ... [0, 1, ..., 9]
  1462. ... '''
  1463. >>> test = doctest.DocTestFinder().find(f)[0]
  1464. >>> doctest.DocTestRunner(verbose=False,
  1465. ... optionflags=doctest.ELLIPSIS).run(test)
  1466. ... # doctest: +ELLIPSIS
  1467. **********************************************************************
  1468. File ..., line 6, in f
  1469. Failed example:
  1470. print(list(range(10))) # doctest: -ELLIPSIS
  1471. Expected:
  1472. [0, 1, ..., 9]
  1473. Got:
  1474. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1475. TestResults(failed=1, attempted=2)
  1476. Option directives affect only the example that they appear with; they
  1477. do not change the options for surrounding examples:
  1478. >>> def f(x): r'''
  1479. ... >>> print(list(range(10))) # Should fail: no ellipsis
  1480. ... [0, 1, ..., 9]
  1481. ...
  1482. ... >>> print(list(range(10))) # doctest: +ELLIPSIS
  1483. ... [0, 1, ..., 9]
  1484. ...
  1485. ... >>> print(list(range(10))) # Should fail: no ellipsis
  1486. ... [0, 1, ..., 9]
  1487. ... '''
  1488. >>> test = doctest.DocTestFinder().find(f)[0]
  1489. >>> doctest.DocTestRunner(verbose=False).run(test)
  1490. ... # doctest: +ELLIPSIS
  1491. **********************************************************************
  1492. File ..., line 2, in f
  1493. Failed example:
  1494. print(list(range(10))) # Should fail: no ellipsis
  1495. Expected:
  1496. [0, 1, ..., 9]
  1497. Got:
  1498. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1499. **********************************************************************
  1500. File ..., line 8, in f
  1501. Failed example:
  1502. print(list(range(10))) # Should fail: no ellipsis
  1503. Expected:
  1504. [0, 1, ..., 9]
  1505. Got:
  1506. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1507. TestResults(failed=2, attempted=3)
  1508. Multiple options may be modified by a single option directive. They
  1509. may be separated by whitespace, commas, or both:
  1510. >>> def f(x): r'''
  1511. ... >>> print(list(range(10))) # Should fail
  1512. ... [0, 1, ..., 9]
  1513. ... >>> print(list(range(10))) # Should succeed
  1514. ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  1515. ... [0, 1, ..., 9]
  1516. ... '''
  1517. >>> test = doctest.DocTestFinder().find(f)[0]
  1518. >>> doctest.DocTestRunner(verbose=False).run(test)
  1519. ... # doctest: +ELLIPSIS
  1520. **********************************************************************
  1521. File ..., line 2, in f
  1522. Failed example:
  1523. print(list(range(10))) # Should fail
  1524. Expected:
  1525. [0, 1, ..., 9]
  1526. Got:
  1527. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1528. TestResults(failed=1, attempted=2)
  1529. >>> def f(x): r'''
  1530. ... >>> print(list(range(10))) # Should fail
  1531. ... [0, 1, ..., 9]
  1532. ... >>> print(list(range(10))) # Should succeed
  1533. ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
  1534. ... [0, 1, ..., 9]
  1535. ... '''
  1536. >>> test = doctest.DocTestFinder().find(f)[0]
  1537. >>> doctest.DocTestRunner(verbose=False).run(test)
  1538. ... # doctest: +ELLIPSIS
  1539. **********************************************************************
  1540. File ..., line 2, in f
  1541. Failed example:
  1542. print(list(range(10))) # Should fail
  1543. Expected:
  1544. [0, 1, ..., 9]
  1545. Got:
  1546. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1547. TestResults(failed=1, attempted=2)
  1548. >>> def f(x): r'''
  1549. ... >>> print(list(range(10))) # Should fail
  1550. ... [0, 1, ..., 9]
  1551. ... >>> print(list(range(10))) # Should succeed
  1552. ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  1553. ... [0, 1, ..., 9]
  1554. ... '''
  1555. >>> test = doctest.DocTestFinder().find(f)[0]
  1556. >>> doctest.DocTestRunner(verbose=False).run(test)
  1557. ... # doctest: +ELLIPSIS
  1558. **********************************************************************
  1559. File ..., line 2, in f
  1560. Failed example:
  1561. print(list(range(10))) # Should fail
  1562. Expected:
  1563. [0, 1, ..., 9]
  1564. Got:
  1565. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1566. TestResults(failed=1, attempted=2)
  1567. The option directive may be put on the line following the source, as
  1568. long as a continuation prompt is used:
  1569. >>> def f(x): r'''
  1570. ... >>> print(list(range(10)))
  1571. ... ... # doctest: +ELLIPSIS
  1572. ... [0, 1, ..., 9]
  1573. ... '''
  1574. >>> test = doctest.DocTestFinder().find(f)[0]
  1575. >>> doctest.DocTestRunner(verbose=False).run(test)
  1576. TestResults(failed=0, attempted=1)
  1577. For examples with multi-line source, the option directive may appear
  1578. at the end of any line:
  1579. >>> def f(x): r'''
  1580. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1581. ... ... print(' ', x, end='', sep='')
  1582. ... 0 1 2 ... 9
  1583. ...
  1584. ... >>> for x in range(10):
  1585. ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
  1586. ... 0 1 2 ... 9
  1587. ... '''
  1588. >>> test = doctest.DocTestFinder().find(f)[0]
  1589. >>> doctest.DocTestRunner(verbose=False).run(test)
  1590. TestResults(failed=0, attempted=2)
  1591. If more than one line of an example with multi-line source has an
  1592. option directive, then they are combined:
  1593. >>> def f(x): r'''
  1594. ... Should fail (option directive not on the last line):
  1595. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1596. ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
  1597. ... 0 1 2...9
  1598. ... '''
  1599. >>> test = doctest.DocTestFinder().find(f)[0]
  1600. >>> doctest.DocTestRunner(verbose=False).run(test)
  1601. TestResults(failed=0, attempted=1)
  1602. It is an error to have a comment of the form ``# doctest:`` that is
  1603. *not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
  1604. ``OPTION`` is an option that has been registered with
  1605. `register_option`:
  1606. >>> # Error: Option not registered
  1607. >>> s = '>>> print(12) #doctest: +BADOPTION'
  1608. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1609. Traceback (most recent call last):
  1610. ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
  1611. >>> # Error: No + or - prefix
  1612. >>> s = '>>> print(12) #doctest: ELLIPSIS'
  1613. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1614. Traceback (most recent call last):
  1615. ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
  1616. It is an error to use an option directive on a line that contains no
  1617. source:
  1618. >>> s = '>>> # doctest: +ELLIPSIS'
  1619. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1620. Traceback (most recent call last):
  1621. ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
  1622. """
  1623. def test_testsource(): r"""
  1624. Unit tests for `testsource()`.
  1625. The testsource() function takes a module and a name, finds the (first)
  1626. test with that name in that module, and converts it to a script. The
  1627. example code is converted to regular Python code. The surrounding
  1628. words and expected output are converted to comments:
  1629. >>> import test.test_doctest
  1630. >>> name = 'test.test_doctest.sample_func'
  1631. >>> print(doctest.testsource(test.test_doctest, name))
  1632. # Blah blah
  1633. #
  1634. print(sample_func(22))
  1635. # Expected:
  1636. ## 44
  1637. #
  1638. # Yee ha!
  1639. <BLANKLINE>
  1640. >>> name = 'test.test_doctest.SampleNewStyleClass'
  1641. >>> print(doctest.testsource(test.test_doctest, name))
  1642. print('1\n2\n3')
  1643. # Expected:
  1644. ## 1
  1645. ## 2
  1646. ## 3
  1647. <BLANKLINE>
  1648. >>> name = 'test.test_doctest.SampleClass.a_classmethod'
  1649. >>> print(doctest.testsource(test.test_doctest, name))
  1650. print(SampleClass.a_classmethod(10))
  1651. # Expected:
  1652. ## 12
  1653. print(SampleClass(0).a_classmethod(10))
  1654. # Expected:
  1655. ## 12
  1656. <BLANKLINE>
  1657. """
  1658. def test_debug(): r"""
  1659. Create a docstring that we want to debug:
  1660. >>> s = '''
  1661. ... >>> x = 12
  1662. ... >>> print(x)
  1663. ... 12
  1664. ... '''
  1665. Create some fake stdin input, to feed to the debugger:
  1666. >>> real_stdin = sys.stdin
  1667. >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
  1668. Run the debugger on the docstring, and then restore sys.stdin.
  1669. >>> try: doctest.debug_src(s)
  1670. ... finally: sys.stdin = real_stdin
  1671. > <string>(1)<module>()
  1672. (Pdb) next
  1673. 12
  1674. --Return--
  1675. > <string>(1)<module>()->None
  1676. (Pdb) print(x)
  1677. 12
  1678. (Pdb) continue
  1679. """
  1680. if not hasattr(sys, 'gettrace') or not sys.gettrace():
  1681. def test_pdb_set_trace():
  1682. """Using pdb.set_trace from a doctest.
  1683. You can use pdb.set_trace from a doctest. To do so, you must
  1684. retrieve the set_trace function from the pdb module at the time
  1685. you use it. The doctest module changes sys.stdout so that it can
  1686. capture program output. It also temporarily replaces pdb.set_trace
  1687. with a version that restores stdout. This is necessary for you to
  1688. see debugger output.
  1689. >>> doc = '''
  1690. ... >>> x = 42
  1691. ... >>> raise Exception('clé')
  1692. ... Traceback (most recent call last):
  1693. ... Exception: clé
  1694. ... >>> import pdb; pdb.set_trace()
  1695. ... '''
  1696. >>> parser = doctest.DocTestParser()
  1697. >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
  1698. >>> runner = doctest.DocTestRunner(verbose=False)
  1699. To demonstrate this, we'll create a fake standard input that
  1700. captures our debugger input:
  1701. >>> real_stdin = sys.stdin
  1702. >>> sys.stdin = _FakeInput([
  1703. ... 'print(x)', # print data defined by the example
  1704. ... 'continue', # stop debugging
  1705. ... ''])
  1706. >>> try: runner.run(test)
  1707. ... finally: sys.stdin = real_stdin
  1708. --Return--
  1709. > <doctest foo-bar@baz[2]>(1)<module>()->None
  1710. -> import pdb; pdb.set_trace()
  1711. (Pdb) print(x)
  1712. 42
  1713. (Pdb) continue
  1714. TestResults(failed=0, attempted=3)
  1715. You can also put pdb.set_trace in a function called from a test:
  1716. >>> def calls_set_trace():
  1717. ... y=2
  1718. ... import pdb; pdb.set_trace()
  1719. >>> doc = '''
  1720. ... >>> x=1
  1721. ... >>> calls_set_trace()
  1722. ... '''
  1723. >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
  1724. >>> real_stdin = sys.stdin
  1725. >>> sys.stdin = _FakeInput([
  1726. ... 'print(y)', # print data defined in the function
  1727. ... 'up', # out of function
  1728. ... 'print(x)', # print data defined by the example
  1729. ... 'continue', # stop debugging
  1730. ... ''])
  1731. >>> try:
  1732. ... runner.run(test)
  1733. ... finally:
  1734. ... sys.stdin = real_stdin
  1735. --Return--
  1736. > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
  1737. -> import pdb; pdb.set_trace()
  1738. (Pdb) print(y)
  1739. 2
  1740. (Pdb) up
  1741. > <doctest foo-bar@baz[1]>(1)<module>()
  1742. -> calls_set_trace()
  1743. (Pdb) print(x)
  1744. 1
  1745. (Pdb) continue
  1746. TestResults(failed=0, attempted=2)
  1747. During interactive debugging, source code is shown, even for
  1748. doctest examples:
  1749. >>> doc = '''
  1750. ... >>> def f(x):
  1751. ... ... g(x*2)
  1752. ... >>> def g(x):
  1753. ... ... print(x+3)
  1754. ... ... import pdb; pdb.set_trace()
  1755. ... >>> f(3)
  1756. ... '''
  1757. >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
  1758. >>> real_stdin = sys.stdin
  1759. >>> sys.stdin = _FakeInput([
  1760. ... 'list', # list source from example 2
  1761. ... 'next', # return from g()
  1762. ... 'list', # list source from example 1
  1763. ... 'next', # return from f()
  1764. ... 'list', # list source from example 3
  1765. ... 'continue', # stop debugging
  1766. ... ''])
  1767. >>> try: runner.run(test)
  1768. ... finally: sys.stdin = real_stdin
  1769. ... # doctest: +NORMALIZE_WHITESPACE
  1770. --Return--
  1771. > <doctest foo-bar@baz[1]>(3)g()->None
  1772. -> import pdb; pdb.set_trace()
  1773. (Pdb) list
  1774. 1 def g(x):
  1775. 2 print(x+3)
  1776. 3 -> import pdb; pdb.set_trace()
  1777. [EOF]
  1778. (Pdb) next
  1779. --Return--
  1780. > <doctest foo-bar@baz[0]>(2)f()->None
  1781. -> g(x*2)
  1782. (Pdb) list
  1783. 1 def f(x):
  1784. 2 -> g(x*2)
  1785. [EOF]
  1786. (Pdb) next
  1787. --Return--
  1788. > <doctest foo-bar@baz[2]>(1)<module>()->None
  1789. -> f(3)
  1790. (Pdb) list
  1791. 1 -> f(3)
  1792. [EOF]
  1793. (Pdb) continue
  1794. **********************************************************************
  1795. File "foo-bar@baz.py", line 7, in foo-bar@baz
  1796. Failed example:
  1797. f(3)
  1798. Expected nothing
  1799. Got:
  1800. 9
  1801. TestResults(failed=1, attempted=3)
  1802. """
  1803. def test_pdb_set_trace_nested():
  1804. """This illustrates more-demanding use of set_trace with nested functions.
  1805. >>> class C(object):
  1806. ... def calls_set_trace(self):
  1807. ... y = 1
  1808. ... import pdb; pdb.set_trace()
  1809. ... self.f1()
  1810. ... y = 2
  1811. ... def f1(self):
  1812. ... x = 1
  1813. ... self.f2()
  1814. ... x = 2
  1815. ... def f2(self):
  1816. ... z = 1
  1817. ... z = 2
  1818. >>> calls_set_trace = C().calls_set_trace
  1819. >>> doc = '''
  1820. ... >>> a = 1
  1821. ... >>> calls_set_trace()
  1822. ... '''
  1823. >>> parser = doctest.DocTestParser()
  1824. >>> runner = doctest.DocTestRunner(verbose=False)
  1825. >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
  1826. >>> real_stdin = sys.stdin
  1827. >>> sys.stdin = _FakeInput([
  1828. ... 'print(y)', # print data defined in the function
  1829. ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
  1830. ... 'up', 'print(x)',
  1831. ... 'up', 'print(y)',
  1832. ... 'up', 'print(foo)',
  1833. ... 'continue', # stop debugging
  1834. ... ''])
  1835. >>> try:
  1836. ... runner.run(test)
  1837. ... finally:
  1838. ... sys.stdin = real_stdin
  1839. ... # doctest: +REPORT_NDIFF
  1840. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
  1841. -> self.f1()
  1842. (Pdb) print(y)
  1843. 1
  1844. (Pdb) step
  1845. --Call--
  1846. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
  1847. -> def f1(self):
  1848. (Pdb) step
  1849. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
  1850. -> x = 1
  1851. (Pdb) step
  1852. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
  1853. -> self.f2()
  1854. (Pdb) step
  1855. --Call--
  1856. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
  1857. -> def f2(self):
  1858. (Pdb) step
  1859. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
  1860. -> z = 1
  1861. (Pdb) step
  1862. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
  1863. -> z = 2
  1864. (Pdb) print(z)
  1865. 1
  1866. (Pdb) up
  1867. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
  1868. -> self.f2()
  1869. (Pdb) print(x)
  1870. 1
  1871. (Pdb) up
  1872. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
  1873. -> self.f1()
  1874. (Pdb) print(y)
  1875. 1
  1876. (Pdb) up
  1877. > <doctest foo-bar@baz[1]>(1)<module>()
  1878. -> calls_set_trace()
  1879. (Pdb) print(foo)
  1880. *** NameError: name 'foo' is not defined
  1881. (Pdb) continue
  1882. TestResults(failed=0, attempted=2)
  1883. """
  1884. def test_DocTestSuite():
  1885. """DocTestSuite creates a unittest test suite from a doctest.
  1886. We create a Suite by providing a module. A module can be provided
  1887. by passing a module object:
  1888. >>> import unittest
  1889. >>> import test.sample_doctest
  1890. >>> suite = doctest.DocTestSuite(test.sample_doctest)
  1891. >>> suite.run(unittest.TestResult())
  1892. <unittest.result.TestResult run=9 errors=0 failures=4>
  1893. We can also supply the module by name:
  1894. >>> suite = doctest.DocTestSuite('test.sample_doctest')
  1895. >>> suite.run(unittest.TestResult())
  1896. <unittest.result.TestResult run=9 errors=0 failures=4>
  1897. The module need not contain any doctest examples:
  1898. >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
  1899. >>> suite.run(unittest.TestResult())
  1900. <unittest.result.TestResult run=0 errors=0 failures=0>
  1901. The module need not contain any docstrings either:
  1902. >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings')
  1903. >>> suite.run(unittest.TestResult())
  1904. <unittest.result.TestResult run=0 errors=0 failures=0>
  1905. We can use the current module:
  1906. >>> suite = test.sample_doctest.test_suite()
  1907. >>> suite.run(unittest.TestResult())
  1908. <unittest.result.TestResult run=9 errors=0 failures=4>
  1909. We can also provide a DocTestFinder:
  1910. >>> finder = doctest.DocTestFinder()
  1911. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1912. ... test_finder=finder)
  1913. >>> suite.run(unittest.TestResult())
  1914. <unittest.result.TestResult run=9 errors=0 failures=4>
  1915. The DocTestFinder need not return any tests:
  1916. >>> finder = doctest.DocTestFinder()
  1917. >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
  1918. ... test_finder=finder)
  1919. >>> suite.run(unittest.TestResult())
  1920. <unittest.result.TestResult run=0 errors=0 failures=0>
  1921. We can supply global variables. If we pass globs, they will be
  1922. used instead of the module globals. Here we'll pass an empty
  1923. globals, triggering an extra error:
  1924. >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
  1925. >>> suite.run(unittest.TestResult())
  1926. <unittest.result.TestResult run=9 errors=0 failures=5>
  1927. Alternatively, we can provide extra globals. Here we'll make an
  1928. error go away by providing an extra global variable:
  1929. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1930. ... extraglobs={'y': 1})
  1931. >>> suite.run(unittest.TestResult())
  1932. <unittest.result.TestResult run=9 errors=0 failures=3>
  1933. You can pass option flags. Here we'll cause an extra error
  1934. by disabling the blank-line feature:
  1935. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1936. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
  1937. >>> suite.run(unittest.TestResult())
  1938. <unittest.result.TestResult run=9 errors=0 failures=5>
  1939. You can supply setUp and tearDown functions:
  1940. >>> def setUp(t):
  1941. ... import test.test_doctest
  1942. ... test.test_doctest.sillySetup = True
  1943. >>> def tearDown(t):
  1944. ... import test.test_doctest
  1945. ... del test.test_doctest.sillySetup
  1946. Here, we installed a silly variable that the test expects:
  1947. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1948. ... setUp=setUp, tearDown=tearDown)
  1949. >>> suite.run(unittest.TestResult())
  1950. <unittest.result.TestResult run=9 errors=0 failures=3>
  1951. But the tearDown restores sanity:
  1952. >>> import test.test_doctest
  1953. >>> test.test_doctest.sillySetup
  1954. Traceback (most recent call last):
  1955. ...
  1956. AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
  1957. The setUp and tearDown functions are passed test objects. Here
  1958. we'll use the setUp function to supply the missing variable y:
  1959. >>> def setUp(test):
  1960. ... test.globs['y'] = 1
  1961. >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
  1962. >>> suite.run(unittest.TestResult())
  1963. <unittest.result.TestResult run=9 errors=0 failures=3>
  1964. Here, we didn't need to use a tearDown function because we
  1965. modified the test globals, which are a copy of the
  1966. sample_doctest module dictionary. The test globals are
  1967. automatically cleared for us after a test.
  1968. """
  1969. def test_DocFileSuite():
  1970. """We can test tests found in text files using a DocFileSuite.
  1971. We create a suite by providing the names of one or more text
  1972. files that include examples:
  1973. >>> import unittest
  1974. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1975. ... 'test_doctest2.txt',
  1976. ... 'test_doctest4.txt')
  1977. >>> suite.run(unittest.TestResult())
  1978. <unittest.result.TestResult run=3 errors=0 failures=2>
  1979. The test files are looked for in the directory containing the
  1980. calling module. A package keyword argument can be provided to
  1981. specify a different relative location.
  1982. >>> import unittest
  1983. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1984. ... 'test_doctest2.txt',
  1985. ... 'test_doctest4.txt',
  1986. ... package='test')
  1987. >>> suite.run(unittest.TestResult())
  1988. <unittest.result.TestResult run=3 errors=0 failures=2>
  1989. Support for using a package's __loader__.get_data() is also
  1990. provided.
  1991. >>> import unittest, pkgutil, test
  1992. >>> added_loader = False
  1993. >>> if not hasattr(test, '__loader__'):
  1994. ... test.__loader__ = pkgutil.get_loader(test)
  1995. ... added_loader = True
  1996. >>> try:
  1997. ... suite = doctest.DocFileSuite('test_doctest.txt',
  1998. ... 'test_doctest2.txt',
  1999. ... 'test_doctest4.txt',
  2000. ... package='test')
  2001. ... suite.run(unittest.TestResult())
  2002. ... finally:
  2003. ... if added_loader:
  2004. ... del test.__loader__
  2005. <unittest.result.TestResult run=3 errors=0 failures=2>
  2006. '/' should be used as a path separator. It will be converted
  2007. to a native separator at run time:
  2008. >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
  2009. >>> suite.run(unittest.TestResult())
  2010. <unittest.result.TestResult run=1 errors=0 failures=1>
  2011. If DocFileSuite is used from an interactive session, then files
  2012. are resolved relative to the directory of sys.argv[0]:
  2013. >>> import types, os.path, test.test_doctest
  2014. >>> save_argv = sys.argv
  2015. >>> sys.argv = [test.test_doctest.__file__]
  2016. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2017. ... package=types.ModuleType('__main__'))
  2018. >>> sys.argv = save_argv
  2019. By setting `module_relative=False`, os-specific paths may be
  2020. used (including absolute paths and paths relative to the
  2021. working directory):
  2022. >>> # Get the absolute path of the test package.
  2023. >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
  2024. >>> test_pkg_path = os.path.split(test_doctest_path)[0]
  2025. >>> # Use it to find the absolute path of test_doctest.txt.
  2026. >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
  2027. >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
  2028. >>> suite.run(unittest.TestResult())
  2029. <unittest.result.TestResult run=1 errors=0 failures=1>
  2030. It is an error to specify `package` when `module_relative=False`:
  2031. >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
  2032. ... package='test')
  2033. Traceback (most recent call last):
  2034. ValueError: Package may only be specified for module-relative paths.
  2035. You can specify initial global variables:
  2036. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2037. ... 'test_doctest2.txt',
  2038. ... 'test_doctest4.txt',
  2039. ... globs={'favorite_color': 'blue'})
  2040. >>> suite.run(unittest.TestResult())
  2041. <unittest.result.TestResult run=3 errors=0 failures=1>
  2042. In this case, we supplied a missing favorite color. You can
  2043. provide doctest options:
  2044. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2045. ... 'test_doctest2.txt',
  2046. ... 'test_doctest4.txt',
  2047. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
  2048. ... globs={'favorite_color': 'blue'})
  2049. >>> suite.run(unittest.TestResult())
  2050. <unittest.result.TestResult run=3 errors=0 failures=2>
  2051. And, you can provide setUp and tearDown functions:
  2052. >>> def setUp(t):
  2053. ... import test.test_doctest
  2054. ... test.test_doctest.sillySetup = True
  2055. >>> def tearDown(t):
  2056. ... import test.test_doctest
  2057. ... del test.test_doctest.sillySetup
  2058. Here, we installed a silly variable that the test expects:
  2059. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2060. ... 'test_doctest2.txt',
  2061. ... 'test_doctest4.txt',
  2062. ... setUp=setUp, tearDown=tearDown)
  2063. >>> suite.run(unittest.TestResult())
  2064. <unittest.result.TestResult run=3 errors=0 failures=1>
  2065. But the tearDown restores sanity:
  2066. >>> import test.test_doctest
  2067. >>> test.test_doctest.sillySetup
  2068. Traceback (most recent call last):
  2069. ...
  2070. AttributeError: module 'test.test_doctest' has no attribute 'sillySetup'
  2071. The setUp and tearDown functions are passed test objects.
  2072. Here, we'll use a setUp function to set the favorite color in
  2073. test_doctest.txt:
  2074. >>> def setUp(test):
  2075. ... test.globs['favorite_color'] = 'blue'
  2076. >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
  2077. >>> suite.run(unittest.TestResult())
  2078. <unittest.result.TestResult run=1 errors=0 failures=0>
  2079. Here, we didn't need to use a tearDown function because we
  2080. modified the test globals. The test globals are
  2081. automatically cleared for us after a test.
  2082. Tests in a file run using `DocFileSuite` can also access the
  2083. `__file__` global, which is set to the name of the file
  2084. containing the tests:
  2085. >>> suite = doctest.DocFileSuite('test_doctest3.txt')
  2086. >>> suite.run(unittest.TestResult())
  2087. <unittest.result.TestResult run=1 errors=0 failures=0>
  2088. If the tests contain non-ASCII characters, we have to specify which
  2089. encoding the file is encoded with. We do so by using the `encoding`
  2090. parameter:
  2091. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2092. ... 'test_doctest2.txt',
  2093. ... 'test_doctest4.txt',
  2094. ... encoding='utf-8')
  2095. >>> suite.run(unittest.TestResult())
  2096. <unittest.result.TestResult run=3 errors=0 failures=2>
  2097. """
  2098. def test_trailing_space_in_test():
  2099. """
  2100. Trailing spaces in expected output are significant:
  2101. >>> x, y = 'foo', ''
  2102. >>> print(x, y)
  2103. foo \n
  2104. """
  2105. class Wrapper:
  2106. def __init__(self, func):
  2107. self.func = func
  2108. functools.update_wrapper(self, func)
  2109. def __call__(self, *args, **kwargs):
  2110. self.func(*args, **kwargs)
  2111. @Wrapper
  2112. def test_look_in_unwrapped():
  2113. """
  2114. Docstrings in wrapped functions must be detected as well.
  2115. >>> 'one other test'
  2116. 'one other test'
  2117. """
  2118. def test_unittest_reportflags():
  2119. """Default unittest reporting flags can be set to control reporting
  2120. Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
  2121. only the first failure of each test. First, we'll look at the
  2122. output without the flag. The file test_doctest.txt file has two
  2123. tests. They both fail if blank lines are disabled:
  2124. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2125. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
  2126. >>> import unittest
  2127. >>> result = suite.run(unittest.TestResult())
  2128. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  2129. Traceback ...
  2130. Failed example:
  2131. favorite_color
  2132. ...
  2133. Failed example:
  2134. if 1:
  2135. ...
  2136. Note that we see both failures displayed.
  2137. >>> old = doctest.set_unittest_reportflags(
  2138. ... doctest.REPORT_ONLY_FIRST_FAILURE)
  2139. Now, when we run the test:
  2140. >>> result = suite.run(unittest.TestResult())
  2141. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  2142. Traceback ...
  2143. Failed example:
  2144. favorite_color
  2145. Exception raised:
  2146. ...
  2147. NameError: name 'favorite_color' is not defined
  2148. <BLANKLINE>
  2149. <BLANKLINE>
  2150. We get only the first failure.
  2151. If we give any reporting options when we set up the tests,
  2152. however:
  2153. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2154. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
  2155. Then the default eporting options are ignored:
  2156. >>> result = suite.run(unittest.TestResult())
  2157. *NOTE*: These doctest are intentionally not placed in raw string to depict
  2158. the trailing whitespace using `\x20` in the diff below.
  2159. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  2160. Traceback ...
  2161. Failed example:
  2162. favorite_color
  2163. ...
  2164. Failed example:
  2165. if 1:
  2166. print('a')
  2167. print()
  2168. print('b')
  2169. Differences (ndiff with -expected +actual):
  2170. a
  2171. - <BLANKLINE>
  2172. +\x20
  2173. b
  2174. <BLANKLINE>
  2175. <BLANKLINE>
  2176. Test runners can restore the formatting flags after they run:
  2177. >>> ignored = doctest.set_unittest_reportflags(old)
  2178. """
  2179. def test_testfile(): r"""
  2180. Tests for the `testfile()` function. This function runs all the
  2181. doctest examples in a given file. In its simple invocation, it is
  2182. called with the name of a file, which is taken to be relative to the
  2183. calling module. The return value is (#failures, #tests).
  2184. We don't want `-v` in sys.argv for these tests.
  2185. >>> save_argv = sys.argv
  2186. >>> if '-v' in sys.argv:
  2187. ... sys.argv = [arg for arg in save_argv if arg != '-v']
  2188. >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
  2189. **********************************************************************
  2190. File "...", line 6, in test_doctest.txt
  2191. Failed example:
  2192. favorite_color
  2193. Exception raised:
  2194. ...
  2195. NameError: name 'favorite_color' is not defined
  2196. **********************************************************************
  2197. 1 items had failures:
  2198. 1 of 2 in test_doctest.txt
  2199. ***Test Failed*** 1 failures.
  2200. TestResults(failed=1, attempted=2)
  2201. >>> doctest.master = None # Reset master.
  2202. (Note: we'll be clearing doctest.master after each call to
  2203. `doctest.testfile`, to suppress warnings about multiple tests with the
  2204. same name.)
  2205. Globals may be specified with the `globs` and `extraglobs` parameters:
  2206. >>> globs = {'favorite_color': 'blue'}
  2207. >>> doctest.testfile('test_doctest.txt', globs=globs)
  2208. TestResults(failed=0, attempted=2)
  2209. >>> doctest.master = None # Reset master.
  2210. >>> extraglobs = {'favorite_color': 'red'}
  2211. >>> doctest.testfile('test_doctest.txt', globs=globs,
  2212. ... extraglobs=extraglobs) # doctest: +ELLIPSIS
  2213. **********************************************************************
  2214. File "...", line 6, in test_doctest.txt
  2215. Failed example:
  2216. favorite_color
  2217. Expected:
  2218. 'blue'
  2219. Got:
  2220. 'red'
  2221. **********************************************************************
  2222. 1 items had failures:
  2223. 1 of 2 in test_doctest.txt
  2224. ***Test Failed*** 1 failures.
  2225. TestResults(failed=1, attempted=2)
  2226. >>> doctest.master = None # Reset master.
  2227. The file may be made relative to a given module or package, using the
  2228. optional `module_relative` parameter:
  2229. >>> doctest.testfile('test_doctest.txt', globs=globs,
  2230. ... module_relative='test')
  2231. TestResults(failed=0, attempted=2)
  2232. >>> doctest.master = None # Reset master.
  2233. Verbosity can be increased with the optional `verbose` parameter:
  2234. >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
  2235. Trying:
  2236. favorite_color
  2237. Expecting:
  2238. 'blue'
  2239. ok
  2240. Trying:
  2241. if 1:
  2242. print('a')
  2243. print()
  2244. print('b')
  2245. Expecting:
  2246. a
  2247. <BLANKLINE>
  2248. b
  2249. ok
  2250. 1 items passed all tests:
  2251. 2 tests in test_doctest.txt
  2252. 2 tests in 1 items.
  2253. 2 passed and 0 failed.
  2254. Test passed.
  2255. TestResults(failed=0, attempted=2)
  2256. >>> doctest.master = None # Reset master.
  2257. The name of the test may be specified with the optional `name`
  2258. parameter:
  2259. >>> doctest.testfile('test_doctest.txt', name='newname')
  2260. ... # doctest: +ELLIPSIS
  2261. **********************************************************************
  2262. File "...", line 6, in newname
  2263. ...
  2264. TestResults(failed=1, attempted=2)
  2265. >>> doctest.master = None # Reset master.
  2266. The summary report may be suppressed with the optional `report`
  2267. parameter:
  2268. >>> doctest.testfile('test_doctest.txt', report=False)
  2269. ... # doctest: +ELLIPSIS
  2270. **********************************************************************
  2271. File "...", line 6, in test_doctest.txt
  2272. Failed example:
  2273. favorite_color
  2274. Exception raised:
  2275. ...
  2276. NameError: name 'favorite_color' is not defined
  2277. TestResults(failed=1, attempted=2)
  2278. >>> doctest.master = None # Reset master.
  2279. The optional keyword argument `raise_on_error` can be used to raise an
  2280. exception on the first error (which may be useful for postmortem
  2281. debugging):
  2282. >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
  2283. ... # doctest: +ELLIPSIS
  2284. Traceback (most recent call last):
  2285. doctest.UnexpectedException: ...
  2286. >>> doctest.master = None # Reset master.
  2287. If the tests contain non-ASCII characters, the tests might fail, since
  2288. it's unknown which encoding is used. The encoding can be specified
  2289. using the optional keyword argument `encoding`:
  2290. >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
  2291. **********************************************************************
  2292. File "...", line 7, in test_doctest4.txt
  2293. Failed example:
  2294. '...'
  2295. Expected:
  2296. 'f\xf6\xf6'
  2297. Got:
  2298. 'f\xc3\xb6\xc3\xb6'
  2299. **********************************************************************
  2300. ...
  2301. **********************************************************************
  2302. 1 items had failures:
  2303. 2 of 2 in test_doctest4.txt
  2304. ***Test Failed*** 2 failures.
  2305. TestResults(failed=2, attempted=2)
  2306. >>> doctest.master = None # Reset master.
  2307. >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
  2308. TestResults(failed=0, attempted=2)
  2309. >>> doctest.master = None # Reset master.
  2310. Test the verbose output:
  2311. >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
  2312. Trying:
  2313. 'föö'
  2314. Expecting:
  2315. 'f\xf6\xf6'
  2316. ok
  2317. Trying:
  2318. 'bąr'
  2319. Expecting:
  2320. 'b\u0105r'
  2321. ok
  2322. 1 items passed all tests:
  2323. 2 tests in test_doctest4.txt
  2324. 2 tests in 1 items.
  2325. 2 passed and 0 failed.
  2326. Test passed.
  2327. TestResults(failed=0, attempted=2)
  2328. >>> doctest.master = None # Reset master.
  2329. >>> sys.argv = save_argv
  2330. """
  2331. class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
  2332. def find_spec(self, fullname, path, target=None):
  2333. return importlib.util.spec_from_file_location(fullname, path, loader=self)
  2334. def get_data(self, path):
  2335. with open(path, mode='rb') as f:
  2336. return f.read()
  2337. class TestHook:
  2338. def __init__(self, pathdir):
  2339. self.sys_path = sys.path[:]
  2340. self.meta_path = sys.meta_path[:]
  2341. self.path_hooks = sys.path_hooks[:]
  2342. sys.path.append(pathdir)
  2343. sys.path_importer_cache.clear()
  2344. self.modules_before = sys.modules.copy()
  2345. self.importer = TestImporter()
  2346. sys.meta_path.append(self.importer)
  2347. def remove(self):
  2348. sys.path[:] = self.sys_path
  2349. sys.meta_path[:] = self.meta_path
  2350. sys.path_hooks[:] = self.path_hooks
  2351. sys.path_importer_cache.clear()
  2352. sys.modules.clear()
  2353. sys.modules.update(self.modules_before)
  2354. @contextlib.contextmanager
  2355. def test_hook(pathdir):
  2356. hook = TestHook(pathdir)
  2357. try:
  2358. yield hook
  2359. finally:
  2360. hook.remove()
  2361. def test_lineendings(): r"""
  2362. *nix systems use \n line endings, while Windows systems use \r\n, and
  2363. old Mac systems used \r, which Python still recognizes as a line ending. Python
  2364. handles this using universal newline mode for reading files. Let's make
  2365. sure doctest does so (issue 8473) by creating temporary test files using each
  2366. of the three line disciplines. At least one will not match either the universal
  2367. newline \n or os.linesep for the platform the test is run on.
  2368. Windows line endings first:
  2369. >>> import tempfile, os
  2370. >>> fn = tempfile.mktemp()
  2371. >>> with open(fn, 'wb') as f:
  2372. ... f.write(b'Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
  2373. 35
  2374. >>> doctest.testfile(fn, module_relative=False, verbose=False)
  2375. TestResults(failed=0, attempted=1)
  2376. >>> os.remove(fn)
  2377. And now *nix line endings:
  2378. >>> fn = tempfile.mktemp()
  2379. >>> with open(fn, 'wb') as f:
  2380. ... f.write(b'Test:\n\n >>> x = 1 + 1\n\nDone.\n')
  2381. 30
  2382. >>> doctest.testfile(fn, module_relative=False, verbose=False)
  2383. TestResults(failed=0, attempted=1)
  2384. >>> os.remove(fn)
  2385. And finally old Mac line endings:
  2386. >>> fn = tempfile.mktemp()
  2387. >>> with open(fn, 'wb') as f:
  2388. ... f.write(b'Test:\r\r >>> x = 1 + 1\r\rDone.\r')
  2389. 30
  2390. >>> doctest.testfile(fn, module_relative=False, verbose=False)
  2391. TestResults(failed=0, attempted=1)
  2392. >>> os.remove(fn)
  2393. Now we test with a package loader that has a get_data method, since that
  2394. bypasses the standard universal newline handling so doctest has to do the
  2395. newline conversion itself; let's make sure it does so correctly (issue 1812).
  2396. We'll write a file inside the package that has all three kinds of line endings
  2397. in it, and use a package hook to install a custom loader; on any platform,
  2398. at least one of the line endings will raise a ValueError for inconsistent
  2399. whitespace if doctest does not correctly do the newline conversion.
  2400. >>> dn = tempfile.mkdtemp()
  2401. >>> pkg = os.path.join(dn, "doctest_testpkg")
  2402. >>> os.mkdir(pkg)
  2403. >>> os_helper.create_empty_file(os.path.join(pkg, "__init__.py"))
  2404. >>> fn = os.path.join(pkg, "doctest_testfile.txt")
  2405. >>> with open(fn, 'wb') as f:
  2406. ... f.write(
  2407. ... b'Test:\r\n\r\n'
  2408. ... b' >>> x = 1 + 1\r\n\r\n'
  2409. ... b'Done.\r\n'
  2410. ... b'Test:\n\n'
  2411. ... b' >>> x = 1 + 1\n\n'
  2412. ... b'Done.\n'
  2413. ... b'Test:\r\r'
  2414. ... b' >>> x = 1 + 1\r\r'
  2415. ... b'Done.\r'
  2416. ... )
  2417. 95
  2418. >>> with test_hook(dn):
  2419. ... doctest.testfile("doctest_testfile.txt", package="doctest_testpkg", verbose=False)
  2420. TestResults(failed=0, attempted=3)
  2421. >>> shutil.rmtree(dn)
  2422. """
  2423. def test_testmod(): r"""
  2424. Tests for the testmod function. More might be useful, but for now we're just
  2425. testing the case raised by Issue 6195, where trying to doctest a C module would
  2426. fail with a UnicodeDecodeError because doctest tried to read the "source" lines
  2427. out of the binary module.
  2428. >>> import unicodedata
  2429. >>> doctest.testmod(unicodedata, verbose=False)
  2430. TestResults(failed=0, attempted=0)
  2431. """
  2432. try:
  2433. os.fsencode("foo-bär@baz.py")
  2434. supports_unicode = True
  2435. except UnicodeEncodeError:
  2436. # Skip the test: the filesystem encoding is unable to encode the filename
  2437. supports_unicode = False
  2438. if supports_unicode:
  2439. def test_unicode(): """
  2440. Check doctest with a non-ascii filename:
  2441. >>> doc = '''
  2442. ... >>> raise Exception('clé')
  2443. ... '''
  2444. ...
  2445. >>> parser = doctest.DocTestParser()
  2446. >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
  2447. >>> test
  2448. <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
  2449. >>> runner = doctest.DocTestRunner(verbose=False)
  2450. >>> runner.run(test) # doctest: +ELLIPSIS
  2451. **********************************************************************
  2452. File "foo-bär@baz.py", line 2, in foo-bär@baz
  2453. Failed example:
  2454. raise Exception('clé')
  2455. Exception raised:
  2456. Traceback (most recent call last):
  2457. File ...
  2458. exec(compile(example.source, filename, "single",
  2459. File "<doctest foo-bär@baz[0]>", line 1, in <module>
  2460. raise Exception('clé')
  2461. Exception: clé
  2462. TestResults(failed=1, attempted=1)
  2463. """
  2464. def test_CLI(): r"""
  2465. The doctest module can be used to run doctests against an arbitrary file.
  2466. These tests test this CLI functionality.
  2467. We'll use the support module's script_helpers for this, and write a test files
  2468. to a temp dir to run the command against. Due to a current limitation in
  2469. script_helpers, though, we need a little utility function to turn the returned
  2470. output into something we can doctest against:
  2471. >>> def normalize(s):
  2472. ... return '\n'.join(s.decode().splitlines())
  2473. With those preliminaries out of the way, we'll start with a file with two
  2474. simple tests and no errors. We'll run both the unadorned doctest command, and
  2475. the verbose version, and then check the output:
  2476. >>> from test.support import script_helper
  2477. >>> from test.support.os_helper import temp_dir
  2478. >>> with temp_dir() as tmpdir:
  2479. ... fn = os.path.join(tmpdir, 'myfile.doc')
  2480. ... with open(fn, 'w', encoding='utf-8') as f:
  2481. ... _ = f.write('This is a very simple test file.\n')
  2482. ... _ = f.write(' >>> 1 + 1\n')
  2483. ... _ = f.write(' 2\n')
  2484. ... _ = f.write(' >>> "a"\n')
  2485. ... _ = f.write(" 'a'\n")
  2486. ... _ = f.write('\n')
  2487. ... _ = f.write('And that is it.\n')
  2488. ... rc1, out1, err1 = script_helper.assert_python_ok(
  2489. ... '-m', 'doctest', fn)
  2490. ... rc2, out2, err2 = script_helper.assert_python_ok(
  2491. ... '-m', 'doctest', '-v', fn)
  2492. With no arguments and passing tests, we should get no output:
  2493. >>> rc1, out1, err1
  2494. (0, b'', b'')
  2495. With the verbose flag, we should see the test output, but no error output:
  2496. >>> rc2, err2
  2497. (0, b'')
  2498. >>> print(normalize(out2))
  2499. Trying:
  2500. 1 + 1
  2501. Expecting:
  2502. 2
  2503. ok
  2504. Trying:
  2505. "a"
  2506. Expecting:
  2507. 'a'
  2508. ok
  2509. 1 items passed all tests:
  2510. 2 tests in myfile.doc
  2511. 2 tests in 1 items.
  2512. 2 passed and 0 failed.
  2513. Test passed.
  2514. Now we'll write a couple files, one with three tests, the other a python module
  2515. with two tests, both of the files having "errors" in the tests that can be made
  2516. non-errors by applying the appropriate doctest options to the run (ELLIPSIS in
  2517. the first file, NORMALIZE_WHITESPACE in the second). This combination will
  2518. allow thoroughly testing the -f and -o flags, as well as the doctest command's
  2519. ability to process more than one file on the command line and, since the second
  2520. file ends in '.py', its handling of python module files (as opposed to straight
  2521. text files).
  2522. >>> from test.support import script_helper
  2523. >>> from test.support.os_helper import temp_dir
  2524. >>> with temp_dir() as tmpdir:
  2525. ... fn = os.path.join(tmpdir, 'myfile.doc')
  2526. ... with open(fn, 'w', encoding="utf-8") as f:
  2527. ... _ = f.write('This is another simple test file.\n')
  2528. ... _ = f.write(' >>> 1 + 1\n')
  2529. ... _ = f.write(' 2\n')
  2530. ... _ = f.write(' >>> "abcdef"\n')
  2531. ... _ = f.write(" 'a...f'\n")
  2532. ... _ = f.write(' >>> "ajkml"\n')
  2533. ... _ = f.write(" 'a...l'\n")
  2534. ... _ = f.write('\n')
  2535. ... _ = f.write('And that is it.\n')
  2536. ... fn2 = os.path.join(tmpdir, 'myfile2.py')
  2537. ... with open(fn2, 'w', encoding='utf-8') as f:
  2538. ... _ = f.write('def test_func():\n')
  2539. ... _ = f.write(' \"\"\"\n')
  2540. ... _ = f.write(' This is simple python test function.\n')
  2541. ... _ = f.write(' >>> 1 + 1\n')
  2542. ... _ = f.write(' 2\n')
  2543. ... _ = f.write(' >>> "abc def"\n')
  2544. ... _ = f.write(" 'abc def'\n")
  2545. ... _ = f.write("\n")
  2546. ... _ = f.write(' \"\"\"\n')
  2547. ... rc1, out1, err1 = script_helper.assert_python_failure(
  2548. ... '-m', 'doctest', fn, fn2)
  2549. ... rc2, out2, err2 = script_helper.assert_python_ok(
  2550. ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
  2551. ... rc3, out3, err3 = script_helper.assert_python_ok(
  2552. ... '-m', 'doctest', '-o', 'ELLIPSIS',
  2553. ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
  2554. ... rc4, out4, err4 = script_helper.assert_python_failure(
  2555. ... '-m', 'doctest', '-f', fn, fn2)
  2556. ... rc5, out5, err5 = script_helper.assert_python_ok(
  2557. ... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
  2558. ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
  2559. Our first test run will show the errors from the first file (doctest stops if a
  2560. file has errors). Note that doctest test-run error output appears on stdout,
  2561. not stderr:
  2562. >>> rc1, err1
  2563. (1, b'')
  2564. >>> print(normalize(out1)) # doctest: +ELLIPSIS
  2565. **********************************************************************
  2566. File "...myfile.doc", line 4, in myfile.doc
  2567. Failed example:
  2568. "abcdef"
  2569. Expected:
  2570. 'a...f'
  2571. Got:
  2572. 'abcdef'
  2573. **********************************************************************
  2574. File "...myfile.doc", line 6, in myfile.doc
  2575. Failed example:
  2576. "ajkml"
  2577. Expected:
  2578. 'a...l'
  2579. Got:
  2580. 'ajkml'
  2581. **********************************************************************
  2582. 1 items had failures:
  2583. 2 of 3 in myfile.doc
  2584. ***Test Failed*** 2 failures.
  2585. With -o ELLIPSIS specified, the second run, against just the first file, should
  2586. produce no errors, and with -o NORMALIZE_WHITESPACE also specified, neither
  2587. should the third, which ran against both files:
  2588. >>> rc2, out2, err2
  2589. (0, b'', b'')
  2590. >>> rc3, out3, err3
  2591. (0, b'', b'')
  2592. The fourth run uses FAIL_FAST, so we should see only one error:
  2593. >>> rc4, err4
  2594. (1, b'')
  2595. >>> print(normalize(out4)) # doctest: +ELLIPSIS
  2596. **********************************************************************
  2597. File "...myfile.doc", line 4, in myfile.doc
  2598. Failed example:
  2599. "abcdef"
  2600. Expected:
  2601. 'a...f'
  2602. Got:
  2603. 'abcdef'
  2604. **********************************************************************
  2605. 1 items had failures:
  2606. 1 of 2 in myfile.doc
  2607. ***Test Failed*** 1 failures.
  2608. The fifth test uses verbose with the two options, so we should get verbose
  2609. success output for the tests in both files:
  2610. >>> rc5, err5
  2611. (0, b'')
  2612. >>> print(normalize(out5))
  2613. Trying:
  2614. 1 + 1
  2615. Expecting:
  2616. 2
  2617. ok
  2618. Trying:
  2619. "abcdef"
  2620. Expecting:
  2621. 'a...f'
  2622. ok
  2623. Trying:
  2624. "ajkml"
  2625. Expecting:
  2626. 'a...l'
  2627. ok
  2628. 1 items passed all tests:
  2629. 3 tests in myfile.doc
  2630. 3 tests in 1 items.
  2631. 3 passed and 0 failed.
  2632. Test passed.
  2633. Trying:
  2634. 1 + 1
  2635. Expecting:
  2636. 2
  2637. ok
  2638. Trying:
  2639. "abc def"
  2640. Expecting:
  2641. 'abc def'
  2642. ok
  2643. 1 items had no tests:
  2644. myfile2
  2645. 1 items passed all tests:
  2646. 2 tests in myfile2.test_func
  2647. 2 tests in 2 items.
  2648. 2 passed and 0 failed.
  2649. Test passed.
  2650. We should also check some typical error cases.
  2651. Invalid file name:
  2652. >>> rc, out, err = script_helper.assert_python_failure(
  2653. ... '-m', 'doctest', 'nosuchfile')
  2654. >>> rc, out
  2655. (1, b'')
  2656. >>> # The exact error message changes depending on the platform.
  2657. >>> print(normalize(err)) # doctest: +ELLIPSIS
  2658. Traceback (most recent call last):
  2659. ...
  2660. FileNotFoundError: [Errno ...] ...nosuchfile...
  2661. Invalid doctest option:
  2662. >>> rc, out, err = script_helper.assert_python_failure(
  2663. ... '-m', 'doctest', '-o', 'nosuchoption')
  2664. >>> rc, out
  2665. (2, b'')
  2666. >>> print(normalize(err)) # doctest: +ELLIPSIS
  2667. usage...invalid...nosuchoption...
  2668. """
  2669. def test_no_trailing_whitespace_stripping():
  2670. r"""
  2671. The fancy reports had a bug for a long time where any trailing whitespace on
  2672. the reported diff lines was stripped, making it impossible to see the
  2673. differences in line reported as different that differed only in the amount of
  2674. trailing whitespace. The whitespace still isn't particularly visible unless
  2675. you use NDIFF, but at least it is now there to be found.
  2676. *NOTE*: This snippet was intentionally put inside a raw string to get rid of
  2677. leading whitespace error in executing the example below
  2678. >>> def f(x):
  2679. ... r'''
  2680. ... >>> print('\n'.join(['a ', 'b']))
  2681. ... a
  2682. ... b
  2683. ... '''
  2684. """
  2685. """
  2686. *NOTE*: These doctest are not placed in raw string to depict the trailing whitespace
  2687. using `\x20`
  2688. >>> test = doctest.DocTestFinder().find(f)[0]
  2689. >>> flags = doctest.REPORT_NDIFF
  2690. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  2691. ... # doctest: +ELLIPSIS
  2692. **********************************************************************
  2693. File ..., line 3, in f
  2694. Failed example:
  2695. print('\n'.join(['a ', 'b']))
  2696. Differences (ndiff with -expected +actual):
  2697. - a
  2698. + a
  2699. b
  2700. TestResults(failed=1, attempted=1)
  2701. *NOTE*: `\x20` is for checking the trailing whitespace on the +a line above.
  2702. We cannot use actual spaces there, as a commit hook prevents from committing
  2703. patches that contain trailing whitespace. More info on Issue 24746.
  2704. """
  2705. def test_run_doctestsuite_multiple_times():
  2706. """
  2707. It was not possible to run the same DocTestSuite multiple times
  2708. http://bugs.python.org/issue2604
  2709. http://bugs.python.org/issue9736
  2710. >>> import unittest
  2711. >>> import test.sample_doctest
  2712. >>> suite = doctest.DocTestSuite(test.sample_doctest)
  2713. >>> suite.run(unittest.TestResult())
  2714. <unittest.result.TestResult run=9 errors=0 failures=4>
  2715. >>> suite.run(unittest.TestResult())
  2716. <unittest.result.TestResult run=9 errors=0 failures=4>
  2717. """
  2718. def load_tests(loader, tests, pattern):
  2719. tests.addTest(doctest.DocTestSuite(doctest))
  2720. tests.addTest(doctest.DocTestSuite())
  2721. return tests
  2722. def test_coverage(coverdir):
  2723. trace = import_helper.import_module('trace')
  2724. tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
  2725. trace=0, count=1)
  2726. tracer.run('test_main()')
  2727. r = tracer.results()
  2728. print('Writing coverage results...')
  2729. r.write_results(show_missing=True, summary=True,
  2730. coverdir=coverdir)
  2731. if __name__ == '__main__':
  2732. if '-c' in sys.argv:
  2733. test_coverage('/tmp/doctest.cover')
  2734. else:
  2735. unittest.main()