PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/doctest.py

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