PageRenderTime 32ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/setuptools/tests/doctest.py

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