PageRenderTime 36ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/unladen_swallow/lib/django/django/test/_doctest.py

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