doctest.py 102 KB

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