PageRenderTime 73ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/doctest.py

https://bitbucket.org/dilettant/pypy
Python | 2731 lines | 2666 code | 13 blank | 52 comment | 29 complexity | dbdfec70f12c69cb3232a7c0363f7288 MD5 | raw file

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

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

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