_doctest.py 97 KB

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