PageRenderTime 60ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/doctest.py

https://bitbucket.org/evelyn559/pypy
Python | 2731 lines | 2666 code | 13 blank | 52 comment | 29 complexity | dbdfec70f12c69cb3232a7c0363f7288 MD5 | raw 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.debugger.set_continue() # ==== Example Finished ====
  1095. exception = None
  1096. except KeyboardInterrupt:
  1097. raise
  1098. except:
  1099. exception = sys.exc_info()
  1100. self.debugger.set_continue() # ==== Example Finished ====
  1101. got = self._fakeout.getvalue() # the actual output
  1102. self._fakeout.truncate(0)
  1103. outcome = FAILURE # guilty until proved innocent or insane
  1104. # If the example executed without raising any exceptions,
  1105. # verify its output.
  1106. if exception is None:
  1107. if check(example.want, got, self.optionflags):
  1108. outcome = SUCCESS
  1109. # The example raised an exception: check if it was expected.
  1110. else:
  1111. exc_info = sys.exc_info()
  1112. exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1113. if not quiet:
  1114. got += _exception_traceback(exc_info)
  1115. # If `example.exc_msg` is None, then we weren't expecting
  1116. # an exception.
  1117. if example.exc_msg is None:
  1118. outcome = BOOM
  1119. # We expected an exception: see whether it matches.
  1120. elif check(example.exc_msg, exc_msg, self.optionflags):
  1121. outcome = SUCCESS
  1122. # Another chance if they didn't care about the detail.
  1123. elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1124. m1 = re.match(r'(?:[^:]*\.)?([^:]*:)', example.exc_msg)
  1125. m2 = re.match(r'(?:[^:]*\.)?([^:]*:)', exc_msg)
  1126. if m1 and m2 and check(m1.group(1), m2.group(1),
  1127. self.optionflags):
  1128. outcome = SUCCESS
  1129. # Report the outcome.
  1130. if outcome is SUCCESS:
  1131. if not quiet:
  1132. self.report_success(out, test, example, got)
  1133. elif outcome is FAILURE:
  1134. if not quiet:
  1135. self.report_failure(out, test, example, got)
  1136. failures += 1
  1137. elif outcome is BOOM:
  1138. if not quiet:
  1139. self.report_unexpected_exception(out, test, example,
  1140. exc_info)
  1141. failures += 1
  1142. else:
  1143. assert False, ("unknown outcome", outcome)
  1144. # Restore the option flags (in case they were modified)
  1145. self.optionflags = original_optionflags
  1146. # Record and return the number of failures and tries.
  1147. self.__record_outcome(test, failures, tries)
  1148. return TestResults(failures, tries)
  1149. def __record_outcome(self, test, f, t):
  1150. """
  1151. Record the fact that the given DocTest (`test`) generated `f`
  1152. failures out of `t` tried examples.
  1153. """
  1154. f2, t2 = self._name2ft.get(test.name, (0,0))
  1155. self._name2ft[test.name] = (f+f2, t+t2)
  1156. self.failures += f
  1157. self.tries += t
  1158. __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
  1159. r'(?P<name>.+)'
  1160. r'\[(?P<examplenum>\d+)\]>$')
  1161. def __patched_linecache_getlines(self, filename, module_globals=None):
  1162. m = self.__LINECACHE_FILENAME_RE.match(filename)
  1163. if m and m.group('name') == self.test.name:
  1164. example = self.test.examples[int(m.group('examplenum'))]
  1165. source = example.source
  1166. if isinstance(source, unicode):
  1167. source = source.encode('ascii', 'backslashreplace')
  1168. return source.splitlines(True)
  1169. else:
  1170. return self.save_linecache_getlines(filename, module_globals)
  1171. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1172. """
  1173. Run the examples in `test`, and display the results using the
  1174. writer function `out`.
  1175. The examples are run in the namespace `test.globs`. If
  1176. `clear_globs` is true (the default), then this namespace will
  1177. be cleared after the test runs, to help with garbage
  1178. collection. If you would like to examine the namespace after
  1179. the test completes, then use `clear_globs=False`.
  1180. `compileflags` gives the set of flags that should be used by
  1181. the Python compiler when running the examples. If not
  1182. specified, then it will default to the set of future-import
  1183. flags that apply to `globs`.
  1184. The output of each example is checked using
  1185. `DocTestRunner.check_output`, and the results are formatted by
  1186. the `DocTestRunner.report_*` methods.
  1187. """
  1188. self.test = test
  1189. if compileflags is None:
  1190. compileflags = _extract_future_flags(test.globs)
  1191. save_stdout = sys.stdout
  1192. if out is None:
  1193. out = save_stdout.write
  1194. sys.stdout = self._fakeout
  1195. # Patch pdb.set_trace to restore sys.stdout during interactive
  1196. # debugging (so it's not still redirected to self._fakeout).
  1197. # Note that the interactive output will go to *our*
  1198. # save_stdout, even if that's not the real sys.stdout; this
  1199. # allows us to write test cases for the set_trace behavior.
  1200. save_set_trace = pdb.set_trace
  1201. self.debugger = _OutputRedirectingPdb(save_stdout)
  1202. self.debugger.reset()
  1203. pdb.set_trace = self.debugger.set_trace
  1204. # Patch linecache.getlines, so we can see the example's source
  1205. # when we're inside the debugger.
  1206. self.save_linecache_getlines = linecache.getlines
  1207. linecache.getlines = self.__patched_linecache_getlines
  1208. # Make sure sys.displayhook just prints the value to stdout
  1209. save_displayhook = sys.displayhook
  1210. sys.displayhook = sys.__displayhook__
  1211. try:
  1212. return self.__run(test, compileflags, out)
  1213. finally:
  1214. sys.stdout = save_stdout
  1215. pdb.set_trace = save_set_trace
  1216. linecache.getlines = self.save_linecache_getlines
  1217. sys.displayhook = save_displayhook
  1218. if clear_globs:
  1219. test.globs.clear()
  1220. #/////////////////////////////////////////////////////////////////
  1221. # Summarization
  1222. #/////////////////////////////////////////////////////////////////
  1223. def summarize(self, verbose=None):
  1224. """
  1225. Print a summary of all the test cases that have been run by
  1226. this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1227. the total number of failed examples, and `t` is the total
  1228. number of tried examples.
  1229. The optional `verbose` argument controls how detailed the
  1230. summary is. If the verbosity is not specified, then the
  1231. DocTestRunner's verbosity is used.
  1232. """
  1233. if verbose is None:
  1234. verbose = self._verbose
  1235. notests = []
  1236. passed = []
  1237. failed = []
  1238. totalt = totalf = 0
  1239. for x in self._name2ft.items():
  1240. name, (f, t) = x
  1241. assert f <= t
  1242. totalt += t
  1243. totalf += f
  1244. if t == 0:
  1245. notests.append(name)
  1246. elif f == 0:
  1247. passed.append( (name, t) )
  1248. else:
  1249. failed.append(x)
  1250. if verbose:
  1251. if notests:
  1252. print len(notests), "items had no tests:"
  1253. notests.sort()
  1254. for thing in notests:
  1255. print " ", thing
  1256. if passed:
  1257. print len(passed), "items passed all tests:"
  1258. passed.sort()
  1259. for thing, count in passed:
  1260. print " %3d tests in %s" % (count, thing)
  1261. if failed:
  1262. print self.DIVIDER
  1263. print len(failed), "items had failures:"
  1264. failed.sort()
  1265. for thing, (f, t) in failed:
  1266. print " %3d of %3d in %s" % (f, t, thing)
  1267. if verbose:
  1268. print totalt, "tests in", len(self._name2ft), "items."
  1269. print totalt - totalf, "passed and", totalf, "failed."
  1270. if totalf:
  1271. print "***Test Failed***", totalf, "failures."
  1272. elif verbose:
  1273. print "Test passed."
  1274. return TestResults(totalf, totalt)
  1275. #/////////////////////////////////////////////////////////////////
  1276. # Backward compatibility cruft to maintain doctest.master.
  1277. #/////////////////////////////////////////////////////////////////
  1278. def merge(self, other):
  1279. d = self._name2ft
  1280. for name, (f, t) in other._name2ft.items():
  1281. if name in d:
  1282. # Don't print here by default, since doing
  1283. # so breaks some of the buildbots
  1284. #print "*** DocTestRunner.merge: '" + name + "' in both" \
  1285. # " testers; summing outcomes."
  1286. f2, t2 = d[name]
  1287. f = f + f2
  1288. t = t + t2
  1289. d[name] = f, t
  1290. class OutputChecker:
  1291. """
  1292. A class used to check the whether the actual output from a doctest
  1293. example matches the expected output. `OutputChecker` defines two
  1294. methods: `check_output`, which compares a given pair of outputs,
  1295. and returns true if they match; and `output_difference`, which
  1296. returns a string describing the differences between two outputs.
  1297. """
  1298. def check_output(self, want, got, optionflags):
  1299. """
  1300. Return True iff the actual output from an example (`got`)
  1301. matches the expected output (`want`). These strings are
  1302. always considered to match if they are identical; but
  1303. depending on what option flags the test runner is using,
  1304. several non-exact match types are also possible. See the
  1305. documentation for `TestRunner` for more information about
  1306. option flags.
  1307. """
  1308. # Handle the common case first, for efficiency:
  1309. # if they're string-identical, always return true.
  1310. if got == want:
  1311. return True
  1312. # The values True and False replaced 1 and 0 as the return
  1313. # value for boolean comparisons in Python 2.3.
  1314. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
  1315. if (got,want) == ("True\n", "1\n"):
  1316. return True
  1317. if (got,want) == ("False\n", "0\n"):
  1318. return True
  1319. # <BLANKLINE> can be used as a special sequence to signify a
  1320. # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
  1321. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1322. # Replace <BLANKLINE> in want with a blank line.
  1323. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
  1324. '', want)
  1325. # If a line in got contains only spaces, then remove the
  1326. # spaces.
  1327. got = re.sub('(?m)^\s*?$', '', got)
  1328. if got == want:
  1329. return True
  1330. # This flag causes doctest to ignore any differences in the
  1331. # contents of whitespace strings. Note that this can be used
  1332. # in conjunction with the ELLIPSIS flag.
  1333. if optionflags & NORMALIZE_WHITESPACE:
  1334. got = ' '.join(got.split())
  1335. want = ' '.join(want.split())
  1336. if got == want:
  1337. return True
  1338. # The ELLIPSIS flag says to let the sequence "..." in `want`
  1339. # match any substring in `got`.
  1340. if optionflags & ELLIPSIS:
  1341. if _ellipsis_match(want, got):
  1342. return True
  1343. # We didn't find any match; return false.
  1344. return False
  1345. # Should we do a fancy diff?
  1346. def _do_a_fancy_diff(self, want, got, optionflags):
  1347. # Not unless they asked for a fancy diff.
  1348. if not optionflags & (REPORT_UDIFF |
  1349. REPORT_CDIFF |
  1350. REPORT_NDIFF):
  1351. return False
  1352. # If expected output uses ellipsis, a meaningful fancy diff is
  1353. # too hard ... or maybe not. In two real-life failures Tim saw,
  1354. # a diff was a major help anyway, so this is commented out.
  1355. # [todo] _ellipsis_match() knows which pieces do and don't match,
  1356. # and could be the basis for a kick-ass diff in this case.
  1357. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
  1358. ## return False
  1359. # ndiff does intraline difference marking, so can be useful even
  1360. # for 1-line differences.
  1361. if optionflags & REPORT_NDIFF:
  1362. return True
  1363. # The other diff types need at least a few lines to be helpful.
  1364. return want.count('\n') > 2 and got.count('\n') > 2
  1365. def output_difference(self, example, got, optionflags):
  1366. """
  1367. Return a string describing the differences between the
  1368. expected output for a given example (`example`) and the actual
  1369. output (`got`). `optionflags` is the set of option flags used
  1370. to compare `want` and `got`.
  1371. """
  1372. want = example.want
  1373. # If <BLANKLINE>s are being used, then replace blank lines
  1374. # with <BLANKLINE> in the actual output string.
  1375. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1376. got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1377. # Check if we should use diff.
  1378. if self._do_a_fancy_diff(want, got, optionflags):
  1379. # Split want & got into lines.
  1380. want_lines = want.splitlines(True) # True == keep line ends
  1381. got_lines = got.splitlines(True)
  1382. # Use difflib to find their differences.
  1383. if optionflags & REPORT_UDIFF:
  1384. diff = difflib.unified_diff(want_lines, got_lines, n=2)
  1385. diff = list(diff)[2:] # strip the diff header
  1386. kind = 'unified diff with -expected +actual'
  1387. elif optionflags & REPORT_CDIFF:
  1388. diff = difflib.context_diff(want_lines, got_lines, n=2)
  1389. diff = list(diff)[2:] # strip the diff header
  1390. kind = 'context diff with expected followed by actual'
  1391. elif optionflags & REPORT_NDIFF:
  1392. engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
  1393. diff = list(engine.compare(want_lines, got_lines))
  1394. kind = 'ndiff with -expected +actual'
  1395. else:
  1396. assert 0, 'Bad diff option'
  1397. # Remove trailing whitespace on diff output.
  1398. diff = [line.rstrip() + '\n' for line in diff]
  1399. return 'Differences (%s):\n' % kind + _indent(''.join(diff))
  1400. # If we're not using diff, then simply list the expected
  1401. # output followed by the actual output.
  1402. if want and got:
  1403. return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1404. elif want:
  1405. return 'Expected:\n%sGot nothing\n' % _indent(want)
  1406. elif got:
  1407. return 'Expected nothing\nGot:\n%s' % _indent(got)
  1408. else:
  1409. return 'Expected nothing\nGot nothing\n'
  1410. class DocTestFailure(Exception):
  1411. """A DocTest example has failed in debugging mode.
  1412. The exception instance has variables:
  1413. - test: the DocTest object being run
  1414. - example: the Example object that failed
  1415. - got: the actual output
  1416. """
  1417. def __init__(self, test, example, got):
  1418. self.test = test
  1419. self.example = example
  1420. self.got = got
  1421. def __str__(self):
  1422. return str(self.test)
  1423. class UnexpectedException(Exception):
  1424. """A DocTest example has encountered an unexpected exception
  1425. The exception instance has variables:
  1426. - test: the DocTest object being run
  1427. - example: the Example object that failed
  1428. - exc_info: the exception info
  1429. """
  1430. def __init__(self, test, example, exc_info):
  1431. self.test = test
  1432. self.example = example
  1433. self.exc_info = exc_info
  1434. def __str__(self):
  1435. return str(self.test)
  1436. class DebugRunner(DocTestRunner):
  1437. r"""Run doc tests but raise an exception as soon as there is a failure.
  1438. If an unexpected exception occurs, an UnexpectedException is raised.
  1439. It contains the test, the example, and the original exception:
  1440. >>> runner = DebugRunner(verbose=False)
  1441. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1442. ... {}, 'foo', 'foo.py', 0)
  1443. >>> try:
  1444. ... runner.run(test)
  1445. ... except UnexpectedException, failure:
  1446. ... pass
  1447. >>> failure.test is test
  1448. True
  1449. >>> failure.example.want
  1450. '42\n'
  1451. >>> exc_info = failure.exc_info
  1452. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1453. Traceback (most recent call last):
  1454. ...
  1455. KeyError
  1456. We wrap the original exception to give the calling application
  1457. access to the test and example information.
  1458. If the output doesn't match, then a DocTestFailure is raised:
  1459. >>> test = DocTestParser().get_doctest('''
  1460. ... >>> x = 1
  1461. ... >>> x
  1462. ... 2
  1463. ... ''', {}, 'foo', 'foo.py', 0)
  1464. >>> try:
  1465. ... runner.run(test)
  1466. ... except DocTestFailure, failure:
  1467. ... pass
  1468. DocTestFailure objects provide access to the test:
  1469. >>> failure.test is test
  1470. True
  1471. As well as to the example:
  1472. >>> failure.example.want
  1473. '2\n'
  1474. and the actual output:
  1475. >>> failure.got
  1476. '1\n'
  1477. If a failure or error occurs, the globals are left intact:
  1478. >>> del test.globs['__builtins__']
  1479. >>> test.globs
  1480. {'x': 1}
  1481. >>> test = DocTestParser().get_doctest('''
  1482. ... >>> x = 2
  1483. ... >>> raise KeyError
  1484. ... ''', {}, 'foo', 'foo.py', 0)
  1485. >>> runner.run(test)
  1486. Traceback (most recent call last):
  1487. ...
  1488. UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1489. >>> del test.globs['__builtins__']
  1490. >>> test.globs
  1491. {'x': 2}
  1492. But the globals are cleared if there is no error:
  1493. >>> test = DocTestParser().get_doctest('''
  1494. ... >>> x = 2
  1495. ... ''', {}, 'foo', 'foo.py', 0)
  1496. >>> runner.run(test)
  1497. TestResults(failed=0, attempted=1)
  1498. >>> test.globs
  1499. {}
  1500. """
  1501. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1502. r = DocTestRunner.run(self, test, compileflags, out, False)
  1503. if clear_globs:
  1504. test.globs.clear()
  1505. return r
  1506. def report_unexpected_exception(self, out, test, example, exc_info):
  1507. raise UnexpectedException(test, example, exc_info)
  1508. def report_failure(self, out, test, example, got):
  1509. raise DocTestFailure(test, example, got)
  1510. ######################################################################
  1511. ## 6. Test Functions
  1512. ######################################################################
  1513. # These should be backwards compatible.
  1514. # For backward compatibility, a global instance of a DocTestRunner
  1515. # class, updated by testmod.
  1516. master = None
  1517. def testmod(m=None, name=None, globs=None, verbose=None,
  1518. report=True, optionflags=0, extraglobs=None,
  1519. raise_on_error=False, exclude_empty=False):
  1520. """m=None, name=None, globs=None, verbose=None, report=True,
  1521. optionflags=0, extraglobs=None, raise_on_error=False,
  1522. exclude_empty=False
  1523. Test examples in docstrings in functions and classes reachable
  1524. from module m (or the current module if m is not supplied), starting
  1525. with m.__doc__.
  1526. Also test examples reachable from dict m.__test__ if it exists and is
  1527. not None. m.__test__ maps names to functions, classes and strings;
  1528. function and class docstrings are tested even if the name is private;
  1529. strings are tested directly, as if they were docstrings.
  1530. Return (#failures, #tests).
  1531. See help(doctest) for an overview.
  1532. Optional keyword arg "name" gives the name of the module; by default
  1533. use m.__name__.
  1534. Optional keyword arg "globs" gives a dict to be used as the globals
  1535. when executing examples; by default, use m.__dict__. A copy of this
  1536. dict is actually used for each docstring, so that each docstring's
  1537. examples start with a clean slate.
  1538. Optional keyword arg "extraglobs" gives a dictionary that should be
  1539. merged into the globals that are used to execute examples. By
  1540. default, no extra globals are used. This is new in 2.4.
  1541. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1542. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1543. Optional keyword arg "report" prints a summary at the end when true,
  1544. else prints nothing at the end. In verbose mode, the summary is
  1545. detailed, else very brief (in fact, empty if all tests passed).
  1546. Optional keyword arg "optionflags" or's together module constants,
  1547. and defaults to 0. This is new in 2.3. Possible values (see the
  1548. docs for details):
  1549. DONT_ACCEPT_TRUE_FOR_1
  1550. DONT_ACCEPT_BLANKLINE
  1551. NORMALIZE_WHITESPACE
  1552. ELLIPSIS
  1553. SKIP
  1554. IGNORE_EXCEPTION_DETAIL
  1555. REPORT_UDIFF
  1556. REPORT_CDIFF
  1557. REPORT_NDIFF
  1558. REPORT_ONLY_FIRST_FAILURE
  1559. Optional keyword arg "raise_on_error" raises an exception on the
  1560. first unexpected exception or failure. This allows failures to be
  1561. post-mortem debugged.
  1562. Advanced tomfoolery: testmod runs methods of a local instance of
  1563. class doctest.Tester, then merges the results into (or creates)
  1564. global Tester instance doctest.master. Methods of doctest.master
  1565. can be called directly too, if you want to do something unusual.
  1566. Passing report=0 to testmod is especially useful then, to delay
  1567. displaying a summary. Invoke doctest.master.summarize(verbose)
  1568. when you're done fiddling.
  1569. """
  1570. global master
  1571. # If no module was given, then use __main__.
  1572. if m is None:
  1573. # DWA - m will still be None if this wasn't invoked from the command
  1574. # line, in which case the following TypeError is about as good an error
  1575. # as we should expect
  1576. m = sys.modules.get('__main__')
  1577. # Check that we were actually given a module.
  1578. if not inspect.ismodule(m):
  1579. raise TypeError("testmod: module required; %r" % (m,))
  1580. # If no name was given, then use the module's name.
  1581. if name is None:
  1582. name = m.__name__
  1583. # Find, parse, and run all tests in the given module.
  1584. finder = DocTestFinder(exclude_empty=exclude_empty)
  1585. if raise_on_error:
  1586. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1587. else:
  1588. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1589. for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
  1590. runner.run(test)
  1591. if report:
  1592. runner.summarize()
  1593. if master is None:
  1594. master = runner
  1595. else:
  1596. master.merge(runner)
  1597. return TestResults(runner.failures, runner.tries)
  1598. def testfile(filename, module_relative=True, name=None, package=None,
  1599. globs=None, verbose=None, report=True, optionflags=0,
  1600. extraglobs=None, raise_on_error=False, parser=DocTestParser(),
  1601. encoding=None):
  1602. """
  1603. Test examples in the given file. Return (#failures, #tests).
  1604. Optional keyword arg "module_relative" specifies how filenames
  1605. should be interpreted:
  1606. - If "module_relative" is True (the default), then "filename"
  1607. specifies a module-relative path. By default, this path is
  1608. relative to the calling module's directory; but if the
  1609. "package" argument is specified, then it is relative to that
  1610. package. To ensure os-independence, "filename" should use
  1611. "/" characters to separate path segments, and should not
  1612. be an absolute path (i.e., it may not begin with "/").
  1613. - If "module_relative" is False, then "filename" specifies an
  1614. os-specific path. The path may be absolute or relative (to
  1615. the current working directory).
  1616. Optional keyword arg "name" gives the name of the test; by default
  1617. use the file's basename.
  1618. Optional keyword argument "package" is a Python package or the
  1619. name of a Python package whose directory should be used as the
  1620. base directory for a module relative filename. If no package is
  1621. specified, then the calling module's directory is used as the base
  1622. directory for module relative filenames. It is an error to
  1623. specify "package" if "module_relative" is False.
  1624. Optional keyword arg "globs" gives a dict to be used as the globals
  1625. when executing examples; by default, use {}. A copy of this dict
  1626. is actually used for each docstring, so that each docstring's
  1627. examples start with a clean slate.
  1628. Optional keyword arg "extraglobs" gives a dictionary that should be
  1629. merged into the globals that are used to execute examples. By
  1630. default, no extra globals are used.
  1631. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1632. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1633. Optional keyword arg "report" prints a summary at the end when true,
  1634. else prints nothing at the end. In verbose mode, the summary is
  1635. detailed, else very brief (in fact, empty if all tests passed).
  1636. Optional keyword arg "optionflags" or's together module constants,
  1637. and defaults to 0. Possible values (see the docs for details):
  1638. DONT_ACCEPT_TRUE_FOR_1
  1639. DONT_ACCEPT_BLANKLINE
  1640. NORMALIZE_WHITESPACE
  1641. ELLIPSIS
  1642. SKIP
  1643. IGNORE_EXCEPTION_DETAIL
  1644. REPORT_UDIFF
  1645. REPORT_CDIFF
  1646. REPORT_NDIFF
  1647. REPORT_ONLY_FIRST_FAILURE
  1648. Optional keyword arg "raise_on_error" raises an exception on the
  1649. first unexpected exception or failure. This allows failures to be
  1650. post-mortem debugged.
  1651. Optional keyword arg "parser" specifies a DocTestParser (or
  1652. subclass) that should be used to extract tests from the files.
  1653. Optional keyword arg "encoding" specifies an encoding that should
  1654. be used to convert the file to unicode.
  1655. Advanced tomfoolery: testmod runs methods of a local instance of
  1656. class doctest.Tester, then merges the results into (or creates)
  1657. global Tester instance doctest.master. Methods of doctest.master
  1658. can be called directly too, if you want to do something unusual.
  1659. Passing report=0 to testmod is especially useful then, to delay
  1660. displaying a summary. Invoke doctest.master.summarize(verbose)
  1661. when you're done fiddling.
  1662. """
  1663. global master
  1664. if package and not module_relative:
  1665. raise ValueError("Package may only be specified for module-"
  1666. "relative paths.")
  1667. # Relativize the path
  1668. text, filename = _load_testfile(filename, package, module_relative)
  1669. # If no name was given, then use the file's name.
  1670. if name is None:
  1671. name = os.path.basename(filename)
  1672. # Assemble the globals.
  1673. if globs is None:
  1674. globs = {}
  1675. else:
  1676. globs = globs.copy()
  1677. if extraglobs is not None:
  1678. globs.update(extraglobs)
  1679. if '__name__' not in globs:
  1680. globs['__name__'] = '__main__'
  1681. if raise_on_error:
  1682. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1683. else:
  1684. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1685. if encoding is not None:
  1686. text = text.decode(encoding)
  1687. # Read the file, convert it to a test, and run it.
  1688. test = parser.get_doctest(text, globs, name, filename, 0)
  1689. runner.run(test)
  1690. if report:
  1691. runner.summarize()
  1692. if master is None:
  1693. master = runner
  1694. else:
  1695. master.merge(runner)
  1696. return TestResults(runner.failures, runner.tries)
  1697. def run_docstring_examples(f, globs, verbose=False, name="NoName",
  1698. compileflags=None, optionflags=0):
  1699. """
  1700. Test examples in the given object's docstring (`f`), using `globs`
  1701. as globals. Optional argument `name` is used in failure messages.
  1702. If the optional argument `verbose` is true, then generate output
  1703. even if there are no failures.
  1704. `compileflags` gives the set of flags that should be used by the
  1705. Python compiler when running the examples. If not specified, then
  1706. it will default to the set of future-import flags that apply to
  1707. `globs`.
  1708. Optional keyword arg `optionflags` specifies options for the
  1709. testing and output. See the documentation for `testmod` for more
  1710. information.
  1711. """
  1712. # Find, parse, and run all tests in the given module.
  1713. finder = DocTestFinder(verbose=verbose, recurse=False)
  1714. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1715. for test in finder.find(f, name, globs=globs):
  1716. runner.run(test, compileflags=compileflags)
  1717. ######################################################################
  1718. ## 7. Tester
  1719. ######################################################################
  1720. # This is provided only for backwards compatibility. It's not
  1721. # actually used in any way.
  1722. class Tester:
  1723. def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
  1724. warnings.warn("class Tester is deprecated; "
  1725. "use class doctest.DocTestRunner instead",
  1726. DeprecationWarning, stacklevel=2)
  1727. if mod is None and globs is None:
  1728. raise TypeError("Tester.__init__: must specify mod or globs")
  1729. if mod is not None and not inspect.ismodule(mod):
  1730. raise TypeError("Tester.__init__: mod must be a module; %r" %
  1731. (mod,))
  1732. if globs is None:
  1733. globs = mod.__dict__
  1734. self.globs = globs
  1735. self.verbose = verbose
  1736. self.optionflags = optionflags
  1737. self.testfinder = DocTestFinder()
  1738. self.testrunner = DocTestRunner(verbose=verbose,
  1739. optionflags=optionflags)
  1740. def runstring(self, s, name):
  1741. test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1742. if self.verbose:
  1743. print "Running string", name
  1744. (f,t) = self.testrunner.run(test)
  1745. if self.verbose:
  1746. print f, "of", t, "examples failed in string", name
  1747. return TestResults(f,t)
  1748. def rundoc(self, object, name=None, module=None):
  1749. f = t = 0
  1750. tests = self.testfinder.find(object, name, module=module,
  1751. globs=self.globs)
  1752. for test in tests:
  1753. (f2, t2) = self.testrunner.run(test)
  1754. (f,t) = (f+f2, t+t2)
  1755. return TestResults(f,t)
  1756. def rundict(self, d, name, module=None):
  1757. import types
  1758. m = types.ModuleType(name)
  1759. m.__dict__.update(d)
  1760. if module is None:
  1761. module = False
  1762. return self.rundoc(m, name, module)
  1763. def run__test__(self, d, name):
  1764. import types
  1765. m = types.ModuleType(name)
  1766. m.__test__ = d
  1767. return self.rundoc(m, name)
  1768. def summarize(self, verbose=None):
  1769. return self.testrunner.summarize(verbose)
  1770. def merge(self, other):
  1771. self.testrunner.merge(other.testrunner)
  1772. ######################################################################
  1773. ## 8. Unittest Support
  1774. ######################################################################
  1775. _unittest_reportflags = 0
  1776. def set_unittest_reportflags(flags):
  1777. """Sets the unittest option flags.
  1778. The old flag is returned so that a runner could restore the old
  1779. value if it wished to:
  1780. >>> import doctest
  1781. >>> old = doctest._unittest_reportflags
  1782. >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1783. ... REPORT_ONLY_FIRST_FAILURE) == old
  1784. True
  1785. >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1786. ... REPORT_ONLY_FIRST_FAILURE)
  1787. True
  1788. Only reporting flags can be set:
  1789. >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1790. Traceback (most recent call last):
  1791. ...
  1792. ValueError: ('Only reporting flags allowed', 8)
  1793. >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1794. ... REPORT_ONLY_FIRST_FAILURE)
  1795. True
  1796. """
  1797. global _unittest_reportflags
  1798. if (flags & REPORTING_FLAGS) != flags:
  1799. raise ValueError("Only reporting flags allowed", flags)
  1800. old = _unittest_reportflags
  1801. _unittest_reportflags = flags
  1802. return old
  1803. class DocTestCase(unittest.TestCase):
  1804. def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
  1805. checker=None):
  1806. unittest.TestCase.__init__(self)
  1807. self._dt_optionflags = optionflags
  1808. self._dt_checker = checker
  1809. self._dt_test = test
  1810. self._dt_setUp = setUp
  1811. self._dt_tearDown = tearDown
  1812. def setUp(self):
  1813. test = self._dt_test
  1814. if self._dt_setUp is not None:
  1815. self._dt_setUp(test)
  1816. def tearDown(self):
  1817. test = self._dt_test
  1818. if self._dt_tearDown is not None:
  1819. self._dt_tearDown(test)
  1820. test.globs.clear()
  1821. def runTest(self):
  1822. test = self._dt_test
  1823. old = sys.stdout
  1824. new = StringIO()
  1825. optionflags = self._dt_optionflags
  1826. if not (optionflags & REPORTING_FLAGS):
  1827. # The option flags don't include any reporting flags,
  1828. # so add the default reporting flags
  1829. optionflags |= _unittest_reportflags
  1830. runner = DocTestRunner(optionflags=optionflags,
  1831. checker=self._dt_checker, verbose=False)
  1832. try:
  1833. runner.DIVIDER = "-"*70
  1834. failures, tries = runner.run(
  1835. test, out=new.write, clear_globs=False)
  1836. finally:
  1837. sys.stdout = old
  1838. if failures:
  1839. raise self.failureException(self.format_failure(new.getvalue()))
  1840. def format_failure(self, err):
  1841. test = self._dt_test
  1842. if test.lineno is None:
  1843. lineno = 'unknown line number'
  1844. else:
  1845. lineno = '%s' % test.lineno
  1846. lname = '.'.join(test.name.split('.')[-1:])
  1847. return ('Failed doctest test for %s\n'
  1848. ' File "%s", line %s, in %s\n\n%s'
  1849. % (test.name, test.filename, lineno, lname, err)
  1850. )
  1851. def debug(self):
  1852. r"""Run the test case without results and without catching exceptions
  1853. The unit test framework includes a debug method on test cases
  1854. and test suites to support post-mortem debugging. The test code
  1855. is run in such a way that errors are not caught. This way a
  1856. caller can catch the errors and initiate post-mortem debugging.
  1857. The DocTestCase provides a debug method that raises
  1858. UnexpectedException errors if there is an unexpected
  1859. exception:
  1860. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1861. ... {}, 'foo', 'foo.py', 0)
  1862. >>> case = DocTestCase(test)
  1863. >>> try:
  1864. ... case.debug()
  1865. ... except UnexpectedException, failure:
  1866. ... pass
  1867. The UnexpectedException contains the test, the example, and
  1868. the original exception:
  1869. >>> failure.test is test
  1870. True
  1871. >>> failure.example.want
  1872. '42\n'
  1873. >>> exc_info = failure.exc_info
  1874. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1875. Traceback (most recent call last):
  1876. ...
  1877. KeyError
  1878. If the output doesn't match, then a DocTestFailure is raised:
  1879. >>> test = DocTestParser().get_doctest('''
  1880. ... >>> x = 1
  1881. ... >>> x
  1882. ... 2
  1883. ... ''', {}, 'foo', 'foo.py', 0)
  1884. >>> case = DocTestCase(test)
  1885. >>> try:
  1886. ... case.debug()
  1887. ... except DocTestFailure, failure:
  1888. ... pass
  1889. DocTestFailure objects provide access to the test:
  1890. >>> failure.test is test
  1891. True
  1892. As well as to the example:
  1893. >>> failure.example.want
  1894. '2\n'
  1895. and the actual output:
  1896. >>> failure.got
  1897. '1\n'
  1898. """
  1899. self.setUp()
  1900. runner = DebugRunner(optionflags=self._dt_optionflags,
  1901. checker=self._dt_checker, verbose=False)
  1902. runner.run(self._dt_test, clear_globs=False)
  1903. self.tearDown()
  1904. def id(self):
  1905. return self._dt_test.name
  1906. def __repr__(self):
  1907. name = self._dt_test.name.split('.')
  1908. return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
  1909. __str__ = __repr__
  1910. def shortDescription(self):
  1911. return "Doctest: " + self._dt_test.name
  1912. class SkipDocTestCase(DocTestCase):
  1913. def __init__(self):
  1914. DocTestCase.__init__(self, None)
  1915. def setUp(self):
  1916. self.skipTest("DocTestSuite will not work with -O2 and above")
  1917. def test_skip(self):
  1918. pass
  1919. def shortDescription(self):
  1920. return "Skipping tests from %s" % module.__name__
  1921. def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
  1922. **options):
  1923. """
  1924. Convert doctest tests for a module to a unittest test suite.
  1925. This converts each documentation string in a module that
  1926. contains doctest tests to a unittest test case. If any of the
  1927. tests in a doc string fail, then the test case fails. An exception
  1928. is raised showing the name of the file containing the test and a
  1929. (sometimes approximate) line number.
  1930. The `module` argument provides the module to be tested. The argument
  1931. can be either a module or a module name.
  1932. If no argument is given, the calling module is used.
  1933. A number of options may be provided as keyword arguments:
  1934. setUp
  1935. A set-up function. This is called before running the
  1936. tests in each file. The setUp function will be passed a DocTest
  1937. object. The setUp function can access the test globals as the
  1938. globs attribute of the test passed.
  1939. tearDown
  1940. A tear-down function. This is called after running the
  1941. tests in each file. The tearDown function will be passed a DocTest
  1942. object. The tearDown function can access the test globals as the
  1943. globs attribute of the test passed.
  1944. globs
  1945. A dictionary containing initial global variables for the tests.
  1946. optionflags
  1947. A set of doctest option flags expressed as an integer.
  1948. """
  1949. if test_finder is None:
  1950. test_finder = DocTestFinder()
  1951. module = _normalize_module(module)
  1952. tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
  1953. if not tests and sys.flags.optimize >=2:
  1954. # Skip doctests when running with -O2
  1955. suite = unittest.TestSuite()
  1956. suite.addTest(SkipDocTestCase())
  1957. return suite
  1958. elif not tests:
  1959. # Why do we want to do this? Because it reveals a bug that might
  1960. # otherwise be hidden.
  1961. raise ValueError(module, "has no tests")
  1962. tests.sort()
  1963. suite = unittest.TestSuite()
  1964. for test in tests:
  1965. if len(test.examples) == 0:
  1966. continue
  1967. if not test.filename:
  1968. filename = module.__file__
  1969. if filename[-4:] in (".pyc", ".pyo"):
  1970. filename = filename[:-1]
  1971. test.filename = filename
  1972. suite.addTest(DocTestCase(test, **options))
  1973. return suite
  1974. class DocFileCase(DocTestCase):
  1975. def id(self):
  1976. return '_'.join(self._dt_test.name.split('.'))
  1977. def __repr__(self):
  1978. return self._dt_test.filename
  1979. __str__ = __repr__
  1980. def format_failure(self, err):
  1981. return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
  1982. % (self._dt_test.name, self._dt_test.filename, err)
  1983. )
  1984. def DocFileTest(path, module_relative=True, package=None,
  1985. globs=None, parser=DocTestParser(),
  1986. encoding=None, **options):
  1987. if globs is None:
  1988. globs = {}
  1989. else:
  1990. globs = globs.copy()
  1991. if package and not module_relative:
  1992. raise ValueError("Package may only be specified for module-"
  1993. "relative paths.")
  1994. # Relativize the path.
  1995. doc, path = _load_testfile(path, package, module_relative)
  1996. if "__file__" not in globs:
  1997. globs["__file__"] = path
  1998. # Find the file and read it.
  1999. name = os.path.basename(path)
  2000. # If an encoding is specified, use it to convert the file to unicode
  2001. if encoding is not None:
  2002. doc = doc.decode(encoding)
  2003. # Convert it to a test, and wrap it in a DocFileCase.
  2004. test = parser.get_doctest(doc, globs, name, path, 0)
  2005. return DocFileCase(test, **options)
  2006. def DocFileSuite(*paths, **kw):
  2007. """A unittest suite for one or more doctest files.
  2008. The path to each doctest file is given as a string; the
  2009. interpretation of that string depends on the keyword argument
  2010. "module_relative".
  2011. A number of options may be provided as keyword arguments:
  2012. module_relative
  2013. If "module_relative" is True, then the given file paths are
  2014. interpreted as os-independent module-relative paths. By
  2015. default, these paths are relative to the calling module's
  2016. directory; but if the "package" argument is specified, then
  2017. they are relative to that package. To ensure os-independence,
  2018. "filename" should use "/" characters to separate path
  2019. segments, and may not be an absolute path (i.e., it may not
  2020. begin with "/").
  2021. If "module_relative" is False, then the given file paths are
  2022. interpreted as os-specific paths. These paths may be absolute
  2023. or relative (to the current working directory).
  2024. package
  2025. A Python package or the name of a Python package whose directory
  2026. should be used as the base directory for module relative paths.
  2027. If "package" is not specified, then the calling module's
  2028. directory is used as the base directory for module relative
  2029. filenames. It is an error to specify "package" if
  2030. "module_relative" is False.
  2031. setUp
  2032. A set-up function. This is called before running the
  2033. tests in each file. The setUp function will be passed a DocTest
  2034. object. The setUp function can access the test globals as the
  2035. globs attribute of the test passed.
  2036. tearDown
  2037. A tear-down function. This is called after running the
  2038. tests in each file. The tearDown function will be passed a DocTest
  2039. object. The tearDown function can access the test globals as the
  2040. globs attribute of the test passed.
  2041. globs
  2042. A dictionary containing initial global variables for the tests.
  2043. optionflags
  2044. A set of doctest option flags expressed as an integer.
  2045. parser
  2046. A DocTestParser (or subclass) that should be used to extract
  2047. tests from the files.
  2048. encoding
  2049. An encoding that will be used to convert the files to unicode.
  2050. """
  2051. suite = unittest.TestSuite()
  2052. # We do this here so that _normalize_module is called at the right
  2053. # level. If it were called in DocFileTest, then this function
  2054. # would be the caller and we might guess the package incorrectly.
  2055. if kw.get('module_relative', True):
  2056. kw['package'] = _normalize_module(kw.get('package'))
  2057. for path in paths:
  2058. suite.addTest(DocFileTest(path, **kw))
  2059. return suite
  2060. ######################################################################
  2061. ## 9. Debugging Support
  2062. ######################################################################
  2063. def script_from_examples(s):
  2064. r"""Extract script from text with examples.
  2065. Converts text with examples to a Python script. Example input is
  2066. converted to regular code. Example output and all other words
  2067. are converted to comments:
  2068. >>> text = '''
  2069. ... Here are examples of simple math.
  2070. ...
  2071. ... Python has super accurate integer addition
  2072. ...
  2073. ... >>> 2 + 2
  2074. ... 5
  2075. ...
  2076. ... And very friendly error messages:
  2077. ...
  2078. ... >>> 1/0
  2079. ... To Infinity
  2080. ... And
  2081. ... Beyond
  2082. ...
  2083. ... You can use logic if you want:
  2084. ...
  2085. ... >>> if 0:
  2086. ... ... blah
  2087. ... ... blah
  2088. ... ...
  2089. ...
  2090. ... Ho hum
  2091. ... '''
  2092. >>> print script_from_examples(text)
  2093. # Here are examples of simple math.
  2094. #
  2095. # Python has super accurate integer addition
  2096. #
  2097. 2 + 2
  2098. # Expected:
  2099. ## 5
  2100. #
  2101. # And very friendly error messages:
  2102. #
  2103. 1/0
  2104. # Expected:
  2105. ## To Infinity
  2106. ## And
  2107. ## Beyond
  2108. #
  2109. # You can use logic if you want:
  2110. #
  2111. if 0:
  2112. blah
  2113. blah
  2114. #
  2115. # Ho hum
  2116. <BLANKLINE>
  2117. """
  2118. output = []
  2119. for piece in DocTestParser().parse(s):
  2120. if isinstance(piece, Example):
  2121. # Add the example's source code (strip trailing NL)
  2122. output.append(piece.source[:-1])
  2123. # Add the expected output:
  2124. want = piece.want
  2125. if want:
  2126. output.append('# Expected:')
  2127. output += ['## '+l for l in want.split('\n')[:-1]]
  2128. else:
  2129. # Add non-example text.
  2130. output += [_comment_line(l)
  2131. for l in piece.split('\n')[:-1]]
  2132. # Trim junk on both ends.
  2133. while output and output[-1] == '#':
  2134. output.pop()
  2135. while output and output[0] == '#':
  2136. output.pop(0)
  2137. # Combine the output, and return it.
  2138. # Add a courtesy newline to prevent exec from choking (see bug #1172785)
  2139. return '\n'.join(output) + '\n'
  2140. def testsource(module, name):
  2141. """Extract the test sources from a doctest docstring as a script.
  2142. Provide the module (or dotted name of the module) containing the
  2143. test to be debugged and the name (within the module) of the object
  2144. with the doc string with tests to be debugged.
  2145. """
  2146. module = _normalize_module(module)
  2147. tests = DocTestFinder().find(module)
  2148. test = [t for t in tests if t.name == name]
  2149. if not test:
  2150. raise ValueError(name, "not found in tests")
  2151. test = test[0]
  2152. testsrc = script_from_examples(test.docstring)
  2153. return testsrc
  2154. def debug_src(src, pm=False, globs=None):
  2155. """Debug a single doctest docstring, in argument `src`'"""
  2156. testsrc = script_from_examples(src)
  2157. debug_script(testsrc, pm, globs)
  2158. def debug_script(src, pm=False, globs=None):
  2159. "Debug a test script. `src` is the script, as a string."
  2160. import pdb
  2161. # Note that tempfile.NameTemporaryFile() cannot be used. As the
  2162. # docs say, a file so created cannot be opened by name a second time
  2163. # on modern Windows boxes, and execfile() needs to open it.
  2164. srcfilename = tempfile.mktemp(".py", "doctestdebug")
  2165. f = open(srcfilename, 'w')
  2166. f.write(src)
  2167. f.close()
  2168. try:
  2169. if globs:
  2170. globs = globs.copy()
  2171. else:
  2172. globs = {}
  2173. if pm:
  2174. try:
  2175. execfile(srcfilename, globs, globs)
  2176. except:
  2177. print sys.exc_info()[1]
  2178. pdb.post_mortem(sys.exc_info()[2])
  2179. else:
  2180. # Note that %r is vital here. '%s' instead can, e.g., cause
  2181. # backslashes to get treated as metacharacters on Windows.
  2182. pdb.run("execfile(%r)" % srcfilename, globs, globs)
  2183. finally:
  2184. os.remove(srcfilename)
  2185. def debug(module, name, pm=False):
  2186. """Debug a single doctest docstring.
  2187. Provide the module (or dotted name of the module) containing the
  2188. test to be debugged and the name (within the module) of the object
  2189. with the docstring with tests to be debugged.
  2190. """
  2191. module = _normalize_module(module)
  2192. testsrc = testsource(module, name)
  2193. debug_script(testsrc, pm, module.__dict__)
  2194. ######################################################################
  2195. ## 10. Example Usage
  2196. ######################################################################
  2197. class _TestClass:
  2198. """
  2199. A pointless class, for sanity-checking of docstring testing.
  2200. Methods:
  2201. square()
  2202. get()
  2203. >>> _TestClass(13).get() + _TestClass(-12).get()
  2204. 1
  2205. >>> hex(_TestClass(13).square().get())
  2206. '0xa9'
  2207. """
  2208. def __init__(self, val):
  2209. """val -> _TestClass object with associated value val.
  2210. >>> t = _TestClass(123)
  2211. >>> print t.get()
  2212. 123
  2213. """
  2214. self.val = val
  2215. def square(self):
  2216. """square() -> square TestClass's associated value
  2217. >>> _TestClass(13).square().get()
  2218. 169
  2219. """
  2220. self.val = self.val ** 2
  2221. return self
  2222. def get(self):
  2223. """get() -> return TestClass's associated value.
  2224. >>> x = _TestClass(-42)
  2225. >>> print x.get()
  2226. -42
  2227. """
  2228. return self.val
  2229. __test__ = {"_TestClass": _TestClass,
  2230. "string": r"""
  2231. Example of a string object, searched as-is.
  2232. >>> x = 1; y = 2
  2233. >>> x + y, x * y
  2234. (3, 2)
  2235. """,
  2236. "bool-int equivalence": r"""
  2237. In 2.2, boolean expressions displayed
  2238. 0 or 1. By default, we still accept
  2239. them. This can be disabled by passing
  2240. DONT_ACCEPT_TRUE_FOR_1 to the new
  2241. optionflags argument.
  2242. >>> 4 == 4
  2243. 1
  2244. >>> 4 == 4
  2245. True
  2246. >>> 4 > 4
  2247. 0
  2248. >>> 4 > 4
  2249. False
  2250. """,
  2251. "blank lines": r"""
  2252. Blank lines can be marked with <BLANKLINE>:
  2253. >>> print 'foo\n\nbar\n'
  2254. foo
  2255. <BLANKLINE>
  2256. bar
  2257. <BLANKLINE>
  2258. """,
  2259. "ellipsis": r"""
  2260. If the ellipsis flag is used, then '...' can be used to
  2261. elide substrings in the desired output:
  2262. >>> print range(1000) #doctest: +ELLIPSIS
  2263. [0, 1, 2, ..., 999]
  2264. """,
  2265. "whitespace normalization": r"""
  2266. If the whitespace normalization flag is used, then
  2267. differences in whitespace are ignored.
  2268. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
  2269. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  2270. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  2271. 27, 28, 29]
  2272. """,
  2273. }
  2274. def _test():
  2275. testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
  2276. if not testfiles:
  2277. name = os.path.basename(sys.argv[0])
  2278. if '__loader__' in globals(): # python -m
  2279. name, _ = os.path.splitext(name)
  2280. print("usage: {0} [-v] file ...".format(name))
  2281. return 2
  2282. for filename in testfiles:
  2283. if filename.endswith(".py"):
  2284. # It is a module -- insert its dir into sys.path and try to
  2285. # import it. If it is part of a package, that possibly
  2286. # won't work because of package imports.
  2287. dirname, filename = os.path.split(filename)
  2288. sys.path.insert(0, dirname)
  2289. m = __import__(filename[:-3])
  2290. del sys.path[0]
  2291. failures, _ = testmod(m)
  2292. else:
  2293. failures, _ = testfile(filename, module_relative=False)
  2294. if failures:
  2295. return 1
  2296. return 0
  2297. if __name__ == "__main__":
  2298. sys.exit(_test())