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

/lib-python/2.7/doctest.py

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