doctest.py 103 KB

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