dtcompat.py 86 KB

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