PageRenderTime 66ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/python/lib/Lib/doctest.py

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