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

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

https://bitbucket.org/hexdump42/pypy-benchmarks
Python | 2693 lines | 2567 code | 21 blank | 105 comment | 40 complexity | b349816d3dc51c36f42d814079e5a39b MD5 | raw file
Possible License(s): Apache-2.0, GPL-2.0, BSD-3-Clause

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

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

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