PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/doctest.py

http://github.com/JetBrains/intellij-community
Python | 2665 lines | 2600 code | 13 blank | 52 comment | 27 complexity | d5a0cfebce75dabd4392e28fafffc6c9 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0

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. r"""Module doctest -- a framework for running examples in docstrings.
  8. In simplest use, end each module M to be tested with:
  9. def _test():
  10. import doctest
  11. doctest.testmod()
  12. if __name__ == "__main__":
  13. _test()
  14. Then running the module as a script will cause the examples in the
  15. docstrings to get executed and verified:
  16. python M.py
  17. This won't display anything unless an example fails, in which case the
  18. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  19. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  20. line of output is "Test failed.".
  21. Run it with the -v switch instead:
  22. python M.py -v
  23. and a detailed report of all examples tried is printed to stdout, along
  24. with assorted summaries at the end.
  25. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  26. it by passing "verbose=False". In either of those cases, sys.argv is not
  27. examined by testmod.
  28. There are a variety of other ways to run doctests, including integration
  29. with the unittest framework, and support for running non-Python text
  30. files containing doctests. There are also many ways to override parts
  31. of doctest's default behaviors. See the Library Reference Manual for
  32. details.
  33. """
  34. __docformat__ = 'reStructuredText en'
  35. __all__ = [
  36. # 0, Option Flags
  37. 'register_optionflag',
  38. 'DONT_ACCEPT_TRUE_FOR_1',
  39. 'DONT_ACCEPT_BLANKLINE',
  40. 'NORMALIZE_WHITESPACE',
  41. 'ELLIPSIS',
  42. 'SKIP',
  43. 'IGNORE_EXCEPTION_DETAIL',
  44. 'COMPARISON_FLAGS',
  45. 'REPORT_UDIFF',
  46. 'REPORT_CDIFF',
  47. 'REPORT_NDIFF',
  48. 'REPORT_ONLY_FIRST_FAILURE',
  49. 'REPORTING_FLAGS',
  50. # 1. Utility Functions
  51. # 2. Example & DocTest
  52. 'Example',
  53. 'DocTest',
  54. # 3. Doctest Parser
  55. 'DocTestParser',
  56. # 4. Doctest Finder
  57. 'DocTestFinder',
  58. # 5. Doctest Runner
  59. 'DocTestRunner',
  60. 'OutputChecker',
  61. 'DocTestFailure',
  62. 'UnexpectedException',
  63. 'DebugRunner',
  64. # 6. Test Functions
  65. 'testmod',
  66. 'testfile',
  67. 'run_docstring_examples',
  68. # 7. Tester
  69. 'Tester',
  70. # 8. Unittest Support
  71. 'DocTestSuite',
  72. 'DocFileSuite',
  73. 'set_unittest_reportflags',
  74. # 9. Debugging Support
  75. 'script_from_examples',
  76. 'testsource',
  77. 'debug_src',
  78. 'debug',
  79. ]
  80. import __future__
  81. import sys, traceback, inspect, linecache, os, re
  82. import unittest, difflib, pdb, tempfile
  83. import warnings
  84. from StringIO import StringIO
  85. # There are 4 basic classes:
  86. # - Example: a <source, want> pair, plus an intra-docstring line number.
  87. # - DocTest: a collection of examples, parsed from a docstring, plus
  88. # info about where the docstring came from (name, filename, lineno).
  89. # - DocTestFinder: extracts DocTests from a given object's docstring and
  90. # its contained objects' docstrings.
  91. # - DocTestRunner: runs DocTest cases, and accumulates statistics.
  92. #
  93. # So the basic picture is:
  94. #
  95. # list of:
  96. # +------+ +---------+ +-------+
  97. # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
  98. # +------+ +---------+ +-------+
  99. # | Example |
  100. # | ... |
  101. # | Example |
  102. # +---------+
  103. # Option constants.
  104. OPTIONFLAGS_BY_NAME = {}
  105. def register_optionflag(name):
  106. # Create a new flag unless `name` is already known.
  107. return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  108. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  109. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  110. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  111. ELLIPSIS = register_optionflag('ELLIPSIS')
  112. SKIP = register_optionflag('SKIP')
  113. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  114. COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
  115. DONT_ACCEPT_BLANKLINE |
  116. NORMALIZE_WHITESPACE |
  117. ELLIPSIS |
  118. SKIP |
  119. IGNORE_EXCEPTION_DETAIL)
  120. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  121. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  122. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  123. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  124. REPORTING_FLAGS = (REPORT_UDIFF |
  125. REPORT_CDIFF |
  126. REPORT_NDIFF |
  127. REPORT_ONLY_FIRST_FAILURE)
  128. # Special string markers for use in `want` strings:
  129. BLANKLINE_MARKER = '<BLANKLINE>'
  130. ELLIPSIS_MARKER = '...'
  131. ######################################################################
  132. ## Table of Contents
  133. ######################################################################
  134. # 1. Utility Functions
  135. # 2. Example & DocTest -- store test cases
  136. # 3. DocTest Parser -- extracts examples from strings
  137. # 4. DocTest Finder -- extracts test cases from objects
  138. # 5. DocTest Runner -- runs test cases
  139. # 6. Test Functions -- convenient wrappers for testing
  140. # 7. Tester Class -- for backwards compatibility
  141. # 8. Unittest Support
  142. # 9. Debugging Support
  143. # 10. Example Usage
  144. ######################################################################
  145. ## 1. Utility Functions
  146. ######################################################################
  147. def _extract_future_flags(globs):
  148. """
  149. Return the compiler-flags associated with the future features that
  150. have been imported into the given namespace (globs).
  151. """
  152. flags = 0
  153. for fname in __future__.all_feature_names:
  154. feature = globs.get(fname, None)
  155. if feature is getattr(__future__, fname):
  156. flags |= feature.compiler_flag
  157. return flags
  158. def _normalize_module(module, depth=2):
  159. """
  160. Return the module specified by `module`. In particular:
  161. - If `module` is a module, then return module.
  162. - If `module` is a string, then import and return the
  163. module with that name.
  164. - If `module` is None, then return the calling module.
  165. The calling module is assumed to be the module of
  166. the stack frame at the given depth in the call stack.
  167. """
  168. if inspect.ismodule(module):
  169. return module
  170. elif isinstance(module, (str, unicode)):
  171. return __import__(module, globals(), locals(), ["*"])
  172. elif module is None:
  173. return sys.modules[sys._getframe(depth).f_globals['__name__']]
  174. else:
  175. raise TypeError("Expected a module, string, or None")
  176. def _load_testfile(filename, package, module_relative):
  177. if module_relative:
  178. package = _normalize_module(package, 3)
  179. filename = _module_relative_path(package, filename)
  180. if hasattr(package, '__loader__'):
  181. if hasattr(package.__loader__, 'get_data'):
  182. file_contents = package.__loader__.get_data(filename)
  183. # get_data() opens files as 'rb', so one must do the equivalent
  184. # conversion as universal newlines would do.
  185. return file_contents.replace(os.linesep, '\n'), filename
  186. return open(filename).read(), filename
  187. def _indent(s, indent=4):
  188. """
  189. Add the given number of space characters to the beginning every
  190. non-blank line in `s`, and return the result.
  191. """
  192. # This regexp matches the start of non-blank lines:
  193. return re.sub('(?m)^(?!$)', indent*' ', s)
  194. def _exception_traceback(exc_info):
  195. """
  196. Return a string containing a traceback message for the given
  197. exc_info tuple (as returned by sys.exc_info()).
  198. """
  199. # Get a traceback message.
  200. excout = StringIO()
  201. exc_type, exc_val, exc_tb = exc_info
  202. traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
  203. return excout.getvalue()
  204. # Override some StringIO methods.
  205. class _SpoofOut(StringIO):
  206. def getvalue(self):
  207. result = StringIO.getvalue(self)
  208. # If anything at all was written, make sure there's a trailing
  209. # newline. There's no way for the expected output to indicate
  210. # that a trailing newline is missing.
  211. if result and not result.endswith("\n"):
  212. result += "\n"
  213. # Prevent softspace from screwing up the next test case, in
  214. # case they used print with a trailing comma in an example.
  215. if hasattr(self, "softspace"):
  216. del self.softspace
  217. return result
  218. def truncate(self, size=None):
  219. StringIO.truncate(self, size)
  220. if hasattr(self, "softspace"):
  221. del self.softspace
  222. # Worst-case linear-time ellipsis matching.
  223. def _ellipsis_match(want, got):
  224. """
  225. Essentially the only subtle case:
  226. >>> _ellipsis_match('aa...aa', 'aaa')
  227. False
  228. """
  229. if ELLIPSIS_MARKER not in want:
  230. return want == got
  231. # Find "the real" strings.
  232. ws = want.split(ELLIPSIS_MARKER)
  233. assert len(ws) >= 2
  234. # Deal with exact matches possibly needed at one or both ends.
  235. startpos, endpos = 0, len(got)
  236. w = ws[0]
  237. if w: # starts with exact match
  238. if got.startswith(w):
  239. startpos = len(w)
  240. del ws[0]
  241. else:
  242. return False
  243. w = ws[-1]
  244. if w: # ends with exact match
  245. if got.endswith(w):
  246. endpos -= len(w)
  247. del ws[-1]
  248. else:
  249. return False
  250. if startpos > endpos:
  251. # Exact end matches required more characters than we have, as in
  252. # _ellipsis_match('aa...aa', 'aaa')
  253. return False
  254. # For the rest, we only need to find the leftmost non-overlapping
  255. # match for each piece. If there's no overall match that way alone,
  256. # there's no overall match period.
  257. for w in ws:
  258. # w may be '' at times, if there are consecutive ellipses, or
  259. # due to an ellipsis at the start or end of `want`. That's OK.
  260. # Search for an empty string succeeds, and doesn't change startpos.
  261. startpos = got.find(w, startpos, endpos)
  262. if startpos < 0:
  263. return False
  264. startpos += len(w)
  265. return True
  266. def _comment_line(line):
  267. "Return a commented form of the given line"
  268. line = line.rstrip()
  269. if line:
  270. return '# '+line
  271. else:
  272. return '#'
  273. class _OutputRedirectingPdb(pdb.Pdb):
  274. """
  275. A specialized version of the python debugger that redirects stdout
  276. to a given stream when interacting with the user. Stdout is *not*
  277. redirected when traced code is executed.
  278. """
  279. def __init__(self, out):
  280. self.__out = out
  281. self.__debugger_used = False
  282. pdb.Pdb.__init__(self, stdout=out)
  283. def set_trace(self, frame=None):
  284. self.__debugger_used = True
  285. if frame is None:
  286. frame = sys._getframe().f_back
  287. pdb.Pdb.set_trace(self, frame)
  288. def set_continue(self):
  289. # Calling set_continue unconditionally would break unit test
  290. # coverage reporting, as Bdb.set_continue calls sys.settrace(None).
  291. if self.__debugger_used:
  292. pdb.Pdb.set_continue(self)
  293. def trace_dispatch(self, *args):
  294. # Redirect stdout to the given stream.
  295. save_stdout = sys.stdout
  296. sys.stdout = self.__out
  297. # Call Pdb's trace dispatch method.
  298. try:
  299. return pdb.Pdb.trace_dispatch(self, *args)
  300. finally:
  301. sys.stdout = save_stdout
  302. # [XX] Normalize with respect to os.path.pardir?
  303. def _module_relative_path(module, path):
  304. if not inspect.ismodule(module):
  305. raise TypeError, 'Expected a module: %r' % module
  306. if path.startswith('/'):
  307. raise ValueError, 'Module-relative files may not have absolute paths'
  308. # Find the base directory for the path.
  309. if hasattr(module, '__file__'):
  310. # A normal module/package
  311. basedir = os.path.split(module.__file__)[0]
  312. elif module.__name__ == '__main__':
  313. # An interactive session.
  314. if len(sys.argv)>0 and sys.argv[0] != '':
  315. basedir = os.path.split(sys.argv[0])[0]
  316. else:
  317. basedir = os.curdir
  318. else:
  319. # A module w/o __file__ (this includes builtins)
  320. raise ValueError("Can't resolve paths relative to the module " +
  321. module + " (it has no __file__)")
  322. # Combine the base directory and the path.
  323. return os.path.join(basedir, *(path.split('/')))
  324. ######################################################################
  325. ## 2. Example & DocTest
  326. ######################################################################
  327. ## - An "example" is a <source, want> pair, where "source" is a
  328. ## fragment of source code, and "want" is the expected output for
  329. ## "source." The Example class also includes information about
  330. ## where the example was extracted from.
  331. ##
  332. ## - A "doctest" is a collection of examples, typically extracted from
  333. ## a string (such as an object's docstring). The DocTest class also
  334. ## includes information about where the string was extracted from.
  335. class Example:
  336. """
  337. A single doctest example, consisting of source code and expected
  338. output. `Example` defines the following attributes:
  339. - source: A single Python statement, always ending with a newline.
  340. The constructor adds a newline if needed.
  341. - want: The expected output from running the source code (either
  342. from stdout, or a traceback in case of exception). `want` ends
  343. with a newline unless it's empty, in which case it's an empty
  344. string. The constructor adds a newline if needed.
  345. - exc_msg: The exception message generated by the example, if
  346. the example is expected to generate an exception; or `None` if
  347. it is not expected to generate an exception. This exception
  348. message is compared against the return value of
  349. `traceback.format_exception_only()`. `exc_msg` ends with a
  350. newline unless it's `None`. The constructor adds a newline
  351. if needed.
  352. - lineno: The line number within the DocTest string containing
  353. this Example where the Example begins. This line number is
  354. zero-based, with respect to the beginning of the DocTest.
  355. - indent: The example's indentation in the DocTest string.
  356. I.e., the number of space characters that preceed the
  357. example's first prompt.
  358. - options: A dictionary mapping from option flags to True or
  359. False, which is used to override default options for this
  360. example. Any option flags not contained in this dictionary
  361. are left at their default value (as specified by the
  362. DocTestRunner's optionflags). By default, no options are set.
  363. """
  364. def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
  365. options=None):
  366. # Normalize inputs.
  367. if not source.endswith('\n'):
  368. source += '\n'
  369. if want and not want.endswith('\n'):
  370. want += '\n'
  371. if exc_msg is not None and not exc_msg.endswith('\n'):
  372. exc_msg += '\n'
  373. # Store properties.
  374. self.source = source
  375. self.want = want
  376. self.lineno = lineno
  377. self.indent = indent
  378. if options is None: options = {}
  379. self.options = options
  380. self.exc_msg = exc_msg
  381. class DocTest:
  382. """
  383. A collection of doctest examples that should be run in a single
  384. namespace. Each `DocTest` defines the following attributes:
  385. - examples: the list of examples.
  386. - globs: The namespace (aka globals) that the examples should
  387. be run in.
  388. - name: A name identifying the DocTest (typically, the name of
  389. the object whose docstring this DocTest was extracted from).
  390. - filename: The name of the file that this DocTest was extracted
  391. from, or `None` if the filename is unknown.
  392. - lineno: The line number within filename where this DocTest
  393. begins, or `None` if the line number is unavailable. This
  394. line number is zero-based, with respect to the beginning of
  395. the file.
  396. - docstring: The string that the examples were extracted from,
  397. or `None` if the string is unavailable.
  398. """
  399. def __init__(self, examples, globs, name, filename, lineno, docstring):
  400. """
  401. Create a new DocTest containing the given examples. The
  402. DocTest's globals are initialized with a copy of `globs`.
  403. """
  404. assert not isinstance(examples, basestring), \
  405. "DocTest no longer accepts str; use DocTestParser instead"
  406. self.examples = examples
  407. self.docstring = docstring
  408. self.globs = globs.copy()
  409. self.name = name
  410. self.filename = filename
  411. self.lineno = lineno
  412. def __repr__(self):
  413. if len(self.examples) == 0:
  414. examples = 'no examples'
  415. elif len(self.examples) == 1:
  416. examples = '1 example'
  417. else:
  418. examples = '%d examples' % len(self.examples)
  419. return ('<DocTest %s from %s:%s (%s)>' %
  420. (self.name, self.filename, self.lineno, examples))
  421. # This lets us sort tests by name:
  422. def __cmp__(self, other):
  423. if not isinstance(other, DocTest):
  424. return -1
  425. return cmp((self.name, self.filename, self.lineno, id(self)),
  426. (other.name, other.filename, other.lineno, id(other)))
  427. ######################################################################
  428. ## 3. DocTestParser
  429. ######################################################################
  430. class DocTestParser:
  431. """
  432. A class used to parse strings containing doctest examples.
  433. """
  434. # This regular expression is used to find doctest examples in a
  435. # string. It defines three groups: `source` is the source code
  436. # (including leading indentation and prompts); `indent` is the
  437. # indentation of the first (PS1) line of the source code; and
  438. # `want` is the expected output (including leading indentation).
  439. _EXAMPLE_RE = re.compile(r'''
  440. # Source consists of a PS1 line followed by zero or more PS2 lines.
  441. (?P<source>
  442. (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
  443. (?:\n [ ]* \.\.\. .*)*) # PS2 lines
  444. \n?
  445. # Want consists of any non-blank lines that do not start with PS1.
  446. (?P<want> (?:(?![ ]*$) # Not a blank line
  447. (?![ ]*>>>) # Not a line starting with PS1
  448. .*$\n? # But any other line
  449. )*)
  450. ''', re.MULTILINE | re.VERBOSE)
  451. # A regular expression for handling `want` strings that contain
  452. # expected exceptions. It divides `want` into three pieces:
  453. # - the traceback header line (`hdr`)
  454. # - the traceback stack (`stack`)
  455. # - the exception message (`msg`), as generated by
  456. # traceback.format_exception_only()
  457. # `msg` may have multiple lines. We assume/require that the
  458. # exception message is the first non-indented line starting with a word
  459. # character following the traceback header line.
  460. _EXCEPTION_RE = re.compile(r"""
  461. # Grab the traceback header. Different versions of Python have
  462. # said different things on the first traceback line.
  463. ^(?P<hdr> Traceback\ \(
  464. (?: most\ recent\ call\ last
  465. | innermost\ last
  466. ) \) :
  467. )
  468. \s* $ # toss trailing whitespace on the header.
  469. (?P<stack> .*?) # don't blink: absorb stuff until...
  470. ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
  471. """, re.VERBOSE | re.MULTILINE | re.DOTALL)
  472. # A callable returning a true value iff its argument is a blank line
  473. # or contains a single comment.
  474. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
  475. def parse(self, string, name='<string>'):
  476. """
  477. Divide the given string into examples and intervening text,
  478. and return them as a list of alternating Examples and strings.
  479. Line numbers for the Examples are 0-based. The optional
  480. argument `name` is a name identifying this string, and is only
  481. used for error messages.
  482. """
  483. string = string.expandtabs()
  484. # If all lines begin with the same indentation, then strip it.
  485. min_indent = self._min_indent(string)
  486. if min_indent > 0:
  487. string = '\n'.join([l[min_indent:] for l in string.split('\n')])
  488. output = []
  489. charno, lineno = 0, 0
  490. # Find all doctest examples in the string:
  491. for m in self._EXAMPLE_RE.finditer(string):
  492. # Add the pre-example text to `output`.
  493. output.append(string[charno:m.start()])
  494. # Update lineno (lines before this example)
  495. lineno += string.count('\n', charno, m.start())
  496. # Extract info from the regexp match.
  497. (source, options, want, exc_msg) = \
  498. self._parse_example(m, name, lineno)
  499. # Create an Example, and add it to the list.
  500. if not self._IS_BLANK_OR_COMMENT(source):
  501. output.append( Example(source, want, exc_msg,
  502. lineno=lineno,
  503. indent=min_indent+len(m.group('indent')),
  504. options=options) )
  505. # Update lineno (lines inside this example)
  506. lineno += string.count('\n', m.start(), m.end())
  507. # Update charno.
  508. charno = m.end()
  509. # Add any remaining post-example text to `output`.
  510. output.append(string[charno:])
  511. return output
  512. def get_doctest(self, string, globs, name, filename, lineno):
  513. """
  514. Extract all doctest examples from the given string, and
  515. collect them into a `DocTest` object.
  516. `globs`, `name`, `filename`, and `lineno` are attributes for
  517. the new `DocTest` object. See the documentation for `DocTest`
  518. for more information.
  519. """
  520. return DocTest(self.get_examples(string, name), globs,
  521. name, filename, lineno, string)
  522. def get_examples(self, string, name='<string>'):
  523. """
  524. Extract all doctest examples from the given string, and return
  525. them as a list of `Example` objects. Line numbers are
  526. 0-based, because it's most common in doctests that nothing
  527. interesting appears on the same line as opening triple-quote,
  528. and so the first interesting line is called \"line 1\" then.
  529. The optional argument `name` is a name identifying this
  530. string, and is only used for error messages.
  531. """
  532. return [x for x in self.parse(string, name)
  533. if isinstance(x, Example)]
  534. def _parse_example(self, m, name, lineno):
  535. """
  536. Given a regular expression match from `_EXAMPLE_RE` (`m`),
  537. return a pair `(source, want)`, where `source` is the matched
  538. example's source code (with prompts and indentation stripped);
  539. and `want` is the example's expected output (with indentation
  540. stripped).
  541. `name` is the string's name, and `lineno` is the line number
  542. where the example starts; both are used for error messages.
  543. """
  544. # Get the example's indentation level.
  545. indent = len(m.group('indent'))
  546. # Divide source into lines; check that they're properly
  547. # indented; and then strip their indentation & prompts.
  548. source_lines = m.group('source').split('\n')
  549. self._check_prompt_blank(source_lines, indent, name, lineno)
  550. self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
  551. source = '\n'.join([sl[indent+4:] for sl in source_lines])
  552. # Divide want into lines; check that it's properly indented; and
  553. # then strip the indentation. Spaces before the last newline should
  554. # be preserved, so plain rstrip() isn't good enough.
  555. want = m.group('want')
  556. want_lines = want.split('\n')
  557. if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
  558. del want_lines[-1] # forget final newline & spaces after it
  559. self._check_prefix(want_lines, ' '*indent, name,
  560. lineno + len(source_lines))
  561. want = '\n'.join([wl[indent:] for wl in want_lines])
  562. # If `want` contains a traceback message, then extract it.
  563. m = self._EXCEPTION_RE.match(want)
  564. if m:
  565. exc_msg = m.group('msg')
  566. else:
  567. exc_msg = None
  568. # Extract options from the source.
  569. options = self._find_options(source, name, lineno)
  570. return source, options, want, exc_msg
  571. # This regular expression looks for option directives in the
  572. # source code of an example. Option directives are comments
  573. # starting with "doctest:". Warning: this may give false
  574. # positives for string-literals that contain the string
  575. # "#doctest:". Eliminating these false positives would require
  576. # actually parsing the string; but we limit them by ignoring any
  577. # line containing "#doctest:" that is *followed* by a quote mark.
  578. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
  579. re.MULTILINE)
  580. def _find_options(self, source, name, lineno):
  581. """
  582. Return a dictionary containing option overrides extracted from
  583. option directives in the given source string.
  584. `name` is the string's name, and `lineno` is the line number
  585. where the example starts; both are used for error messages.
  586. """
  587. options = {}
  588. # (note: with the current regexp, this will match at most once:)
  589. for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  590. option_strings = m.group(1).replace(',', ' ').split()
  591. for option in option_strings:
  592. if (option[0] not in '+-' or
  593. option[1:] not in OPTIONFLAGS_BY_NAME):
  594. raise ValueError('line %r of the doctest for %s '
  595. 'has an invalid option: %r' %
  596. (lineno+1, name, option))
  597. flag = OPTIONFLAGS_BY_NAME[option[1:]]
  598. options[flag] = (option[0] == '+')
  599. if options and self._IS_BLANK_OR_COMMENT(source):
  600. raise ValueError('line %r of the doctest for %s has an option '
  601. 'directive on a line with no example: %r' %
  602. (lineno, name, source))
  603. return options
  604. # This regular expression finds the indentation of every non-blank
  605. # line in a string.
  606. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
  607. def _min_indent(self, s):
  608. "Return the minimum indentation of any non-blank line in `s`"
  609. indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
  610. if len(indents) > 0:
  611. return min(indents)
  612. else:
  613. return 0
  614. def _check_prompt_blank(self, lines, indent, name, lineno):
  615. """
  616. Given the lines of a source string (including prompts and
  617. leading indentation), check to make sure that every prompt is
  618. followed by a space character. If any line is not followed by
  619. a space character, then raise ValueError.
  620. """
  621. for i, line in enumerate(lines):
  622. if len(line) >= indent+4 and line[indent+3] != ' ':
  623. raise ValueError('line %r of the docstring for %s '
  624. 'lacks blank after %s: %r' %
  625. (lineno+i+1, name,
  626. line[indent:indent+3], line))
  627. def _check_prefix(self, lines, prefix, name, lineno):
  628. """
  629. Check that every line in the given list starts with the given
  630. prefix; if any line does not, then raise a ValueError.
  631. """
  632. for i, line in enumerate(lines):
  633. if line and not line.startswith(prefix):
  634. raise ValueError('line %r of the docstring for %s has '
  635. 'inconsistent leading whitespace: %r' %
  636. (lineno+i+1, name, line))
  637. ######################################################################
  638. ## 4. DocTest Finder
  639. ######################################################################
  640. class DocTestFinder:
  641. """
  642. A class used to extract the DocTests that are relevant to a given
  643. object, from its docstring and the docstrings of its contained
  644. objects. Doctests can currently be extracted from the following
  645. object types: modules, functions, classes, methods, staticmethods,
  646. classmethods, and properties.
  647. """
  648. def __init__(self, verbose=False, parser=DocTestParser(),
  649. recurse=True, exclude_empty=True):
  650. """
  651. Create a new doctest finder.
  652. The optional argument `parser` specifies a class or
  653. function that should be used to create new DocTest objects (or
  654. objects that implement the same interface as DocTest). The
  655. signature for this factory function should match the signature
  656. of the DocTest constructor.
  657. If the optional argument `recurse` is false, then `find` will
  658. only examine the given object, and not any contained objects.
  659. If the optional argument `exclude_empty` is false, then `find`
  660. will include tests for objects with empty docstrings.
  661. """
  662. self._parser = parser
  663. self._verbose = verbose
  664. self._recurse = recurse
  665. self._exclude_empty = exclude_empty
  666. def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
  667. """
  668. Return a list of the DocTests that are defined by the given
  669. object's docstring, or by any of its contained objects'
  670. docstrings.
  671. The optional parameter `module` is the module that contains
  672. the given object. If the module is not specified or is None, then
  673. the test finder will attempt to automatically determine the
  674. correct module. The object's module is used:
  675. - As a default namespace, if `globs` is not specified.
  676. - To prevent the DocTestFinder from extracting DocTests
  677. from objects that are imported from other modules.
  678. - To find the name of the file containing the object.
  679. - To help find the line number of the object within its
  680. file.
  681. Contained objects whose module does not match `module` are ignored.
  682. If `module` is False, no attempt to find the module will be made.
  683. This is obscure, of use mostly in tests: if `module` is False, or
  684. is None but cannot be found automatically, then all objects are
  685. considered to belong to the (non-existent) module, so all contained
  686. objects will (recursively) be searched for doctests.
  687. The globals for each DocTest is formed by combining `globs`
  688. and `extraglobs` (bindings in `extraglobs` override bindings
  689. in `globs`). A new copy of the globals dictionary is created
  690. for each DocTest. If `globs` is not specified, then it
  691. defaults to the module's `__dict__`, if specified, or {}
  692. otherwise. If `extraglobs` is not specified, then it defaults
  693. to {}.
  694. """
  695. # If name was not specified, then extract it from the object.
  696. if name is None:
  697. name = getattr(obj, '__name__', None)
  698. if name is None:
  699. raise ValueError("DocTestFinder.find: name must be given "
  700. "when obj.__name__ doesn't exist: %r" %
  701. (type(obj),))
  702. # Find the module that contains the given object (if obj is
  703. # a module, then module=obj.). Note: this may fail, in which
  704. # case module will be None.
  705. if module is False:
  706. module = None
  707. elif module is None:
  708. module = inspect.getmodule(obj)
  709. # Read the module's source code. This is used by
  710. # DocTestFinder._find_lineno to find the line number for a
  711. # given object's docstring.
  712. try:
  713. file = inspect.getsourcefile(obj) or inspect.getfile(obj)
  714. source_lines = linecache.getlines(file)
  715. if not source_lines:
  716. source_lines = None
  717. except TypeError:
  718. source_lines = None
  719. # Initialize globals, and merge in extraglobs.
  720. if globs is None:
  721. if module is None:
  722. globs = {}
  723. else:
  724. globs = module.__dict__.copy()
  725. else:
  726. globs = globs.copy()
  727. if extraglobs is not None:
  728. globs.update(extraglobs)
  729. # Recursively expore `obj`, extracting DocTests.
  730. tests = []
  731. self._find(tests, obj, name, module, source_lines, globs, {})
  732. # Sort the tests by alpha order of names, for consistency in
  733. # verbose-mode output. This was a feature of doctest in Pythons
  734. # <= 2.3 that got lost by accident in 2.4. It was repaired in
  735. # 2.4.4 and 2.5.
  736. tests.sort()
  737. return tests
  738. def _from_module(self, module, object):
  739. """
  740. Return true if the given object is defined in the given
  741. module.
  742. """
  743. if module is None:
  744. return True
  745. elif inspect.isfunction(object):
  746. return module.__dict__ is object.func_globals
  747. elif inspect.isclass(object):
  748. # XXX: Jython transition 2.5
  749. # Java classes appear as Python classes to inspect, but they
  750. # have no __module__ http://jython.org/bugs/1758279
  751. # org.python.modules uses Java classes to masq
  752. if not hasattr(object, '__module__'):
  753. return False
  754. return module.__name__ == object.__module__
  755. elif inspect.getmodule(object) is not None:
  756. return module is inspect.getmodule(object)
  757. elif hasattr(object, '__module__'):
  758. return module.__name__ == object.__module__
  759. elif isinstance(object, property):
  760. return True # [XX] no way not be sure.
  761. else:
  762. raise ValueError("object must be a class or function")
  763. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  764. """
  765. Find tests for the given object and any contained objects, and
  766. add them to `tests`.
  767. """
  768. if self._verbose:
  769. print 'Finding tests in %s' % name
  770. # If we've already processed this object, then ignore it.
  771. if id(obj) in seen:
  772. return
  773. seen[id(obj)] = 1
  774. # Find a test for this object, and add it to the list of tests.
  775. test = self._get_test(obj, name, module, globs, source_lines)
  776. if test is not None:
  777. tests.append(test)
  778. # Look for tests in a module's contained objects.
  779. if inspect.ismodule(obj) and self._recurse:
  780. for valname, val in obj.__dict__.items():
  781. valname = '%s.%s' % (name, valname)
  782. # Recurse to functions & classes.
  783. if ((inspect.isfunction(val) or inspect.isclass(val)) and
  784. self._from_module(module, val)):
  785. self._find(tests, val, valname, module, source_lines,
  786. globs, seen)
  787. # Look for tests in a module's __test__ dictionary.
  788. if inspect.ismodule(obj) and self._recurse:
  789. for valname, val in getattr(obj, '__test__', {}).items():
  790. if not isinstance(valname, basestring):
  791. raise ValueError("DocTestFinder.find: __test__ keys "
  792. "must be strings: %r" %
  793. (type(valname),))
  794. if not (inspect.isfunction(val) or inspect.isclass(val) or
  795. inspect.ismethod(val) or inspect.ismodule(val) or
  796. isinstance(val, basestring)):
  797. raise ValueError("DocTestFinder.find: __test__ values "
  798. "must be strings, functions, methods, "
  799. "classes, or modules: %r" %
  800. (type(val),))
  801. valname = '%s.__test__.%s' % (name, valname)
  802. self._find(tests, val, valname, module, source_lines,
  803. globs, seen)
  804. # Look for tests in a class's contained objects.
  805. if inspect.isclass(obj) and self._recurse:
  806. for valname, val in obj.__dict__.items():
  807. # Special handling for staticmethod/classmethod.
  808. if isinstance(val, staticmethod):
  809. val = getattr(obj, valname)
  810. if isinstance(val, classmethod):
  811. val = getattr(obj, valname).im_func
  812. # Recurse to methods, properties, and nested classes.
  813. if ((inspect.isfunction(val) or inspect.isclass(val) or
  814. isinstance(val, property)) and
  815. self._from_module(module, val)):
  816. valname = '%s.%s' % (name, valname)
  817. self._find(tests, val, valname, module, source_lines,
  818. globs, seen)
  819. def _get_test(self, obj, name, module, globs, source_lines):
  820. """
  821. Return a DocTest for the given object, if it defines a docstring;
  822. otherwise, return None.
  823. """
  824. # Extract the object's docstring. If it doesn't have one,
  825. # then return None (no test for this object).
  826. if isinstance(obj, basestring):
  827. docstring = obj
  828. else:
  829. try:
  830. if obj.__doc__ is None:
  831. docstring = ''
  832. else:
  833. docstring = obj.__doc__
  834. if not isinstance(docstring, basestring):
  835. docstring = str(docstring)
  836. except (TypeError, AttributeError):
  837. docstring = ''
  838. # Find the docstring's location in the file.
  839. lineno = self._find_lineno(obj, source_lines)
  840. # Don't bother if the docstring is empty.
  841. if self._exclude_empty and not docstring:
  842. return None
  843. # Return a DocTest for this object.
  844. if module is None:
  845. filename = None
  846. else:
  847. filename = getattr(module, '__file__', module.__name__)
  848. if filename[-4:] in (".pyc", ".pyo"):
  849. filename = filename[:-1]
  850. elif filename.endswith('$py.class'):
  851. filename = '%s.py' % filename[:-9]
  852. return self._parser.get_doctest(docstring, globs, name,
  853. filename, lineno)
  854. def _find_lineno(self, obj, source_lines):
  855. """
  856. Return a line number of the given object's docstring. Note:
  857. this method assumes that the object has a docstring.
  858. """
  859. lineno = None
  860. # Find the line number for modules.
  861. if inspect.ismodule(obj):
  862. lineno = 0
  863. # Find the line number for classes.
  864. # Note: this could be fooled if a class is defined multiple
  865. # times in a single file.
  866. if inspect.isclass(obj):
  867. if source_lines is None:
  868. return None
  869. pat = re.compile(r'^\s*class\s*%s\b' %
  870. getattr(obj, '__name__', '-'))
  871. for i, line in enumerate(source_lines):
  872. if pat.match(line):
  873. lineno = i
  874. break
  875. # Find the line number for functions & methods.
  876. if inspect.ismethod(obj): obj = obj.im_func
  877. if inspect.isfunction(obj): obj = obj.func_code
  878. if inspect.istraceback(obj): obj = obj.tb_frame
  879. if inspect.isframe(obj): obj = obj.f_code
  880. if inspect.iscode(obj):
  881. lineno = getattr(obj, 'co_firstlineno', None)-1
  882. # Find the line number where the docstring starts. Assume
  883. # that it's the first line that begins with a quote mark.
  884. # Note: this could be fooled by a multiline function
  885. # signature, where a continuation line begins with a quote
  886. # mark.
  887. if lineno is not None:
  888. if source_lines is None:
  889. return lineno+1
  890. pat = re.compile('(^|.*:)\s*\w*("|\')')
  891. for lineno in range(lineno, len(source_lines)):
  892. if pat.match(source_lines[lineno]):
  893. return lineno
  894. # We couldn't find the line number.
  895. return None
  896. ######################################################################
  897. ## 5. DocTest Runner
  898. ######################################################################
  899. class DocTestRunner:
  900. """
  901. A class used to run DocTest test cases, and accumulate statistics.
  902. The `run` method is used to process a single DocTest case. It
  903. returns a tuple `(f, t)`, where `t` is the number of test cases
  904. tried, and `f` is the number of test cases that failed.
  905. >>> tests = DocTestFinder().find(_TestClass)
  906. >>> runner = DocTestRunner(verbose=False)
  907. >>> tests.sort(key = lambda test: test.name)
  908. >>> for test in tests:
  909. ... print test.name, '->', runner.run(test)
  910. _TestClass -> (0, 2)
  911. _TestClass.__init__ -> (0, 2)
  912. _TestClass.get -> (0, 2)
  913. _TestClass.square -> (0, 1)
  914. The `summarize` method prints a summary of all the test cases that
  915. have been run by the runner, and returns an aggregated `(f, t)`
  916. tuple:
  917. >>> runner.summarize(verbose=1)
  918. 4 items passed all tests:
  919. 2 tests in _TestClass
  920. 2 tests in _TestClass.__init__
  921. 2 tests in _TestClass.get
  922. 1 tests in _TestClass.square
  923. 7 tests in 4 items.
  924. 7 passed and 0 failed.
  925. Test passed.
  926. (0, 7)
  927. The aggregated number of tried examples and failed examples is
  928. also available via the `tries` and `failures` attributes:
  929. >>> runner.tries
  930. 7
  931. >>> runner.failures
  932. 0
  933. The comparison between expected outputs and actual outputs is done
  934. by an `OutputChecker`. This comparison may be customized with a
  935. number of option flags; see the documentation for `testmod` for
  936. more information. If the option flags are insufficient, then the
  937. comparison may also be customized by passing a subclass of
  938. `OutputChecker` to the constructor.
  939. The test runner's display output can be controlled in two ways.
  940. First, an output function (`out) can be passed to
  941. `TestRunner.run`; this function will be called with strings that
  942. should be displayed. It defaults to `sys.stdout.write`. If
  943. capturing the output is not sufficient, then the display output
  944. can be also customized by subclassing DocTestRunner, and
  945. overriding the methods `report_start`, `report_success`,
  946. `report_unexpected_exception`, and `report_failure`.
  947. """
  948. # This divider string is used to separate failure messages, and to
  949. # separate sections of the summary.
  950. DIVIDER = "*" * 70
  951. def __init__(self, checker=None, verbose=None, optionflags=0):
  952. """
  953. Create a new test runner.
  954. Optional keyword arg `checker` is the `OutputChecker` that
  955. should be used to compare the expected outputs and actual
  956. outputs of doctest examples.
  957. Optional keyword arg 'verbose' prints lots of stuff if true,
  958. only failures if false; by default, it's true iff '-v' is in
  959. sys.argv.
  960. Optional argument `optionflags` can be used to control how the
  961. test runner compares expected output to actual output, and how
  962. it displays failures. See the documentation for `testmod` for
  963. more information.
  964. """
  965. self._checker = checker or OutputChecker()
  966. if verbose is None:
  967. verbose = '-v' in sys.argv
  968. self._verbose = verbose
  969. self.optionflags = optionflags
  970. self.original_optionflags = optionflags
  971. # Keep track of the examples we've run.
  972. self.tries = 0
  973. self.failures = 0
  974. self._name2ft = {}
  975. # Create a fake output target for capturing doctest output.
  976. self._fakeout = _SpoofOut()
  977. #/////////////////////////////////////////////////////////////////
  978. # Reporting methods
  979. #/////////////////////////////////////////////////////////////////
  980. def report_start(self, out, test, example):
  981. """
  982. Report that the test runner is about to process the given
  983. example. (Only displays a message if verbose=True)
  984. """
  985. if self._verbose:
  986. if example.want:
  987. out('Trying:\n' + _indent(example.source) +
  988. 'Expecting:\n' + _indent(example.want))
  989. else:
  990. out('Trying:\n' + _indent(example.source) +
  991. 'Expecting nothing\n')
  992. def report_success(self, out, test, example, got):
  993. """
  994. Report that the given example ran successfully. (Only
  995. displays a message if verbose=True)
  996. """
  997. if self._verbose:
  998. out("ok\n")
  999. def report_failure(self, out, test, example, got):
  1000. """
  1001. Report that the given example failed.
  1002. """
  1003. out(self._failure_header(test, example) +
  1004. self._checker.output_difference(example, got, self.optionflags))
  1005. def report_unexpected_exception(self, out, test, example, exc_info):
  1006. """
  1007. Report that the given example raised an unexpected exception.
  1008. """
  1009. out(self._failure_header(test, example) +
  1010. 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  1011. def _failure_header(self, test, example):
  1012. out = [self.DIVIDER]
  1013. if test.filename:
  1014. if test.lineno is not None and example.lineno is not None:
  1015. lineno = test.lineno + example.lineno + 1
  1016. else:
  1017. lineno = '?'
  1018. out.append('File "%s", line %s, in %s' %
  1019. (test.filename, lineno, test.name))
  1020. else:
  1021. out.append('Line %s, in %s' % (example.lineno+1, test.name))
  1022. out.append('Failed example:')
  1023. source = example.source
  1024. out.append(_indent(source))
  1025. return '\n'.join(out)
  1026. #/////////////////////////////////////////////////////////////////
  1027. # DocTest Running
  1028. #/////////////////////////////////////////////////////////////////
  1029. def __run(self, test, compileflags, out):
  1030. """
  1031. Run the examples in `test`. Write the outcome of each example
  1032. with one of the `DocTestRunner.report_*` methods, using the
  1033. writer function `out`. `compileflags` is the set of compiler
  1034. flags that should be used to execute examples. Return a tuple
  1035. `(f, t)`, where `t` is the number of examples tried, and `f`
  1036. is the number of examples that failed. The examples are run
  1037. in the namespace `test.globs`.
  1038. """
  1039. # Keep track of the number of failures and tries.
  1040. failures = tries = 0
  1041. # Save the option flags (since option directives can be used
  1042. # to modify them).
  1043. original_optionflags = self.optionflags
  1044. SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
  1045. check = self._checker.check_output
  1046. # Process each example.
  1047. for examplenum, example in enumerate(test.examples):
  1048. # If REPORT_ONLY_FIRST_FAILURE is set, then supress
  1049. # reporting after the first failure.
  1050. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
  1051. failures > 0)
  1052. # Merge in the example's options.
  1053. self.optionflags = original_optionflags
  1054. if example.options:
  1055. for (optionflag, val) in example.options.items():
  1056. if val:
  1057. self.optionflags |= optionflag
  1058. else:
  1059. self.optionflags &= ~optionflag
  1060. # If 'SKIP' is set, then skip this example.
  1061. if self.optionflags & SKIP:
  1062. continue
  1063. # Record that we started this example.
  1064. tries += 1
  1065. if not quiet:
  1066. self.report_start(out, test, example)
  1067. # Use a special filename for compile(), so we can retrieve
  1068. # the source code during interactive debugging (see
  1069. # __patched_linecache_getlines).
  1070. filename = '<doctest %s[%d]>' % (test.name, examplenum)
  1071. # Run the example in the given context (globs), and record
  1072. # any exception that gets raised. (But don't intercept
  1073. # keyboard interrupts.)
  1074. try:
  1075. # Don't blink! This is where the user's code gets run.
  1076. exec compile(example.source, filename, "single",
  1077. compileflags, 1) in test.globs
  1078. self.debugger.set_continue() # ==== Example Finished ====
  1079. exception = None
  1080. except KeyboardInterrupt:
  1081. raise
  1082. except:
  1083. exception = sys.exc_info()
  1084. self.debugger.set_continue() # ==== Example Finished ====
  1085. got = self._fakeout.getvalue() # the actual output
  1086. self._fakeout.truncate(0)
  1087. outcome = FAILURE # guilty until proved innocent or insane
  1088. # If the example executed without raising any exceptions,
  1089. # verify its output.
  1090. if exception is None:
  1091. if check(example.want, got, self.optionflags):
  1092. outcome = SUCCESS
  1093. # The example raised an exception: check if it was expected.
  1094. else:
  1095. exc_info = sys.exc_info()
  1096. exc_msg = traceback.format_…

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