PageRenderTime 74ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/doctest.py

https://bitbucket.org/chrish42/pypy
Python | 2792 lines | 2727 code | 13 blank | 52 comment | 29 complexity | 1ed4d520e8d0d72aa54d903097db7d14 MD5 | raw file
Possible License(s): Apache-2.0

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

  1. # Module doctest.
  2. # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
  3. # Major enhancements and refactoring by:
  4. # Jim Fulton
  5. # Edward Loper
  6. # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
  7. r"""Module doctest -- a framework for running examples in docstrings.
  8. In simplest use, end each module M to be tested with:
  9. def _test():
  10. import doctest
  11. doctest.testmod()
  12. if __name__ == "__main__":
  13. _test()
  14. Then running the module as a script will cause the examples in the
  15. docstrings to get executed and verified:
  16. python M.py
  17. This won't display anything unless an example fails, in which case the
  18. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  19. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  20. line of output is "Test failed.".
  21. Run it with the -v switch instead:
  22. python M.py -v
  23. and a detailed report of all examples tried is printed to stdout, along
  24. with assorted summaries at the end.
  25. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  26. it by passing "verbose=False". In either of those cases, sys.argv is not
  27. examined by testmod.
  28. There are a variety of other ways to run doctests, including integration
  29. with the unittest framework, and support for running non-Python text
  30. files containing doctests. There are also many ways to override parts
  31. of doctest's default behaviors. See the Library Reference Manual for
  32. details.
  33. """
  34. __docformat__ = 'reStructuredText en'
  35. __all__ = [
  36. # 0, Option Flags
  37. 'register_optionflag',
  38. 'DONT_ACCEPT_TRUE_FOR_1',
  39. 'DONT_ACCEPT_BLANKLINE',
  40. 'NORMALIZE_WHITESPACE',
  41. 'ELLIPSIS',
  42. 'SKIP',
  43. 'IGNORE_EXCEPTION_DETAIL',
  44. 'COMPARISON_FLAGS',
  45. 'REPORT_UDIFF',
  46. 'REPORT_CDIFF',
  47. 'REPORT_NDIFF',
  48. 'REPORT_ONLY_FIRST_FAILURE',
  49. 'REPORTING_FLAGS',
  50. # 1. Utility Functions
  51. # 2. Example & DocTest
  52. 'Example',
  53. 'DocTest',
  54. # 3. Doctest Parser
  55. 'DocTestParser',
  56. # 4. Doctest Finder
  57. 'DocTestFinder',
  58. # 5. Doctest Runner
  59. 'DocTestRunner',
  60. 'OutputChecker',
  61. 'DocTestFailure',
  62. 'UnexpectedException',
  63. 'DebugRunner',
  64. # 6. Test Functions
  65. 'testmod',
  66. 'testfile',
  67. 'run_docstring_examples',
  68. # 7. Tester
  69. 'Tester',
  70. # 8. Unittest Support
  71. 'DocTestSuite',
  72. 'DocFileSuite',
  73. 'set_unittest_reportflags',
  74. # 9. Debugging Support
  75. 'script_from_examples',
  76. 'testsource',
  77. 'debug_src',
  78. 'debug',
  79. ]
  80. import __future__
  81. import sys, traceback, inspect, linecache, os, re
  82. import unittest, difflib, pdb, tempfile
  83. import warnings
  84. from StringIO import StringIO
  85. 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 precede 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. def __eq__(self, other):
  396. if type(self) is not type(other):
  397. return NotImplemented
  398. return self.source == other.source and \
  399. self.want == other.want and \
  400. self.lineno == other.lineno and \
  401. self.indent == other.indent and \
  402. self.options == other.options and \
  403. self.exc_msg == other.exc_msg
  404. def __ne__(self, other):
  405. return not self == other
  406. def __hash__(self):
  407. return hash((self.source, self.want, self.lineno, self.indent,
  408. self.exc_msg))
  409. class DocTest:
  410. """
  411. A collection of doctest examples that should be run in a single
  412. namespace. Each `DocTest` defines the following attributes:
  413. - examples: the list of examples.
  414. - globs: The namespace (aka globals) that the examples should
  415. be run in.
  416. - name: A name identifying the DocTest (typically, the name of
  417. the object whose docstring this DocTest was extracted from).
  418. - filename: The name of the file that this DocTest was extracted
  419. from, or `None` if the filename is unknown.
  420. - lineno: The line number within filename where this DocTest
  421. begins, or `None` if the line number is unavailable. This
  422. line number is zero-based, with respect to the beginning of
  423. the file.
  424. - docstring: The string that the examples were extracted from,
  425. or `None` if the string is unavailable.
  426. """
  427. def __init__(self, examples, globs, name, filename, lineno, docstring):
  428. """
  429. Create a new DocTest containing the given examples. The
  430. DocTest's globals are initialized with a copy of `globs`.
  431. """
  432. assert not isinstance(examples, basestring), \
  433. "DocTest no longer accepts str; use DocTestParser instead"
  434. self.examples = examples
  435. self.docstring = docstring
  436. self.globs = globs.copy()
  437. self.name = name
  438. self.filename = filename
  439. self.lineno = lineno
  440. def __repr__(self):
  441. if len(self.examples) == 0:
  442. examples = 'no examples'
  443. elif len(self.examples) == 1:
  444. examples = '1 example'
  445. else:
  446. examples = '%d examples' % len(self.examples)
  447. return ('<DocTest %s from %s:%s (%s)>' %
  448. (self.name, self.filename, self.lineno, examples))
  449. def __eq__(self, other):
  450. if type(self) is not type(other):
  451. return NotImplemented
  452. return self.examples == other.examples and \
  453. self.docstring == other.docstring and \
  454. self.globs == other.globs and \
  455. self.name == other.name and \
  456. self.filename == other.filename and \
  457. self.lineno == other.lineno
  458. def __ne__(self, other):
  459. return not self == other
  460. def __hash__(self):
  461. return hash((self.docstring, self.name, self.filename, self.lineno))
  462. # This lets us sort tests by name:
  463. def __cmp__(self, other):
  464. if not isinstance(other, DocTest):
  465. return -1
  466. return cmp((self.name, self.filename, self.lineno, id(self)),
  467. (other.name, other.filename, other.lineno, id(other)))
  468. ######################################################################
  469. ## 3. DocTestParser
  470. ######################################################################
  471. class DocTestParser:
  472. """
  473. A class used to parse strings containing doctest examples.
  474. """
  475. # This regular expression is used to find doctest examples in a
  476. # string. It defines three groups: `source` is the source code
  477. # (including leading indentation and prompts); `indent` is the
  478. # indentation of the first (PS1) line of the source code; and
  479. # `want` is the expected output (including leading indentation).
  480. _EXAMPLE_RE = re.compile(r'''
  481. # Source consists of a PS1 line followed by zero or more PS2 lines.
  482. (?P<source>
  483. (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
  484. (?:\n [ ]* \.\.\. .*)*) # PS2 lines
  485. \n?
  486. # Want consists of any non-blank lines that do not start with PS1.
  487. (?P<want> (?:(?![ ]*$) # Not a blank line
  488. (?![ ]*>>>) # Not a line starting with PS1
  489. .+$\n? # But any other line
  490. )*)
  491. ''', re.MULTILINE | re.VERBOSE)
  492. # A regular expression for handling `want` strings that contain
  493. # expected exceptions. It divides `want` into three pieces:
  494. # - the traceback header line (`hdr`)
  495. # - the traceback stack (`stack`)
  496. # - the exception message (`msg`), as generated by
  497. # traceback.format_exception_only()
  498. # `msg` may have multiple lines. We assume/require that the
  499. # exception message is the first non-indented line starting with a word
  500. # character following the traceback header line.
  501. _EXCEPTION_RE = re.compile(r"""
  502. # Grab the traceback header. Different versions of Python have
  503. # said different things on the first traceback line.
  504. ^(?P<hdr> Traceback\ \(
  505. (?: most\ recent\ call\ last
  506. | innermost\ last
  507. ) \) :
  508. )
  509. \s* $ # toss trailing whitespace on the header.
  510. (?P<stack> .*?) # don't blink: absorb stuff until...
  511. ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
  512. """, re.VERBOSE | re.MULTILINE | re.DOTALL)
  513. # A callable returning a true value iff its argument is a blank line
  514. # or contains a single comment.
  515. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
  516. def parse(self, string, name='<string>'):
  517. """
  518. Divide the given string into examples and intervening text,
  519. and return them as a list of alternating Examples and strings.
  520. Line numbers for the Examples are 0-based. The optional
  521. argument `name` is a name identifying this string, and is only
  522. used for error messages.
  523. """
  524. string = string.expandtabs()
  525. # If all lines begin with the same indentation, then strip it.
  526. min_indent = self._min_indent(string)
  527. if min_indent > 0:
  528. string = '\n'.join([l[min_indent:] for l in string.split('\n')])
  529. output = []
  530. charno, lineno = 0, 0
  531. # Find all doctest examples in the string:
  532. for m in self._EXAMPLE_RE.finditer(string):
  533. # Add the pre-example text to `output`.
  534. output.append(string[charno:m.start()])
  535. # Update lineno (lines before this example)
  536. lineno += string.count('\n', charno, m.start())
  537. # Extract info from the regexp match.
  538. (source, options, want, exc_msg) = \
  539. self._parse_example(m, name, lineno)
  540. # Create an Example, and add it to the list.
  541. if not self._IS_BLANK_OR_COMMENT(source):
  542. output.append( Example(source, want, exc_msg,
  543. lineno=lineno,
  544. indent=min_indent+len(m.group('indent')),
  545. options=options) )
  546. # Update lineno (lines inside this example)
  547. lineno += string.count('\n', m.start(), m.end())
  548. # Update charno.
  549. charno = m.end()
  550. # Add any remaining post-example text to `output`.
  551. output.append(string[charno:])
  552. return output
  553. def get_doctest(self, string, globs, name, filename, lineno):
  554. """
  555. Extract all doctest examples from the given string, and
  556. collect them into a `DocTest` object.
  557. `globs`, `name`, `filename`, and `lineno` are attributes for
  558. the new `DocTest` object. See the documentation for `DocTest`
  559. for more information.
  560. """
  561. return DocTest(self.get_examples(string, name), globs,
  562. name, filename, lineno, string)
  563. def get_examples(self, string, name='<string>'):
  564. """
  565. Extract all doctest examples from the given string, and return
  566. them as a list of `Example` objects. Line numbers are
  567. 0-based, because it's most common in doctests that nothing
  568. interesting appears on the same line as opening triple-quote,
  569. and so the first interesting line is called \"line 1\" then.
  570. The optional argument `name` is a name identifying this
  571. string, and is only used for error messages.
  572. """
  573. return [x for x in self.parse(string, name)
  574. if isinstance(x, Example)]
  575. def _parse_example(self, m, name, lineno):
  576. """
  577. Given a regular expression match from `_EXAMPLE_RE` (`m`),
  578. return a pair `(source, want)`, where `source` is the matched
  579. example's source code (with prompts and indentation stripped);
  580. and `want` is the example's expected output (with indentation
  581. stripped).
  582. `name` is the string's name, and `lineno` is the line number
  583. where the example starts; both are used for error messages.
  584. """
  585. # Get the example's indentation level.
  586. indent = len(m.group('indent'))
  587. # Divide source into lines; check that they're properly
  588. # indented; and then strip their indentation & prompts.
  589. source_lines = m.group('source').split('\n')
  590. self._check_prompt_blank(source_lines, indent, name, lineno)
  591. self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
  592. source = '\n'.join([sl[indent+4:] for sl in source_lines])
  593. # Divide want into lines; check that it's properly indented; and
  594. # then strip the indentation. Spaces before the last newline should
  595. # be preserved, so plain rstrip() isn't good enough.
  596. want = m.group('want')
  597. want_lines = want.split('\n')
  598. if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
  599. del want_lines[-1] # forget final newline & spaces after it
  600. self._check_prefix(want_lines, ' '*indent, name,
  601. lineno + len(source_lines))
  602. want = '\n'.join([wl[indent:] for wl in want_lines])
  603. # If `want` contains a traceback message, then extract it.
  604. m = self._EXCEPTION_RE.match(want)
  605. if m:
  606. exc_msg = m.group('msg')
  607. else:
  608. exc_msg = None
  609. # Extract options from the source.
  610. options = self._find_options(source, name, lineno)
  611. return source, options, want, exc_msg
  612. # This regular expression looks for option directives in the
  613. # source code of an example. Option directives are comments
  614. # starting with "doctest:". Warning: this may give false
  615. # positives for string-literals that contain the string
  616. # "#doctest:". Eliminating these false positives would require
  617. # actually parsing the string; but we limit them by ignoring any
  618. # line containing "#doctest:" that is *followed* by a quote mark.
  619. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
  620. re.MULTILINE)
  621. def _find_options(self, source, name, lineno):
  622. """
  623. Return a dictionary containing option overrides extracted from
  624. option directives in the given source string.
  625. `name` is the string's name, and `lineno` is the line number
  626. where the example starts; both are used for error messages.
  627. """
  628. options = {}
  629. # (note: with the current regexp, this will match at most once:)
  630. for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  631. option_strings = m.group(1).replace(',', ' ').split()
  632. for option in option_strings:
  633. if (option[0] not in '+-' or
  634. option[1:] not in OPTIONFLAGS_BY_NAME):
  635. raise ValueError('line %r of the doctest for %s '
  636. 'has an invalid option: %r' %
  637. (lineno+1, name, option))
  638. flag = OPTIONFLAGS_BY_NAME[option[1:]]
  639. options[flag] = (option[0] == '+')
  640. if options and self._IS_BLANK_OR_COMMENT(source):
  641. raise ValueError('line %r of the doctest for %s has an option '
  642. 'directive on a line with no example: %r' %
  643. (lineno, name, source))
  644. return options
  645. # This regular expression finds the indentation of every non-blank
  646. # line in a string.
  647. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
  648. def _min_indent(self, s):
  649. "Return the minimum indentation of any non-blank line in `s`"
  650. indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
  651. if len(indents) > 0:
  652. return min(indents)
  653. else:
  654. return 0
  655. def _check_prompt_blank(self, lines, indent, name, lineno):
  656. """
  657. Given the lines of a source string (including prompts and
  658. leading indentation), check to make sure that every prompt is
  659. followed by a space character. If any line is not followed by
  660. a space character, then raise ValueError.
  661. """
  662. for i, line in enumerate(lines):
  663. if len(line) >= indent+4 and line[indent+3] != ' ':
  664. raise ValueError('line %r of the docstring for %s '
  665. 'lacks blank after %s: %r' %
  666. (lineno+i+1, name,
  667. line[indent:indent+3], line))
  668. def _check_prefix(self, lines, prefix, name, lineno):
  669. """
  670. Check that every line in the given list starts with the given
  671. prefix; if any line does not, then raise a ValueError.
  672. """
  673. for i, line in enumerate(lines):
  674. if line and not line.startswith(prefix):
  675. raise ValueError('line %r of the docstring for %s has '
  676. 'inconsistent leading whitespace: %r' %
  677. (lineno+i+1, name, line))
  678. ######################################################################
  679. ## 4. DocTest Finder
  680. ######################################################################
  681. class DocTestFinder:
  682. """
  683. A class used to extract the DocTests that are relevant to a given
  684. object, from its docstring and the docstrings of its contained
  685. objects. Doctests can currently be extracted from the following
  686. object types: modules, functions, classes, methods, staticmethods,
  687. classmethods, and properties.
  688. """
  689. def __init__(self, verbose=False, parser=DocTestParser(),
  690. recurse=True, exclude_empty=True):
  691. """
  692. Create a new doctest finder.
  693. The optional argument `parser` specifies a class or
  694. function that should be used to create new DocTest objects (or
  695. objects that implement the same interface as DocTest). The
  696. signature for this factory function should match the signature
  697. of the DocTest constructor.
  698. If the optional argument `recurse` is false, then `find` will
  699. only examine the given object, and not any contained objects.
  700. If the optional argument `exclude_empty` is false, then `find`
  701. will include tests for objects with empty docstrings.
  702. """
  703. self._parser = parser
  704. self._verbose = verbose
  705. self._recurse = recurse
  706. self._exclude_empty = exclude_empty
  707. def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
  708. """
  709. Return a list of the DocTests that are defined by the given
  710. object's docstring, or by any of its contained objects'
  711. docstrings.
  712. The optional parameter `module` is the module that contains
  713. the given object. If the module is not specified or is None, then
  714. the test finder will attempt to automatically determine the
  715. correct module. The object's module is used:
  716. - As a default namespace, if `globs` is not specified.
  717. - To prevent the DocTestFinder from extracting DocTests
  718. from objects that are imported from other modules.
  719. - To find the name of the file containing the object.
  720. - To help find the line number of the object within its
  721. file.
  722. Contained objects whose module does not match `module` are ignored.
  723. If `module` is False, no attempt to find the module will be made.
  724. This is obscure, of use mostly in tests: if `module` is False, or
  725. is None but cannot be found automatically, then all objects are
  726. considered to belong to the (non-existent) module, so all contained
  727. objects will (recursively) be searched for doctests.
  728. The globals for each DocTest is formed by combining `globs`
  729. and `extraglobs` (bindings in `extraglobs` override bindings
  730. in `globs`). A new copy of the globals dictionary is created
  731. for each DocTest. If `globs` is not specified, then it
  732. defaults to the module's `__dict__`, if specified, or {}
  733. otherwise. If `extraglobs` is not specified, then it defaults
  734. to {}.
  735. """
  736. # If name was not specified, then extract it from the object.
  737. if name is None:
  738. name = getattr(obj, '__name__', None)
  739. if name is None:
  740. raise ValueError("DocTestFinder.find: name must be given "
  741. "when obj.__name__ doesn't exist: %r" %
  742. (type(obj),))
  743. # Find the module that contains the given object (if obj is
  744. # a module, then module=obj.). Note: this may fail, in which
  745. # case module will be None.
  746. if module is False:
  747. module = None
  748. elif module is None:
  749. module = inspect.getmodule(obj)
  750. # Read the module's source code. This is used by
  751. # DocTestFinder._find_lineno to find the line number for a
  752. # given object's docstring.
  753. try:
  754. file = inspect.getsourcefile(obj) or inspect.getfile(obj)
  755. if module is not None:
  756. # Supply the module globals in case the module was
  757. # originally loaded via a PEP 302 loader and
  758. # file is not a valid filesystem path
  759. source_lines = linecache.getlines(file, module.__dict__)
  760. else:
  761. # No access to a loader, so assume it's a normal
  762. # filesystem path
  763. source_lines = linecache.getlines(file)
  764. if not source_lines:
  765. source_lines = None
  766. except TypeError:
  767. source_lines = None
  768. # Initialize globals, and merge in extraglobs.
  769. if globs is None:
  770. if module is None:
  771. globs = {}
  772. else:
  773. globs = module.__dict__.copy()
  774. else:
  775. globs = globs.copy()
  776. if extraglobs is not None:
  777. globs.update(extraglobs)
  778. if '__name__' not in globs:
  779. globs['__name__'] = '__main__' # provide a default module name
  780. # Recursively explore `obj`, extracting DocTests.
  781. tests = []
  782. self._find(tests, obj, name, module, source_lines, globs, {})
  783. # Sort the tests by alpha order of names, for consistency in
  784. # verbose-mode output. This was a feature of doctest in Pythons
  785. # <= 2.3 that got lost by accident in 2.4. It was repaired in
  786. # 2.4.4 and 2.5.
  787. tests.sort()
  788. return tests
  789. def _from_module(self, module, object):
  790. """
  791. Return true if the given object is defined in the given
  792. module.
  793. """
  794. if module is None:
  795. return True
  796. elif inspect.getmodule(object) is not None:
  797. return module is inspect.getmodule(object)
  798. elif inspect.isfunction(object):
  799. return module.__dict__ is object.func_globals
  800. elif inspect.isclass(object):
  801. return module.__name__ == object.__module__
  802. elif hasattr(object, '__module__'):
  803. return module.__name__ == object.__module__
  804. elif isinstance(object, property):
  805. return True # [XX] no way not be sure.
  806. else:
  807. raise ValueError("object must be a class or function")
  808. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  809. """
  810. Find tests for the given object and any contained objects, and
  811. add them to `tests`.
  812. """
  813. if self._verbose:
  814. print 'Finding tests in %s' % name
  815. # If we've already processed this object, then ignore it.
  816. if id(obj) in seen:
  817. return
  818. seen[id(obj)] = 1
  819. # Find a test for this object, and add it to the list of tests.
  820. test = self._get_test(obj, name, module, globs, source_lines)
  821. if test is not None:
  822. tests.append(test)
  823. # Look for tests in a module's contained objects.
  824. if inspect.ismodule(obj) and self._recurse:
  825. for valname, val in obj.__dict__.items():
  826. valname = '%s.%s' % (name, valname)
  827. # Recurse to functions & classes.
  828. if ((inspect.isfunction(val) or inspect.isclass(val)) and
  829. self._from_module(module, val)):
  830. self._find(tests, val, valname, module, source_lines,
  831. globs, seen)
  832. # Look for tests in a module's __test__ dictionary.
  833. if inspect.ismodule(obj) and self._recurse:
  834. for valname, val in getattr(obj, '__test__', {}).items():
  835. if not isinstance(valname, basestring):
  836. raise ValueError("DocTestFinder.find: __test__ keys "
  837. "must be strings: %r" %
  838. (type(valname),))
  839. if not (inspect.isfunction(val) or inspect.isclass(val) or
  840. inspect.ismethod(val) or inspect.ismodule(val) or
  841. isinstance(val, basestring)):
  842. raise ValueError("DocTestFinder.find: __test__ values "
  843. "must be strings, functions, methods, "
  844. "classes, or modules: %r" %
  845. (type(val),))
  846. valname = '%s.__test__.%s' % (name, valname)
  847. self._find(tests, val, valname, module, source_lines,
  848. globs, seen)
  849. # Look for tests in a class's contained objects.
  850. if inspect.isclass(obj) and self._recurse:
  851. for valname, val in obj.__dict__.items():
  852. # Special handling for staticmethod/classmethod.
  853. if isinstance(val, staticmethod):
  854. val = getattr(obj, valname)
  855. if isinstance(val, classmethod):
  856. val = getattr(obj, valname).im_func
  857. # Recurse to methods, properties, and nested classes.
  858. if ((inspect.isfunction(val) or inspect.isclass(val) or
  859. isinstance(val, property)) and
  860. self._from_module(module, val)):
  861. valname = '%s.%s' % (name, valname)
  862. self._find(tests, val, valname, module, source_lines,
  863. globs, seen)
  864. def _get_test(self, obj, name, module, globs, source_lines):
  865. """
  866. Return a DocTest for the given object, if it defines a docstring;
  867. otherwise, return None.
  868. """
  869. # Extract the object's docstring. If it doesn't have one,
  870. # then return None (no test for this object).
  871. if isinstance(obj, basestring):
  872. docstring = obj
  873. else:
  874. try:
  875. if obj.__doc__ is None:
  876. docstring = ''
  877. else:
  878. docstring = obj.__doc__
  879. if not isinstance(docstring, basestring):
  880. docstring = str(docstring)
  881. except (TypeError, AttributeError):
  882. docstring = ''
  883. # Find the docstring's location in the file.
  884. lineno = self._find_lineno(obj, source_lines)
  885. # Don't bother if the docstring is empty.
  886. if self._exclude_empty and not docstring:
  887. return None
  888. # Return a DocTest for this object.
  889. if module is None:
  890. filename = None
  891. else:
  892. filename = getattr(module, '__file__', module.__name__)
  893. if filename[-4:] in (".pyc", ".pyo"):
  894. filename = filename[:-1]
  895. return self._parser.get_doctest(docstring, globs, name,
  896. filename, lineno)
  897. def _find_lineno(self, obj, source_lines):
  898. """
  899. Return a line number of the given object's docstring. Note:
  900. this method assumes that the object has a docstring.
  901. """
  902. lineno = None
  903. # Find the line number for modules.
  904. if inspect.ismodule(obj):
  905. lineno = 0
  906. # Find the line number for classes.
  907. # Note: this could be fooled if a class is defined multiple
  908. # times in a single file.
  909. if inspect.isclass(obj):
  910. if source_lines is None:
  911. return None
  912. pat = re.compile(r'^\s*class\s*%s\b' %
  913. getattr(obj, '__name__', '-'))
  914. for i, line in enumerate(source_lines):
  915. if pat.match(line):
  916. lineno = i
  917. break
  918. # Find the line number for functions & methods.
  919. if inspect.ismethod(obj): obj = obj.im_func
  920. if inspect.isfunction(obj): obj = obj.func_code
  921. if inspect.istraceback(obj): obj = obj.tb_frame
  922. if inspect.isframe(obj): obj = obj.f_code
  923. if inspect.iscode(obj):
  924. lineno = getattr(obj, 'co_firstlineno', None)-1
  925. # Find the line number where the docstring starts. Assume
  926. # that it's the first line that begins with a quote mark.
  927. # Note: this could be fooled by a multiline function
  928. # signature, where a continuation line begins with a quote
  929. # mark.
  930. if lineno is not None:
  931. if source_lines is None:
  932. return lineno+1
  933. pat = re.compile('(^|.*:)\s*\w*("|\')')
  934. for lineno in range(lineno, len(source_lines)):
  935. if pat.match(source_lines[lineno]):
  936. return lineno
  937. # We couldn't find the line number.
  938. return None
  939. ######################################################################
  940. ## 5. DocTest Runner
  941. ######################################################################
  942. class DocTestRunner:
  943. """
  944. A class used to run DocTest test cases, and accumulate statistics.
  945. The `run` method is used to process a single DocTest case. It
  946. returns a tuple `(f, t)`, where `t` is the number of test cases
  947. tried, and `f` is the number of test cases that failed.
  948. >>> tests = DocTestFinder().find(_TestClass)
  949. >>> runner = DocTestRunner(verbose=False)
  950. >>> tests.sort(key = lambda test: test.name)
  951. >>> for test in tests:
  952. ... print test.name, '->', runner.run(test)
  953. _TestClass -> TestResults(failed=0, attempted=2)
  954. _TestClass.__init__ -> TestResults(failed=0, attempted=2)
  955. _TestClass.get -> TestResults(failed=0, attempted=2)
  956. _TestClass.square -> TestResults(failed=0, attempted=1)
  957. The `summarize` method prints a summary of all the test cases that
  958. have been run by the runner, and returns an aggregated `(f, t)`
  959. tuple:
  960. >>> runner.summarize(verbose=1)
  961. 4 items passed all tests:
  962. 2 tests in _TestClass
  963. 2 tests in _TestClass.__init__
  964. 2 tests in _TestClass.get
  965. 1 tests in _TestClass.square
  966. 7 tests in 4 items.
  967. 7 passed and 0 failed.
  968. Test passed.
  969. TestResults(failed=0, attempted=7)
  970. The aggregated number of tried examples and failed examples is
  971. also available via the `tries` and `failures` attributes:
  972. >>> runner.tries
  973. 7
  974. >>> runner.failures
  975. 0
  976. The comparison between expected outputs and actual outputs is done
  977. by an `OutputChecker`. This comparison may be customized with a
  978. number of option flags; see the documentation for `testmod` for
  979. more information. If the option flags are insufficient, then the
  980. comparison may also be customized by passing a subclass of
  981. `OutputChecker` to the constructor.
  982. The test runner's display output can be controlled in two ways.
  983. First, an output function (`out) can be passed to
  984. `TestRunner.run`; this function will be called with strings that
  985. should be displayed. It defaults to `sys.stdout.write`. If
  986. capturing the output is not sufficient, then the display output
  987. can be also customized by subclassing DocTestRunner, and
  988. overriding the methods `report_start`, `report_success`,
  989. `report_unexpected_exception`, and `report_failure`.
  990. """
  991. # This divider string is used to separate failure messages, and to
  992. # separate sections of the summary.
  993. DIVIDER = "*" * 70
  994. def __init__(self, checker=None, verbose=None, optionflags=0):
  995. """
  996. Create a new test runner.
  997. Optional keyword arg `checker` is the `OutputChecker` that
  998. should be used to compare the expected outputs and actual
  999. outputs of doctest examples.
  1000. Optional keyword arg 'verbose' prints lots of stuff if true,
  1001. only failures if false; by default, it's true iff '-v' is in
  1002. sys.argv.
  1003. Optional argument `optionflags` can be used to control how the
  1004. test runner compares expected output to actual output, and how
  1005. it displays failures. See the documentation for `testmod` for
  1006. more information.
  1007. """
  1008. self._checker = checker or OutputChecker()
  1009. if verbose is None:
  1010. verbose = '-v' in sys.argv
  1011. self._verbose = verbose
  1012. self.optionflags = optionflags
  1013. self.original_optionflags = optionflags
  1014. # Keep track of the examples we've run.
  1015. self.tries = 0
  1016. self.failures = 0
  1017. self._name2ft = {}
  1018. # Create a fake output target for capturing doctest output.
  1019. self._fakeout = _SpoofOut()
  1020. #/////////////////////////////////////////////////////////////////
  1021. # Reporting methods
  1022. #/////////////////////////////////////////////////////////////////
  1023. def report_start(self, out, test, example):
  1024. """
  1025. Report that the test runner is about to process the given
  1026. example. (Only displays a message if verbose=True)
  1027. """
  1028. if self._verbose:
  1029. if example.want:
  1030. out('Trying:\n' + _indent(example.source) +
  1031. 'Expecting:\n' + _indent(example.want))
  1032. else:
  1033. out('Trying:\n' + _indent(example.source) +
  1034. 'Expecting nothing\n')
  1035. def report_success(self, out, test, example, got):
  1036. """
  1037. Report that the given example ran successfully. (Only
  1038. displays a message if verbose=True)
  1039. """
  1040. if self._verbose:
  1041. out("ok\n")
  1042. def report_failure(self, out, test, example, got):
  1043. """
  1044. Report that the given example failed.
  1045. """
  1046. out(self._failure_header(test, example) +
  1047. self._checker.output_difference(example, got, self.optionflags))
  1048. def report_unexpected_exception(self, out, test, example, exc_info):
  1049. """
  1050. Report that the given example raised an unexpected exception.
  1051. """
  1052. out(self._failure_header(test, example) +
  1053. 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  1054. def _failure_header(self, test, example):
  1055. out = [self.DIVIDER]
  1056. if test.filename:
  1057. if test.lineno is not None and example.lineno is not None:
  1058. lineno = test.lineno + example.lineno + 1
  1059. else:
  1060. lineno = '?'
  1061. out.append('File "%s", line %s, in %s' %
  1062. (test.filename, lineno, test.name))
  1063. else:
  1064. out.append('Line %s, in %s' % (example.lineno+1, test.name))
  1065. out.append('Failed example:')
  1066. source = example.source
  1067. out.append(_indent(source))
  1068. return '\n'.join(out)
  1069. #/////////////////////////////////////////////////////////////////
  1070. # DocTest Running
  1071. #/////////////////////////////////////////////////////////////////
  1072. def __run(self, test, compileflags, out):
  1073. """
  1074. Run the examples in `test`. Write the outcome of each example
  1075. with one of the `DocTestRunner.report_*` methods, using the
  1076. writer function `out`. `compileflags` is the set of compiler
  1077. flags that should be used to execute examples. Return a tuple
  1078. `(f, t)`, where `t` is the number of examples tried, and `f`
  1079. is the number of examples that failed. The examples are run
  1080. in the namespace `test.globs`.
  1081. """
  1082. # Keep track of the number of failures and tries.
  1083. failures = tries = 0
  1084. # Save the option flags (since option directives can be used
  1085. # to modify them).
  1086. original_optionflags = self.optionflags
  1087. SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
  1088. check = self._checker.check_output
  1089. # Process each example.
  1090. for examplenum, example in enumerate(test.examples):
  1091. # If REPORT_ONLY_FIRST_FAILURE is set, then suppress
  1092. # reporting after the first failure.
  1093. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
  1094. failures > 0)
  1095. # Merge in the example's options.
  1096. self.optionflags = original_optionflags
  1097. if example.options:

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