_doctest.py 101 KB

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