doctest.py 104 KB

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