PageRenderTime 65ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/unladen_swallow/lib/google_appengine/lib/django/django/test/doctest.py

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