PageRenderTime 62ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/doctest.py

http://unladen-swallow.googlecode.com/
Python | 2686 lines | 2621 code | 13 blank | 52 comment | 27 complexity | 7d583fc0f10531949ea1ba679be0b68e MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  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. return open(filename).read(), filename
  189. def _indent(s, indent=4):
  190. """
  191. Add the given number of space characters to the beginning every
  192. non-blank line in `s`, and return the result.
  193. """
  194. # This regexp matches the start of non-blank lines:
  195. return re.sub('(?m)^(?!$)', indent*' ', s)
  196. def _exception_traceback(exc_info):
  197. """
  198. Return a string containing a traceback message for the given
  199. exc_info tuple (as returned by sys.exc_info()).
  200. """
  201. # Get a traceback message.
  202. excout = StringIO()
  203. exc_type, exc_val, exc_tb = exc_info
  204. traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
  205. return excout.getvalue()
  206. # Override some StringIO methods.
  207. class _SpoofOut(StringIO):
  208. def getvalue(self):
  209. result = StringIO.getvalue(self)
  210. # If anything at all was written, make sure there's a trailing
  211. # newline. There's no way for the expected output to indicate
  212. # that a trailing newline is missing.
  213. if result and not result.endswith("\n"):
  214. result += "\n"
  215. # Prevent softspace from screwing up the next test case, in
  216. # case they used print with a trailing comma in an example.
  217. if hasattr(self, "softspace"):
  218. del self.softspace
  219. return result
  220. def truncate(self, size=None):
  221. StringIO.truncate(self, size)
  222. if hasattr(self, "softspace"):
  223. del self.softspace
  224. # Worst-case linear-time ellipsis matching.
  225. def _ellipsis_match(want, got):
  226. """
  227. Essentially the only subtle case:
  228. >>> _ellipsis_match('aa...aa', 'aaa')
  229. False
  230. """
  231. if ELLIPSIS_MARKER not in want:
  232. return want == got
  233. # Find "the real" strings.
  234. ws = want.split(ELLIPSIS_MARKER)
  235. assert len(ws) >= 2
  236. # Deal with exact matches possibly needed at one or both ends.
  237. startpos, endpos = 0, len(got)
  238. w = ws[0]
  239. if w: # starts with exact match
  240. if got.startswith(w):
  241. startpos = len(w)
  242. del ws[0]
  243. else:
  244. return False
  245. w = ws[-1]
  246. if w: # ends with exact match
  247. if got.endswith(w):
  248. endpos -= len(w)
  249. del ws[-1]
  250. else:
  251. return False
  252. if startpos > endpos:
  253. # Exact end matches required more characters than we have, as in
  254. # _ellipsis_match('aa...aa', 'aaa')
  255. return False
  256. # For the rest, we only need to find the leftmost non-overlapping
  257. # match for each piece. If there's no overall match that way alone,
  258. # there's no overall match period.
  259. for w in ws:
  260. # w may be '' at times, if there are consecutive ellipses, or
  261. # due to an ellipsis at the start or end of `want`. That's OK.
  262. # Search for an empty string succeeds, and doesn't change startpos.
  263. startpos = got.find(w, startpos, endpos)
  264. if startpos < 0:
  265. return False
  266. startpos += len(w)
  267. return True
  268. def _comment_line(line):
  269. "Return a commented form of the given line"
  270. line = line.rstrip()
  271. if line:
  272. return '# '+line
  273. else:
  274. return '#'
  275. class _OutputRedirectingPdb(pdb.Pdb):
  276. """
  277. A specialized version of the python debugger that redirects stdout
  278. to a given stream when interacting with the user. Stdout is *not*
  279. redirected when traced code is executed.
  280. """
  281. def __init__(self, out):
  282. self.__out = out
  283. self.__debugger_used = False
  284. pdb.Pdb.__init__(self, stdout=out)
  285. def set_trace(self, frame=None):
  286. self.__debugger_used = True
  287. if frame is None:
  288. frame = sys._getframe().f_back
  289. pdb.Pdb.set_trace(self, frame)
  290. def set_continue(self):
  291. # Calling set_continue unconditionally would break unit test
  292. # coverage reporting, as Bdb.set_continue calls sys.settrace(None).
  293. if self.__debugger_used:
  294. pdb.Pdb.set_continue(self)
  295. def trace_dispatch(self, *args):
  296. # Redirect stdout to the given stream.
  297. save_stdout = sys.stdout
  298. sys.stdout = self.__out
  299. # Call Pdb's trace dispatch method.
  300. try:
  301. return pdb.Pdb.trace_dispatch(self, *args)
  302. finally:
  303. sys.stdout = save_stdout
  304. # [XX] Normalize with respect to os.path.pardir?
  305. def _module_relative_path(module, path):
  306. if not inspect.ismodule(module):
  307. raise TypeError, 'Expected a module: %r' % module
  308. if path.startswith('/'):
  309. raise ValueError, 'Module-relative files may not have absolute paths'
  310. # Find the base directory for the path.
  311. if hasattr(module, '__file__'):
  312. # A normal module/package
  313. basedir = os.path.split(module.__file__)[0]
  314. elif module.__name__ == '__main__':
  315. # An interactive session.
  316. if len(sys.argv)>0 and sys.argv[0] != '':
  317. basedir = os.path.split(sys.argv[0])[0]
  318. else:
  319. basedir = os.curdir
  320. else:
  321. # A module w/o __file__ (this includes builtins)
  322. raise ValueError("Can't resolve paths relative to the module " +
  323. module + " (it has no __file__)")
  324. # Combine the base directory and the path.
  325. return os.path.join(basedir, *(path.split('/')))
  326. ######################################################################
  327. ## 2. Example & DocTest
  328. ######################################################################
  329. ## - An "example" is a <source, want> pair, where "source" is a
  330. ## fragment of source code, and "want" is the expected output for
  331. ## "source." The Example class also includes information about
  332. ## where the example was extracted from.
  333. ##
  334. ## - A "doctest" is a collection of examples, typically extracted from
  335. ## a string (such as an object's docstring). The DocTest class also
  336. ## includes information about where the string was extracted from.
  337. class Example:
  338. """
  339. A single doctest example, consisting of source code and expected
  340. output. `Example` defines the following attributes:
  341. - source: A single Python statement, always ending with a newline.
  342. The constructor adds a newline if needed.
  343. - want: The expected output from running the source code (either
  344. from stdout, or a traceback in case of exception). `want` ends
  345. with a newline unless it's empty, in which case it's an empty
  346. string. The constructor adds a newline if needed.
  347. - exc_msg: The exception message generated by the example, if
  348. the example is expected to generate an exception; or `None` if
  349. it is not expected to generate an exception. This exception
  350. message is compared against the return value of
  351. `traceback.format_exception_only()`. `exc_msg` ends with a
  352. newline unless it's `None`. The constructor adds a newline
  353. if needed.
  354. - lineno: The line number within the DocTest string containing
  355. this Example where the Example begins. This line number is
  356. zero-based, with respect to the beginning of the DocTest.
  357. - indent: The example's indentation in the DocTest string.
  358. I.e., the number of space characters that preceed the
  359. example's first prompt.
  360. - options: A dictionary mapping from option flags to True or
  361. False, which is used to override default options for this
  362. example. Any option flags not contained in this dictionary
  363. are left at their default value (as specified by the
  364. DocTestRunner's optionflags). By default, no options are set.
  365. """
  366. def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
  367. options=None):
  368. # Normalize inputs.
  369. if not source.endswith('\n'):
  370. source += '\n'
  371. if want and not want.endswith('\n'):
  372. want += '\n'
  373. if exc_msg is not None and not exc_msg.endswith('\n'):
  374. exc_msg += '\n'
  375. # Store properties.
  376. self.source = source
  377. self.want = want
  378. self.lineno = lineno
  379. self.indent = indent
  380. if options is None: options = {}
  381. self.options = options
  382. self.exc_msg = exc_msg
  383. class DocTest:
  384. """
  385. A collection of doctest examples that should be run in a single
  386. namespace. Each `DocTest` defines the following attributes:
  387. - examples: the list of examples.
  388. - globs: The namespace (aka globals) that the examples should
  389. be run in.
  390. - name: A name identifying the DocTest (typically, the name of
  391. the object whose docstring this DocTest was extracted from).
  392. - filename: The name of the file that this DocTest was extracted
  393. from, or `None` if the filename is unknown.
  394. - lineno: The line number within filename where this DocTest
  395. begins, or `None` if the line number is unavailable. This
  396. line number is zero-based, with respect to the beginning of
  397. the file.
  398. - docstring: The string that the examples were extracted from,
  399. or `None` if the string is unavailable.
  400. """
  401. def __init__(self, examples, globs, name, filename, lineno, docstring):
  402. """
  403. Create a new DocTest containing the given examples. The
  404. DocTest's globals are initialized with a copy of `globs`.
  405. """
  406. assert not isinstance(examples, basestring), \
  407. "DocTest no longer accepts str; use DocTestParser instead"
  408. self.examples = examples
  409. self.docstring = docstring
  410. self.globs = globs.copy()
  411. self.name = name
  412. self.filename = filename
  413. self.lineno = lineno
  414. def __repr__(self):
  415. if len(self.examples) == 0:
  416. examples = 'no examples'
  417. elif len(self.examples) == 1:
  418. examples = '1 example'
  419. else:
  420. examples = '%d examples' % len(self.examples)
  421. return ('<DocTest %s from %s:%s (%s)>' %
  422. (self.name, self.filename, self.lineno, examples))
  423. # This lets us sort tests by name:
  424. def __cmp__(self, other):
  425. if not isinstance(other, DocTest):
  426. return -1
  427. return cmp((self.name, self.filename, self.lineno, id(self)),
  428. (other.name, other.filename, other.lineno, id(other)))
  429. ######################################################################
  430. ## 3. DocTestParser
  431. ######################################################################
  432. class DocTestParser:
  433. """
  434. A class used to parse strings containing doctest examples.
  435. """
  436. # This regular expression is used to find doctest examples in a
  437. # string. It defines three groups: `source` is the source code
  438. # (including leading indentation and prompts); `indent` is the
  439. # indentation of the first (PS1) line of the source code; and
  440. # `want` is the expected output (including leading indentation).
  441. _EXAMPLE_RE = re.compile(r'''
  442. # Source consists of a PS1 line followed by zero or more PS2 lines.
  443. (?P<source>
  444. (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
  445. (?:\n [ ]* \.\.\. .*)*) # PS2 lines
  446. \n?
  447. # Want consists of any non-blank lines that do not start with PS1.
  448. (?P<want> (?:(?![ ]*$) # Not a blank line
  449. (?![ ]*>>>) # Not a line starting with PS1
  450. .*$\n? # But any other line
  451. )*)
  452. ''', re.MULTILINE | re.VERBOSE)
  453. # A regular expression for handling `want` strings that contain
  454. # expected exceptions. It divides `want` into three pieces:
  455. # - the traceback header line (`hdr`)
  456. # - the traceback stack (`stack`)
  457. # - the exception message (`msg`), as generated by
  458. # traceback.format_exception_only()
  459. # `msg` may have multiple lines. We assume/require that the
  460. # exception message is the first non-indented line starting with a word
  461. # character following the traceback header line.
  462. _EXCEPTION_RE = re.compile(r"""
  463. # Grab the traceback header. Different versions of Python have
  464. # said different things on the first traceback line.
  465. ^(?P<hdr> Traceback\ \(
  466. (?: most\ recent\ call\ last
  467. | innermost\ last
  468. ) \) :
  469. )
  470. \s* $ # toss trailing whitespace on the header.
  471. (?P<stack> .*?) # don't blink: absorb stuff until...
  472. ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
  473. """, re.VERBOSE | re.MULTILINE | re.DOTALL)
  474. # A callable returning a true value iff its argument is a blank line
  475. # or contains a single comment.
  476. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
  477. def parse(self, string, name='<string>'):
  478. """
  479. Divide the given string into examples and intervening text,
  480. and return them as a list of alternating Examples and strings.
  481. Line numbers for the Examples are 0-based. The optional
  482. argument `name` is a name identifying this string, and is only
  483. used for error messages.
  484. """
  485. string = string.expandtabs()
  486. # If all lines begin with the same indentation, then strip it.
  487. min_indent = self._min_indent(string)
  488. if min_indent > 0:
  489. string = '\n'.join([l[min_indent:] for l in string.split('\n')])
  490. output = []
  491. charno, lineno = 0, 0
  492. # Find all doctest examples in the string:
  493. for m in self._EXAMPLE_RE.finditer(string):
  494. # Add the pre-example text to `output`.
  495. output.append(string[charno:m.start()])
  496. # Update lineno (lines before this example)
  497. lineno += string.count('\n', charno, m.start())
  498. # Extract info from the regexp match.
  499. (source, options, want, exc_msg) = \
  500. self._parse_example(m, name, lineno)
  501. # Create an Example, and add it to the list.
  502. if not self._IS_BLANK_OR_COMMENT(source):
  503. output.append( Example(source, want, exc_msg,
  504. lineno=lineno,
  505. indent=min_indent+len(m.group('indent')),
  506. options=options) )
  507. # Update lineno (lines inside this example)
  508. lineno += string.count('\n', m.start(), m.end())
  509. # Update charno.
  510. charno = m.end()
  511. # Add any remaining post-example text to `output`.
  512. output.append(string[charno:])
  513. return output
  514. def get_doctest(self, string, globs, name, filename, lineno):
  515. """
  516. Extract all doctest examples from the given string, and
  517. collect them into a `DocTest` object.
  518. `globs`, `name`, `filename`, and `lineno` are attributes for
  519. the new `DocTest` object. See the documentation for `DocTest`
  520. for more information.
  521. """
  522. return DocTest(self.get_examples(string, name), globs,
  523. name, filename, lineno, string)
  524. def get_examples(self, string, name='<string>'):
  525. """
  526. Extract all doctest examples from the given string, and return
  527. them as a list of `Example` objects. Line numbers are
  528. 0-based, because it's most common in doctests that nothing
  529. interesting appears on the same line as opening triple-quote,
  530. and so the first interesting line is called \"line 1\" then.
  531. The optional argument `name` is a name identifying this
  532. string, and is only used for error messages.
  533. """
  534. return [x for x in self.parse(string, name)
  535. if isinstance(x, Example)]
  536. def _parse_example(self, m, name, lineno):
  537. """
  538. Given a regular expression match from `_EXAMPLE_RE` (`m`),
  539. return a pair `(source, want)`, where `source` is the matched
  540. example's source code (with prompts and indentation stripped);
  541. and `want` is the example's expected output (with indentation
  542. stripped).
  543. `name` is the string's name, and `lineno` is the line number
  544. where the example starts; both are used for error messages.
  545. """
  546. # Get the example's indentation level.
  547. indent = len(m.group('indent'))
  548. # Divide source into lines; check that they're properly
  549. # indented; and then strip their indentation & prompts.
  550. source_lines = m.group('source').split('\n')
  551. self._check_prompt_blank(source_lines, indent, name, lineno)
  552. self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
  553. source = '\n'.join([sl[indent+4:] for sl in source_lines])
  554. # Divide want into lines; check that it's properly indented; and
  555. # then strip the indentation. Spaces before the last newline should
  556. # be preserved, so plain rstrip() isn't good enough.
  557. want = m.group('want')
  558. want_lines = want.split('\n')
  559. if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
  560. del want_lines[-1] # forget final newline & spaces after it
  561. self._check_prefix(want_lines, ' '*indent, name,
  562. lineno + len(source_lines))
  563. want = '\n'.join([wl[indent:] for wl in want_lines])
  564. # If `want` contains a traceback message, then extract it.
  565. m = self._EXCEPTION_RE.match(want)
  566. if m:
  567. exc_msg = m.group('msg')
  568. else:
  569. exc_msg = None
  570. # Extract options from the source.
  571. options = self._find_options(source, name, lineno)
  572. return source, options, want, exc_msg
  573. # This regular expression looks for option directives in the
  574. # source code of an example. Option directives are comments
  575. # starting with "doctest:". Warning: this may give false
  576. # positives for string-literals that contain the string
  577. # "#doctest:". Eliminating these false positives would require
  578. # actually parsing the string; but we limit them by ignoring any
  579. # line containing "#doctest:" that is *followed* by a quote mark.
  580. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
  581. re.MULTILINE)
  582. def _find_options(self, source, name, lineno):
  583. """
  584. Return a dictionary containing option overrides extracted from
  585. option directives in the given source string.
  586. `name` is the string's name, and `lineno` is the line number
  587. where the example starts; both are used for error messages.
  588. """
  589. options = {}
  590. # (note: with the current regexp, this will match at most once:)
  591. for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  592. option_strings = m.group(1).replace(',', ' ').split()
  593. for option in option_strings:
  594. if (option[0] not in '+-' or
  595. option[1:] not in OPTIONFLAGS_BY_NAME):
  596. raise ValueError('line %r of the doctest for %s '
  597. 'has an invalid option: %r' %
  598. (lineno+1, name, option))
  599. flag = OPTIONFLAGS_BY_NAME[option[1:]]
  600. options[flag] = (option[0] == '+')
  601. if options and self._IS_BLANK_OR_COMMENT(source):
  602. raise ValueError('line %r of the doctest for %s has an option '
  603. 'directive on a line with no example: %r' %
  604. (lineno, name, source))
  605. return options
  606. # This regular expression finds the indentation of every non-blank
  607. # line in a string.
  608. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
  609. def _min_indent(self, s):
  610. "Return the minimum indentation of any non-blank line in `s`"
  611. indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
  612. if len(indents) > 0:
  613. return min(indents)
  614. else:
  615. return 0
  616. def _check_prompt_blank(self, lines, indent, name, lineno):
  617. """
  618. Given the lines of a source string (including prompts and
  619. leading indentation), check to make sure that every prompt is
  620. followed by a space character. If any line is not followed by
  621. a space character, then raise ValueError.
  622. """
  623. for i, line in enumerate(lines):
  624. if len(line) >= indent+4 and line[indent+3] != ' ':
  625. raise ValueError('line %r of the docstring for %s '
  626. 'lacks blank after %s: %r' %
  627. (lineno+i+1, name,
  628. line[indent:indent+3], line))
  629. def _check_prefix(self, lines, prefix, name, lineno):
  630. """
  631. Check that every line in the given list starts with the given
  632. prefix; if any line does not, then raise a ValueError.
  633. """
  634. for i, line in enumerate(lines):
  635. if line and not line.startswith(prefix):
  636. raise ValueError('line %r of the docstring for %s has '
  637. 'inconsistent leading whitespace: %r' %
  638. (lineno+i+1, name, line))
  639. ######################################################################
  640. ## 4. DocTest Finder
  641. ######################################################################
  642. class DocTestFinder:
  643. """
  644. A class used to extract the DocTests that are relevant to a given
  645. object, from its docstring and the docstrings of its contained
  646. objects. Doctests can currently be extracted from the following
  647. object types: modules, functions, classes, methods, staticmethods,
  648. classmethods, and properties.
  649. """
  650. def __init__(self, verbose=False, parser=DocTestParser(),
  651. recurse=True, exclude_empty=True):
  652. """
  653. Create a new doctest finder.
  654. The optional argument `parser` specifies a class or
  655. function that should be used to create new DocTest objects (or
  656. objects that implement the same interface as DocTest). The
  657. signature for this factory function should match the signature
  658. of the DocTest constructor.
  659. If the optional argument `recurse` is false, then `find` will
  660. only examine the given object, and not any contained objects.
  661. If the optional argument `exclude_empty` is false, then `find`
  662. will include tests for objects with empty docstrings.
  663. """
  664. self._parser = parser
  665. self._verbose = verbose
  666. self._recurse = recurse
  667. self._exclude_empty = exclude_empty
  668. def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
  669. """
  670. Return a list of the DocTests that are defined by the given
  671. object's docstring, or by any of its contained objects'
  672. docstrings.
  673. The optional parameter `module` is the module that contains
  674. the given object. If the module is not specified or is None, then
  675. the test finder will attempt to automatically determine the
  676. correct module. The object's module is used:
  677. - As a default namespace, if `globs` is not specified.
  678. - To prevent the DocTestFinder from extracting DocTests
  679. from objects that are imported from other modules.
  680. - To find the name of the file containing the object.
  681. - To help find the line number of the object within its
  682. file.
  683. Contained objects whose module does not match `module` are ignored.
  684. If `module` is False, no attempt to find the module will be made.
  685. This is obscure, of use mostly in tests: if `module` is False, or
  686. is None but cannot be found automatically, then all objects are
  687. considered to belong to the (non-existent) module, so all contained
  688. objects will (recursively) be searched for doctests.
  689. The globals for each DocTest is formed by combining `globs`
  690. and `extraglobs` (bindings in `extraglobs` override bindings
  691. in `globs`). A new copy of the globals dictionary is created
  692. for each DocTest. If `globs` is not specified, then it
  693. defaults to the module's `__dict__`, if specified, or {}
  694. otherwise. If `extraglobs` is not specified, then it defaults
  695. to {}.
  696. """
  697. # If name was not specified, then extract it from the object.
  698. if name is None:
  699. name = getattr(obj, '__name__', None)
  700. if name is None:
  701. raise ValueError("DocTestFinder.find: name must be given "
  702. "when obj.__name__ doesn't exist: %r" %
  703. (type(obj),))
  704. # Find the module that contains the given object (if obj is
  705. # a module, then module=obj.). Note: this may fail, in which
  706. # case module will be None.
  707. if module is False:
  708. module = None
  709. elif module is None:
  710. module = inspect.getmodule(obj)
  711. # Read the module's source code. This is used by
  712. # DocTestFinder._find_lineno to find the line number for a
  713. # given object's docstring.
  714. try:
  715. file = inspect.getsourcefile(obj) or inspect.getfile(obj)
  716. if module is not None:
  717. # Supply the module globals in case the module was
  718. # originally loaded via a PEP 302 loader and
  719. # file is not a valid filesystem path
  720. source_lines = linecache.getlines(file, module.__dict__)
  721. else:
  722. # No access to a loader, so assume it's a normal
  723. # filesystem path
  724. source_lines = linecache.getlines(file)
  725. if not source_lines:
  726. source_lines = None
  727. except TypeError:
  728. source_lines = None
  729. # Initialize globals, and merge in extraglobs.
  730. if globs is None:
  731. if module is None:
  732. globs = {}
  733. else:
  734. globs = module.__dict__.copy()
  735. else:
  736. globs = globs.copy()
  737. if extraglobs is not None:
  738. globs.update(extraglobs)
  739. if '__name__' not in globs:
  740. globs['__name__'] = '__main__' # provide a default module name
  741. # Recursively expore `obj`, extracting DocTests.
  742. tests = []
  743. self._find(tests, obj, name, module, source_lines, globs, {})
  744. # Sort the tests by alpha order of names, for consistency in
  745. # verbose-mode output. This was a feature of doctest in Pythons
  746. # <= 2.3 that got lost by accident in 2.4. It was repaired in
  747. # 2.4.4 and 2.5.
  748. tests.sort()
  749. return tests
  750. def _from_module(self, module, object):
  751. """
  752. Return true if the given object is defined in the given
  753. module.
  754. """
  755. if module is None:
  756. return True
  757. elif inspect.getmodule(object) is not None:
  758. return module is inspect.getmodule(object)
  759. elif inspect.isfunction(object):
  760. return module.__dict__ is object.func_globals
  761. elif inspect.isclass(object):
  762. return module.__name__ == object.__module__
  763. elif hasattr(object, '__module__'):
  764. return module.__name__ == object.__module__
  765. elif isinstance(object, property):
  766. return True # [XX] no way not be sure.
  767. else:
  768. raise ValueError("object must be a class or function")
  769. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  770. """
  771. Find tests for the given object and any contained objects, and
  772. add them to `tests`.
  773. """
  774. if self._verbose:
  775. print 'Finding tests in %s' % name
  776. # If we've already processed this object, then ignore it.
  777. if id(obj) in seen:
  778. return
  779. seen[id(obj)] = 1
  780. # Find a test for this object, and add it to the list of tests.
  781. test = self._get_test(obj, name, module, globs, source_lines)
  782. if test is not None:
  783. tests.append(test)
  784. # Look for tests in a module's contained objects.
  785. if inspect.ismodule(obj) and self._recurse:
  786. for valname, val in obj.__dict__.items():
  787. valname = '%s.%s' % (name, valname)
  788. # Recurse to functions & classes.
  789. if ((inspect.isfunction(val) or inspect.isclass(val)) and
  790. self._from_module(module, val)):
  791. self._find(tests, val, valname, module, source_lines,
  792. globs, seen)
  793. # Look for tests in a module's __test__ dictionary.
  794. if inspect.ismodule(obj) and self._recurse:
  795. for valname, val in getattr(obj, '__test__', {}).items():
  796. if not isinstance(valname, basestring):
  797. raise ValueError("DocTestFinder.find: __test__ keys "
  798. "must be strings: %r" %
  799. (type(valname),))
  800. if not (inspect.isfunction(val) or inspect.isclass(val) or
  801. inspect.ismethod(val) or inspect.ismodule(val) or
  802. isinstance(val, basestring)):
  803. raise ValueError("DocTestFinder.find: __test__ values "
  804. "must be strings, functions, methods, "
  805. "classes, or modules: %r" %
  806. (type(val),))
  807. valname = '%s.__test__.%s' % (name, valname)
  808. self._find(tests, val, valname, module, source_lines,
  809. globs, seen)
  810. # Look for tests in a class's contained objects.
  811. if inspect.isclass(obj) and self._recurse:
  812. for valname, val in obj.__dict__.items():
  813. # Special handling for staticmethod/classmethod.
  814. if isinstance(val, staticmethod):
  815. val = getattr(obj, valname)
  816. if isinstance(val, classmethod):
  817. val = getattr(obj, valname).im_func
  818. # Recurse to methods, properties, and nested classes.
  819. if ((inspect.isfunction(val) or inspect.isclass(val) or
  820. isinstance(val, property)) and
  821. self._from_module(module, val)):
  822. valname = '%s.%s' % (name, valname)
  823. self._find(tests, val, valname, module, source_lines,
  824. globs, seen)
  825. def _get_test(self, obj, name, module, globs, source_lines):
  826. """
  827. Return a DocTest for the given object, if it defines a docstring;
  828. otherwise, return None.
  829. """
  830. # Extract the object's docstring. If it doesn't have one,
  831. # then return None (no test for this object).
  832. if isinstance(obj, basestring):
  833. docstring = obj
  834. else:
  835. try:
  836. if obj.__doc__ is None:
  837. docstring = ''
  838. else:
  839. docstring = obj.__doc__
  840. if not isinstance(docstring, basestring):
  841. docstring = str(docstring)
  842. except (TypeError, AttributeError):
  843. docstring = ''
  844. # Find the docstring's location in the file.
  845. lineno = self._find_lineno(obj, source_lines)
  846. # Don't bother if the docstring is empty.
  847. if self._exclude_empty and not docstring:
  848. return None
  849. # Return a DocTest for this object.
  850. if module is None:
  851. filename = None
  852. else:
  853. filename = getattr(module, '__file__', module.__name__)
  854. if filename[-4:] in (".pyc", ".pyo"):
  855. filename = filename[:-1]
  856. return self._parser.get_doctest(docstring, globs, name,
  857. filename, lineno)
  858. def _find_lineno(self, obj, source_lines):
  859. """
  860. Return a line number of the given object's docstring. Note:
  861. this method assumes that the object has a docstring.
  862. """
  863. lineno = None
  864. # Find the line number for modules.
  865. if inspect.ismodule(obj):
  866. lineno = 0
  867. # Find the line number for classes.
  868. # Note: this could be fooled if a class is defined multiple
  869. # times in a single file.
  870. if inspect.isclass(obj):
  871. if source_lines is None:
  872. return None
  873. pat = re.compile(r'^\s*class\s*%s\b' %
  874. getattr(obj, '__name__', '-'))
  875. for i, line in enumerate(source_lines):
  876. if pat.match(line):
  877. lineno = i
  878. break
  879. # Find the line number for functions & methods.
  880. if inspect.ismethod(obj): obj = obj.im_func
  881. if inspect.isfunction(obj): obj = obj.func_code
  882. if inspect.istraceback(obj): obj = obj.tb_frame
  883. if inspect.isframe(obj): obj = obj.f_code
  884. if inspect.iscode(obj):
  885. lineno = getattr(obj, 'co_firstlineno', None)-1
  886. # Find the line number where the docstring starts. Assume
  887. # that it's the first line that begins with a quote mark.
  888. # Note: this could be fooled by a multiline function
  889. # signature, where a continuation line begins with a quote
  890. # mark.
  891. if lineno is not None:
  892. if source_lines is None:
  893. return lineno+1
  894. pat = re.compile('(^|.*:)\s*\w*("|\')')
  895. for lineno in range(lineno, len(source_lines)):
  896. if pat.match(source_lines[lineno]):
  897. return lineno
  898. # We couldn't find the line number.
  899. return None
  900. ######################################################################
  901. ## 5. DocTest Runner
  902. ######################################################################
  903. class DocTestRunner:
  904. """
  905. A class used to run DocTest test cases, and accumulate statistics.
  906. The `run` method is used to process a single DocTest case. It
  907. returns a tuple `(f, t)`, where `t` is the number of test cases
  908. tried, and `f` is the number of test cases that failed.
  909. >>> tests = DocTestFinder().find(_TestClass)
  910. >>> runner = DocTestRunner(verbose=False)
  911. >>> tests.sort(key = lambda test: test.name)
  912. >>> for test in tests:
  913. ... print test.name, '->', runner.run(test)
  914. _TestClass -> TestResults(failed=0, attempted=2)
  915. _TestClass.__init__ -> TestResults(failed=0, attempted=2)
  916. _TestClass.get -> TestResults(failed=0, attempted=2)
  917. _TestClass.square -> TestResults(failed=0, attempted=1)
  918. The `summarize` method prints a summary of all the test cases that
  919. have been run by the runner, and returns an aggregated `(f, t)`
  920. tuple:
  921. >>> runner.summarize(verbose=1)
  922. 4 items passed all tests:
  923. 2 tests in _TestClass
  924. 2 tests in _TestClass.__init__
  925. 2 tests in _TestClass.get
  926. 1 tests in _TestClass.square
  927. 7 tests in 4 items.
  928. 7 passed and 0 failed.
  929. Test passed.
  930. TestResults(failed=0, attempted=7)
  931. The aggregated number of tried examples and failed examples is
  932. also available via the `tries` and `failures` attributes:
  933. >>> runner.tries
  934. 7
  935. >>> runner.failures
  936. 0
  937. The comparison between expected outputs and actual outputs is done
  938. by an `OutputChecker`. This comparison may be customized with a
  939. number of option flags; see the documentation for `testmod` for
  940. more information. If the option flags are insufficient, then the
  941. comparison may also be customized by passing a subclass of
  942. `OutputChecker` to the constructor.
  943. The test runner's display output can be controlled in two ways.
  944. First, an output function (`out) can be passed to
  945. `TestRunner.run`; this function will be called with strings that
  946. should be displayed. It defaults to `sys.stdout.write`. If
  947. capturing the output is not sufficient, then the display output
  948. can be also customized by subclassing DocTestRunner, and
  949. overriding the methods `report_start`, `report_success`,
  950. `report_unexpected_exception`, and `report_failure`.
  951. """
  952. # This divider string is used to separate failure messages, and to
  953. # separate sections of the summary.
  954. DIVIDER = "*" * 70
  955. def __init__(self, checker=None, verbose=None, optionflags=0):
  956. """
  957. Create a new test runner.
  958. Optional keyword arg `checker` is the `OutputChecker` that
  959. should be used to compare the expected outputs and actual
  960. outputs of doctest examples.
  961. Optional keyword arg 'verbose' prints lots of stuff if true,
  962. only failures if false; by default, it's true iff '-v' is in
  963. sys.argv.
  964. Optional argument `optionflags` can be used to control how the
  965. test runner compares expected output to actual output, and how
  966. it displays failures. See the documentation for `testmod` for
  967. more information.
  968. """
  969. self._checker = checker or OutputChecker()
  970. if verbose is None:
  971. verbose = '-v' in sys.argv
  972. self._verbose = verbose
  973. self.optionflags = optionflags
  974. self.original_optionflags = optionflags
  975. # Keep track of the examples we've run.
  976. self.tries = 0
  977. self.failures = 0
  978. self._name2ft = {}
  979. # Create a fake output target for capturing doctest output.
  980. self._fakeout = _SpoofOut()
  981. #/////////////////////////////////////////////////////////////////
  982. # Reporting methods
  983. #/////////////////////////////////////////////////////////////////
  984. def report_start(self, out, test, example):
  985. """
  986. Report that the test runner is about to process the given
  987. example. (Only displays a message if verbose=True)
  988. """
  989. if self._verbose:
  990. if example.want:
  991. out('Trying:\n' + _indent(example.source) +
  992. 'Expecting:\n' + _indent(example.want))
  993. else:
  994. out('Trying:\n' + _indent(example.source) +
  995. 'Expecting nothing\n')
  996. def report_success(self, out, test, example, got):
  997. """
  998. Report that the given example ran successfully. (Only
  999. displays a message if verbose=True)
  1000. """
  1001. if self._verbose:
  1002. out("ok\n")
  1003. def report_failure(self, out, test, example, got):
  1004. """
  1005. Report that the given example failed.
  1006. """
  1007. out(self._failure_header(test, example) +
  1008. self._checker.output_difference(example, got, self.optionflags))
  1009. def report_unexpected_exception(self, out, test, example, exc_info):
  1010. """
  1011. Report that the given example raised an unexpected exception.
  1012. """
  1013. out(self._failure_header(test, example) +
  1014. 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  1015. def _failure_header(self, test, example):
  1016. out = [self.DIVIDER]
  1017. if test.filename:
  1018. if test.lineno is not None and example.lineno is not None:
  1019. lineno = test.lineno + example.lineno + 1
  1020. else:
  1021. lineno = '?'
  1022. out.append('File "%s", line %s, in %s' %
  1023. (test.filename, lineno, test.name))
  1024. else:
  1025. out.append('Line %s, in %s' % (example.lineno+1, test.name))
  1026. out.append('Failed example:')
  1027. source = example.source
  1028. out.append(_indent(source))
  1029. return '\n'.join(out)
  1030. #/////////////////////////////////////////////////////////////////
  1031. # DocTest Running
  1032. #/////////////////////////////////////////////////////////////////
  1033. def __run(self, test, compileflags, out):
  1034. """
  1035. Run the examples in `test`. Write the outcome of each example
  1036. with one of the `DocTestRunner.report_*` methods, using the
  1037. writer function `out`. `compileflags` is the set of compiler
  1038. flags that should be used to execute examples. Return a tuple
  1039. `(f, t)`, where `t` is the number of examples tried, and `f`
  1040. is the number of examples that failed. The examples are run
  1041. in the namespace `test.globs`.
  1042. """
  1043. # Keep track of the number of failures and tries.
  1044. failures = tries = 0
  1045. # Save the option flags (since option directives can be used
  1046. # to modify them).
  1047. original_optionflags = self.optionflags
  1048. SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
  1049. check = self._checker.check_output
  1050. # Process each example.
  1051. for examplenum, example in enumerate(test.examples):
  1052. # If REPORT_ONLY_FIRST_FAILURE is set, then supress
  1053. # reporting after the first failure.
  1054. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
  1055. failures > 0)
  1056. # Merge in the example's options.
  1057. self.optionflags = original_optionflags
  1058. if example.options:
  1059. for (optionflag, val) in example.options.items():
  1060. if val:
  1061. self.optionflags |= optionflag
  1062. else:
  1063. self.optionflags &= ~optionflag
  1064. # If 'SKIP' is set, then skip this example.
  1065. if self.optionflags & SKIP:
  1066. continue
  1067. # Record that we started this example.
  1068. tries += 1
  1069. if not quiet:
  1070. self.report_start(out, test, example)
  1071. # Use a special filename for compile(), so we can retrieve
  1072. # the source code during interactive debugging (see
  1073. # __patched_linecache_getlines).
  1074. filename = '<doctest %s[%d]>' % (test.name, examplenum)
  1075. # Run the example in the given context (globs), and record
  1076. # any exception that gets raised. (But don't intercept
  1077. # keyboard interrupts.)
  1078. try:
  1079. # Don't blink! This is where the user's code gets run.
  1080. exec compile(example.source, filename, "single",
  1081. compileflags, 1) in test.globs
  1082. self.debugger.set_continue() # ==== Example Finished ====
  1083. exception = None
  1084. except KeyboardInterrupt:
  1085. raise
  1086. except:
  1087. exception = sys.exc_info()
  1088. self.debugger.set_continue() # ==== Example Finished ====
  1089. got = self._fakeout.getvalue() # the actual output
  1090. self._fakeout.truncate(0)
  1091. outcome = FAILURE # guilty until proved innocent or insane
  1092. # If the example executed without raising any exceptions,
  1093. # verify its output.
  1094. if exception is None:
  1095. if check(example.want, got, self.optionflags):
  1096. outcome = SUCCESS
  1097. # The example raised an exception: check if it was expected.
  1098. else:
  1099. exc_info = sys.exc_info()
  1100. exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1101. if not quiet:
  1102. got += _exception_traceback(exc_info)
  1103. # If `example.exc_msg` is None, then we weren't expecting
  1104. # an exception.
  1105. if example.exc_msg is None:
  1106. outcome = BOOM
  1107. # We expected an exception: see whether it matches.
  1108. elif check(example.exc_msg, exc_msg, self.optionflags):
  1109. outcome = SUCCESS
  1110. # Another chance if they didn't care about the detail.
  1111. elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1112. m1 = re.match(r'[^:]*:', example.exc_msg)
  1113. m2 = re.match(r'[^:]*:', exc_msg)
  1114. if m1 and m2 and check(m1.group(0), m2.group(0),
  1115. self.optionflags):
  1116. outcome = SUCCESS
  1117. # Report the outcome.
  1118. if outcome is SUCCESS:
  1119. if not quiet:
  1120. self.report_success(out, test, example, got)
  1121. elif outcome is FAILURE:
  1122. if not quiet:
  1123. self.report_failure(out, test, example, got)
  1124. failures += 1
  1125. elif outcome is BOOM:
  1126. if not quiet:
  1127. self.report_unexpected_exception(out, test, example,
  1128. exc_info)
  1129. failures += 1
  1130. else:
  1131. assert False, ("unknown outcome", outcome)
  1132. # Restore the option flags (in case they were modified)
  1133. self.optionflags = original_optionflags
  1134. # Record and return the number of failures and tries.
  1135. self.__record_outcome(test, failures, tries)
  1136. return TestResults(failures, tries)
  1137. def __record_outcome(self, test, f, t):
  1138. """
  1139. Record the fact that the given DocTest (`test`) generated `f`
  1140. failures out of `t` tried examples.
  1141. """
  1142. f2, t2 = self._name2ft.get(test.name, (0,0))
  1143. self._name2ft[test.name] = (f+f2, t+t2)
  1144. self.failures += f
  1145. self.tries += t
  1146. __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
  1147. r'(?P<name>[\w\.]+)'
  1148. r'\[(?P<examplenum>\d+)\]>$')
  1149. def __patched_linecache_getlines(self, filename, module_globals=None):
  1150. m = self.__LINECACHE_FILENAME_RE.match(filename)
  1151. if m and m.group('name') == self.test.name:
  1152. example = self.test.examples[int(m.group('examplenum'))]
  1153. return example.source.splitlines(True)
  1154. else:
  1155. return self.save_linecache_getlines(filename, module_globals)
  1156. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1157. """
  1158. Run the examples in `test`, and display the results using the
  1159. writer function `out`.
  1160. The examples are run in the namespace `test.globs`. If
  1161. `clear_globs` is true (the default), then this namespace will
  1162. be cleared after the test runs, to help with garbage
  1163. collection. If you would like to examine the namespace after
  1164. the test completes, then use `clear_globs=False`.
  1165. `compileflags` gives the set of flags that should be used by
  1166. the Python compiler when running the examples. If not
  1167. specified, then it will default to the set of future-import
  1168. flags that apply to `globs`.
  1169. The output of each example is checked using
  1170. `DocTestRunner.check_output`, and the results are formatted by
  1171. the `DocTestRunner.report_*` methods.
  1172. """
  1173. self.test = test
  1174. if compileflags is None:
  1175. compileflags = _extract_future_flags(test.globs)
  1176. save_stdout = sys.stdout
  1177. if out is None:
  1178. out = save_stdout.write
  1179. sys.stdout = self._fakeout
  1180. # Patch pdb.set_trace to restore sys.stdout during interactive
  1181. # debugging (so it's not still redirected to self._fakeout).
  1182. # Note that the interactive output will go to *our*
  1183. # save_stdout, even if that's not the real sys.stdout; this
  1184. # allows us to write test cases for the set_trace behavior.
  1185. save_set_trace = pdb.set_trace
  1186. self.debugger = _OutputRedirectingPdb(save_stdout)
  1187. self.debugger.reset()
  1188. pdb.set_trace = self.debugger.set_trace
  1189. # Patch linecache.getlines, so we can see the example's source
  1190. # when we're inside the debugger.
  1191. self.save_linecache_getlines = linecache.getlines
  1192. linecache.getlines = self.__patched_linecache_getlines
  1193. try:
  1194. return self.__run(test, compileflags, out)
  1195. finally:
  1196. sys.stdout = save_stdout
  1197. pdb.set_trace = save_set_trace
  1198. linecache.getlines = self.save_linecache_getlines
  1199. if clear_globs:
  1200. test.globs.clear()
  1201. #/////////////////////////////////////////////////////////////////
  1202. # Summarization
  1203. #/////////////////////////////////////////////////////////////////
  1204. def summarize(self, verbose=None):
  1205. """
  1206. Print a summary of all the test cases that have been run by
  1207. this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1208. the total number of failed examples, and `t` is the total
  1209. number of tried examples.
  1210. The optional `verbose` argument controls how detailed the
  1211. summary is. If the verbosity is not specified, then the
  1212. DocTestRunner's verbosity is used.
  1213. """
  1214. if verbose is None:
  1215. verbose = self._verbose
  1216. notests = []
  1217. passed = []
  1218. failed = []
  1219. totalt = totalf = 0
  1220. for x in self._name2ft.items():
  1221. name, (f, t) = x
  1222. assert f <= t
  1223. totalt += t
  1224. totalf += f
  1225. if t == 0:
  1226. notests.append(name)
  1227. elif f == 0:
  1228. passed.append( (name, t) )
  1229. else:
  1230. failed.append(x)
  1231. if verbose:
  1232. if notests:
  1233. print len(notests), "items had no tests:"
  1234. notests.sort()
  1235. for thing in notests:
  1236. print " ", thing
  1237. if passed:
  1238. print len(passed), "items passed all tests:"
  1239. passed.sort()
  1240. for thing, count in passed:
  1241. print " %3d tests in %s" % (count, thing)
  1242. if failed:
  1243. print self.DIVIDER
  1244. print len(failed), "items had failures:"
  1245. failed.sort()
  1246. for thing, (f, t) in failed:
  1247. print " %3d of %3d in %s" % (f, t, thing)
  1248. if verbose:
  1249. print totalt, "tests in", len(self._name2ft), "items."
  1250. print totalt - totalf, "passed and", totalf, "failed."
  1251. if totalf:
  1252. print "***Test Failed***", totalf, "failures."
  1253. elif verbose:
  1254. print "Test passed."
  1255. return TestResults(totalf, totalt)
  1256. #/////////////////////////////////////////////////////////////////
  1257. # Backward compatibility cruft to maintain doctest.master.
  1258. #/////////////////////////////////////////////////////////////////
  1259. def merge(self, other):
  1260. d = self._name2ft
  1261. for name, (f, t) in other._name2ft.items():
  1262. if name in d:
  1263. # Don't print here by default, since doing
  1264. # so breaks some of the buildbots
  1265. #print "*** DocTestRunner.merge: '" + name + "' in both" \
  1266. # " testers; summing outcomes."
  1267. f2, t2 = d[name]
  1268. f = f + f2
  1269. t = t + t2
  1270. d[name] = f, t
  1271. class OutputChecker:
  1272. """
  1273. A class used to check the whether the actual output from a doctest
  1274. example matches the expected output. `OutputChecker` defines two
  1275. methods: `check_output`, which compares a given pair of outputs,
  1276. and returns true if they match; and `output_difference`, which
  1277. returns a string describing the differences between two outputs.
  1278. """
  1279. def check_output(self, want, got, optionflags):
  1280. """
  1281. Return True iff the actual output from an example (`got`)
  1282. matches the expected output (`want`). These strings are
  1283. always considered to match if they are identical; but
  1284. depending on what option flags the test runner is using,
  1285. several non-exact match types are also possible. See the
  1286. documentation for `TestRunner` for more information about
  1287. option flags.
  1288. """
  1289. # Handle the common case first, for efficiency:
  1290. # if they're string-identical, always return true.
  1291. if got == want:
  1292. return True
  1293. # The values True and False replaced 1 and 0 as the return
  1294. # value for boolean comparisons in Python 2.3.
  1295. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
  1296. if (got,want) == ("True\n", "1\n"):
  1297. return True
  1298. if (got,want) == ("False\n", "0\n"):
  1299. return True
  1300. # <BLANKLINE> can be used as a special sequence to signify a
  1301. # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
  1302. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1303. # Replace <BLANKLINE> in want with a blank line.
  1304. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
  1305. '', want)
  1306. # If a line in got contains only spaces, then remove the
  1307. # spaces.
  1308. got = re.sub('(?m)^\s*?$', '', got)
  1309. if got == want:
  1310. return True
  1311. # This flag causes doctest to ignore any differences in the
  1312. # contents of whitespace strings. Note that this can be used
  1313. # in conjunction with the ELLIPSIS flag.
  1314. if optionflags & NORMALIZE_WHITESPACE:
  1315. got = ' '.join(got.split())
  1316. want = ' '.join(want.split())
  1317. if got == want:
  1318. return True
  1319. # The ELLIPSIS flag says to let the sequence "..." in `want`
  1320. # match any substring in `got`.
  1321. if optionflags & ELLIPSIS:
  1322. if _ellipsis_match(want, got):
  1323. return True
  1324. # We didn't find any match; return false.
  1325. return False
  1326. # Should we do a fancy diff?
  1327. def _do_a_fancy_diff(self, want, got, optionflags):
  1328. # Not unless they asked for a fancy diff.
  1329. if not optionflags & (REPORT_UDIFF |
  1330. REPORT_CDIFF |
  1331. REPORT_NDIFF):
  1332. return False
  1333. # If expected output uses ellipsis, a meaningful fancy diff is
  1334. # too hard ... or maybe not. In two real-life failures Tim saw,
  1335. # a diff was a major help anyway, so this is commented out.
  1336. # [todo] _ellipsis_match() knows which pieces do and don't match,
  1337. # and could be the basis for a kick-ass diff in this case.
  1338. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
  1339. ## return False
  1340. # ndiff does intraline difference marking, so can be useful even
  1341. # for 1-line differences.
  1342. if optionflags & REPORT_NDIFF:
  1343. return True
  1344. # The other diff types need at least a few lines to be helpful.
  1345. return want.count('\n') > 2 and got.count('\n') > 2
  1346. def output_difference(self, example, got, optionflags):
  1347. """
  1348. Return a string describing the differences between the
  1349. expected output for a given example (`example`) and the actual
  1350. output (`got`). `optionflags` is the set of option flags used
  1351. to compare `want` and `got`.
  1352. """
  1353. want = example.want
  1354. # If <BLANKLINE>s are being used, then replace blank lines
  1355. # with <BLANKLINE> in the actual output string.
  1356. if not (optionflags & DONT_ACCEPT_BLANKLINE):
  1357. got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1358. # Check if we should use diff.
  1359. if self._do_a_fancy_diff(want, got, optionflags):
  1360. # Split want & got into lines.
  1361. want_lines = want.splitlines(True) # True == keep line ends
  1362. got_lines = got.splitlines(True)
  1363. # Use difflib to find their differences.
  1364. if optionflags & REPORT_UDIFF:
  1365. diff = difflib.unified_diff(want_lines, got_lines, n=2)
  1366. diff = list(diff)[2:] # strip the diff header
  1367. kind = 'unified diff with -expected +actual'
  1368. elif optionflags & REPORT_CDIFF:
  1369. diff = difflib.context_diff(want_lines, got_lines, n=2)
  1370. diff = list(diff)[2:] # strip the diff header
  1371. kind = 'context diff with expected followed by actual'
  1372. elif optionflags & REPORT_NDIFF:
  1373. engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
  1374. diff = list(engine.compare(want_lines, got_lines))
  1375. kind = 'ndiff with -expected +actual'
  1376. else:
  1377. assert 0, 'Bad diff option'
  1378. # Remove trailing whitespace on diff output.
  1379. diff = [line.rstrip() + '\n' for line in diff]
  1380. return 'Differences (%s):\n' % kind + _indent(''.join(diff))
  1381. # If we're not using diff, then simply list the expected
  1382. # output followed by the actual output.
  1383. if want and got:
  1384. return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1385. elif want:
  1386. return 'Expected:\n%sGot nothing\n' % _indent(want)
  1387. elif got:
  1388. return 'Expected nothing\nGot:\n%s' % _indent(got)
  1389. else:
  1390. return 'Expected nothing\nGot nothing\n'
  1391. class DocTestFailure(Exception):
  1392. """A DocTest example has failed in debugging mode.
  1393. The exception instance has variables:
  1394. - test: the DocTest object being run
  1395. - example: the Example object that failed
  1396. - got: the actual output
  1397. """
  1398. def __init__(self, test, example, got):
  1399. self.test = test
  1400. self.example = example
  1401. self.got = got
  1402. def __str__(self):
  1403. return str(self.test)
  1404. class UnexpectedException(Exception):
  1405. """A DocTest example has encountered an unexpected exception
  1406. The exception instance has variables:
  1407. - test: the DocTest object being run
  1408. - example: the Example object that failed
  1409. - exc_info: the exception info
  1410. """
  1411. def __init__(self, test, example, exc_info):
  1412. self.test = test
  1413. self.example = example
  1414. self.exc_info = exc_info
  1415. def __str__(self):
  1416. return str(self.test)
  1417. class DebugRunner(DocTestRunner):
  1418. r"""Run doc tests but raise an exception as soon as there is a failure.
  1419. If an unexpected exception occurs, an UnexpectedException is raised.
  1420. It contains the test, the example, and the original exception:
  1421. >>> runner = DebugRunner(verbose=False)
  1422. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1423. ... {}, 'foo', 'foo.py', 0)
  1424. >>> try:
  1425. ... runner.run(test)
  1426. ... except UnexpectedException, failure:
  1427. ... pass
  1428. >>> failure.test is test
  1429. True
  1430. >>> failure.example.want
  1431. '42\n'
  1432. >>> exc_info = failure.exc_info
  1433. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1434. Traceback (most recent call last):
  1435. ...
  1436. KeyError
  1437. We wrap the original exception to give the calling application
  1438. access to the test and example information.
  1439. If the output doesn't match, then a DocTestFailure is raised:
  1440. >>> test = DocTestParser().get_doctest('''
  1441. ... >>> x = 1
  1442. ... >>> x
  1443. ... 2
  1444. ... ''', {}, 'foo', 'foo.py', 0)
  1445. >>> try:
  1446. ... runner.run(test)
  1447. ... except DocTestFailure, failure:
  1448. ... pass
  1449. DocTestFailure objects provide access to the test:
  1450. >>> failure.test is test
  1451. True
  1452. As well as to the example:
  1453. >>> failure.example.want
  1454. '2\n'
  1455. and the actual output:
  1456. >>> failure.got
  1457. '1\n'
  1458. If a failure or error occurs, the globals are left intact:
  1459. >>> del test.globs['__builtins__']
  1460. >>> test.globs
  1461. {'x': 1}
  1462. >>> test = DocTestParser().get_doctest('''
  1463. ... >>> x = 2
  1464. ... >>> raise KeyError
  1465. ... ''', {}, 'foo', 'foo.py', 0)
  1466. >>> runner.run(test)
  1467. Traceback (most recent call last):
  1468. ...
  1469. UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1470. >>> del test.globs['__builtins__']
  1471. >>> test.globs
  1472. {'x': 2}
  1473. But the globals are cleared if there is no error:
  1474. >>> test = DocTestParser().get_doctest('''
  1475. ... >>> x = 2
  1476. ... ''', {}, 'foo', 'foo.py', 0)
  1477. >>> runner.run(test)
  1478. TestResults(failed=0, attempted=1)
  1479. >>> test.globs
  1480. {}
  1481. """
  1482. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1483. r = DocTestRunner.run(self, test, compileflags, out, False)
  1484. if clear_globs:
  1485. test.globs.clear()
  1486. return r
  1487. def report_unexpected_exception(self, out, test, example, exc_info):
  1488. raise UnexpectedException(test, example, exc_info)
  1489. def report_failure(self, out, test, example, got):
  1490. raise DocTestFailure(test, example, got)
  1491. ######################################################################
  1492. ## 6. Test Functions
  1493. ######################################################################
  1494. # These should be backwards compatible.
  1495. # For backward compatibility, a global instance of a DocTestRunner
  1496. # class, updated by testmod.
  1497. master = None
  1498. def testmod(m=None, name=None, globs=None, verbose=None,
  1499. report=True, optionflags=0, extraglobs=None,
  1500. raise_on_error=False, exclude_empty=False):
  1501. """m=None, name=None, globs=None, verbose=None, report=True,
  1502. optionflags=0, extraglobs=None, raise_on_error=False,
  1503. exclude_empty=False
  1504. Test examples in docstrings in functions and classes reachable
  1505. from module m (or the current module if m is not supplied), starting
  1506. with m.__doc__.
  1507. Also test examples reachable from dict m.__test__ if it exists and is
  1508. not None. m.__test__ maps names to functions, classes and strings;
  1509. function and class docstrings are tested even if the name is private;
  1510. strings are tested directly, as if they were docstrings.
  1511. Return (#failures, #tests).
  1512. See doctest.__doc__ for an overview.
  1513. Optional keyword arg "name" gives the name of the module; by default
  1514. use m.__name__.
  1515. Optional keyword arg "globs" gives a dict to be used as the globals
  1516. when executing examples; by default, use m.__dict__. A copy of this
  1517. dict is actually used for each docstring, so that each docstring's
  1518. examples start with a clean slate.
  1519. Optional keyword arg "extraglobs" gives a dictionary that should be
  1520. merged into the globals that are used to execute examples. By
  1521. default, no extra globals are used. This is new in 2.4.
  1522. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1523. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1524. Optional keyword arg "report" prints a summary at the end when true,
  1525. else prints nothing at the end. In verbose mode, the summary is
  1526. detailed, else very brief (in fact, empty if all tests passed).
  1527. Optional keyword arg "optionflags" or's together module constants,
  1528. and defaults to 0. This is new in 2.3. Possible values (see the
  1529. docs for details):
  1530. DONT_ACCEPT_TRUE_FOR_1
  1531. DONT_ACCEPT_BLANKLINE
  1532. NORMALIZE_WHITESPACE
  1533. ELLIPSIS
  1534. SKIP
  1535. IGNORE_EXCEPTION_DETAIL
  1536. REPORT_UDIFF
  1537. REPORT_CDIFF
  1538. REPORT_NDIFF
  1539. REPORT_ONLY_FIRST_FAILURE
  1540. Optional keyword arg "raise_on_error" raises an exception on the
  1541. first unexpected exception or failure. This allows failures to be
  1542. post-mortem debugged.
  1543. Advanced tomfoolery: testmod runs methods of a local instance of
  1544. class doctest.Tester, then merges the results into (or creates)
  1545. global Tester instance doctest.master. Methods of doctest.master
  1546. can be called directly too, if you want to do something unusual.
  1547. Passing report=0 to testmod is especially useful then, to delay
  1548. displaying a summary. Invoke doctest.master.summarize(verbose)
  1549. when you're done fiddling.
  1550. """
  1551. global master
  1552. # If no module was given, then use __main__.
  1553. if m is None:
  1554. # DWA - m will still be None if this wasn't invoked from the command
  1555. # line, in which case the following TypeError is about as good an error
  1556. # as we should expect
  1557. m = sys.modules.get('__main__')
  1558. # Check that we were actually given a module.
  1559. if not inspect.ismodule(m):
  1560. raise TypeError("testmod: module required; %r" % (m,))
  1561. # If no name was given, then use the module's name.
  1562. if name is None:
  1563. name = m.__name__
  1564. # Find, parse, and run all tests in the given module.
  1565. finder = DocTestFinder(exclude_empty=exclude_empty)
  1566. if raise_on_error:
  1567. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1568. else:
  1569. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1570. for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
  1571. runner.run(test)
  1572. if report:
  1573. runner.summarize()
  1574. if master is None:
  1575. master = runner
  1576. else:
  1577. master.merge(runner)
  1578. return TestResults(runner.failures, runner.tries)
  1579. def testfile(filename, module_relative=True, name=None, package=None,
  1580. globs=None, verbose=None, report=True, optionflags=0,
  1581. extraglobs=None, raise_on_error=False, parser=DocTestParser(),
  1582. encoding=None):
  1583. """
  1584. Test examples in the given file. Return (#failures, #tests).
  1585. Optional keyword arg "module_relative" specifies how filenames
  1586. should be interpreted:
  1587. - If "module_relative" is True (the default), then "filename"
  1588. specifies a module-relative path. By default, this path is
  1589. relative to the calling module's directory; but if the
  1590. "package" argument is specified, then it is relative to that
  1591. package. To ensure os-independence, "filename" should use
  1592. "/" characters to separate path segments, and should not
  1593. be an absolute path (i.e., it may not begin with "/").
  1594. - If "module_relative" is False, then "filename" specifies an
  1595. os-specific path. The path may be absolute or relative (to
  1596. the current working directory).
  1597. Optional keyword arg "name" gives the name of the test; by default
  1598. use the file's basename.
  1599. Optional keyword argument "package" is a Python package or the
  1600. name of a Python package whose directory should be used as the
  1601. base directory for a module relative filename. If no package is
  1602. specified, then the calling module's directory is used as the base
  1603. directory for module relative filenames. It is an error to
  1604. specify "package" if "module_relative" is False.
  1605. Optional keyword arg "globs" gives a dict to be used as the globals
  1606. when executing examples; by default, use {}. A copy of this dict
  1607. is actually used for each docstring, so that each docstring's
  1608. examples start with a clean slate.
  1609. Optional keyword arg "extraglobs" gives a dictionary that should be
  1610. merged into the globals that are used to execute examples. By
  1611. default, no extra globals are used.
  1612. Optional keyword arg "verbose" prints lots of stuff if true, prints
  1613. only failures if false; by default, it's true iff "-v" is in sys.argv.
  1614. Optional keyword arg "report" prints a summary at the end when true,
  1615. else prints nothing at the end. In verbose mode, the summary is
  1616. detailed, else very brief (in fact, empty if all tests passed).
  1617. Optional keyword arg "optionflags" or's together module constants,
  1618. and defaults to 0. Possible values (see the docs for details):
  1619. DONT_ACCEPT_TRUE_FOR_1
  1620. DONT_ACCEPT_BLANKLINE
  1621. NORMALIZE_WHITESPACE
  1622. ELLIPSIS
  1623. SKIP
  1624. IGNORE_EXCEPTION_DETAIL
  1625. REPORT_UDIFF
  1626. REPORT_CDIFF
  1627. REPORT_NDIFF
  1628. REPORT_ONLY_FIRST_FAILURE
  1629. Optional keyword arg "raise_on_error" raises an exception on the
  1630. first unexpected exception or failure. This allows failures to be
  1631. post-mortem debugged.
  1632. Optional keyword arg "parser" specifies a DocTestParser (or
  1633. subclass) that should be used to extract tests from the files.
  1634. Optional keyword arg "encoding" specifies an encoding that should
  1635. be used to convert the file to unicode.
  1636. Advanced tomfoolery: testmod runs methods of a local instance of
  1637. class doctest.Tester, then merges the results into (or creates)
  1638. global Tester instance doctest.master. Methods of doctest.master
  1639. can be called directly too, if you want to do something unusual.
  1640. Passing report=0 to testmod is especially useful then, to delay
  1641. displaying a summary. Invoke doctest.master.summarize(verbose)
  1642. when you're done fiddling.
  1643. """
  1644. global master
  1645. if package and not module_relative:
  1646. raise ValueError("Package may only be specified for module-"
  1647. "relative paths.")
  1648. # Relativize the path
  1649. text, filename = _load_testfile(filename, package, module_relative)
  1650. # If no name was given, then use the file's name.
  1651. if name is None:
  1652. name = os.path.basename(filename)
  1653. # Assemble the globals.
  1654. if globs is None:
  1655. globs = {}
  1656. else:
  1657. globs = globs.copy()
  1658. if extraglobs is not None:
  1659. globs.update(extraglobs)
  1660. if '__name__' not in globs:
  1661. globs['__name__'] = '__main__'
  1662. if raise_on_error:
  1663. runner = DebugRunner(verbose=verbose, optionflags=optionflags)
  1664. else:
  1665. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1666. if encoding is not None:
  1667. text = text.decode(encoding)
  1668. # Read the file, convert it to a test, and run it.
  1669. test = parser.get_doctest(text, globs, name, filename, 0)
  1670. runner.run(test)
  1671. if report:
  1672. runner.summarize()
  1673. if master is None:
  1674. master = runner
  1675. else:
  1676. master.merge(runner)
  1677. return TestResults(runner.failures, runner.tries)
  1678. def run_docstring_examples(f, globs, verbose=False, name="NoName",
  1679. compileflags=None, optionflags=0):
  1680. """
  1681. Test examples in the given object's docstring (`f`), using `globs`
  1682. as globals. Optional argument `name` is used in failure messages.
  1683. If the optional argument `verbose` is true, then generate output
  1684. even if there are no failures.
  1685. `compileflags` gives the set of flags that should be used by the
  1686. Python compiler when running the examples. If not specified, then
  1687. it will default to the set of future-import flags that apply to
  1688. `globs`.
  1689. Optional keyword arg `optionflags` specifies options for the
  1690. testing and output. See the documentation for `testmod` for more
  1691. information.
  1692. """
  1693. # Find, parse, and run all tests in the given module.
  1694. finder = DocTestFinder(verbose=verbose, recurse=False)
  1695. runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
  1696. for test in finder.find(f, name, globs=globs):
  1697. runner.run(test, compileflags=compileflags)
  1698. ######################################################################
  1699. ## 7. Tester
  1700. ######################################################################
  1701. # This is provided only for backwards compatibility. It's not
  1702. # actually used in any way.
  1703. class Tester:
  1704. def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
  1705. warnings.warn("class Tester is deprecated; "
  1706. "use class doctest.DocTestRunner instead",
  1707. DeprecationWarning, stacklevel=2)
  1708. if mod is None and globs is None:
  1709. raise TypeError("Tester.__init__: must specify mod or globs")
  1710. if mod is not None and not inspect.ismodule(mod):
  1711. raise TypeError("Tester.__init__: mod must be a module; %r" %
  1712. (mod,))
  1713. if globs is None:
  1714. globs = mod.__dict__
  1715. self.globs = globs
  1716. self.verbose = verbose
  1717. self.optionflags = optionflags
  1718. self.testfinder = DocTestFinder()
  1719. self.testrunner = DocTestRunner(verbose=verbose,
  1720. optionflags=optionflags)
  1721. def runstring(self, s, name):
  1722. test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1723. if self.verbose:
  1724. print "Running string", name
  1725. (f,t) = self.testrunner.run(test)
  1726. if self.verbose:
  1727. print f, "of", t, "examples failed in string", name
  1728. return TestResults(f,t)
  1729. def rundoc(self, object, name=None, module=None):
  1730. f = t = 0
  1731. tests = self.testfinder.find(object, name, module=module,
  1732. globs=self.globs)
  1733. for test in tests:
  1734. (f2, t2) = self.testrunner.run(test)
  1735. (f,t) = (f+f2, t+t2)
  1736. return TestResults(f,t)
  1737. def rundict(self, d, name, module=None):
  1738. import types
  1739. m = types.ModuleType(name)
  1740. m.__dict__.update(d)
  1741. if module is None:
  1742. module = False
  1743. return self.rundoc(m, name, module)
  1744. def run__test__(self, d, name):
  1745. import types
  1746. m = types.ModuleType(name)
  1747. m.__test__ = d
  1748. return self.rundoc(m, name)
  1749. def summarize(self, verbose=None):
  1750. return self.testrunner.summarize(verbose)
  1751. def merge(self, other):
  1752. self.testrunner.merge(other.testrunner)
  1753. ######################################################################
  1754. ## 8. Unittest Support
  1755. ######################################################################
  1756. _unittest_reportflags = 0
  1757. def set_unittest_reportflags(flags):
  1758. """Sets the unittest option flags.
  1759. The old flag is returned so that a runner could restore the old
  1760. value if it wished to:
  1761. >>> import doctest
  1762. >>> old = doctest._unittest_reportflags
  1763. >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1764. ... REPORT_ONLY_FIRST_FAILURE) == old
  1765. True
  1766. >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1767. ... REPORT_ONLY_FIRST_FAILURE)
  1768. True
  1769. Only reporting flags can be set:
  1770. >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1771. Traceback (most recent call last):
  1772. ...
  1773. ValueError: ('Only reporting flags allowed', 8)
  1774. >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1775. ... REPORT_ONLY_FIRST_FAILURE)
  1776. True
  1777. """
  1778. global _unittest_reportflags
  1779. if (flags & REPORTING_FLAGS) != flags:
  1780. raise ValueError("Only reporting flags allowed", flags)
  1781. old = _unittest_reportflags
  1782. _unittest_reportflags = flags
  1783. return old
  1784. class DocTestCase(unittest.TestCase):
  1785. def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
  1786. checker=None):
  1787. unittest.TestCase.__init__(self)
  1788. self._dt_optionflags = optionflags
  1789. self._dt_checker = checker
  1790. self._dt_test = test
  1791. self._dt_setUp = setUp
  1792. self._dt_tearDown = tearDown
  1793. def setUp(self):
  1794. test = self._dt_test
  1795. if self._dt_setUp is not None:
  1796. self._dt_setUp(test)
  1797. def tearDown(self):
  1798. test = self._dt_test
  1799. if self._dt_tearDown is not None:
  1800. self._dt_tearDown(test)
  1801. test.globs.clear()
  1802. def runTest(self):
  1803. test = self._dt_test
  1804. old = sys.stdout
  1805. new = StringIO()
  1806. optionflags = self._dt_optionflags
  1807. if not (optionflags & REPORTING_FLAGS):
  1808. # The option flags don't include any reporting flags,
  1809. # so add the default reporting flags
  1810. optionflags |= _unittest_reportflags
  1811. runner = DocTestRunner(optionflags=optionflags,
  1812. checker=self._dt_checker, verbose=False)
  1813. try:
  1814. runner.DIVIDER = "-"*70
  1815. failures, tries = runner.run(
  1816. test, out=new.write, clear_globs=False)
  1817. finally:
  1818. sys.stdout = old
  1819. if failures:
  1820. raise self.failureException(self.format_failure(new.getvalue()))
  1821. def format_failure(self, err):
  1822. test = self._dt_test
  1823. if test.lineno is None:
  1824. lineno = 'unknown line number'
  1825. else:
  1826. lineno = '%s' % test.lineno
  1827. lname = '.'.join(test.name.split('.')[-1:])
  1828. return ('Failed doctest test for %s\n'
  1829. ' File "%s", line %s, in %s\n\n%s'
  1830. % (test.name, test.filename, lineno, lname, err)
  1831. )
  1832. def debug(self):
  1833. r"""Run the test case without results and without catching exceptions
  1834. The unit test framework includes a debug method on test cases
  1835. and test suites to support post-mortem debugging. The test code
  1836. is run in such a way that errors are not caught. This way a
  1837. caller can catch the errors and initiate post-mortem debugging.
  1838. The DocTestCase provides a debug method that raises
  1839. UnexpectedException errors if there is an unexepcted
  1840. exception:
  1841. >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
  1842. ... {}, 'foo', 'foo.py', 0)
  1843. >>> case = DocTestCase(test)
  1844. >>> try:
  1845. ... case.debug()
  1846. ... except UnexpectedException, failure:
  1847. ... pass
  1848. The UnexpectedException contains the test, the example, and
  1849. the original exception:
  1850. >>> failure.test is test
  1851. True
  1852. >>> failure.example.want
  1853. '42\n'
  1854. >>> exc_info = failure.exc_info
  1855. >>> raise exc_info[0], exc_info[1], exc_info[2]
  1856. Traceback (most recent call last):
  1857. ...
  1858. KeyError
  1859. If the output doesn't match, then a DocTestFailure is raised:
  1860. >>> test = DocTestParser().get_doctest('''
  1861. ... >>> x = 1
  1862. ... >>> x
  1863. ... 2
  1864. ... ''', {}, 'foo', 'foo.py', 0)
  1865. >>> case = DocTestCase(test)
  1866. >>> try:
  1867. ... case.debug()
  1868. ... except DocTestFailure, failure:
  1869. ... pass
  1870. DocTestFailure objects provide access to the test:
  1871. >>> failure.test is test
  1872. True
  1873. As well as to the example:
  1874. >>> failure.example.want
  1875. '2\n'
  1876. and the actual output:
  1877. >>> failure.got
  1878. '1\n'
  1879. """
  1880. self.setUp()
  1881. runner = DebugRunner(optionflags=self._dt_optionflags,
  1882. checker=self._dt_checker, verbose=False)
  1883. runner.run(self._dt_test, clear_globs=False)
  1884. self.tearDown()
  1885. def id(self):
  1886. return self._dt_test.name
  1887. def __repr__(self):
  1888. name = self._dt_test.name.split('.')
  1889. return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
  1890. __str__ = __repr__
  1891. def shortDescription(self):
  1892. return "Doctest: " + self._dt_test.name
  1893. def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
  1894. **options):
  1895. """
  1896. Convert doctest tests for a module to a unittest test suite.
  1897. This converts each documentation string in a module that
  1898. contains doctest tests to a unittest test case. If any of the
  1899. tests in a doc string fail, then the test case fails. An exception
  1900. is raised showing the name of the file containing the test and a
  1901. (sometimes approximate) line number.
  1902. The `module` argument provides the module to be tested. The argument
  1903. can be either a module or a module name.
  1904. If no argument is given, the calling module is used.
  1905. A number of options may be provided as keyword arguments:
  1906. setUp
  1907. A set-up function. This is called before running the
  1908. tests in each file. The setUp function will be passed a DocTest
  1909. object. The setUp function can access the test globals as the
  1910. globs attribute of the test passed.
  1911. tearDown
  1912. A tear-down function. This is called after running the
  1913. tests in each file. The tearDown function will be passed a DocTest
  1914. object. The tearDown function can access the test globals as the
  1915. globs attribute of the test passed.
  1916. globs
  1917. A dictionary containing initial global variables for the tests.
  1918. optionflags
  1919. A set of doctest option flags expressed as an integer.
  1920. """
  1921. if test_finder is None:
  1922. test_finder = DocTestFinder()
  1923. module = _normalize_module(module)
  1924. tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
  1925. if not tests:
  1926. # Why do we want to do this? Because it reveals a bug that might
  1927. # otherwise be hidden.
  1928. raise ValueError(module, "has no tests")
  1929. tests.sort()
  1930. suite = unittest.TestSuite()
  1931. for test in tests:
  1932. if len(test.examples) == 0:
  1933. continue
  1934. if not test.filename:
  1935. filename = module.__file__
  1936. if filename[-4:] in (".pyc", ".pyo"):
  1937. filename = filename[:-1]
  1938. test.filename = filename
  1939. suite.addTest(DocTestCase(test, **options))
  1940. return suite
  1941. class DocFileCase(DocTestCase):
  1942. def id(self):
  1943. return '_'.join(self._dt_test.name.split('.'))
  1944. def __repr__(self):
  1945. return self._dt_test.filename
  1946. __str__ = __repr__
  1947. def format_failure(self, err):
  1948. return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
  1949. % (self._dt_test.name, self._dt_test.filename, err)
  1950. )
  1951. def DocFileTest(path, module_relative=True, package=None,
  1952. globs=None, parser=DocTestParser(),
  1953. encoding=None, **options):
  1954. if globs is None:
  1955. globs = {}
  1956. else:
  1957. globs = globs.copy()
  1958. if package and not module_relative:
  1959. raise ValueError("Package may only be specified for module-"
  1960. "relative paths.")
  1961. # Relativize the path.
  1962. doc, path = _load_testfile(path, package, module_relative)
  1963. if "__file__" not in globs:
  1964. globs["__file__"] = path
  1965. # Find the file and read it.
  1966. name = os.path.basename(path)
  1967. # If an encoding is specified, use it to convert the file to unicode
  1968. if encoding is not None:
  1969. doc = doc.decode(encoding)
  1970. # Convert it to a test, and wrap it in a DocFileCase.
  1971. test = parser.get_doctest(doc, globs, name, path, 0)
  1972. return DocFileCase(test, **options)
  1973. def DocFileSuite(*paths, **kw):
  1974. """A unittest suite for one or more doctest files.
  1975. The path to each doctest file is given as a string; the
  1976. interpretation of that string depends on the keyword argument
  1977. "module_relative".
  1978. A number of options may be provided as keyword arguments:
  1979. module_relative
  1980. If "module_relative" is True, then the given file paths are
  1981. interpreted as os-independent module-relative paths. By
  1982. default, these paths are relative to the calling module's
  1983. directory; but if the "package" argument is specified, then
  1984. they are relative to that package. To ensure os-independence,
  1985. "filename" should use "/" characters to separate path
  1986. segments, and may not be an absolute path (i.e., it may not
  1987. begin with "/").
  1988. If "module_relative" is False, then the given file paths are
  1989. interpreted as os-specific paths. These paths may be absolute
  1990. or relative (to the current working directory).
  1991. package
  1992. A Python package or the name of a Python package whose directory
  1993. should be used as the base directory for module relative paths.
  1994. If "package" is not specified, then the calling module's
  1995. directory is used as the base directory for module relative
  1996. filenames. It is an error to specify "package" if
  1997. "module_relative" is False.
  1998. setUp
  1999. A set-up function. This is called before running the
  2000. tests in each file. The setUp function will be passed a DocTest
  2001. object. The setUp function can access the test globals as the
  2002. globs attribute of the test passed.
  2003. tearDown
  2004. A tear-down function. This is called after running the
  2005. tests in each file. The tearDown function will be passed a DocTest
  2006. object. The tearDown function can access the test globals as the
  2007. globs attribute of the test passed.
  2008. globs
  2009. A dictionary containing initial global variables for the tests.
  2010. optionflags
  2011. A set of doctest option flags expressed as an integer.
  2012. parser
  2013. A DocTestParser (or subclass) that should be used to extract
  2014. tests from the files.
  2015. encoding
  2016. An encoding that will be used to convert the files to unicode.
  2017. """
  2018. suite = unittest.TestSuite()
  2019. # We do this here so that _normalize_module is called at the right
  2020. # level. If it were called in DocFileTest, then this function
  2021. # would be the caller and we might guess the package incorrectly.
  2022. if kw.get('module_relative', True):
  2023. kw['package'] = _normalize_module(kw.get('package'))
  2024. for path in paths:
  2025. suite.addTest(DocFileTest(path, **kw))
  2026. return suite
  2027. ######################################################################
  2028. ## 9. Debugging Support
  2029. ######################################################################
  2030. def script_from_examples(s):
  2031. r"""Extract script from text with examples.
  2032. Converts text with examples to a Python script. Example input is
  2033. converted to regular code. Example output and all other words
  2034. are converted to comments:
  2035. >>> text = '''
  2036. ... Here are examples of simple math.
  2037. ...
  2038. ... Python has super accurate integer addition
  2039. ...
  2040. ... >>> 2 + 2
  2041. ... 5
  2042. ...
  2043. ... And very friendly error messages:
  2044. ...
  2045. ... >>> 1/0
  2046. ... To Infinity
  2047. ... And
  2048. ... Beyond
  2049. ...
  2050. ... You can use logic if you want:
  2051. ...
  2052. ... >>> if 0:
  2053. ... ... blah
  2054. ... ... blah
  2055. ... ...
  2056. ...
  2057. ... Ho hum
  2058. ... '''
  2059. >>> print script_from_examples(text)
  2060. # Here are examples of simple math.
  2061. #
  2062. # Python has super accurate integer addition
  2063. #
  2064. 2 + 2
  2065. # Expected:
  2066. ## 5
  2067. #
  2068. # And very friendly error messages:
  2069. #
  2070. 1/0
  2071. # Expected:
  2072. ## To Infinity
  2073. ## And
  2074. ## Beyond
  2075. #
  2076. # You can use logic if you want:
  2077. #
  2078. if 0:
  2079. blah
  2080. blah
  2081. #
  2082. # Ho hum
  2083. <BLANKLINE>
  2084. """
  2085. output = []
  2086. for piece in DocTestParser().parse(s):
  2087. if isinstance(piece, Example):
  2088. # Add the example's source code (strip trailing NL)
  2089. output.append(piece.source[:-1])
  2090. # Add the expected output:
  2091. want = piece.want
  2092. if want:
  2093. output.append('# Expected:')
  2094. output += ['## '+l for l in want.split('\n')[:-1]]
  2095. else:
  2096. # Add non-example text.
  2097. output += [_comment_line(l)
  2098. for l in piece.split('\n')[:-1]]
  2099. # Trim junk on both ends.
  2100. while output and output[-1] == '#':
  2101. output.pop()
  2102. while output and output[0] == '#':
  2103. output.pop(0)
  2104. # Combine the output, and return it.
  2105. # Add a courtesy newline to prevent exec from choking (see bug #1172785)
  2106. return '\n'.join(output) + '\n'
  2107. def testsource(module, name):
  2108. """Extract the test sources from a doctest docstring as a script.
  2109. Provide the module (or dotted name of the module) containing the
  2110. test to be debugged and the name (within the module) of the object
  2111. with the doc string with tests to be debugged.
  2112. """
  2113. module = _normalize_module(module)
  2114. tests = DocTestFinder().find(module)
  2115. test = [t for t in tests if t.name == name]
  2116. if not test:
  2117. raise ValueError(name, "not found in tests")
  2118. test = test[0]
  2119. testsrc = script_from_examples(test.docstring)
  2120. return testsrc
  2121. def debug_src(src, pm=False, globs=None):
  2122. """Debug a single doctest docstring, in argument `src`'"""
  2123. testsrc = script_from_examples(src)
  2124. debug_script(testsrc, pm, globs)
  2125. def debug_script(src, pm=False, globs=None):
  2126. "Debug a test script. `src` is the script, as a string."
  2127. import pdb
  2128. # Note that tempfile.NameTemporaryFile() cannot be used. As the
  2129. # docs say, a file so created cannot be opened by name a second time
  2130. # on modern Windows boxes, and execfile() needs to open it.
  2131. srcfilename = tempfile.mktemp(".py", "doctestdebug")
  2132. f = open(srcfilename, 'w')
  2133. f.write(src)
  2134. f.close()
  2135. try:
  2136. if globs:
  2137. globs = globs.copy()
  2138. else:
  2139. globs = {}
  2140. if pm:
  2141. try:
  2142. execfile(srcfilename, globs, globs)
  2143. except:
  2144. print sys.exc_info()[1]
  2145. pdb.post_mortem(sys.exc_info()[2])
  2146. else:
  2147. # Note that %r is vital here. '%s' instead can, e.g., cause
  2148. # backslashes to get treated as metacharacters on Windows.
  2149. pdb.run("execfile(%r)" % srcfilename, globs, globs)
  2150. finally:
  2151. os.remove(srcfilename)
  2152. def debug(module, name, pm=False):
  2153. """Debug a single doctest docstring.
  2154. Provide the module (or dotted name of the module) containing the
  2155. test to be debugged and the name (within the module) of the object
  2156. with the docstring with tests to be debugged.
  2157. """
  2158. module = _normalize_module(module)
  2159. testsrc = testsource(module, name)
  2160. debug_script(testsrc, pm, module.__dict__)
  2161. ######################################################################
  2162. ## 10. Example Usage
  2163. ######################################################################
  2164. class _TestClass:
  2165. """
  2166. A pointless class, for sanity-checking of docstring testing.
  2167. Methods:
  2168. square()
  2169. get()
  2170. >>> _TestClass(13).get() + _TestClass(-12).get()
  2171. 1
  2172. >>> hex(_TestClass(13).square().get())
  2173. '0xa9'
  2174. """
  2175. def __init__(self, val):
  2176. """val -> _TestClass object with associated value val.
  2177. >>> t = _TestClass(123)
  2178. >>> print t.get()
  2179. 123
  2180. """
  2181. self.val = val
  2182. def square(self):
  2183. """square() -> square TestClass's associated value
  2184. >>> _TestClass(13).square().get()
  2185. 169
  2186. """
  2187. self.val = self.val ** 2
  2188. return self
  2189. def get(self):
  2190. """get() -> return TestClass's associated value.
  2191. >>> x = _TestClass(-42)
  2192. >>> print x.get()
  2193. -42
  2194. """
  2195. return self.val
  2196. __test__ = {"_TestClass": _TestClass,
  2197. "string": r"""
  2198. Example of a string object, searched as-is.
  2199. >>> x = 1; y = 2
  2200. >>> x + y, x * y
  2201. (3, 2)
  2202. """,
  2203. "bool-int equivalence": r"""
  2204. In 2.2, boolean expressions displayed
  2205. 0 or 1. By default, we still accept
  2206. them. This can be disabled by passing
  2207. DONT_ACCEPT_TRUE_FOR_1 to the new
  2208. optionflags argument.
  2209. >>> 4 == 4
  2210. 1
  2211. >>> 4 == 4
  2212. True
  2213. >>> 4 > 4
  2214. 0
  2215. >>> 4 > 4
  2216. False
  2217. """,
  2218. "blank lines": r"""
  2219. Blank lines can be marked with <BLANKLINE>:
  2220. >>> print 'foo\n\nbar\n'
  2221. foo
  2222. <BLANKLINE>
  2223. bar
  2224. <BLANKLINE>
  2225. """,
  2226. "ellipsis": r"""
  2227. If the ellipsis flag is used, then '...' can be used to
  2228. elide substrings in the desired output:
  2229. >>> print range(1000) #doctest: +ELLIPSIS
  2230. [0, 1, 2, ..., 999]
  2231. """,
  2232. "whitespace normalization": r"""
  2233. If the whitespace normalization flag is used, then
  2234. differences in whitespace are ignored.
  2235. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
  2236. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  2237. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  2238. 27, 28, 29]
  2239. """,
  2240. }
  2241. def _test():
  2242. testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
  2243. if testfiles:
  2244. for filename in testfiles:
  2245. if filename.endswith(".py"):
  2246. # It is a module -- insert its dir into sys.path and try to
  2247. # import it. If it is part of a package, that possibly won't work
  2248. # because of package imports.
  2249. dirname, filename = os.path.split(filename)
  2250. sys.path.insert(0, dirname)
  2251. m = __import__(filename[:-3])
  2252. del sys.path[0]
  2253. failures, _ = testmod(m)
  2254. else:
  2255. failures, _ = testfile(filename, module_relative=False)
  2256. if failures:
  2257. return 1
  2258. else:
  2259. r = unittest.TextTestRunner()
  2260. r.run(DocTestSuite())
  2261. return 0
  2262. if __name__ == "__main__":
  2263. sys.exit(_test())