doctest.py 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672
  1. # Module doctest.
  2. # Released to the public domain 16-Jan-2001, by Tim Peters ([email protected]).
  3. # Major enhancements and refactoring by:
  4. # Jim Fulton
  5. # Edward Loper
  6. # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
  7. r"""Module doctest -- a framework for running examples in docstrings.
  8. In simplest use, end each module M to be tested with:
  9. def _test():
  10. import doctest
  11. doctest.testmod()
  12. if __name__ == "__main__":
  13. _test()
  14. Then running the module as a script will cause the examples in the
  15. docstrings to get executed and verified:
  16. python M.py
  17. This won't display anything unless an example fails, in which case the
  18. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  19. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  20. line of output is "Test failed.".
  21. Run it with the -v switch instead:
  22. python M.py -v
  23. and a detailed report of all examples tried is printed to stdout, along
  24. with assorted summaries at the end.
  25. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  26. it by passing "verbose=False". In either of those cases, sys.argv is not
  27. examined by testmod.
  28. There are a variety of other ways to run doctests, including integration
  29. with the unittest framework, and support for running non-Python text
  30. files containing doctests. There are also many ways to override parts
  31. of doctest's default behaviors. See the Library Reference Manual for
  32. details.
  33. """
  34. __docformat__ = 'reStructuredText en'
  35. __all__ = [
  36. # 0, Option Flags
  37. 'register_optionflag',
  38. 'DONT_ACCEPT_TRUE_FOR_1',
  39. 'DONT_ACCEPT_BLANKLINE',
  40. 'NORMALIZE_WHITESPACE',
  41. 'ELLIPSIS',
  42. 'IGNORE_EXCEPTION_DETAIL',
  43. 'COMPARISON_FLAGS',
  44. 'REPORT_UDIFF',
  45. 'REPORT_CDIFF',
  46. 'REPORT_NDIFF',
  47. 'REPORT_ONLY_FIRST_FAILURE',
  48. 'REPORTING_FLAGS',
  49. # 1. Utility Functions
  50. 'is_private',
  51. # 2. Example & DocTest
  52. 'Example',
  53. 'DocTest',
  54. # 3. Doctest Parser
  55. 'DocTestParser',
  56. # 4. Doctest Finder
  57. 'DocTestFinder',
  58. # 5. Doctest Runner
  59. 'DocTestRunner',
  60. 'OutputChecker',
  61. 'DocTestFailure',
  62. 'UnexpectedException',
  63. 'DebugRunner',
  64. # 6. Test Functions
  65. 'testmod',
  66. 'testfile',
  67. 'run_docstring_examples',
  68. # 7. Tester
  69. 'Tester',
  70. # 8. Unittest Support
  71. 'DocTestSuite',
  72. 'DocFileSuite',
  73. 'set_unittest_reportflags',
  74. # 9. Debugging Support
  75. 'script_from_examples',
  76. 'testsource',
  77. 'debug_src',
  78. 'debug',
  79. ]
  80. import __future__
  81. import sys, traceback, inspect, linecache, os, re, types
  82. import unittest, difflib, pdb, tempfile
  83. import warnings
  84. from StringIO import StringIO
  85. # Don't whine about the deprecated is_private function in this
  86. # module's tests.
  87. warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
  88. __name__, 0)
  89. # There are 4 basic classes:
  90. # - Example: a <source, want> pair, plus an intra-docstring line number.
  91. # - DocTest: a collection of examples, parsed from a docstring, plus
  92. # info about where the docstring came from (name, filename, lineno).
  93. # - DocTestFinder: extracts DocTests from a given object's docstring and
  94. # its contained objects' docstrings.
  95. # - DocTestRunner: runs DocTest cases, and accumulates statistics.
  96. #
  97. # So the basic picture is:
  98. #
  99. # list of:
  100. # +------+ +---------+ +-------+
  101. # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
  102. # +------+ +---------+ +-------+
  103. # | Example |
  104. # | ... |
  105. # | Example |
  106. # +---------+
  107. # Option constants.
  108. OPTIONFLAGS_BY_NAME = {}
  109. def register_optionflag(name):
  110. # Create a new flag unless `name` is already known.
  111. return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  112. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  113. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  114. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  115. ELLIPSIS = register_optionflag('ELLIPSIS')
  116. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  117. COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
  118. DONT_ACCEPT_BLANKLINE |
  119. NORMALIZE_WHITESPACE |
  120. ELLIPSIS |
  121. IGNORE_EXCEPTION_DETAIL)
  122. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  123. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  124. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  125. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  126. REPORTING_FLAGS = (REPORT_UDIFF |
  127. REPORT_CDIFF |
  128. REPORT_NDIFF |
  129. REPORT_ONLY_FIRST_FAILURE)
  130. # Special string markers for use in `want` strings:
  131. BLANKLINE_MARKER = '<BLANKLINE>'
  132. ELLIPSIS_MARKER = '...'
  133. ######################################################################
  134. ## Table of Contents
  135. ######################################################################
  136. # 1. Utility Functions
  137. # 2. Example & DocTest -- store test cases
  138. # 3. DocTest Parser -- extracts examples from strings
  139. # 4. DocTest Finder -- extracts test cases from objects
  140. # 5. DocTest Runner -- runs test cases
  141. # 6. Test Functions -- convenient wrappers for testing
  142. # 7. Tester Class -- for backwards compatibility
  143. # 8. Unittest Support
  144. # 9. Debugging Support
  145. # 10. Example Usage
  146. ######################################################################
  147. ## 1. Utility Functions
  148. ######################################################################
  149. def is_private(prefix, base):
  150. """prefix, base -> true iff name prefix + "." + base is "private".
  151. Prefix may be an empty string, and base does not contain a period.
  152. Prefix is ignored (although functions you write conforming to this
  153. protocol may make use of it).
  154. Return true iff base begins with an (at least one) underscore, but
  155. does not both begin and end with (at least) two underscores.
  156. >>> is_private("a.b", "my_func")
  157. False
  158. >>> is_private("____", "_my_func")
  159. True
  160. >>> is_private("someclass", "__init__")
  161. False
  162. >>> is_private("sometypo", "__init_")
  163. True
  164. >>> is_private("x.y.z", "_")
  165. True
  166. >>> is_private("_x.y.z", "__")
  167. False
  168. >>> is_private("", "") # senseless but consistent
  169. False
  170. """
  171. warnings.warn("is_private is deprecated; it wasn't useful; "
  172. "examine DocTestFinder.find() lists instead",
  173. DeprecationWarning, stacklevel=2)
  174. return base[:1] == "_" and not base[:2] == "__" == base[-2:]
  175. def _extract_future_flags(globs):
  176. """
  177. Return the compiler-flags associated with the future features that
  178. have been imported into the given namespace (globs).
  179. """
  180. flags = 0
  181. for fname in __future__.all_feature_names:
  182. feature = globs.get(fname, None)
  183. if feature is getattr(__future__, fname):
  184. flags |= feature.compiler_flag
  185. return flags
  186. def _normalize_module(module, depth=2):
  187. """
  188. Return the module specified by `module`. In particular:
  189. - If `module` is a module, then return module.
  190. - If `module` is a string, then import and return the
  191. module with that name.
  192. - If `module` is None, then return the calling module.
  193. The calling module is assumed to be the module of
  194. the stack frame at the given depth in the call stack.
  195. """
  196. if inspect.ismodule(module):
  197. return module
  198. elif isinstance(module, (str, unicode)):
  199. return __import__(module, globals(), locals(), ["*"])
  200. elif module is None:
  201. return sys.modules[sys._getframe(depth).f_globals['__name__']]
  202. else:
  203. raise TypeError("Expected a module, string, or None")
  204. def _indent(s, indent=4):
  205. """
  206. Add the given number of space characters to the beginning every
  207. non-blank line in `s`, and return the result.
  208. """
  209. # This regexp matches the start of non-blank lines:
  210. return re.sub('(?m)^(?!$)', indent*' ', s)
  211. def _exception_traceback(exc_info):
  212. """
  213. Return a string containing a traceback message for the given
  214. exc_info tuple (as returned by sys.exc_info()).
  215. """
  216. # Get a traceback message.
  217. excout = StringIO()
  218. exc_type, exc_val, exc_tb = exc_info
  219. traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
  220. return excout.getvalue()
  221. # Override some StringIO methods.
  222. class _SpoofOut(StringIO):
  223. def getvalue(self):
  224. result = StringIO.getvalue(self)
  225. # If anything at all was written, make sure there's a trailing
  226. # newline. There's no way for the expected output to indicate
  227. # that a trailing newline is missing.
  228. if result and not result.endswith("\n"):
  229. result += "\n"
  230. # Prevent softspace from screwing up the next test case, in
  231. # case they used print with a trailing comma in an example.
  232. if hasattr(self, "softspace"):
  233. del self.softspace
  234. return result
  235. def truncate(self, size=None):
  236. StringIO.truncate(self, size)
  237. if hasattr(self, "softspace"):
  238. del self.softspace
  239. # Worst-case linear-time ellipsis matching.
  240. def _ellipsis_match(want, got):
  241. """
  242. Essentially the only subtle case:
  243. >>> _ellipsis_match('aa...aa', 'aaa')
  244. False
  245. """
  246. if ELLIPSIS_MARKER not in want:
  247. return want == got
  248. # Find "the real" strings.
  249. ws = want.split(ELLIPSIS_MARKER)
  250. assert len(ws) >= 2
  251. # Deal with exact matches possibly needed at one or both ends.
  252. startpos, endpos = 0, len(got)
  253. w = ws[0]
  254. if w: # starts with exact match
  255. if got.startswith(w):
  256. startpos = len(w)
  257. del ws[0]
  258. else:
  259. return False
  260. w = ws[-1]
  261. if w: # ends with exact match
  262. if got.endswith(w):
  263. endpos -= len(w)
  264. del ws[-1]
  265. else:
  266. return False
  267. if startpos > endpos:
  268. # Exact end matches required more characters than we have, as in
  269. # _ellipsis_match('aa...aa', 'aaa')
  270. return False
  271. # For the rest, we only need to find the leftmost non-overlapping
  272. # match for each piece. If there's no overall match that way alone,
  273. # there's no overall match period.
  274. for w in ws:
  275. # w may be '' at times, if there are consecutive ellipses, or
  276. # due to an ellipsis at the start or end of `want`. That's OK.
  277. # Search for an empty string succeeds, and doesn't change startpos.
  278. startpos = got.find(w, startpos, endpos)
  279. if startpos < 0:
  280. return False
  281. startpos += len(w)
  282. return True
  283. def _comment_line(line):
  284. "Return a commented form of the given line"
  285. line = line.rstrip()
  286. if line:
  287. return '# '+line
  288. else:
  289. return '#'
  290. class _OutputRedirectingPdb(pdb.Pdb):
  291. """
  292. A specialized version of the python debugger that redirects stdout
  293. to a given stream when interacting with the user. Stdout is *not*
  294. redirected when traced code is executed.
  295. """
  296. def __init__(self, out):
  297. self.__out = out
  298. pdb.Pdb.__init__(self)
  299. def trace_dispatch(self, *args):
  300. # Redirect stdout to the given stream.
  301. save_stdout = sys.stdout
  302. sys.stdout = self.__out
  303. # Call Pdb's trace dispatch method.
  304. try:
  305. return pdb.Pdb.trace_dispatch(self, *args)
  306. finally:
  307. sys.stdout = save_stdout
  308. # [XX] Normalize with respect to os.path.pardir?
  309. def _module_relative_path(module, path):
  310. if not inspect.ismodule(module):
  311. raise TypeError, 'Expected a module: %r' % module
  312. if path.startswith('/'):
  313. raise ValueError, 'Module-relative files may not have absolute paths'
  314. # Find the base directory for the path.
  315. if hasattr(module, '__file__'):
  316. # A normal module/package
  317. basedir = os.path.split(module.__file__)[0]
  318. elif module.__name__ == '__main__':
  319. # An interactive session.
  320. if len(sys.argv)>0 and sys.argv[0] != '':
  321. basedir = os.path.split(sys.argv[0])[0]
  322. else:
  323. basedir = os.curdir
  324. else:
  325. # A module w/o __file__ (this includes builtins)
  326. raise ValueError("Can't resolve paths relative to the module " +
  327. module + " (it has no __file__)")
  328. # Combine the base directory and the path.
  329. return os.path.join(basedir, *(path.split('/')))
  330. ######################################################################
  331. ## 2. Example & DocTest
  332. ######################################################################
  333. ## - An "example" is a <source, want> pair, where "source" is a
  334. ## fragment of source code, and "want" is the expected output for
  335. ## "source." The Example class also includes information about
  336. ## where the example was extracted from.
  337. ##
  338. ## - A "doctest" is a collection of examples, typically extracted from
  339. ## a string (such as an object's docstring). The DocTest class also
  340. ## includes information about where the string was extracted from.
  341. class Example:
  342. """
  343. A single doctest example, consisting of source code and expected
  344. output. `Example` defines the following attributes:
  345. - source: A single Python statement, always ending with a newline.
  346. The constructor adds a newline if needed.
  347. - want: The expected output from running the source code (either
  348. from stdout, or a traceback in case of exception). `want` ends
  349. with a newline unless it's empty, in which case it's an empty
  350. string. The constructor adds a newline if needed.
  351. - exc_msg: The exception message generated by the example, if
  352. the example is expected to generate an exception; or `None` if
  353. it is not expected to generate an exception. This exception
  354. message is compared against the return value of
  355. `traceback.format_exception_only()`. `exc_msg` ends with a
  356. newline unless it's `None`. The constructor adds a newline
  357. if needed.
  358. - lineno: The line number within the DocTest string containing
  359. this Example where the Example begins. This line number is
  360. zero-based, with respect to the beginning of the DocTest.
  361. - indent: The example's indentation in the DocTest string.
  362. I.e., the number of space characters that preceed the
  363. example's first prompt.
  364. - options: A dictionary mapping from option flags to True or
  365. False, which is used to override default options for this
  366. example. Any option flags not contained in this dictionary
  367. are left at their default value (as specified by the
  368. DocTestRunner's optionflags). By default, no options are set.
  369. """
  370. def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
  371. options=None):
  372. # Normalize inputs.
  373. if not source.endswith('\n'):
  374. source += '\n'
  375. if want and not want.endswith('\n'):
  376. want += '\n'
  377. if exc_msg is not None and not exc_msg.endswith('\n'):
  378. exc_msg += '\n'
  379. # Store properties.
  380. self.source = source
  381. self.want = want
  382. self.lineno = lineno
  383. self.indent = indent
  384. if options is None: options = {}
  385. self.options = options
  386. self.exc_msg = exc_msg
  387. class DocTest:
  388. """
  389. A collection of doctest examples that should be run in a single
  390. namespace. Each `DocTest` defines the following attributes:
  391. - examples: the list of examples.
  392. - globs: The namespace (aka globals) that the examples should
  393. be run in.
  394. - name: A name identifying the DocTest (typically, the name of
  395. the object whose docstring this DocTest was extracted from).
  396. - filename: The name of the file that this DocTest was extracted
  397. from, or `None` if the filename is unknown.
  398. - lineno: The line number within filename where this DocTest
  399. begins, or `None` if the line number is unavailable. This
  400. line number is zero-based, with respect to the beginning of
  401. the file.
  402. - docstring: The string that the examples were extracted from,
  403. or `None` if the string is unavailable.
  404. """
  405. def __init__(self, examples, globs, name, filename, lineno, docstring):
  406. """
  407. Create a new DocTest containing the given examples. The
  408. DocTest's globals are initialized with a copy of `globs`.
  409. """
  410. assert not isinstance(examples, basestring), \
  411. "DocTest no longer accepts str; use DocTestParser instead"
  412. self.examples = examples
  413. self.docstring = docstring
  414. self.globs = globs.copy()
  415. self.name = name
  416. self.filename = filename
  417. self.lineno = lineno
  418. def __repr__(self):
  419. if len(self.examples) == 0:
  420. examples = 'no examples'
  421. elif len(self.examples) == 1:
  422. examples = '1 example'
  423. else:
  424. examples = '%d examples' % len(self.examples)
  425. return ('<DocTest %s from %s:%s (%s)>' %
  426. (self.name, self.filename, self.lineno, examples))
  427. # This lets us sort tests by name:
  428. def __cmp__(self, other):
  429. if not isinstance(other, DocTest):
  430. return -1
  431. return cmp((self.name, self.filename, self.lineno, id(self)),
  432. (other.name, other.filename, other.lineno, id(other)))
  433. ######################################################################
  434. ## 3. DocTestParser
  435. ######################################################################
  436. class DocTestParser:
  437. """
  438. A class used to parse strings containing doctest examples.
  439. """
  440. # This regular expression is used to find doctest examples in a
  441. # string. It defines three groups: `source` is the source code
  442. # (including leading indentation and prompts); `indent` is the
  443. # indentation of the first (PS1) line of the source code; and
  444. # `want` is the expected output (including leading indentation).
  445. _EXAMPLE_RE = re.compile(r'''
  446. # Source consists of a PS1 line followed by zero or more PS2 lines.
  447. (?P<source>
  448. (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
  449. (?:\n [ ]* \.\.\. .*)*) # PS2 lines
  450. \n?
  451. # Want consists of any non-blank lines that do not start with PS1.
  452. (?P<want> (?:(?![ ]*$) # Not a blank line
  453. (?![ ]*>>>) # Not a line starting with PS1
  454. .*$\n? # But any other line
  455. )*)
  456. ''', re.MULTILINE | re.VERBOSE)
  457. # A regular expression for handling `want` strings that contain
  458. # expected exceptions. It divides `want` into three pieces:
  459. # - the traceback header line (`hdr`)
  460. # - the traceback stack (`stack`)
  461. # - the exception message (`msg`), as generated by
  462. # traceback.format_exception_only()
  463. # `msg` may have multiple lines. We assume/require that the
  464. # exception message is the first non-indented line starting with a word
  465. # character following the traceback header line.
  466. _EXCEPTION_RE = re.compile(r"""
  467. # Grab the traceback header. Different versions of Python have
  468. # said different things on the first traceback line.
  469. ^(?P<hdr> Traceback\ \(
  470. (?: most\ recent\ call\ last
  471. | innermost\ last
  472. ) \) :
  473. )
  474. \s* $ # toss trailing whitespace on the header.
  475. (?P<stack> .*?) # don't blink: absorb stuff until...
  476. ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
  477. """, re.VERBOSE | re.MULTILINE | re.DOTALL)
  478. # A callable returning a true value iff its argument is a blank line
  479. # or contains a single comment.
  480. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
  481. def parse(self, string, name='<string>'):
  482. """
  483. Divide the given string into examples and intervening text,
  484. and return them as a list of alternating Examples and strings.
  485. Line numbers for the Examples are 0-based. The optional
  486. argument `name` is a name identifying this string, and is only
  487. used for error messages.
  488. """
  489. string = string.expandtabs()
  490. # If all lines begin with the same indentation, then strip it.
  491. min_indent = self._min_indent(string)
  492. if min_indent > 0:
  493. string = '\n'.join([l[min_indent:] for l in string.split('\n')])
  494. output = []
  495. charno, lineno = 0, 0
  496. # Find all doctest examples in the string:
  497. for m in self._EXAMPLE_RE.finditer(string):
  498. # Add the pre-example text to `output`.
  499. output.append(string[charno:m.start()])
  500. # Update lineno (lines before this example)
  501. lineno += string.count('\n', charno, m.start())
  502. # Extract info from the regexp match.
  503. (source, options, want, exc_msg) = \
  504. self._parse_example(m, name, lineno)
  505. # Create an Example, and add it to the list.
  506. if not self._IS_BLANK_OR_COMMENT(source):
  507. output.append( Example(source, want, exc_msg,
  508. lineno=lineno,
  509. indent=min_indent+len(m.group('indent')),
  510. options=options) )
  511. # Update lineno (lines inside this example)
  512. lineno += string.count('\n', m.start(), m.end())
  513. # Update charno.
  514. charno = m.end()
  515. # Add any remaining post-example text to `output`.
  516. output.append(string[charno:])
  517. return output
  518. def get_doctest(self, string, globs, name, filename, lineno):
  519. """
  520. Extract all doctest examples from the given string, and
  521. collect them into a `DocTest` object.
  522. `globs`, `name`, `filename`, and `lineno` are attributes for
  523. the new `DocTest` object. See the documentation for `DocTest`
  524. for more information.
  525. """
  526. return DocTest(self.get_examples(string, name), globs,
  527. name, filename, lineno, string)
  528. def get_examples(self, string, name='<string>'):
  529. """
  530. Extract all doctest examples from the given string, and return
  531. them as a list of `Example` objects. Line numbers are
  532. 0-based, because it's most common in doctests that nothing
  533. interesting appears on the same line as opening triple-quote,
  534. and so the first interesting line is called \"line 1\" then.
  535. The optional argument `name` is a name identifying this
  536. string, and is only used for error messages.
  537. """
  538. return [x for x in self.parse(string, name)
  539. if isinstance(x, Example)]
  540. def _parse_example(self, m, name, lineno):
  541. """
  542. Given a regular expression match from `_EXAMPLE_RE` (`m`),
  543. return a pair `(source, want)`, where `source` is the matched
  544. example's source code (with prompts and indentation stripped);
  545. and `want` is the example's expected output (with indentation
  546. stripped).
  547. `name` is the string's name, and `lineno` is the line number
  548. where the example starts; both are used for error messages.
  549. """
  550. # Get the example's indentation level.
  551. indent = len(m.group('indent'))
  552. # Divide source into lines; check that they're properly
  553. # indented; and then strip their indentation & prompts.
  554. source_lines = m.group('source').split('\n')
  555. self._check_prompt_blank(source_lines, indent, name, lineno)
  556. self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
  557. source = '\n'.join([sl[indent+4:] for sl in source_lines])
  558. # Divide want into lines; check that it's properly indented; and
  559. # then strip the indentation. Spaces before the last newline should
  560. # be preserved, so plain rstrip() isn't good enough.
  561. want = m.group('want')
  562. want_lines = want.split('\n')
  563. if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
  564. del want_lines[-1] # forget final newline & spaces after it
  565. self._check_prefix(want_lines, ' '*indent, name,
  566. lineno + len(source_lines))
  567. want = '\n'.join([wl[indent:] for wl in want_lines])
  568. # If `want` contains a traceback message, then extract it.
  569. m = self._EXCEPTION_RE.match(want)
  570. if m:
  571. exc_msg = m.group('msg')
  572. else:
  573. exc_msg = None
  574. # Extract options from the source.
  575. options = self._find_options(source, name, lineno)
  576. return source, options, want, exc_msg
  577. # This regular expression looks for option directives in the
  578. # source code of an example. Option directives are comments
  579. # starting with "doctest:". Warning: this may give false
  580. # positives for string-literals that contain the string
  581. # "#doctest:". Eliminating these false positives would require
  582. # actually parsing the string; but we limit them by ignoring any
  583. # line containing "#doctest:" that is *followed* by a quote mark.
  584. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
  585. re.MULTILINE)
  586. def _find_options(self, source, name, lineno):
  587. """
  588. Return a dictionary containing option overrides extracted from
  589. option directives in the given source string.
  590. `name` is the string's name, and `lineno` is the line number
  591. where the example starts; both are used for error messages.
  592. """
  593. options = {}
  594. # (note: with the current regexp, this will match at most once:)
  595. for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  596. option_strings = m.group(1).replace(',', ' ').split()
  597. for option in option_strings:
  598. if (option[0] not in '+-' or
  599. option[1:] not in OPTIONFLAGS_BY_NAME):
  600. raise ValueError('line %r of the doctest for %s '
  601. 'has an invalid option: %r' %
  602. (lineno+1, name, option))
  603. flag = OPTIONFLAGS_BY_NAME[option[1:]]
  604. options[flag] = (option[0] == '+')
  605. if options and self._IS_BLANK_OR_COMMENT(source):
  606. raise ValueError('line %r of the doctest for %s has an option '
  607. 'directive on a line with no example: %r' %
  608. (lineno, name, source))
  609. return options
  610. # This regular expression finds the indentation of every non-blank
  611. # line in a string.
  612. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
  613. def _min_indent(self, s):
  614. "Return the minimum indentation of any non-blank line in `s`"
  615. indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
  616. if len(indents) > 0:
  617. return min(indents)
  618. else:
  619. return 0
  620. def _check_prompt_blank(self, lines, indent, name, lineno):
  621. """
  622. Given the lines of a source string (including prompts and
  623. leading indentation), check to make sure that every prompt is
  624. followed by a space character. If any line is not followed by
  625. a space character, then raise ValueError.
  626. """
  627. for i, line in enumerate(lines):
  628. if len(line) >= indent+4 and line[indent+3] != ' ':
  629. raise ValueError('line %r of the docstring for %s '
  630. 'lacks blank after %s: %r' %
  631. (lineno+i+1, name,
  632. line[indent:indent+3], line))
  633. def _check_prefix(self, lines, prefix, name, lineno):
  634. """
  635. Check that every line in the given list starts with the given
  636. prefix; if any line does not, then raise a ValueError.
  637. """
  638. for i, line in enumerate(lines):
  639. if line and not line.startswith(prefix):
  640. raise ValueError('line %r of the docstring for %s has '
  641. 'inconsistent leading whitespace: %r' %
  642. (lineno+i+1, name, line))
  643. ######################################################################
  644. ## 4. DocTest Finder
  645. ######################################################################
  646. class DocTestFinder:
  647. """
  648. A class used to extract the DocTests that are relevant to a given
  649. object, from its docstring and the docstrings of its contained
  650. objects. Doctests can currently be extracted from the following
  651. object types: modules, functions, classes, methods, staticmethods,
  652. classmethods, and properties.
  653. """
  654. def __init__(self, verbose=False, parser=DocTestParser(),
  655. recurse=True, _namefilter=None, exclude_empty=True):
  656. """
  657. Create a new doctest finder.
  658. The optional argument `parser` specifies a class or
  659. function that should be used to create new DocTest objects (or
  660. objects that implement the same interface as DocTest). The
  661. signature for this factory function should match the signature
  662. of the DocTest constructor.
  663. If the optional argument `recurse` is false, then `find` will
  664. only examine the given object, and not any contained objects.
  665. If the optional argument `exclude_empty` is false, then `find`
  666. will include tests for objects with empty docstrings.
  667. """
  668. self._parser = parser
  669. self._verbose = verbose
  670. self._recurse = recurse
  671. self._exclude_empty = exclude_empty
  672. # _namefilter is undocumented, and exists only for temporary backward-
  673. # compatibility support of testmod's deprecated isprivate mess.
  674. self._namefilter = _namefilter
  675. def find(self, obj, name=None, module=None, globs=None,
  676. extraglobs=None):
  677. """
  678. Return a list of the DocTests that are defined by the given
  679. object's docstring, or by any of its contained objects'
  680. docstrings.
  681. The optional parameter `module` is the module that contains
  682. the given object. If the module is not specified or is None, then
  683. the test finder will attempt to automatically determine the
  684. correct module. The object's module is used:
  685. - As a default namespace, if `globs` is not specified.
  686. - To prevent the DocTestFinder from extracting DocTests
  687. from objects that are imported from other modules.
  688. - To find the name of the file containing the object.
  689. - To help find the line number of the object within its
  690. file.
  691. Contained objects whose module does not match `module` are ignored.
  692. If `module` is False, no attempt to find the module will be made.
  693. This is obscure, of use mostly in tests: if `module` is False, or
  694. is None but cannot be found automatically, then all objects are
  695. considered to belong to the (non-existent) module, so all contained
  696. objects will (recursively) be searched for doctests.
  697. The globals for each DocTest is formed by combining `globs`
  698. and `extraglobs` (bindings in `extraglobs` override bindings
  699. in `globs`). A new copy of the globals dictionary is created
  700. for each DocTest. If `globs` is not specified, then it
  701. defaults to the module's `__dict__`, if specified, or {}
  702. otherwise. If `extraglobs` is not specified, then it defaults
  703. to {}.
  704. """
  705. # If name was not specified, then extract it from the object.
  706. if name is None:
  707. name = getattr(obj, '__name__', None)
  708. if name is None:
  709. raise ValueError("DocTestFinder.find: name must be given "
  710. "when obj.__name__ doesn't exist: %r" %
  711. (type(obj),))
  712. # Find the module that contains the given object (if obj is
  713. # a module, then module=obj.). Note: this may fail, in which
  714. # case module will be None.
  715. if module is False:
  716. module = None
  717. elif module is None:
  718. module = inspect.getmodule(obj)
  719. # Read the module's source code. This is used by
  720. # DocTestFinder._find_lineno to find the line number for a
  721. # given object's docstring.
  722. try:
  723. file = inspect.getsourcefile(obj) or inspect.getfile(obj)
  724. source_lines = linecache.getlines(file)
  725. if not source_lines:
  726. source_lines = None
  727. except TypeError:
  728. source_lines = None
  729. # Initialize globals, and merge in extraglobs.
  730. if globs is None:
  731. if module is None:
  732. globs = {}
  733. else:
  734. globs = module.__dict__.copy()
  735. else:
  736. globs = globs.copy()
  737. if extraglobs is not None:
  738. globs.update(extraglobs)
  739. # Recursively expore `obj`, extracting DocTests.
  740. tests = []
  741. self._find(tests, obj, name, module, source_lines, globs, {})
  742. # Sort the tests by alpha order of names, for consistency in
  743. # verbose-mode output. This was a feature of doctest in Pythons
  744. # <= 2.3 that got lost by accident in 2.4. It was repaired in
  745. # 2.4.4 and 2.5.
  746. tests.sort()
  747. return tests
  748. def _filter(self, obj, prefix, base):
  749. """
  750. Return true if the given object should not be examined.
  751. """
  752. return (self._namefilter is not None and
  753. self._namefilter(prefix, base))
  754. def _from_module(self, module, object):
  755. """
  756. Return true if the given object is defined in the given
  757. module.
  758. """
  759. if module is None:
  760. return True
  761. elif inspect.isfunction(object):
  762. return module.__dict__ is object.func_globals
  763. elif inspect.isclass(object):
  764. return module.__name__ == object.__module__
  765. elif inspect.getmodule(object) is not None:
  766. return module is inspect.getmodule(object)
  767. elif hasattr(object, '__module__'):
  768. return module.__name__ == object.__module__
  769. elif isinstance(object, property):
  770. return True # [XX] no way not be sure.
  771. else:
  772. raise ValueError("object must be a class or function")
  773. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  774. """
  775. Find tests for the given object and any contained objects, and
  776. add them to `tests`.
  777. """
  778. if self._verbose:
  779. print 'Finding tests in %s' % name
  780. # If we've already processed this object, then ignore it.
  781. if id(obj) in seen:
  782. return
  783. seen[id(obj)] = 1
  784. # Find a test for this object, and add it to the list of tests.
  785. test = self._get_test(obj, name, module, globs, source_lines)
  786. if test is not None:
  787. tests.append(test)
  788. # Look for tests in a module's contained objects.
  789. if inspect.ismodule(obj) and self._recurse:
  790. for valname, val in obj.__dict__.items():
  791. # Check if this contained object should be ignored.
  792. if self._filter(val, name, valname):
  793. continue
  794. valname = '%s.%s' % (name, valname)
  795. # Recurse to functions & classes.
  796. if ((inspect.isfunction(val) or inspect.isclass(val)) and
  797. self._from_module(module, val)):
  798. self._find(tests, val, valname, module, source_lines,
  799. globs, seen)
  800. # Look for tests in a module's __test__ dictionary.
  801. if inspect.ismodule(obj) and self._recurse:
  802. for valname, val in getattr(obj, '__test__', {}).items():
  803. if not isinstance(valname, basestring):
  804. raise ValueError("DocTestFinder.find: __test__ keys "
  805. "must be strings: %r" %
  806. (type(valname),))
  807. if not (inspect.isfunction(val) or inspect.isclass(val) or
  808. inspect.ismethod(val) or inspect.ismodule(val) or
  809. isinstance(val, basestring)):
  810. raise ValueError("DocTestFinder.find: __test__ values "
  811. "must be strings, functions, methods, "
  812. "classes, or modules: %r" %
  813. (type(val),))
  814. valname = '%s.__test__.%s' % (name, valname)
  815. self._find(tests, val, valname, module, source_lines,
  816. globs, seen)
  817. # Look for tests in a class's contained objects.
  818. if inspect.isclass(obj) and self._recurse:
  819. for valname, val in obj.__dict__.items():
  820. # Check if this contained object should be ignored.
  821. if self._filter(val, name, valname):
  822. continue
  823. # Special handling for staticmethod/classmethod.
  824. if isinstance(val, staticmethod):
  825. val = getattr(obj, valname)
  826. if isinstance(val, classmethod):
  827. val = getattr(obj, valname).im_func
  828. # Recurse to methods, properties, and nested classes.
  829. if ((inspect.isfunction(val) or inspect.isclass(val) or
  830. isinstance(val, property)) and
  831. self._from_module(module, val)):
  832. valname = '%s.%s' % (name, valname)
  833. self._find(tests, val, valname, module, source_lines,
  834. globs, seen)
  835. def _get_test(self, obj, name, module, globs, source_lines):
  836. """
  837. Return a DocTest for the given object, if it defines a docstring;
  838. otherwise, return None.
  839. """
  840. # Extract the object's docstring. If it doesn't have one,
  841. # then return None (no test for this object).
  842. if isinstance(obj, basestring):
  843. docstring = obj
  844. else:
  845. try:
  846. if obj.__doc__ is None:
  847. docstring = ''
  848. else:
  849. docstring = obj.__doc__
  850. if not isinstance(docstring, basestring):
  851. docstring = str(docstring)
  852. except (TypeError, AttributeError):
  853. docstring = ''
  854. # Find the docstring's location in the file.
  855. lineno = self._find_lineno(obj, source_lines)
  856. # Don't bother if the docstring is empty.
  857. if self._exclude_empty and not docstring:
  858. return None
  859. # Return a DocTest for this object.
  860. if module is None:
  861. filename = None
  862. else:
  863. filename = getattr(module, '__file__', module.__name__)
  864. if filename[-4:] in (".pyc", ".pyo"):
  865. filename = filename[:-1]
  866. return self._parser.get_doctest(docstring, globs, name,
  867. filename, lineno)
  868. def _find_lineno(self, obj, source_lines):
  869. """
  870. Return a line number of the given object's docstring. Note:
  871. this method assumes that the object has a docstring.
  872. """
  873. lineno = None
  874. # Find the line number for modules.
  875. if inspect.ismodule(obj):
  876. lineno = 0
  877. # Find the line number for classes.
  878. # Note: this could be fooled if a class is defined multiple
  879. # times in a single file.
  880. if inspect.isclass(obj):
  881. if source_lines is None:
  882. return None
  883. pat = re.compile(r'^\s*class\s*%s\b' %
  884. getattr(obj, '__name__', '-'))
  885. for i, line in enumerate(source_lines):
  886. if pat.match(line):
  887. lineno = i
  888. break
  889. # Find the line number for functions & methods.
  890. if inspect.ismethod(obj): obj = obj.im_func
  891. if inspect.isfunction(obj): obj = obj.func_code
  892. if inspect.istraceback(obj): obj = obj.tb_frame
  893. if inspect.isframe(obj): obj = obj.f_code
  894. if inspect.iscode(obj):
  895. lineno = getattr(obj, 'co_firstlineno', None)-1
  896. # Find the line number where the docstring starts. Assume
  897. # that it's the first line that begins with a quote mark.
  898. # Note: this could be fooled by a multiline function
  899. # signature, where a continuation line begins with a quote
  900. # mark.
  901. if lineno is not None:
  902. if source_lines is None:
  903. return lineno+1
  904. pat = re.compile('(^|.*:)\s*\w*("|\')')
  905. for lineno in range(lineno, len(source_lines)):
  906. if pat.match(source_lines[lineno]):
  907. return lineno
  908. # We couldn't find the line number.
  909. return None
  910. ######################################################################
  911. ## 5. DocTest Runner
  912. ######################################################################
  913. class DocTestRunner:
  914. """
  915. A class used to run DocTest test cases, and accumulate statistics.
  916. The `run` method is used to process a single DocTest case. It
  917. returns a tuple `(f, t)`, where `t` is the number of test cases
  918. tried, and `f` is the number of test cases that failed.
  919. >>> tests = DocTestFinder().find(_TestClass)
  920. >>> runner = DocTestRunner(verbose=False)
  921. >>> tests.sort(key = lambda test: test.name)
  922. >>> for test in tests:
  923. ... print test.name, '->', runner.run(test)
  924. _TestClass -> (0, 2)
  925. _TestClass.__init__ -> (0, 2)
  926. _TestClass.get -> (0, 2)
  927. _TestClass.square -> (0, 1)
  928. The `summarize` method prints a summary of all the test cases that
  929. have been run by the runner, and returns an aggregated `(f, t)`
  930. tuple:
  931. >>> runner.summarize(verbose=1)
  932. 4 items passed all tests:
  933. 2 tests in _TestClass
  934. 2 tests in _TestClass.__init__
  935. 2 tests in _TestClass.get
  936. 1 tests in _TestClass.square
  937. 7 tests in 4 items.
  938. 7 passed and 0 failed.
  939. Test passed.
  940. (0, 7)
  941. The aggregated number of tried examples and failed examples is
  942. also available via the `tries` and `failures` attributes:
  943. >>> runner.tries
  944. 7
  945. >>> runner.failures
  946. 0
  947. The comparison between expected outputs and actual outputs is done
  948. by an `OutputChecker`. This comparison may be customized with a
  949. number of option flags; see the documentation for `testmod` for
  950. more information. If the option flags are insufficient, then the
  951. comparison may also be customized by passing a subclass of
  952. `OutputChecker` to the constructor.
  953. The test runner's display output can be controlled in two ways.
  954. First, an output function (`out) can be passed to
  955. `TestRunner.run`; this function will be called with strings that
  956. should be displayed. It defaults to `sys.stdout.write`. If
  957. capturing the output is not sufficient, then the display output
  958. can be also customized by subclassing DocTestRunner, and
  959. overriding the methods `report_start`, `report_success`,
  960. `report_unexpected_exception`, and `report_failure`.
  961. """
  962. # This divider string is used to separate failure messages, and to
  963. # separate sections of the summary.
  964. DIVIDER = "*" * 70
  965. def __init__(self, checker=None, verbose=None, optionflags=0):
  966. """
  967. Create a new test runner.
  968. Optional keyword arg `checker` is the `OutputChecker` that
  969. should be used to compare the expected outputs and actual
  970. outputs of doctest examples.
  971. Optional keyword arg 'verbose' prints lots of stuff if true,
  972. only failures if false; by default, it's true iff '-v' is in
  973. sys.argv.
  974. Optional argument `optionflags` can be used to control how the
  975. test runner compares expected output to actual output, and how
  976. it displays failures. See the documentation for `testmod` for
  977. more information.
  978. """
  979. self._checker = checker or OutputChecker()
  980. if verbose is None:
  981. verbose = '-v' in sys.argv
  982. self._verbose = verbose
  983. self.optionflags = optionflags
  984. self.original_optionflags = optionflags
  985. # Keep track of the examples we've run.
  986. self.tries = 0
  987. self.failures = 0
  988. self._name2ft = {}
  989. # Create a fake output target for capturing doctest output.
  990. self._fakeout = _SpoofOut()
  991. #/////////////////////////////////////////////////////////////////
  992. # Reporting methods
  993. #/////////////////////////////////////////////////////////////////
  994. def report_start(self, out, test, example):
  995. """
  996. Report that the test runner is about to process the given
  997. example. (Only displays a message if verbose=True)
  998. """
  999. if self._verbose:
  1000. if example.want:
  1001. out('Trying:\n' + _indent(example.source) +
  1002. 'Expecting:\n' + _indent(example.want))
  1003. else:
  1004. out('Trying:\n' + _indent(example.source) +
  1005. 'Expecting nothing\n')
  1006. def report_success(self, out, test, example, got):
  1007. """
  1008. Report that the given example ran successfully. (Only
  1009. displays a message if verbose=True)
  1010. """
  1011. if self._verbose:
  1012. out("ok\n")
  1013. def report_failure(self, out, test, example, got):
  1014. """
  1015. Report that the given example failed.
  1016. """
  1017. out(self._failure_header(test, example) +
  1018. self._checker.output_difference(example, got, self.optionflags))
  1019. def report_unexpected_exception(self, out, test, example, exc_info):
  1020. """
  1021. Report that the given example raised an unexpected exception.
  1022. """
  1023. out(self._failure_header(test, example) +
  1024. 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  1025. def _failure_header(self, test, example):
  1026. out = [self.DIVIDER]
  1027. if test.filename:
  1028. if test.lineno is not None and example.lineno is not None:
  1029. lineno = test.lineno + example.lineno + 1
  1030. else:
  1031. lineno = '?'
  1032. out.append('File "%s", line %s, in %s' %
  1033. (test.filename, lineno, test.name))
  1034. else:
  1035. out.append('Line %s, in %s' % (example.lineno+1, test.name))
  1036. out.append('Failed example:')
  1037. source = example.source
  1038. out.append(_indent(source))
  1039. return '\n'.join(out)
  1040. #/////////////////////////////////////////////////////////////////
  1041. # DocTest Running
  1042. #/////////////////////////////////////////////////////////////////
  1043. def __run(self, test, compileflags, out):
  1044. """
  1045. Run the examples in `test`. Write the outcome of each example
  1046. with one of the `DocTestRunner.report_*` methods, using the
  1047. writer function `out`. `compileflags` is the set of compiler
  1048. flags that should be used to execute examples. Return a tuple
  1049. `(f, t)`, where `t` is the number of examples tried, and `f`
  1050. is the number of examples that failed. The examples are run
  1051. in the namespace `test.globs`.
  1052. """
  1053. # Keep track of the number of failures and tries.
  1054. failures = tries = 0
  1055. # Save the option flags (since option directives can be used
  1056. # to modify them).
  1057. original_optionflags = self.optionflags
  1058. SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
  1059. check = self._checker.check_output
  1060. # Process each example.
  1061. for examplenum, example in enumerate(test.examples):
  1062. # If REPORT_ONLY_FIRST_FAILURE is set, then supress
  1063. # reporting after the first failure.
  1064. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
  1065. failures > 0)
  1066. # Merge in the example's options.
  1067. self.optionflags = original_optionflags
  1068. if example.options:
  1069. for (optionflag, val) in example.options.items():
  1070. if val:
  1071. self.optionflags |= optionflag
  1072. else:
  1073. self.optionflags &= ~optionflag
  1074. # Record that we started this example.
  1075. tries += 1
  1076. if not quiet:
  1077. self.report_start(out, test, example)
  1078. # Use a special filename for compile(), so we can retrieve
  1079. # the source code during interactive debugging (see
  1080. # __patched_linecache_getlines).
  1081. filename = '<doctest %s[%d]>' % (test.name, examplenum)
  1082. # Run the example in the given context (globs), and record
  1083. # any exception that gets raised. (But don't intercept
  1084. # keyboard interrupts.)
  1085. try:
  1086. # Don't blink! This is where the user's code gets run.
  1087. exec compile(example.source, filename, "single",
  1088. compileflags, 1) in test.globs
  1089. self.debugger.set_continue() # ==== Example Finished ====
  1090. exception = None
  1091. except KeyboardInterrupt:
  1092. raise
  1093. except:
  1094. exception = sys.exc_info()
  1095. self.debugger.set_continue() # ==== Example Finished ====
  1096. got = self._fakeout.getvalue() # the actual output
  1097. self._fakeout.truncate(0)
  1098. outcome = FAILURE # guilty until proved innocent or insane
  1099. # If the example executed without raising any exceptions,
  1100. # verify its output.
  1101. if exception is None:
  1102. if check(example.want, got, self.optionflags):
  1103. outcome = SUCCESS
  1104. # The example raised an exception: check if it was expected.
  1105. else:
  1106. exc_info = sys.exc_info()
  1107. exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1108. if not quiet:
  1109. got += _exception_traceback(exc_info)
  1110. # If `example.exc_msg` is None, then we weren't expecting
  1111. # an exception.
  1112. if example.exc_msg is None:
  1113. outcome = BOOM
  1114. # We expected an exception: see whether it matches.
  1115. elif check(example.exc_msg, exc_msg, self.optionflags):
  1116. outcome = SUCCESS
  1117. # Another chance if they didn't care about the detail.
  1118. elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1119. m1 = re.match(r'[^:]*:', example.exc_msg)
  1120. m2 = re.match(r'[^:]*:', exc_msg)
  1121. if m1 and m2 and check(m1.group(0), m2.group(0),
  1122. self.optionflags):
  1123. outcome = SUCCESS
  1124. # Report the outcome.
  1125. if outcome is SUCCESS:
  1126. if not quiet:
  1127. self.report_success(out, test, example, got)
  1128. elif outcome is FAILURE:
  1129. if not quiet:
  1130. self.report_failure(out, test, example, got)
  1131. failures += 1
  1132. elif outcome is BOOM:
  1133. if not quiet:
  1134. self.report_unexpected_exception(out, test, example,
  1135. exc_info)
  1136. failures += 1
  1137. else:
  1138. assert False, ("unknown outcome", outcome)
  1139. # Restore the option flags (in case they were modified)
  1140. self.optionflags = original_optionflags
  1141. # Record and return the number of failures and tries.
  1142. self.__record_outcome(test, failures, tries)
  1143. return failures, tries
  1144. def __record_outcome(self, test, f, t):
  1145. """
  1146. Record the fact that the given DocTest (`test`) generated `f`
  1147. failures out of `t` tried examples.
  1148. """
  1149. f2, t2 = self._name2ft.get(test.name, (0,0))
  1150. self._name2ft[test.name] = (f+f2, t+t2)
  1151. self.failures += f
  1152. self.tries += t
  1153. __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
  1154. r'(?P<name>[\w\.]+)'
  1155. r'\[(?P<examplenum>\d+)\]>$')
  1156. def __patched_linecache_getlines(self, filename):
  1157. m = self.__LINECACHE_FILENAME_RE.match(filename)
  1158. if m and m.group('name') == self.test.name:
  1159. example = self.test.examples[int(m.group('examplenum'))]
  1160. return example.source.splitlines(True)
  1161. else:
  1162. return self.save_linecache_getlines(filename)
  1163. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1164. """
  1165. Run the examples in `test`, and display the results using the
  1166. writer function `out`.
  1167. The examples are run in the namespace `test.globs`. If
  1168. `clear_globs` is true (the default), then this namespace will
  1169. be cleared after the test runs, to help with garbage
  1170. collection. If you would like to examine the namespace after
  1171. the test completes, then use `clear_globs=False`.
  1172. `compileflags` gives the set of flags that should be used by
  1173. the Python compiler when running the examples. If not
  1174. specified, then it will default to the set of future-import
  1175. flags that apply to `globs`.
  1176. The output of each example is checked using
  1177. `DocTestRunner.check_output`, and the results are formatted by
  1178. the `DocTestRunner.report_*` methods.
  1179. """
  1180. self.test = test
  1181. if compileflags is None:
  1182. compileflags = _extract_future_flags(test.globs)
  1183. save_stdout = sys.stdout
  1184. if out is None:
  1185. out = save_stdout.write
  1186. sys.stdout = self._fakeout
  1187. # Patch pdb.set_trace to restore sys.stdout during interactive
  1188. # debugging (so it's not still redirected to self._fakeout).
  1189. # Note that the interactive output will go to *our*
  1190. # save_stdout, even if that's not the real sys.stdout; this
  1191. # allows us to write test cases for the set_trace behavior.
  1192. save_set_trace = pdb.set_trace
  1193. self.debugger = _OutputRedirectingPdb(save_stdout)
  1194. self.debugger.reset()
  1195. pdb.set_trace = self.debugger.set_trace
  1196. # Patch linecache.getlines, so we can see the example's source
  1197. # when we're inside the debugger.
  1198. self.save_linecache_getlines = linecache.getlines
  1199. linecache.getlines = self.__patched_linecache_getlines
  1200. try:
  1201. return self.__run(test, compileflags, out)
  1202. finally:
  1203. sys.stdout = save_stdout
  1204. pdb.set_trace = save_set_trace
  1205. linecache.getlines = self.save_linecache_getlines
  1206. if clear_globs:
  1207. test.globs.clear()
  1208. #/////////////////////////////////////////////////////////////////
  1209. # Summarization
  1210. #/////////////////////////////////////////////////////////////////
  1211. def summarize(self, verbose=None):
  1212. """
  1213. Print a summary of all the test cases that have been run by
  1214. this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1215. the total number of failed examples, and `t` is the total
  1216. number of tried examples.
  1217. The optional `verbose` argument controls how detailed the
  1218. summary is. If the verbosity is not specified, then the
  1219. DocTestRunner's verbosity is used.
  1220. """
  1221. if verbose is None:
  1222. verbose = self._verbose
  1223. notests = []
  1224. passed = []
  1225. failed = []
  1226. totalt = totalf = 0
  1227. for x in self._name2ft.items():
  1228. name, (f, t) = x
  1229. assert f <= t
  1230. totalt += t
  1231. totalf += f
  1232. if t == 0:
  1233. notests.append(name)
  1234. elif f == 0:
  1235. passed.append( (name, t) )
  1236. else:
  1237. failed.append(x)
  1238. if verbose:
  1239. if notests:
  1240. print len(notests), "items had no tests:"
  1241. notests.sort()
  1242. for thing in notests:
  1243. print " ", thing
  1244. if passed:
  1245. print len(passed), "items passed all tests:"
  1246. passed.sort()
  1247. for thing, count in passed:
  1248. print " %3d tests in %s" % (count, thing)
  1249. if failed:
  1250. print self.DIVIDER
  1251. print len(failed), "items had failures:"
  1252. failed.sort()
  1253. for thing, (f, t) in failed:
  1254. print " %3d of %3d in %s" % (f, t, thing)
  1255. if verbose:
  1256. print totalt, "tests in", len(self._name2ft), "items."
  1257. print totalt - totalf, "passed and", totalf, "failed."
  1258. if totalf:
  1259. print "***Test Failed***", totalf, "failures."
  1260. elif verbose:
  1261. print "Test passed."
  1262. return totalf, totalt
  1263. #/////////////////////////////////////////////////////////////////
  1264. # Backward compatibility cruft to maintain doctest.master.
  1265. #/////////////////////////////////////////////////////////////////
  1266. def merge(self, other):
  1267. d = self._name2ft
  1268. for name, (f, t) in other._name2ft.items():
  1269. if name in d:
  1270. print "*** DocTestRunner.merge: '" + name + "' in both" \
  1271. " testers; summing outcomes."
  1272. f2, t2 = d[name]
  1273. f = f + f2
  1274. t = t + t2
  1275. d[name] = f, t
  1276. class OutputChecker:
  1277. """
  1278. A class used to check the whether the actual output from a doctest
  1279. example matches the expected output. `OutputChecker` defines two
  1280. methods: `check_output`, which compares a given pair of outputs,
  1281. and returns true if they match; and `output_difference`, which
  1282. returns a string describing the differences between two outputs.
  1283. """
  1284. def check_output(self, want, got, optionflags):
  1285. """
  1286. Return True iff the actual output from an example (`got`)
  1287. matches the expected output (`want`). These strings are
  1288. always considered to match if they are identical; but
  1289. depending on what option flags the test runner is using,
  1290. several non-exact match types are also possible. See the
  1291. documentation for `TestRunner` for more information about
  1292. option flags.
  1293. """
  1294. # Handle the common case first, for efficiency:
  1295. # if they're string-identical, always return true.
  1296. if got == want:
  1297. return True
  1298. # The values True and False replaced 1 and 0 as the return
  1299. # value for boolean comparisons in Python 2.3.
  1300. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
  1301. if (got,want) == ("True\n", "1\n"):
  1302. return True
  1303. if (got,want) == ("False\n", "0\n"):
  1304. return True
  1305. # <BLANKLINE> can be used as a special sequence to signify a
  1306. # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
  1307. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1308. # Replace <BLANKLINE> in want with a blank line.
  1309. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
  1310. '', want)
  1311. # If a line in got contains only spaces, then remove the
  1312. # spaces.
  1313. got = re.sub('(?m)^\s*?$', '', got)
  1314. if got == want:
  1315. return True
  1316. # This flag causes doctest to ignore any differences in the
  1317. # contents of whitespace strings. Note that this can be used
  1318. # in conjunction with the ELLIPSIS flag.
  1319. if optionflags & NORMALIZE_WHITESPACE:
  1320. got = ' '.join(got.split())
  1321. want = ' '.join(want.split())
  1322. if got == want:
  1323. return True
  1324. # The ELLIPSIS flag says to let the sequence "..." in `want`
  1325. # match any substring in `got`.
  1326. if optionflags & ELLIPSIS:
  1327. if _ellipsis_match(want, got):
  1328. return True
  1329. # We didn't find any match; return false.
  1330. return False
  1331. # Should we do a fancy diff?
  1332. def _do_a_fancy_diff(self, want, got, optionflags):
  1333. # Not unless they asked for a fancy diff.
  1334. if not optionflags & (REPORT_UDIFF |
  1335. REPORT_CDIFF |
  1336. REPORT_NDIFF):
  1337. return False
  1338. # If expected output uses ellipsis, a meaningful fancy diff is
  1339. # too hard ... or maybe not. In two real-life failures Tim saw,
  1340. # a diff was a major help anyway, so this is commented out.
  1341. # [todo] _ellipsis_match() knows which pieces do and don't match,
  1342. # and could be the basis for a kick-ass diff in this case.
  1343. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
  1344. ## return False
  1345. # ndiff does intraline difference marking, so can be useful even
  1346. # for 1-line differences.
  1347. if optionflags & REPORT_NDIFF:
  1348. return True
  1349. # The other diff types need at least a few lines to be helpful.
  1350. return want.count('\n') > 2 and got.count('\n') > 2
  1351. def output_difference(self, example, got, optionflags):
  1352. """
  1353. Return a string describing the differences between the
  1354. expected output for a given example (`example`) and the actual
  1355. output (`got`). `optionflags` is the set of option flags used
  1356. to compare `want` and `got`.
  1357. """
  1358. want = example.want
  1359. # If <BLANKLINE>s are being used, then replace blank lines
  1360. # with <BLANKLINE> in the actual output string.
  1361. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1362. got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1363. # Check if we should use diff.
  1364. if self._do_a_fancy_diff(want, got, optionflags):
  1365. # Split want & got into lines.
  1366. want_lines = want.splitlines(True) # True == keep line ends
  1367. got_lines = got.splitlines(True)
  1368. # Use difflib to find their differences.
  1369. if optionflags & REPORT_UDIFF:
  1370. diff = difflib.unified_diff(want_lines, got_lines, n=2)
  1371. diff = list(diff)[2:] # strip the diff header
  1372. kind = 'unified diff with -expected +actual'
  1373. elif optionflags & REPORT_CDIFF:
  1374. diff = difflib.context_diff(want_lines, got_lines, n=2)
  1375. diff = list(diff)[2:] # strip the diff header
  1376. kind = 'context diff with expected followed by actual'
  1377. elif optionflags & REPORT_NDIFF:
  1378. engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
  1379. diff = list(engine.compare(want_lines, got_lines))
  1380. kind = 'ndiff with -expected +actual'
  1381. else:
  1382. assert 0, 'Bad diff option'
  1383. # Remove trailing whitespace on diff output.
  1384. diff = [line.rstrip() + '\n' for line in diff]
  1385. return 'Differences (%s):\n' % kind + _indent(''.join(diff))
  1386. # If we're not using diff, then simply list the expected
  1387. # output followed by the actual output.
  1388. if want and got:
  1389. return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1390. elif want:
  1391. return 'Expected:\n%sGot nothing\n' % _indent(want)
  1392. elif got:
  1393. return 'Expected nothing\nGot:\n%s' % _indent(got)
  1394. else:
  1395. return 'Expected nothing\nGot nothing\n'
  1396. class DocTestFailure(Exception):
  1397. """A DocTest example has failed in debugging mode.
  1398. The exception instance has variables:
  1399. - test: the DocTest object being run
  1400. - excample: the Example object that failed
  1401. - got: the actual output
  1402. """
  1403. def __init__(self, test, example, got):
  1404. self.test = test
  1405. self.example = example
  1406. self.got = got
  1407. def __str__(self):
  1408. return str(self.test)
  1409. class UnexpectedException(Exception):
  1410. """A DocTest example has encountered an unexpected exception
  1411. The exception instance has variables:
  1412. - test: the DocTest object being run
  1413. - excample: the Example object that failed
  1414. - exc_info: the exception info
  1415. """
  1416. def __init__(self, test, example, exc_info):
  1417. self.test = test
  1418. self.example = example
  1419. self.exc_info = exc_info
  1420. def __str__(self):
  1421. return str(self.test)
  1422. class DebugRunner(DocTestRunner):
  1423. r"""Run doc tests but raise an exception as soon as there is a failure.
  1424. If an unexpected exception occurs, an UnexpectedException is raised.
  1425. It contains the test, the example, and the original exception:
  1426. >>> runner = DebugRunner(verbose=False)
  1427. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1428. ... {}, 'foo', 'foo.py', 0)
  1429. >>> try:
  1430. ... runner.run(test)
  1431. ... except UnexpectedException, failure:
  1432. ... pass
  1433. >>> failure.test is test
  1434. True
  1435. >>> failure.example.want
  1436. '42\n'
  1437. >>> exc_info = failure.exc_info
  1438. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1439. Traceback (most recent call last):
  1440. ...
  1441. KeyError
  1442. We wrap the original exception to give the calling application
  1443. access to the test and example information.
  1444. If the output doesn't match, then a DocTestFailure is raised:
  1445. >>> test = DocTestParser().get_doctest('''
  1446. ... >>> x = 1
  1447. ... >>> x
  1448. ... 2
  1449. ... ''', {}, 'foo', 'foo.py', 0)
  1450. >>> try:
  1451. ... runner.run(test)
  1452. ... except DocTestFailure, failure:
  1453. ... pass
  1454. DocTestFailure objects provide access to the test:
  1455. >>> failure.test is test
  1456. True
  1457. As well as to the example:
  1458. >>> failure.example.want
  1459. '2\n'
  1460. and the actual output:
  1461. >>> failure.got
  1462. '1\n'
  1463. If a failure or error occurs, the globals are left intact:
  1464. >>> del test.globs['__builtins__']
  1465. >>> test.globs
  1466. {'x': 1}
  1467. >>> test = DocTestParser().get_doctest('''
  1468. ... >>> x = 2
  1469. ... >>> raise KeyError
  1470. ... ''', {}, 'foo', 'foo.py', 0)
  1471. >>> runner.run(test)
  1472. Traceback (most recent call last):
  1473. ...
  1474. UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1475. >>> del test.globs['__builtins__']
  1476. >>> test.globs
  1477. {'x': 2}
  1478. But the globals are cleared if there is no error:
  1479. >>> test = DocTestParser().get_doctest('''
  1480. ... >>> x = 2
  1481. ... ''', {}, 'foo', 'foo.py', 0)
  1482. >>> runner.run(test)
  1483. (0, 1)
  1484. >>> test.globs
  1485. {}
  1486. """
  1487. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1488. r = DocTestRunner.run(self, test, compileflags, out, False)
  1489. if clear_globs:
  1490. test.globs.clear()
  1491. return r
  1492. def report_unexpected_exception(self, out, test, example, exc_info):
  1493. raise UnexpectedException(test, example, exc_info)
  1494. def report_failure(self, out, test, example, got):
  1495. raise DocTestFailure(test, example, got)
  1496. ######################################################################
  1497. ## 6. Test Functions
  1498. ######################################################################
  1499. # These should be backwards compatible.
  1500. # For backward compatibility, a global instance of a DocTestRunner
  1501. # class, updated by testmod.
  1502. master = None
  1503. def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
  1504. report=True, optionflags=0, extraglobs=None,
  1505. raise_on_error=False, exclude_empty=False):
  1506. """m=None, name=None, globs=None, verbose=None, isprivate=None,
  1507. report=True, optionflags=0, extraglobs=None, raise_on_error=False,
  1508. exclude_empty=False
  1509. Test examples in docstrings in functions and classes reachable
  1510. from module m (or the current module if m is not supplied), starting
  1511. with m.__doc__. Unless isprivate is specified, private names
  1512. are not skipped.
  1513. Also test examples reachable from dict m.__test__ if it exists and is
  1514. not None. m.__test__ maps names to functions, classes and strings;
  1515. function and class docstrings are tested even if the name is private;
  1516. strings are tested directly, as if they were docstrings.
  1517. Return (#failures, #tests).
  1518. See doctest.__doc__ for an overview.
  1519. Optional keyword arg "name" gives the name of the module; by default
  1520. use m.__name__.
  1521. Optional keyword arg "globs" gives a dict to be used as the globals
  1522. when executing examples; by default, use m.__dict__. A copy of this
  1523. dict is actually used for each docstring, so that each docstring's
  1524. examples start with a clean slate.
  1525. Optional keyword arg "extraglobs" gives a dictionary that should be
  1526. merged into the globals that are used to execute examples. By
  1527. default, no extra globals are used. This is new in 2.4.
  1528. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1529. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1530. Optional keyword arg "report" prints a summary at the end when true,
  1531. else prints nothing at the end. In verbose mode, the summary is
  1532. detailed, else very brief (in fact, empty if all tests passed).
  1533. Optional keyword arg "optionflags" or's together module constants,
  1534. and defaults to 0. This is new in 2.3. Possible values (see the
  1535. docs for details):
  1536. DONT_ACCEPT_TRUE_FOR_1
  1537. DONT_ACCEPT_BLANKLINE
  1538. NORMALIZE_WHITESPACE
  1539. ELLIPSIS
  1540. IGNORE_EXCEPTION_DETAIL
  1541. REPORT_UDIFF
  1542. REPORT_CDIFF
  1543. REPORT_NDIFF
  1544. REPORT_ONLY_FIRST_FAILURE
  1545. Optional keyword arg "raise_on_error" raises an exception on the
  1546. first unexpected exception or failure. This allows failures to be
  1547. post-mortem debugged.
  1548. Deprecated in Python 2.4:
  1549. Optional keyword arg "isprivate" specifies a function used to
  1550. determine whether a name is private. The default function is
  1551. treat all functions as public. Optionally, "isprivate" can be
  1552. set to doctest.is_private to skip over functions marked as private
  1553. using the underscore naming convention; see its docs for details.
  1554. Advanced tomfoolery: testmod runs methods of a local instance of
  1555. class doctest.Tester, then merges the results into (or creates)
  1556. global Tester instance doctest.master. Methods of doctest.master
  1557. can be called directly too, if you want to do something unusual.
  1558. Passing report=0 to testmod is especially useful then, to delay
  1559. displaying a summary. Invoke doctest.master.summarize(verbose)
  1560. when you're done fiddling.
  1561. """
  1562. global master
  1563. if isprivate is not None:
  1564. warnings.warn("the isprivate argument is deprecated; "
  1565. "examine DocTestFinder.find() lists instead",
  1566. DeprecationWarning)
  1567. # If no module was given, then use __main__.
  1568. if m is None:
  1569. # DWA - m will still be None if this wasn't invoked from the command
  1570. # line, in which case the following TypeError is about as good an error
  1571. # as we should expect
  1572. m = sys.modules.get('__main__')
  1573. # Check that we were actually given a module.
  1574. if not inspect.ismodule(m):
  1575. raise TypeError("testmod: module required; %r" % (m,))
  1576. # If no name was given, then use the module's name.
  1577. if name is None:
  1578. name = m.__name__
  1579. # Find, parse, and run all tests in the given module.
  1580. finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
  1581. if raise_on_error:
  1582. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1583. else:
  1584. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1585. for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
  1586. runner.run(test)
  1587. if report:
  1588. runner.summarize()
  1589. if master is None:
  1590. master = runner
  1591. else:
  1592. master.merge(runner)
  1593. return runner.failures, runner.tries
  1594. def testfile(filename, module_relative=True, name=None, package=None,
  1595. globs=None, verbose=None, report=True, optionflags=0,
  1596. extraglobs=None, raise_on_error=False, parser=DocTestParser()):
  1597. """
  1598. Test examples in the given file. Return (#failures, #tests).
  1599. Optional keyword arg "module_relative" specifies how filenames
  1600. should be interpreted:
  1601. - If "module_relative" is True (the default), then "filename"
  1602. specifies a module-relative path. By default, this path is
  1603. relative to the calling module's directory; but if the
  1604. "package" argument is specified, then it is relative to that
  1605. package. To ensure os-independence, "filename" should use
  1606. "/" characters to separate path segments, and should not
  1607. be an absolute path (i.e., it may not begin with "/").
  1608. - If "module_relative" is False, then "filename" specifies an
  1609. os-specific path. The path may be absolute or relative (to
  1610. the current working directory).
  1611. Optional keyword arg "name" gives the name of the test; by default
  1612. use the file's basename.
  1613. Optional keyword argument "package" is a Python package or the
  1614. name of a Python package whose directory should be used as the
  1615. base directory for a module relative filename. If no package is
  1616. specified, then the calling module's directory is used as the base
  1617. directory for module relative filenames. It is an error to
  1618. specify "package" if "module_relative" is False.
  1619. Optional keyword arg "globs" gives a dict to be used as the globals
  1620. when executing examples; by default, use {}. A copy of this dict
  1621. is actually used for each docstring, so that each docstring's
  1622. examples start with a clean slate.
  1623. Optional keyword arg "extraglobs" gives a dictionary that should be
  1624. merged into the globals that are used to execute examples. By
  1625. default, no extra globals are used.
  1626. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1627. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1628. Optional keyword arg "report" prints a summary at the end when true,
  1629. else prints nothing at the end. In verbose mode, the summary is
  1630. detailed, else very brief (in fact, empty if all tests passed).
  1631. Optional keyword arg "optionflags" or's together module constants,
  1632. and defaults to 0. Possible values (see the docs for details):
  1633. DONT_ACCEPT_TRUE_FOR_1
  1634. DONT_ACCEPT_BLANKLINE
  1635. NORMALIZE_WHITESPACE
  1636. ELLIPSIS
  1637. IGNORE_EXCEPTION_DETAIL
  1638. REPORT_UDIFF
  1639. REPORT_CDIFF
  1640. REPORT_NDIFF
  1641. REPORT_ONLY_FIRST_FAILURE
  1642. Optional keyword arg "raise_on_error" raises an exception on the
  1643. first unexpected exception or failure. This allows failures to be
  1644. post-mortem debugged.
  1645. Optional keyword arg "parser" specifies a DocTestParser (or
  1646. subclass) that should be used to extract tests from the files.
  1647. Advanced tomfoolery: testmod runs methods of a local instance of
  1648. class doctest.Tester, then merges the results into (or creates)
  1649. global Tester instance doctest.master. Methods of doctest.master
  1650. can be called directly too, if you want to do something unusual.
  1651. Passing report=0 to testmod is especially useful then, to delay
  1652. displaying a summary. Invoke doctest.master.summarize(verbose)
  1653. when you're done fiddling.
  1654. """
  1655. global master
  1656. if package and not module_relative:
  1657. raise ValueError("Package may only be specified for module-"
  1658. "relative paths.")
  1659. # Relativize the path
  1660. if module_relative:
  1661. package = _normalize_module(package)
  1662. filename = _module_relative_path(package, filename)
  1663. # If no name was given, then use the file's name.
  1664. if name is None:
  1665. name = os.path.basename(filename)
  1666. # Assemble the globals.
  1667. if globs is None:
  1668. globs = {}
  1669. else:
  1670. globs = globs.copy()
  1671. if extraglobs is not None:
  1672. globs.update(extraglobs)
  1673. if raise_on_error:
  1674. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1675. else:
  1676. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1677. # Read the file, convert it to a test, and run it.
  1678. s = open(filename).read()
  1679. test = parser.get_doctest(s, globs, name, filename, 0)
  1680. runner.run(test)
  1681. if report:
  1682. runner.summarize()
  1683. if master is None:
  1684. master = runner
  1685. else:
  1686. master.merge(runner)
  1687. return runner.failures, runner.tries
  1688. def run_docstring_examples(f, globs, verbose=False, name="NoName",
  1689. compileflags=None, optionflags=0):
  1690. """
  1691. Test examples in the given object's docstring (`f`), using `globs`
  1692. as globals. Optional argument `name` is used in failure messages.
  1693. If the optional argument `verbose` is true, then generate output
  1694. even if there are no failures.
  1695. `compileflags` gives the set of flags that should be used by the
  1696. Python compiler when running the examples. If not specified, then
  1697. it will default to the set of future-import flags that apply to
  1698. `globs`.
  1699. Optional keyword arg `optionflags` specifies options for the
  1700. testing and output. See the documentation for `testmod` for more
  1701. information.
  1702. """
  1703. # Find, parse, and run all tests in the given module.
  1704. finder = DocTestFinder(verbose=verbose, recurse=False)
  1705. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1706. for test in finder.find(f, name, globs=globs):
  1707. runner.run(test, compileflags=compileflags)
  1708. ######################################################################
  1709. ## 7. Tester
  1710. ######################################################################
  1711. # This is provided only for backwards compatibility. It's not
  1712. # actually used in any way.
  1713. class Tester:
  1714. def __init__(self, mod=None, globs=None, verbose=None,
  1715. isprivate=None, optionflags=0):
  1716. warnings.warn("class Tester is deprecated; "
  1717. "use class doctest.DocTestRunner instead",
  1718. DeprecationWarning, stacklevel=2)
  1719. if mod is None and globs is None:
  1720. raise TypeError("Tester.__init__: must specify mod or globs")
  1721. if mod is not None and not inspect.ismodule(mod):
  1722. raise TypeError("Tester.__init__: mod must be a module; %r" %
  1723. (mod,))
  1724. if globs is None:
  1725. globs = mod.__dict__
  1726. self.globs = globs
  1727. self.verbose = verbose
  1728. self.isprivate = isprivate
  1729. self.optionflags = optionflags
  1730. self.testfinder = DocTestFinder(_namefilter=isprivate)
  1731. self.testrunner = DocTestRunner(verbose=verbose,
  1732. optionflags=optionflags)
  1733. def runstring(self, s, name):
  1734. test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1735. if self.verbose:
  1736. print "Running string", name
  1737. (f,t) = self.testrunner.run(test)
  1738. if self.verbose:
  1739. print f, "of", t, "examples failed in string", name
  1740. return (f,t)
  1741. def rundoc(self, object, name=None, module=None):
  1742. f = t = 0
  1743. tests = self.testfinder.find(object, name, module=module,
  1744. globs=self.globs)
  1745. for test in tests:
  1746. (f2, t2) = self.testrunner.run(test)
  1747. (f,t) = (f+f2, t+t2)
  1748. return (f,t)
  1749. def rundict(self, d, name, module=None):
  1750. import new
  1751. m = new.module(name)
  1752. m.__dict__.update(d)
  1753. if module is None:
  1754. module = False
  1755. return self.rundoc(m, name, module)
  1756. def run__test__(self, d, name):
  1757. import new
  1758. m = new.module(name)
  1759. m.__test__ = d
  1760. return self.rundoc(m, name)
  1761. def summarize(self, verbose=None):
  1762. return self.testrunner.summarize(verbose)
  1763. def merge(self, other):
  1764. self.testrunner.merge(other.testrunner)
  1765. ######################################################################
  1766. ## 8. Unittest Support
  1767. ######################################################################
  1768. _unittest_reportflags = 0
  1769. def set_unittest_reportflags(flags):
  1770. """Sets the unittest option flags.
  1771. The old flag is returned so that a runner could restore the old
  1772. value if it wished to:
  1773. >>> import doctest
  1774. >>> old = doctest._unittest_reportflags
  1775. >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1776. ... REPORT_ONLY_FIRST_FAILURE) == old
  1777. True
  1778. >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1779. ... REPORT_ONLY_FIRST_FAILURE)
  1780. True
  1781. Only reporting flags can be set:
  1782. >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1783. Traceback (most recent call last):
  1784. ...
  1785. ValueError: ('Only reporting flags allowed', 8)
  1786. >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1787. ... REPORT_ONLY_FIRST_FAILURE)
  1788. True
  1789. """
  1790. global _unittest_reportflags
  1791. if (flags & REPORTING_FLAGS) != flags:
  1792. raise ValueError("Only reporting flags allowed", flags)
  1793. old = _unittest_reportflags
  1794. _unittest_reportflags = flags
  1795. return old
  1796. class DocTestCase(unittest.TestCase):
  1797. def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
  1798. checker=None):
  1799. unittest.TestCase.__init__(self)
  1800. self._dt_optionflags = optionflags
  1801. self._dt_checker = checker
  1802. self._dt_test = test
  1803. self._dt_setUp = setUp
  1804. self._dt_tearDown = tearDown
  1805. def setUp(self):
  1806. test = self._dt_test
  1807. if self._dt_setUp is not None:
  1808. self._dt_setUp(test)
  1809. def tearDown(self):
  1810. test = self._dt_test
  1811. if self._dt_tearDown is not None:
  1812. self._dt_tearDown(test)
  1813. test.globs.clear()
  1814. def runTest(self):
  1815. test = self._dt_test
  1816. old = sys.stdout
  1817. new = StringIO()
  1818. optionflags = self._dt_optionflags
  1819. if not (optionflags & REPORTING_FLAGS):
  1820. # The option flags don't include any reporting flags,
  1821. # so add the default reporting flags
  1822. optionflags |= _unittest_reportflags
  1823. runner = DocTestRunner(optionflags=optionflags,
  1824. checker=self._dt_checker, verbose=False)
  1825. try:
  1826. runner.DIVIDER = "-"*70
  1827. failures, tries = runner.run(
  1828. test, out=new.write, clear_globs=False)
  1829. finally:
  1830. sys.stdout = old
  1831. if failures:
  1832. raise self.failureException(self.format_failure(new.getvalue()))
  1833. def format_failure(self, err):
  1834. test = self._dt_test
  1835. if test.lineno is None:
  1836. lineno = 'unknown line number'
  1837. else:
  1838. lineno = '%s' % test.lineno
  1839. lname = '.'.join(test.name.split('.')[-1:])
  1840. return ('Failed doctest test for %s\n'
  1841. ' File "%s", line %s, in %s\n\n%s'
  1842. % (test.name, test.filename, lineno, lname, err)
  1843. )
  1844. def debug(self):
  1845. r"""Run the test case without results and without catching exceptions
  1846. The unit test framework includes a debug method on test cases
  1847. and test suites to support post-mortem debugging. The test code
  1848. is run in such a way that errors are not caught. This way a
  1849. caller can catch the errors and initiate post-mortem debugging.
  1850. The DocTestCase provides a debug method that raises
  1851. UnexpectedException errors if there is an unexepcted
  1852. exception:
  1853. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1854. ... {}, 'foo', 'foo.py', 0)
  1855. >>> case = DocTestCase(test)
  1856. >>> try:
  1857. ... case.debug()
  1858. ... except UnexpectedException, failure:
  1859. ... pass
  1860. The UnexpectedException contains the test, the example, and
  1861. the original exception:
  1862. >>> failure.test is test
  1863. True
  1864. >>> failure.example.want
  1865. '42\n'
  1866. >>> exc_info = failure.exc_info
  1867. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1868. Traceback (most recent call last):
  1869. ...
  1870. KeyError
  1871. If the output doesn't match, then a DocTestFailure is raised:
  1872. >>> test = DocTestParser().get_doctest('''
  1873. ... >>> x = 1
  1874. ... >>> x
  1875. ... 2
  1876. ... ''', {}, 'foo', 'foo.py', 0)
  1877. >>> case = DocTestCase(test)
  1878. >>> try:
  1879. ... case.debug()
  1880. ... except DocTestFailure, failure:
  1881. ... pass
  1882. DocTestFailure objects provide access to the test:
  1883. >>> failure.test is test
  1884. True
  1885. As well as to the example:
  1886. >>> failure.example.want
  1887. '2\n'
  1888. and the actual output:
  1889. >>> failure.got
  1890. '1\n'
  1891. """
  1892. self.setUp()
  1893. runner = DebugRunner(optionflags=self._dt_optionflags,
  1894. checker=self._dt_checker, verbose=False)
  1895. runner.run(self._dt_test)
  1896. self.tearDown()
  1897. def id(self):
  1898. return self._dt_test.name
  1899. def __repr__(self):
  1900. name = self._dt_test.name.split('.')
  1901. return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
  1902. __str__ = __repr__
  1903. def shortDescription(self):
  1904. return "Doctest: " + self._dt_test.name
  1905. def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
  1906. **options):
  1907. """
  1908. Convert doctest tests for a module to a unittest test suite.
  1909. This converts each documentation string in a module that
  1910. contains doctest tests to a unittest test case. If any of the
  1911. tests in a doc string fail, then the test case fails. An exception
  1912. is raised showing the name of the file containing the test and a
  1913. (sometimes approximate) line number.
  1914. The `module` argument provides the module to be tested. The argument
  1915. can be either a module or a module name.
  1916. If no argument is given, the calling module is used.
  1917. A number of options may be provided as keyword arguments:
  1918. setUp
  1919. A set-up function. This is called before running the
  1920. tests in each file. The setUp function will be passed a DocTest
  1921. object. The setUp function can access the test globals as the
  1922. globs attribute of the test passed.
  1923. tearDown
  1924. A tear-down function. This is called after running the
  1925. tests in each file. The tearDown function will be passed a DocTest
  1926. object. The tearDown function can access the test globals as the
  1927. globs attribute of the test passed.
  1928. globs
  1929. A dictionary containing initial global variables for the tests.
  1930. optionflags
  1931. A set of doctest option flags expressed as an integer.
  1932. """
  1933. if test_finder is None:
  1934. test_finder = DocTestFinder()
  1935. module = _normalize_module(module)
  1936. tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
  1937. if globs is None:
  1938. globs = module.__dict__
  1939. if not tests:
  1940. # Why do we want to do this? Because it reveals a bug that might
  1941. # otherwise be hidden.
  1942. raise ValueError(module, "has no tests")
  1943. tests.sort()
  1944. suite = unittest.TestSuite()
  1945. for test in tests:
  1946. if len(test.examples) == 0:
  1947. continue
  1948. if not test.filename:
  1949. filename = module.__file__
  1950. if filename[-4:] in (".pyc", ".pyo"):
  1951. filename = filename[:-1]
  1952. test.filename = filename
  1953. suite.addTest(DocTestCase(test, **options))
  1954. return suite
  1955. class DocFileCase(DocTestCase):
  1956. def id(self):
  1957. return '_'.join(self._dt_test.name.split('.'))
  1958. def __repr__(self):
  1959. return self._dt_test.filename
  1960. __str__ = __repr__
  1961. def format_failure(self, err):
  1962. return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
  1963. % (self._dt_test.name, self._dt_test.filename, err)
  1964. )
  1965. def DocFileTest(path, module_relative=True, package=None,
  1966. globs=None, parser=DocTestParser(), **options):
  1967. if globs is None:
  1968. globs = {}
  1969. if package and not module_relative:
  1970. raise ValueError("Package may only be specified for module-"
  1971. "relative paths.")
  1972. # Relativize the path.
  1973. if module_relative:
  1974. package = _normalize_module(package)
  1975. path = _module_relative_path(package, path)
  1976. # Find the file and read it.
  1977. name = os.path.basename(path)
  1978. doc = open(path).read()
  1979. # Convert it to a test, and wrap it in a DocFileCase.
  1980. test = parser.get_doctest(doc, globs, name, path, 0)
  1981. return DocFileCase(test, **options)
  1982. def DocFileSuite(*paths, **kw):
  1983. """A unittest suite for one or more doctest files.
  1984. The path to each doctest file is given as a string; the
  1985. interpretation of that string depends on the keyword argument
  1986. "module_relative".
  1987. A number of options may be provided as keyword arguments:
  1988. module_relative
  1989. If "module_relative" is True, then the given file paths are
  1990. interpreted as os-independent module-relative paths. By
  1991. default, these paths are relative to the calling module's
  1992. directory; but if the "package" argument is specified, then
  1993. they are relative to that package. To ensure os-independence,
  1994. "filename" should use "/" characters to separate path
  1995. segments, and may not be an absolute path (i.e., it may not
  1996. begin with "/").
  1997. If "module_relative" is False, then the given file paths are
  1998. interpreted as os-specific paths. These paths may be absolute
  1999. or relative (to the current working directory).
  2000. package
  2001. A Python package or the name of a Python package whose directory
  2002. should be used as the base directory for module relative paths.
  2003. If "package" is not specified, then the calling module's
  2004. directory is used as the base directory for module relative
  2005. filenames. It is an error to specify "package" if
  2006. "module_relative" is False.
  2007. setUp
  2008. A set-up function. This is called before running the
  2009. tests in each file. The setUp function will be passed a DocTest
  2010. object. The setUp function can access the test globals as the
  2011. globs attribute of the test passed.
  2012. tearDown
  2013. A tear-down function. This is called after running the
  2014. tests in each file. The tearDown function will be passed a DocTest
  2015. object. The tearDown function can access the test globals as the
  2016. globs attribute of the test passed.
  2017. globs
  2018. A dictionary containing initial global variables for the tests.
  2019. optionflags
  2020. A set of doctest option flags expressed as an integer.
  2021. parser
  2022. A DocTestParser (or subclass) that should be used to extract
  2023. tests from the files.
  2024. """
  2025. suite = unittest.TestSuite()
  2026. # We do this here so that _normalize_module is called at the right
  2027. # level. If it were called in DocFileTest, then this function
  2028. # would be the caller and we might guess the package incorrectly.
  2029. if kw.get('module_relative', True):
  2030. kw['package'] = _normalize_module(kw.get('package'))
  2031. for path in paths:
  2032. suite.addTest(DocFileTest(path, **kw))
  2033. return suite
  2034. ######################################################################
  2035. ## 9. Debugging Support
  2036. ######################################################################
  2037. def script_from_examples(s):
  2038. r"""Extract script from text with examples.
  2039. Converts text with examples to a Python script. Example input is
  2040. converted to regular code. Example output and all other words
  2041. are converted to comments:
  2042. >>> text = '''
  2043. ... Here are examples of simple math.
  2044. ...
  2045. ... Python has super accurate integer addition
  2046. ...
  2047. ... >>> 2 + 2
  2048. ... 5
  2049. ...
  2050. ... And very friendly error messages:
  2051. ...
  2052. ... >>> 1/0
  2053. ... To Infinity
  2054. ... And
  2055. ... Beyond
  2056. ...
  2057. ... You can use logic if you want:
  2058. ...
  2059. ... >>> if 0:
  2060. ... ... blah
  2061. ... ... blah
  2062. ... ...
  2063. ...
  2064. ... Ho hum
  2065. ... '''
  2066. >>> print script_from_examples(text)
  2067. # Here are examples of simple math.
  2068. #
  2069. # Python has super accurate integer addition
  2070. #
  2071. 2 + 2
  2072. # Expected:
  2073. ## 5
  2074. #
  2075. # And very friendly error messages:
  2076. #
  2077. 1/0
  2078. # Expected:
  2079. ## To Infinity
  2080. ## And
  2081. ## Beyond
  2082. #
  2083. # You can use logic if you want:
  2084. #
  2085. if 0:
  2086. blah
  2087. blah
  2088. #
  2089. # Ho hum
  2090. <BLANKLINE>
  2091. """
  2092. output = []
  2093. for piece in DocTestParser().parse(s):
  2094. if isinstance(piece, Example):
  2095. # Add the example's source code (strip trailing NL)
  2096. output.append(piece.source[:-1])
  2097. # Add the expected output:
  2098. want = piece.want
  2099. if want:
  2100. output.append('# Expected:')
  2101. output += ['## '+l for l in want.split('\n')[:-1]]
  2102. else:
  2103. # Add non-example text.
  2104. output += [_comment_line(l)
  2105. for l in piece.split('\n')[:-1]]
  2106. # Trim junk on both ends.
  2107. while output and output[-1] == '#':
  2108. output.pop()
  2109. while output and output[0] == '#':
  2110. output.pop(0)
  2111. # Combine the output, and return it.
  2112. # Add a courtesy newline to prevent exec from choking (see bug #1172785)
  2113. return '\n'.join(output) + '\n'
  2114. def testsource(module, name):
  2115. """Extract the test sources from a doctest docstring as a script.
  2116. Provide the module (or dotted name of the module) containing the
  2117. test to be debugged and the name (within the module) of the object
  2118. with the doc string with tests to be debugged.
  2119. """
  2120. module = _normalize_module(module)
  2121. tests = DocTestFinder().find(module)
  2122. test = [t for t in tests if t.name == name]
  2123. if not test:
  2124. raise ValueError(name, "not found in tests")
  2125. test = test[0]
  2126. testsrc = script_from_examples(test.docstring)
  2127. return testsrc
  2128. def debug_src(src, pm=False, globs=None):
  2129. """Debug a single doctest docstring, in argument `src`'"""
  2130. testsrc = script_from_examples(src)
  2131. debug_script(testsrc, pm, globs)
  2132. def debug_script(src, pm=False, globs=None):
  2133. "Debug a test script. `src` is the script, as a string."
  2134. import pdb
  2135. # Note that tempfile.NameTemporaryFile() cannot be used. As the
  2136. # docs say, a file so created cannot be opened by name a second time
  2137. # on modern Windows boxes, and execfile() needs to open it.
  2138. srcfilename = tempfile.mktemp(".py", "doctestdebug")
  2139. f = open(srcfilename, 'w')
  2140. f.write(src)
  2141. f.close()
  2142. try:
  2143. if globs:
  2144. globs = globs.copy()
  2145. else:
  2146. globs = {}
  2147. if pm:
  2148. try:
  2149. execfile(srcfilename, globs, globs)
  2150. except:
  2151. print sys.exc_info()[1]
  2152. pdb.post_mortem(sys.exc_info()[2])
  2153. else:
  2154. # Note that %r is vital here. '%s' instead can, e.g., cause
  2155. # backslashes to get treated as metacharacters on Windows.
  2156. pdb.run("execfile(%r)" % srcfilename, globs, globs)
  2157. finally:
  2158. os.remove(srcfilename)
  2159. def debug(module, name, pm=False):
  2160. """Debug a single doctest docstring.
  2161. Provide the module (or dotted name of the module) containing the
  2162. test to be debugged and the name (within the module) of the object
  2163. with the docstring with tests to be debugged.
  2164. """
  2165. module = _normalize_module(module)
  2166. testsrc = testsource(module, name)
  2167. debug_script(testsrc, pm, module.__dict__)
  2168. ######################################################################
  2169. ## 10. Example Usage
  2170. ######################################################################
  2171. class _TestClass:
  2172. """
  2173. A pointless class, for sanity-checking of docstring testing.
  2174. Methods:
  2175. square()
  2176. get()
  2177. >>> _TestClass(13).get() + _TestClass(-12).get()
  2178. 1
  2179. >>> hex(_TestClass(13).square().get())
  2180. '0xa9'
  2181. """
  2182. def __init__(self, val):
  2183. """val -> _TestClass object with associated value val.
  2184. >>> t = _TestClass(123)
  2185. >>> print t.get()
  2186. 123
  2187. """
  2188. self.val = val
  2189. def square(self):
  2190. """square() -> square TestClass's associated value
  2191. >>> _TestClass(13).square().get()
  2192. 169
  2193. """
  2194. self.val = self.val ** 2
  2195. return self
  2196. def get(self):
  2197. """get() -> return TestClass's associated value.
  2198. >>> x = _TestClass(-42)
  2199. >>> print x.get()
  2200. -42
  2201. """
  2202. return self.val
  2203. __test__ = {"_TestClass": _TestClass,
  2204. "string": r"""
  2205. Example of a string object, searched as-is.
  2206. >>> x = 1; y = 2
  2207. >>> x + y, x * y
  2208. (3, 2)
  2209. """,
  2210. "bool-int equivalence": r"""
  2211. In 2.2, boolean expressions displayed
  2212. 0 or 1. By default, we still accept
  2213. them. This can be disabled by passing
  2214. DONT_ACCEPT_TRUE_FOR_1 to the new
  2215. optionflags argument.
  2216. >>> 4 == 4
  2217. 1
  2218. >>> 4 == 4
  2219. True
  2220. >>> 4 > 4
  2221. 0
  2222. >>> 4 > 4
  2223. False
  2224. """,
  2225. "blank lines": r"""
  2226. Blank lines can be marked with <BLANKLINE>:
  2227. >>> print 'foo\n\nbar\n'
  2228. foo
  2229. <BLANKLINE>
  2230. bar
  2231. <BLANKLINE>
  2232. """,
  2233. "ellipsis": r"""
  2234. If the ellipsis flag is used, then '...' can be used to
  2235. elide substrings in the desired output:
  2236. >>> print range(1000) #doctest: +ELLIPSIS
  2237. [0, 1, 2, ..., 999]
  2238. """,
  2239. "whitespace normalization": r"""
  2240. If the whitespace normalization flag is used, then
  2241. differences in whitespace are ignored.
  2242. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
  2243. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  2244. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  2245. 27, 28, 29]
  2246. """,
  2247. }
  2248. def _test():
  2249. r = unittest.TextTestRunner()
  2250. r.run(DocTestSuite())
  2251. if __name__ == "__main__":
  2252. _test()