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

/setuptools/tests/doctest.py

https://bitbucket.org/mumak/distribute
Python | 2679 lines | 2560 code | 20 blank | 99 comment | 43 complexity | 1127bf4bb6ba60231b6a9e02d7ced421 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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.f…

Large files files are truncated, but you can click here to view the full file