blob: d609c5def54f6697c79845be443e0573df237458 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
Tim Peters80e53142004-08-09 04:34:45 +000011In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000012
13def _test():
Tim Peters80e53142004-08-09 04:34:45 +000014 import doctest
Tim Peters48983fc2004-09-25 02:41:28 +000015 doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000016
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing example(s) and the cause(s) of the failure(s) are printed to stdout
27(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
Tim Peters80e53142004-08-09 04:34:45 +000037You can force verbose mode by passing "verbose=True" to testmod, or prohibit
38it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000039examined by testmod.
40
Tim Peters80e53142004-08-09 04:34:45 +000041There are a variety of other ways to run doctests, including integration
42with the unittest framework, and support for running non-Python text
43files containing doctests. There are also many ways to override parts
44of doctest's default behaviors. See the Library Reference Manual for
45details.
Tim Peters8a7d2d52001-01-16 07:10:57 +000046"""
Tim Peters48983fc2004-09-25 02:41:28 +000047
Edward Loper8e4a34b2004-08-12 02:34:27 +000048__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +000049
Tim Peters4fd9e2f2001-08-18 00:05:50 +000050__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +000051 # 0, Option Flags
52 'register_optionflag',
53 'DONT_ACCEPT_TRUE_FOR_1',
54 'DONT_ACCEPT_BLANKLINE',
55 'NORMALIZE_WHITESPACE',
56 'ELLIPSIS',
Tim Peters711bf302006-04-25 03:31:36 +000057 'SKIP',
Tim Peters1fbf9c52004-09-04 17:21:02 +000058 'IGNORE_EXCEPTION_DETAIL',
Tim Petersba601962004-09-04 15:04:06 +000059 'COMPARISON_FLAGS',
Edward Loper71f55af2004-08-26 01:41:51 +000060 'REPORT_UDIFF',
61 'REPORT_CDIFF',
62 'REPORT_NDIFF',
Jim Fultonf54bad42004-08-28 14:57:56 +000063 'REPORT_ONLY_FIRST_FAILURE',
Tim Petersba601962004-09-04 15:04:06 +000064 'REPORTING_FLAGS',
Edward Loperb7503ff2004-08-19 19:19:03 +000065 # 1. Utility Functions
Edward Loperb7503ff2004-08-19 19:19:03 +000066 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +000067 'Example',
68 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +000069 # 3. Doctest Parser
70 'DocTestParser',
71 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +000072 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +000073 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +000074 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +000075 'OutputChecker',
76 'DocTestFailure',
77 'UnexpectedException',
78 'DebugRunner',
79 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +000080 'testmod',
Edward Loper052d0cd2004-09-19 17:19:33 +000081 'testfile',
Tim Peters4fd9e2f2001-08-18 00:05:50 +000082 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +000083 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +000084 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +000085 # 8. Unittest Support
Tim Petersdb3756d2003-06-29 05:30:48 +000086 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +000087 'DocFileSuite',
Tim Peters9d02a7c2004-09-26 01:50:24 +000088 'set_unittest_reportflags',
Edward Loperb7503ff2004-08-19 19:19:03 +000089 # 9. Debugging Support
90 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +000091 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +000092 'debug_src',
Tim Petersdb3756d2003-06-29 05:30:48 +000093 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +000094]
Tim Peters8a7d2d52001-01-16 07:10:57 +000095
Tim Peters4fd9e2f2001-08-18 00:05:50 +000096import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +000097
Neal Norwitz052cbcf2006-06-12 03:05:03 +000098import sys, traceback, inspect, linecache, os, re
Jim Fulton356fd192004-08-09 11:34:47 +000099import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000100import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000101from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000102
Tim Peters19397e52004-08-06 22:02:59 +0000103# There are 4 basic classes:
104# - Example: a <source, want> pair, plus an intra-docstring line number.
105# - DocTest: a collection of examples, parsed from a docstring, plus
106# info about where the docstring came from (name, filename, lineno).
107# - DocTestFinder: extracts DocTests from a given object's docstring and
108# its contained objects' docstrings.
109# - DocTestRunner: runs DocTest cases, and accumulates statistics.
110#
111# So the basic picture is:
112#
113# list of:
114# +------+ +---------+ +-------+
115# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
116# +------+ +---------+ +-------+
117# | Example |
118# | ... |
119# | Example |
120# +---------+
121
Edward Loperac20f572004-08-12 02:02:24 +0000122# Option constants.
Tim Peters38330fe2004-08-30 16:19:24 +0000123
Edward Loperac20f572004-08-12 02:02:24 +0000124OPTIONFLAGS_BY_NAME = {}
125def register_optionflag(name):
Tim Petersad2ef332006-05-10 02:43:01 +0000126 # Create a new flag unless `name` is already known.
127 return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
Edward Loperac20f572004-08-12 02:02:24 +0000128
129DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
130DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
131NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
132ELLIPSIS = register_optionflag('ELLIPSIS')
Tim Peters711bf302006-04-25 03:31:36 +0000133SKIP = register_optionflag('SKIP')
Tim Peters1fbf9c52004-09-04 17:21:02 +0000134IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
Tim Peters38330fe2004-08-30 16:19:24 +0000135
136COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
137 DONT_ACCEPT_BLANKLINE |
138 NORMALIZE_WHITESPACE |
Tim Peters1fbf9c52004-09-04 17:21:02 +0000139 ELLIPSIS |
Tim Peters711bf302006-04-25 03:31:36 +0000140 SKIP |
Edward Loper7d88a582004-09-28 05:50:57 +0000141 IGNORE_EXCEPTION_DETAIL)
Tim Peters38330fe2004-08-30 16:19:24 +0000142
Edward Loper71f55af2004-08-26 01:41:51 +0000143REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
144REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
145REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000146REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000147
Tim Peters38330fe2004-08-30 16:19:24 +0000148REPORTING_FLAGS = (REPORT_UDIFF |
149 REPORT_CDIFF |
150 REPORT_NDIFF |
151 REPORT_ONLY_FIRST_FAILURE)
152
Edward Loperac20f572004-08-12 02:02:24 +0000153# Special string markers for use in `want` strings:
154BLANKLINE_MARKER = '<BLANKLINE>'
155ELLIPSIS_MARKER = '...'
156
Tim Peters8485b562004-08-04 18:46:34 +0000157######################################################################
158## Table of Contents
159######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000160# 1. Utility Functions
161# 2. Example & DocTest -- store test cases
162# 3. DocTest Parser -- extracts examples from strings
163# 4. DocTest Finder -- extracts test cases from objects
164# 5. DocTest Runner -- runs test cases
165# 6. Test Functions -- convenient wrappers for testing
166# 7. Tester Class -- for backwards compatibility
167# 8. Unittest Support
168# 9. Debugging Support
169# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000170
Tim Peters8485b562004-08-04 18:46:34 +0000171######################################################################
172## 1. Utility Functions
173######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000174
Tim Peters8485b562004-08-04 18:46:34 +0000175def _extract_future_flags(globs):
176 """
177 Return the compiler-flags associated with the future features that
178 have been imported into the given namespace (globs).
179 """
180 flags = 0
181 for fname in __future__.all_feature_names:
182 feature = globs.get(fname, None)
183 if feature is getattr(__future__, fname):
184 flags |= feature.compiler_flag
185 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000186
Tim Peters8485b562004-08-04 18:46:34 +0000187def _normalize_module(module, depth=2):
188 """
189 Return the module specified by `module`. In particular:
190 - If `module` is a module, then return module.
191 - If `module` is a string, then import and return the
192 module with that name.
193 - If `module` is None, then return the calling module.
194 The calling module is assumed to be the module of
195 the stack frame at the given depth in the call stack.
196 """
197 if inspect.ismodule(module):
198 return module
199 elif isinstance(module, (str, unicode)):
200 return __import__(module, globals(), locals(), ["*"])
201 elif module is None:
202 return sys.modules[sys._getframe(depth).f_globals['__name__']]
203 else:
204 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000205
Phillip J. Eby47032112006-04-11 01:07:43 +0000206def _load_testfile(filename, package, module_relative):
207 if module_relative:
208 package = _normalize_module(package, 3)
209 filename = _module_relative_path(package, filename)
210 if hasattr(package, '__loader__'):
211 if hasattr(package.__loader__, 'get_data'):
Brett Cannond3a81df2007-11-21 00:58:54 +0000212 file_contents = package.__loader__.get_data(filename)
213 # get_data() opens files as 'rb', so one must do the equivalent
214 # conversion as universal newlines would do.
215 return file_contents.replace(os.linesep, '\n'), filename
Phillip J. Eby47032112006-04-11 01:07:43 +0000216 return open(filename).read(), filename
217
Edward Loperaacf0832004-08-26 01:19:50 +0000218def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000219 """
Edward Loperaacf0832004-08-26 01:19:50 +0000220 Add the given number of space characters to the beginning every
221 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000222 """
Edward Loperaacf0832004-08-26 01:19:50 +0000223 # This regexp matches the start of non-blank lines:
224 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000225
Edward Loper8e4a34b2004-08-12 02:34:27 +0000226def _exception_traceback(exc_info):
227 """
228 Return a string containing a traceback message for the given
229 exc_info tuple (as returned by sys.exc_info()).
230 """
231 # Get a traceback message.
232 excout = StringIO()
233 exc_type, exc_val, exc_tb = exc_info
234 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
235 return excout.getvalue()
236
Tim Peters8485b562004-08-04 18:46:34 +0000237# Override some StringIO methods.
238class _SpoofOut(StringIO):
239 def getvalue(self):
240 result = StringIO.getvalue(self)
241 # If anything at all was written, make sure there's a trailing
242 # newline. There's no way for the expected output to indicate
243 # that a trailing newline is missing.
244 if result and not result.endswith("\n"):
245 result += "\n"
246 # Prevent softspace from screwing up the next test case, in
247 # case they used print with a trailing comma in an example.
248 if hasattr(self, "softspace"):
249 del self.softspace
250 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000251
Tim Peters8485b562004-08-04 18:46:34 +0000252 def truncate(self, size=None):
253 StringIO.truncate(self, size)
254 if hasattr(self, "softspace"):
255 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000256
Tim Peters26b3ebb2004-08-19 08:10:08 +0000257# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000258def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000259 """
260 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000261 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000262 False
263 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000264 if ELLIPSIS_MARKER not in want:
265 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000266
Tim Peters26b3ebb2004-08-19 08:10:08 +0000267 # Find "the real" strings.
268 ws = want.split(ELLIPSIS_MARKER)
269 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000270
Tim Petersdc5de3b2004-08-19 14:06:20 +0000271 # Deal with exact matches possibly needed at one or both ends.
272 startpos, endpos = 0, len(got)
273 w = ws[0]
274 if w: # starts with exact match
275 if got.startswith(w):
276 startpos = len(w)
277 del ws[0]
278 else:
279 return False
280 w = ws[-1]
281 if w: # ends with exact match
282 if got.endswith(w):
283 endpos -= len(w)
284 del ws[-1]
285 else:
286 return False
287
288 if startpos > endpos:
289 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000290 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000291 return False
292
293 # For the rest, we only need to find the leftmost non-overlapping
294 # match for each piece. If there's no overall match that way alone,
295 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000296 for w in ws:
297 # w may be '' at times, if there are consecutive ellipses, or
298 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000299 # Search for an empty string succeeds, and doesn't change startpos.
300 startpos = got.find(w, startpos, endpos)
301 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000302 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000303 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000304
Tim Petersdc5de3b2004-08-19 14:06:20 +0000305 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000306
Edward Loper00f8da72004-08-26 18:05:07 +0000307def _comment_line(line):
308 "Return a commented form of the given line"
309 line = line.rstrip()
310 if line:
311 return '# '+line
312 else:
313 return '#'
314
Edward Loper2de91ba2004-08-27 02:07:46 +0000315class _OutputRedirectingPdb(pdb.Pdb):
316 """
317 A specialized version of the python debugger that redirects stdout
318 to a given stream when interacting with the user. Stdout is *not*
319 redirected when traced code is executed.
320 """
321 def __init__(self, out):
322 self.__out = out
Georg Brandl19564802006-05-10 17:13:20 +0000323 pdb.Pdb.__init__(self, stdout=out)
Edward Loper2de91ba2004-08-27 02:07:46 +0000324
325 def trace_dispatch(self, *args):
326 # Redirect stdout to the given stream.
327 save_stdout = sys.stdout
328 sys.stdout = self.__out
329 # Call Pdb's trace dispatch method.
Tim Petersd7bbbbc2004-11-08 22:30:28 +0000330 try:
331 return pdb.Pdb.trace_dispatch(self, *args)
332 finally:
Tim Petersd7bbbbc2004-11-08 22:30:28 +0000333 sys.stdout = save_stdout
Edward Loper2de91ba2004-08-27 02:07:46 +0000334
Edward Lopera2fc7ec2004-09-21 03:24:24 +0000335# [XX] Normalize with respect to os.path.pardir?
Edward Loper052d0cd2004-09-19 17:19:33 +0000336def _module_relative_path(module, path):
337 if not inspect.ismodule(module):
338 raise TypeError, 'Expected a module: %r' % module
339 if path.startswith('/'):
340 raise ValueError, 'Module-relative files may not have absolute paths'
341
342 # Find the base directory for the path.
343 if hasattr(module, '__file__'):
344 # A normal module/package
345 basedir = os.path.split(module.__file__)[0]
346 elif module.__name__ == '__main__':
347 # An interactive session.
348 if len(sys.argv)>0 and sys.argv[0] != '':
349 basedir = os.path.split(sys.argv[0])[0]
350 else:
351 basedir = os.curdir
352 else:
353 # A module w/o __file__ (this includes builtins)
354 raise ValueError("Can't resolve paths relative to the module " +
355 module + " (it has no __file__)")
356
357 # Combine the base directory and the path.
358 return os.path.join(basedir, *(path.split('/')))
359
Tim Peters8485b562004-08-04 18:46:34 +0000360######################################################################
361## 2. Example & DocTest
362######################################################################
363## - An "example" is a <source, want> pair, where "source" is a
364## fragment of source code, and "want" is the expected output for
365## "source." The Example class also includes information about
366## where the example was extracted from.
367##
Edward Lopera1ef6112004-08-09 16:14:41 +0000368## - A "doctest" is a collection of examples, typically extracted from
369## a string (such as an object's docstring). The DocTest class also
370## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000371
Tim Peters8485b562004-08-04 18:46:34 +0000372class Example:
373 """
374 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000375 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000376
Edward Loper74bca7a2004-08-12 02:27:44 +0000377 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000378 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000379
Edward Loper74bca7a2004-08-12 02:27:44 +0000380 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000381 from stdout, or a traceback in case of exception). `want` ends
382 with a newline unless it's empty, in which case it's an empty
383 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000384
Edward Lopera6b68322004-08-26 00:05:43 +0000385 - exc_msg: The exception message generated by the example, if
386 the example is expected to generate an exception; or `None` if
387 it is not expected to generate an exception. This exception
388 message is compared against the return value of
389 `traceback.format_exception_only()`. `exc_msg` ends with a
390 newline unless it's `None`. The constructor adds a newline
391 if needed.
392
Edward Loper74bca7a2004-08-12 02:27:44 +0000393 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000394 this Example where the Example begins. This line number is
395 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000396
397 - indent: The example's indentation in the DocTest string.
398 I.e., the number of space characters that preceed the
399 example's first prompt.
400
401 - options: A dictionary mapping from option flags to True or
402 False, which is used to override default options for this
403 example. Any option flags not contained in this dictionary
404 are left at their default value (as specified by the
405 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000406 """
Edward Lopera6b68322004-08-26 00:05:43 +0000407 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
408 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000409 # Normalize inputs.
410 if not source.endswith('\n'):
411 source += '\n'
412 if want and not want.endswith('\n'):
413 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000414 if exc_msg is not None and not exc_msg.endswith('\n'):
415 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000416 # Store properties.
417 self.source = source
418 self.want = want
419 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000420 self.indent = indent
421 if options is None: options = {}
422 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000423 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000424
Tim Peters8485b562004-08-04 18:46:34 +0000425class DocTest:
426 """
427 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000428 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000429
Tim Peters8485b562004-08-04 18:46:34 +0000430 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000431
Tim Peters8485b562004-08-04 18:46:34 +0000432 - globs: The namespace (aka globals) that the examples should
433 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000434
Tim Peters8485b562004-08-04 18:46:34 +0000435 - name: A name identifying the DocTest (typically, the name of
436 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000437
Tim Peters8485b562004-08-04 18:46:34 +0000438 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000439 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000440
Tim Peters8485b562004-08-04 18:46:34 +0000441 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000442 begins, or `None` if the line number is unavailable. This
443 line number is zero-based, with respect to the beginning of
444 the file.
445
446 - docstring: The string that the examples were extracted from,
447 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000448 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000449 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000450 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000451 Create a new DocTest containing the given examples. The
452 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000453 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000454 assert not isinstance(examples, basestring), \
455 "DocTest no longer accepts str; use DocTestParser instead"
456 self.examples = examples
457 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000458 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000459 self.name = name
460 self.filename = filename
461 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000462
463 def __repr__(self):
464 if len(self.examples) == 0:
465 examples = 'no examples'
466 elif len(self.examples) == 1:
467 examples = '1 example'
468 else:
469 examples = '%d examples' % len(self.examples)
470 return ('<DocTest %s from %s:%s (%s)>' %
471 (self.name, self.filename, self.lineno, examples))
472
473
474 # This lets us sort tests by name:
475 def __cmp__(self, other):
476 if not isinstance(other, DocTest):
477 return -1
478 return cmp((self.name, self.filename, self.lineno, id(self)),
479 (other.name, other.filename, other.lineno, id(other)))
480
481######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000482## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000483######################################################################
484
Edward Lopera1ef6112004-08-09 16:14:41 +0000485class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000486 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000487 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000488 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000489 # This regular expression is used to find doctest examples in a
490 # string. It defines three groups: `source` is the source code
491 # (including leading indentation and prompts); `indent` is the
492 # indentation of the first (PS1) line of the source code; and
493 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000494 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000495 # Source consists of a PS1 line followed by zero or more PS2 lines.
496 (?P<source>
497 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
498 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
499 \n?
500 # Want consists of any non-blank lines that do not start with PS1.
501 (?P<want> (?:(?![ ]*$) # Not a blank line
502 (?![ ]*>>>) # Not a line starting with PS1
503 .*$\n? # But any other line
504 )*)
505 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000506
Edward Lopera6b68322004-08-26 00:05:43 +0000507 # A regular expression for handling `want` strings that contain
508 # expected exceptions. It divides `want` into three pieces:
509 # - the traceback header line (`hdr`)
510 # - the traceback stack (`stack`)
511 # - the exception message (`msg`), as generated by
512 # traceback.format_exception_only()
513 # `msg` may have multiple lines. We assume/require that the
514 # exception message is the first non-indented line starting with a word
515 # character following the traceback header line.
516 _EXCEPTION_RE = re.compile(r"""
517 # Grab the traceback header. Different versions of Python have
518 # said different things on the first traceback line.
519 ^(?P<hdr> Traceback\ \(
520 (?: most\ recent\ call\ last
521 | innermost\ last
522 ) \) :
523 )
524 \s* $ # toss trailing whitespace on the header.
525 (?P<stack> .*?) # don't blink: absorb stuff until...
526 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
527 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
528
Tim Peters7ea48dd2004-08-13 01:52:59 +0000529 # A callable returning a true value iff its argument is a blank line
530 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000531 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000532
Edward Loper00f8da72004-08-26 18:05:07 +0000533 def parse(self, string, name='<string>'):
534 """
535 Divide the given string into examples and intervening text,
536 and return them as a list of alternating Examples and strings.
537 Line numbers for the Examples are 0-based. The optional
538 argument `name` is a name identifying this string, and is only
539 used for error messages.
540 """
541 string = string.expandtabs()
542 # If all lines begin with the same indentation, then strip it.
543 min_indent = self._min_indent(string)
544 if min_indent > 0:
545 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
546
547 output = []
548 charno, lineno = 0, 0
549 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000550 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000551 # Add the pre-example text to `output`.
552 output.append(string[charno:m.start()])
553 # Update lineno (lines before this example)
554 lineno += string.count('\n', charno, m.start())
555 # Extract info from the regexp match.
556 (source, options, want, exc_msg) = \
557 self._parse_example(m, name, lineno)
558 # Create an Example, and add it to the list.
559 if not self._IS_BLANK_OR_COMMENT(source):
560 output.append( Example(source, want, exc_msg,
561 lineno=lineno,
562 indent=min_indent+len(m.group('indent')),
563 options=options) )
564 # Update lineno (lines inside this example)
565 lineno += string.count('\n', m.start(), m.end())
566 # Update charno.
567 charno = m.end()
568 # Add any remaining post-example text to `output`.
569 output.append(string[charno:])
570 return output
571
Edward Lopera1ef6112004-08-09 16:14:41 +0000572 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000573 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000574 Extract all doctest examples from the given string, and
575 collect them into a `DocTest` object.
576
577 `globs`, `name`, `filename`, and `lineno` are attributes for
578 the new `DocTest` object. See the documentation for `DocTest`
579 for more information.
580 """
581 return DocTest(self.get_examples(string, name), globs,
582 name, filename, lineno, string)
583
584 def get_examples(self, string, name='<string>'):
585 """
586 Extract all doctest examples from the given string, and return
587 them as a list of `Example` objects. Line numbers are
588 0-based, because it's most common in doctests that nothing
589 interesting appears on the same line as opening triple-quote,
590 and so the first interesting line is called \"line 1\" then.
591
592 The optional argument `name` is a name identifying this
593 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000594 """
Edward Loper00f8da72004-08-26 18:05:07 +0000595 return [x for x in self.parse(string, name)
596 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000597
Edward Loper74bca7a2004-08-12 02:27:44 +0000598 def _parse_example(self, m, name, lineno):
599 """
600 Given a regular expression match from `_EXAMPLE_RE` (`m`),
601 return a pair `(source, want)`, where `source` is the matched
602 example's source code (with prompts and indentation stripped);
603 and `want` is the example's expected output (with indentation
604 stripped).
605
606 `name` is the string's name, and `lineno` is the line number
607 where the example starts; both are used for error messages.
608 """
Edward Loper7c748462004-08-09 02:06:06 +0000609 # Get the example's indentation level.
610 indent = len(m.group('indent'))
611
612 # Divide source into lines; check that they're properly
613 # indented; and then strip their indentation & prompts.
614 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000615 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000616 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000617 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000618
Tim Petersc5049152004-08-22 17:34:58 +0000619 # Divide want into lines; check that it's properly indented; and
620 # then strip the indentation. Spaces before the last newline should
621 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000622 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000623 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000624 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
625 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000626 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000627 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000628 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000629
Edward Lopera6b68322004-08-26 00:05:43 +0000630 # If `want` contains a traceback message, then extract it.
631 m = self._EXCEPTION_RE.match(want)
632 if m:
633 exc_msg = m.group('msg')
634 else:
635 exc_msg = None
636
Edward Loper00f8da72004-08-26 18:05:07 +0000637 # Extract options from the source.
638 options = self._find_options(source, name, lineno)
639
640 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000641
Edward Loper74bca7a2004-08-12 02:27:44 +0000642 # This regular expression looks for option directives in the
643 # source code of an example. Option directives are comments
644 # starting with "doctest:". Warning: this may give false
645 # positives for string-literals that contain the string
646 # "#doctest:". Eliminating these false positives would require
647 # actually parsing the string; but we limit them by ignoring any
648 # line containing "#doctest:" that is *followed* by a quote mark.
649 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
650 re.MULTILINE)
651
652 def _find_options(self, source, name, lineno):
653 """
654 Return a dictionary containing option overrides extracted from
655 option directives in the given source string.
656
657 `name` is the string's name, and `lineno` is the line number
658 where the example starts; both are used for error messages.
659 """
660 options = {}
661 # (note: with the current regexp, this will match at most once:)
662 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
663 option_strings = m.group(1).replace(',', ' ').split()
664 for option in option_strings:
665 if (option[0] not in '+-' or
666 option[1:] not in OPTIONFLAGS_BY_NAME):
667 raise ValueError('line %r of the doctest for %s '
668 'has an invalid option: %r' %
669 (lineno+1, name, option))
670 flag = OPTIONFLAGS_BY_NAME[option[1:]]
671 options[flag] = (option[0] == '+')
672 if options and self._IS_BLANK_OR_COMMENT(source):
673 raise ValueError('line %r of the doctest for %s has an option '
674 'directive on a line with no example: %r' %
675 (lineno, name, source))
676 return options
677
Edward Lopera5db6002004-08-12 02:41:30 +0000678 # This regular expression finds the indentation of every non-blank
679 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000680 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000681
682 def _min_indent(self, s):
683 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000684 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
685 if len(indents) > 0:
686 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000687 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000688 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000689
Edward Lopera1ef6112004-08-09 16:14:41 +0000690 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000691 """
692 Given the lines of a source string (including prompts and
693 leading indentation), check to make sure that every prompt is
694 followed by a space character. If any line is not followed by
695 a space character, then raise ValueError.
696 """
Edward Loper7c748462004-08-09 02:06:06 +0000697 for i, line in enumerate(lines):
698 if len(line) >= indent+4 and line[indent+3] != ' ':
699 raise ValueError('line %r of the docstring for %s '
700 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000701 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000702 line[indent:indent+3], line))
703
Edward Lopera1ef6112004-08-09 16:14:41 +0000704 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000705 """
706 Check that every line in the given list starts with the given
707 prefix; if any line does not, then raise a ValueError.
708 """
Edward Loper7c748462004-08-09 02:06:06 +0000709 for i, line in enumerate(lines):
710 if line and not line.startswith(prefix):
711 raise ValueError('line %r of the docstring for %s has '
712 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000713 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000714
715
716######################################################################
717## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000718######################################################################
719
720class DocTestFinder:
721 """
722 A class used to extract the DocTests that are relevant to a given
723 object, from its docstring and the docstrings of its contained
724 objects. Doctests can currently be extracted from the following
725 object types: modules, functions, classes, methods, staticmethods,
726 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000727 """
728
Edward Lopera1ef6112004-08-09 16:14:41 +0000729 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersbf0400a2006-06-05 01:43:03 +0000730 recurse=True, exclude_empty=True):
Tim Peters8485b562004-08-04 18:46:34 +0000731 """
732 Create a new doctest finder.
733
Edward Lopera1ef6112004-08-09 16:14:41 +0000734 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000735 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000736 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000737 signature for this factory function should match the signature
738 of the DocTest constructor.
739
Tim Peters8485b562004-08-04 18:46:34 +0000740 If the optional argument `recurse` is false, then `find` will
741 only examine the given object, and not any contained objects.
Edward Loper32ddbf72004-09-13 05:47:24 +0000742
Tim Peters958cc892004-09-13 14:53:28 +0000743 If the optional argument `exclude_empty` is false, then `find`
744 will include tests for objects with empty docstrings.
Tim Peters8485b562004-08-04 18:46:34 +0000745 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000746 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000747 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000748 self._recurse = recurse
Edward Loper32ddbf72004-09-13 05:47:24 +0000749 self._exclude_empty = exclude_empty
Tim Peters8485b562004-08-04 18:46:34 +0000750
Tim Petersbf0400a2006-06-05 01:43:03 +0000751 def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000752 """
753 Return a list of the DocTests that are defined by the given
754 object's docstring, or by any of its contained objects'
755 docstrings.
756
757 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000758 the given object. If the module is not specified or is None, then
759 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000760 correct module. The object's module is used:
761
762 - As a default namespace, if `globs` is not specified.
763 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000764 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000765 - To find the name of the file containing the object.
766 - To help find the line number of the object within its
767 file.
768
Tim Petersf3f57472004-08-08 06:11:48 +0000769 Contained objects whose module does not match `module` are ignored.
770
771 If `module` is False, no attempt to find the module will be made.
772 This is obscure, of use mostly in tests: if `module` is False, or
773 is None but cannot be found automatically, then all objects are
774 considered to belong to the (non-existent) module, so all contained
775 objects will (recursively) be searched for doctests.
776
Tim Peters8485b562004-08-04 18:46:34 +0000777 The globals for each DocTest is formed by combining `globs`
778 and `extraglobs` (bindings in `extraglobs` override bindings
779 in `globs`). A new copy of the globals dictionary is created
780 for each DocTest. If `globs` is not specified, then it
781 defaults to the module's `__dict__`, if specified, or {}
782 otherwise. If `extraglobs` is not specified, then it defaults
783 to {}.
784
Tim Peters8485b562004-08-04 18:46:34 +0000785 """
786 # If name was not specified, then extract it from the object.
787 if name is None:
788 name = getattr(obj, '__name__', None)
789 if name is None:
790 raise ValueError("DocTestFinder.find: name must be given "
791 "when obj.__name__ doesn't exist: %r" %
792 (type(obj),))
793
794 # Find the module that contains the given object (if obj is
795 # a module, then module=obj.). Note: this may fail, in which
796 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000797 if module is False:
798 module = None
799 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000800 module = inspect.getmodule(obj)
801
802 # Read the module's source code. This is used by
803 # DocTestFinder._find_lineno to find the line number for a
804 # given object's docstring.
805 try:
806 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
807 source_lines = linecache.getlines(file)
808 if not source_lines:
809 source_lines = None
810 except TypeError:
811 source_lines = None
812
813 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000814 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000815 if module is None:
816 globs = {}
817 else:
818 globs = module.__dict__.copy()
819 else:
820 globs = globs.copy()
821 if extraglobs is not None:
822 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000823
Tim Peters8485b562004-08-04 18:46:34 +0000824 # Recursively expore `obj`, extracting DocTests.
825 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000826 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters6f681472006-07-27 23:44:37 +0000827 # Sort the tests by alpha order of names, for consistency in
828 # verbose-mode output. This was a feature of doctest in Pythons
829 # <= 2.3 that got lost by accident in 2.4. It was repaired in
830 # 2.4.4 and 2.5.
831 tests.sort()
Tim Peters8485b562004-08-04 18:46:34 +0000832 return tests
833
Tim Peters8485b562004-08-04 18:46:34 +0000834 def _from_module(self, module, object):
835 """
836 Return true if the given object is defined in the given
837 module.
838 """
839 if module is None:
840 return True
841 elif inspect.isfunction(object):
842 return module.__dict__ is object.func_globals
843 elif inspect.isclass(object):
844 return module.__name__ == object.__module__
845 elif inspect.getmodule(object) is not None:
846 return module is inspect.getmodule(object)
847 elif hasattr(object, '__module__'):
848 return module.__name__ == object.__module__
849 elif isinstance(object, property):
850 return True # [XX] no way not be sure.
851 else:
852 raise ValueError("object must be a class or function")
853
Tim Petersf3f57472004-08-08 06:11:48 +0000854 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000855 """
856 Find tests for the given object and any contained objects, and
857 add them to `tests`.
858 """
859 if self._verbose:
860 print 'Finding tests in %s' % name
861
862 # If we've already processed this object, then ignore it.
863 if id(obj) in seen:
864 return
865 seen[id(obj)] = 1
866
867 # Find a test for this object, and add it to the list of tests.
868 test = self._get_test(obj, name, module, globs, source_lines)
869 if test is not None:
870 tests.append(test)
871
872 # Look for tests in a module's contained objects.
873 if inspect.ismodule(obj) and self._recurse:
874 for valname, val in obj.__dict__.items():
Tim Peters8485b562004-08-04 18:46:34 +0000875 valname = '%s.%s' % (name, valname)
876 # Recurse to functions & classes.
877 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000878 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000879 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000880 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000881
882 # Look for tests in a module's __test__ dictionary.
883 if inspect.ismodule(obj) and self._recurse:
884 for valname, val in getattr(obj, '__test__', {}).items():
885 if not isinstance(valname, basestring):
886 raise ValueError("DocTestFinder.find: __test__ keys "
887 "must be strings: %r" %
888 (type(valname),))
889 if not (inspect.isfunction(val) or inspect.isclass(val) or
890 inspect.ismethod(val) or inspect.ismodule(val) or
891 isinstance(val, basestring)):
892 raise ValueError("DocTestFinder.find: __test__ values "
893 "must be strings, functions, methods, "
894 "classes, or modules: %r" %
895 (type(val),))
Tim Petersc5684782004-09-13 01:07:12 +0000896 valname = '%s.__test__.%s' % (name, valname)
Tim Peters8485b562004-08-04 18:46:34 +0000897 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000898 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000899
900 # Look for tests in a class's contained objects.
901 if inspect.isclass(obj) and self._recurse:
902 for valname, val in obj.__dict__.items():
Tim Peters8485b562004-08-04 18:46:34 +0000903 # Special handling for staticmethod/classmethod.
904 if isinstance(val, staticmethod):
905 val = getattr(obj, valname)
906 if isinstance(val, classmethod):
907 val = getattr(obj, valname).im_func
908
909 # Recurse to methods, properties, and nested classes.
910 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000911 isinstance(val, property)) and
912 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000913 valname = '%s.%s' % (name, valname)
914 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000915 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000916
917 def _get_test(self, obj, name, module, globs, source_lines):
918 """
919 Return a DocTest for the given object, if it defines a docstring;
920 otherwise, return None.
921 """
922 # Extract the object's docstring. If it doesn't have one,
923 # then return None (no test for this object).
924 if isinstance(obj, basestring):
925 docstring = obj
926 else:
927 try:
928 if obj.__doc__ is None:
Edward Loper32ddbf72004-09-13 05:47:24 +0000929 docstring = ''
930 else:
Jim Fulton7d428782004-10-13 14:15:32 +0000931 docstring = obj.__doc__
932 if not isinstance(docstring, basestring):
933 docstring = str(docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000934 except (TypeError, AttributeError):
Edward Loper32ddbf72004-09-13 05:47:24 +0000935 docstring = ''
Tim Peters8485b562004-08-04 18:46:34 +0000936
937 # Find the docstring's location in the file.
938 lineno = self._find_lineno(obj, source_lines)
939
Edward Loper32ddbf72004-09-13 05:47:24 +0000940 # Don't bother if the docstring is empty.
941 if self._exclude_empty and not docstring:
942 return None
943
Tim Peters8485b562004-08-04 18:46:34 +0000944 # Return a DocTest for this object.
945 if module is None:
946 filename = None
947 else:
948 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +0000949 if filename[-4:] in (".pyc", ".pyo"):
950 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +0000951 return self._parser.get_doctest(docstring, globs, name,
952 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000953
954 def _find_lineno(self, obj, source_lines):
955 """
956 Return a line number of the given object's docstring. Note:
957 this method assumes that the object has a docstring.
958 """
959 lineno = None
960
961 # Find the line number for modules.
962 if inspect.ismodule(obj):
963 lineno = 0
964
965 # Find the line number for classes.
966 # Note: this could be fooled if a class is defined multiple
967 # times in a single file.
968 if inspect.isclass(obj):
969 if source_lines is None:
970 return None
971 pat = re.compile(r'^\s*class\s*%s\b' %
972 getattr(obj, '__name__', '-'))
973 for i, line in enumerate(source_lines):
974 if pat.match(line):
975 lineno = i
976 break
977
978 # Find the line number for functions & methods.
979 if inspect.ismethod(obj): obj = obj.im_func
980 if inspect.isfunction(obj): obj = obj.func_code
981 if inspect.istraceback(obj): obj = obj.tb_frame
982 if inspect.isframe(obj): obj = obj.f_code
983 if inspect.iscode(obj):
984 lineno = getattr(obj, 'co_firstlineno', None)-1
985
986 # Find the line number where the docstring starts. Assume
987 # that it's the first line that begins with a quote mark.
988 # Note: this could be fooled by a multiline function
989 # signature, where a continuation line begins with a quote
990 # mark.
991 if lineno is not None:
992 if source_lines is None:
993 return lineno+1
994 pat = re.compile('(^|.*:)\s*\w*("|\')')
995 for lineno in range(lineno, len(source_lines)):
996 if pat.match(source_lines[lineno]):
997 return lineno
998
999 # We couldn't find the line number.
1000 return None
1001
1002######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001003## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001004######################################################################
1005
Tim Peters8485b562004-08-04 18:46:34 +00001006class DocTestRunner:
1007 """
1008 A class used to run DocTest test cases, and accumulate statistics.
1009 The `run` method is used to process a single DocTest case. It
1010 returns a tuple `(f, t)`, where `t` is the number of test cases
1011 tried, and `f` is the number of test cases that failed.
1012
1013 >>> tests = DocTestFinder().find(_TestClass)
1014 >>> runner = DocTestRunner(verbose=False)
Armin Rigoa3f09272006-05-28 19:13:17 +00001015 >>> tests.sort(key = lambda test: test.name)
Tim Peters8485b562004-08-04 18:46:34 +00001016 >>> for test in tests:
Armin Rigoa3f09272006-05-28 19:13:17 +00001017 ... print test.name, '->', runner.run(test)
1018 _TestClass -> (0, 2)
1019 _TestClass.__init__ -> (0, 2)
1020 _TestClass.get -> (0, 2)
1021 _TestClass.square -> (0, 1)
Tim Peters8485b562004-08-04 18:46:34 +00001022
1023 The `summarize` method prints a summary of all the test cases that
1024 have been run by the runner, and returns an aggregated `(f, t)`
1025 tuple:
1026
1027 >>> runner.summarize(verbose=1)
1028 4 items passed all tests:
1029 2 tests in _TestClass
1030 2 tests in _TestClass.__init__
1031 2 tests in _TestClass.get
1032 1 tests in _TestClass.square
1033 7 tests in 4 items.
1034 7 passed and 0 failed.
1035 Test passed.
1036 (0, 7)
1037
1038 The aggregated number of tried examples and failed examples is
1039 also available via the `tries` and `failures` attributes:
1040
1041 >>> runner.tries
1042 7
1043 >>> runner.failures
1044 0
1045
1046 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001047 by an `OutputChecker`. This comparison may be customized with a
1048 number of option flags; see the documentation for `testmod` for
1049 more information. If the option flags are insufficient, then the
1050 comparison may also be customized by passing a subclass of
1051 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001052
1053 The test runner's display output can be controlled in two ways.
1054 First, an output function (`out) can be passed to
1055 `TestRunner.run`; this function will be called with strings that
1056 should be displayed. It defaults to `sys.stdout.write`. If
1057 capturing the output is not sufficient, then the display output
1058 can be also customized by subclassing DocTestRunner, and
1059 overriding the methods `report_start`, `report_success`,
1060 `report_unexpected_exception`, and `report_failure`.
1061 """
1062 # This divider string is used to separate failure messages, and to
1063 # separate sections of the summary.
1064 DIVIDER = "*" * 70
1065
Edward Loper34fcb142004-08-09 02:45:41 +00001066 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001067 """
1068 Create a new test runner.
1069
Edward Loper34fcb142004-08-09 02:45:41 +00001070 Optional keyword arg `checker` is the `OutputChecker` that
1071 should be used to compare the expected outputs and actual
1072 outputs of doctest examples.
1073
Tim Peters8485b562004-08-04 18:46:34 +00001074 Optional keyword arg 'verbose' prints lots of stuff if true,
1075 only failures if false; by default, it's true iff '-v' is in
1076 sys.argv.
1077
1078 Optional argument `optionflags` can be used to control how the
1079 test runner compares expected output to actual output, and how
1080 it displays failures. See the documentation for `testmod` for
1081 more information.
1082 """
Edward Loper34fcb142004-08-09 02:45:41 +00001083 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001084 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001085 verbose = '-v' in sys.argv
1086 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001087 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001088 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001089
Tim Peters8485b562004-08-04 18:46:34 +00001090 # Keep track of the examples we've run.
1091 self.tries = 0
1092 self.failures = 0
1093 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001094
Tim Peters8485b562004-08-04 18:46:34 +00001095 # Create a fake output target for capturing doctest output.
1096 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001097
Tim Peters8485b562004-08-04 18:46:34 +00001098 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001099 # Reporting methods
1100 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001101
Tim Peters8485b562004-08-04 18:46:34 +00001102 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001103 """
Tim Peters8485b562004-08-04 18:46:34 +00001104 Report that the test runner is about to process the given
1105 example. (Only displays a message if verbose=True)
1106 """
1107 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001108 if example.want:
1109 out('Trying:\n' + _indent(example.source) +
1110 'Expecting:\n' + _indent(example.want))
1111 else:
1112 out('Trying:\n' + _indent(example.source) +
1113 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001114
Tim Peters8485b562004-08-04 18:46:34 +00001115 def report_success(self, out, test, example, got):
1116 """
1117 Report that the given example ran successfully. (Only
1118 displays a message if verbose=True)
1119 """
1120 if self._verbose:
1121 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001122
Tim Peters8485b562004-08-04 18:46:34 +00001123 def report_failure(self, out, test, example, got):
1124 """
1125 Report that the given example failed.
1126 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001127 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001128 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001129
Tim Peters8485b562004-08-04 18:46:34 +00001130 def report_unexpected_exception(self, out, test, example, exc_info):
1131 """
1132 Report that the given example raised an unexpected exception.
1133 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001134 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001135 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001136
Edward Loper8e4a34b2004-08-12 02:34:27 +00001137 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001138 out = [self.DIVIDER]
1139 if test.filename:
1140 if test.lineno is not None and example.lineno is not None:
1141 lineno = test.lineno + example.lineno + 1
1142 else:
1143 lineno = '?'
1144 out.append('File "%s", line %s, in %s' %
1145 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001146 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001147 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1148 out.append('Failed example:')
1149 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001150 out.append(_indent(source))
1151 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001152
Tim Peters8485b562004-08-04 18:46:34 +00001153 #/////////////////////////////////////////////////////////////////
1154 # DocTest Running
1155 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001156
Tim Peters8485b562004-08-04 18:46:34 +00001157 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001158 """
Tim Peters8485b562004-08-04 18:46:34 +00001159 Run the examples in `test`. Write the outcome of each example
1160 with one of the `DocTestRunner.report_*` methods, using the
1161 writer function `out`. `compileflags` is the set of compiler
1162 flags that should be used to execute examples. Return a tuple
1163 `(f, t)`, where `t` is the number of examples tried, and `f`
1164 is the number of examples that failed. The examples are run
1165 in the namespace `test.globs`.
1166 """
1167 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001168 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001169
1170 # Save the option flags (since option directives can be used
1171 # to modify them).
1172 original_optionflags = self.optionflags
1173
Tim Peters1fbf9c52004-09-04 17:21:02 +00001174 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1175
1176 check = self._checker.check_output
1177
Tim Peters8485b562004-08-04 18:46:34 +00001178 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001179 for examplenum, example in enumerate(test.examples):
1180
Edward Lopera89f88d2004-08-26 02:45:51 +00001181 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1182 # reporting after the first failure.
1183 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1184 failures > 0)
1185
Edward Loper74bca7a2004-08-12 02:27:44 +00001186 # Merge in the example's options.
1187 self.optionflags = original_optionflags
1188 if example.options:
1189 for (optionflag, val) in example.options.items():
1190 if val:
1191 self.optionflags |= optionflag
1192 else:
1193 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001194
Tim Peters711bf302006-04-25 03:31:36 +00001195 # If 'SKIP' is set, then skip this example.
1196 if self.optionflags & SKIP:
1197 continue
1198
Tim Peters8485b562004-08-04 18:46:34 +00001199 # Record that we started this example.
1200 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001201 if not quiet:
1202 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001203
Edward Loper2de91ba2004-08-27 02:07:46 +00001204 # Use a special filename for compile(), so we can retrieve
1205 # the source code during interactive debugging (see
1206 # __patched_linecache_getlines).
1207 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1208
Tim Peters8485b562004-08-04 18:46:34 +00001209 # Run the example in the given context (globs), and record
1210 # any exception that gets raised. (But don't intercept
1211 # keyboard interrupts.)
1212 try:
Tim Peters208ca702004-08-09 04:12:36 +00001213 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001214 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001215 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001216 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001217 exception = None
1218 except KeyboardInterrupt:
1219 raise
1220 except:
1221 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001222 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001223
Tim Peters208ca702004-08-09 04:12:36 +00001224 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001225 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001226 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001227
1228 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001229 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001230 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001231 if check(example.want, got, self.optionflags):
1232 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001233
Tim Peters1fbf9c52004-09-04 17:21:02 +00001234 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001235 else:
1236 exc_info = sys.exc_info()
1237 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001238 if not quiet:
1239 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001240
Tim Peters1fbf9c52004-09-04 17:21:02 +00001241 # If `example.exc_msg` is None, then we weren't expecting
1242 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001243 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001244 outcome = BOOM
1245
1246 # We expected an exception: see whether it matches.
1247 elif check(example.exc_msg, exc_msg, self.optionflags):
1248 outcome = SUCCESS
1249
1250 # Another chance if they didn't care about the detail.
1251 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1252 m1 = re.match(r'[^:]*:', example.exc_msg)
1253 m2 = re.match(r'[^:]*:', exc_msg)
1254 if m1 and m2 and check(m1.group(0), m2.group(0),
1255 self.optionflags):
1256 outcome = SUCCESS
1257
1258 # Report the outcome.
1259 if outcome is SUCCESS:
1260 if not quiet:
1261 self.report_success(out, test, example, got)
1262 elif outcome is FAILURE:
1263 if not quiet:
1264 self.report_failure(out, test, example, got)
1265 failures += 1
1266 elif outcome is BOOM:
1267 if not quiet:
1268 self.report_unexpected_exception(out, test, example,
1269 exc_info)
1270 failures += 1
1271 else:
1272 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001273
1274 # Restore the option flags (in case they were modified)
1275 self.optionflags = original_optionflags
1276
1277 # Record and return the number of failures and tries.
1278 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001279 return failures, tries
1280
Tim Peters8485b562004-08-04 18:46:34 +00001281 def __record_outcome(self, test, f, t):
1282 """
1283 Record the fact that the given DocTest (`test`) generated `f`
1284 failures out of `t` tried examples.
1285 """
1286 f2, t2 = self._name2ft.get(test.name, (0,0))
1287 self._name2ft[test.name] = (f+f2, t+t2)
1288 self.failures += f
1289 self.tries += t
1290
Edward Loper2de91ba2004-08-27 02:07:46 +00001291 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1292 r'(?P<name>[\w\.]+)'
1293 r'\[(?P<examplenum>\d+)\]>$')
Phillip J. Eby47032112006-04-11 01:07:43 +00001294 def __patched_linecache_getlines(self, filename, module_globals=None):
Edward Loper2de91ba2004-08-27 02:07:46 +00001295 m = self.__LINECACHE_FILENAME_RE.match(filename)
1296 if m and m.group('name') == self.test.name:
1297 example = self.test.examples[int(m.group('examplenum'))]
1298 return example.source.splitlines(True)
1299 else:
Phillip J. Eby47032112006-04-11 01:07:43 +00001300 return self.save_linecache_getlines(filename, module_globals)
Edward Loper2de91ba2004-08-27 02:07:46 +00001301
Tim Peters8485b562004-08-04 18:46:34 +00001302 def run(self, test, compileflags=None, out=None, clear_globs=True):
1303 """
1304 Run the examples in `test`, and display the results using the
1305 writer function `out`.
1306
1307 The examples are run in the namespace `test.globs`. If
1308 `clear_globs` is true (the default), then this namespace will
1309 be cleared after the test runs, to help with garbage
1310 collection. If you would like to examine the namespace after
1311 the test completes, then use `clear_globs=False`.
1312
1313 `compileflags` gives the set of flags that should be used by
1314 the Python compiler when running the examples. If not
1315 specified, then it will default to the set of future-import
1316 flags that apply to `globs`.
1317
1318 The output of each example is checked using
1319 `DocTestRunner.check_output`, and the results are formatted by
1320 the `DocTestRunner.report_*` methods.
1321 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001322 self.test = test
1323
Tim Peters8485b562004-08-04 18:46:34 +00001324 if compileflags is None:
1325 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001326
Tim Peters6c542b72004-08-09 16:43:36 +00001327 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001328 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001329 out = save_stdout.write
1330 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001331
Edward Loper2de91ba2004-08-27 02:07:46 +00001332 # Patch pdb.set_trace to restore sys.stdout during interactive
1333 # debugging (so it's not still redirected to self._fakeout).
1334 # Note that the interactive output will go to *our*
1335 # save_stdout, even if that's not the real sys.stdout; this
1336 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001337 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001338 self.debugger = _OutputRedirectingPdb(save_stdout)
1339 self.debugger.reset()
1340 pdb.set_trace = self.debugger.set_trace
1341
1342 # Patch linecache.getlines, so we can see the example's source
1343 # when we're inside the debugger.
1344 self.save_linecache_getlines = linecache.getlines
1345 linecache.getlines = self.__patched_linecache_getlines
1346
Tim Peters8485b562004-08-04 18:46:34 +00001347 try:
Tim Peters8485b562004-08-04 18:46:34 +00001348 return self.__run(test, compileflags, out)
1349 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001350 sys.stdout = save_stdout
1351 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001352 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001353 if clear_globs:
1354 test.globs.clear()
1355
1356 #/////////////////////////////////////////////////////////////////
1357 # Summarization
1358 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001359 def summarize(self, verbose=None):
1360 """
Tim Peters8485b562004-08-04 18:46:34 +00001361 Print a summary of all the test cases that have been run by
1362 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1363 the total number of failed examples, and `t` is the total
1364 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001365
Tim Peters8485b562004-08-04 18:46:34 +00001366 The optional `verbose` argument controls how detailed the
1367 summary is. If the verbosity is not specified, then the
1368 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001369 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001370 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001371 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001372 notests = []
1373 passed = []
1374 failed = []
1375 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001376 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001377 name, (f, t) = x
1378 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001379 totalt += t
1380 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001381 if t == 0:
1382 notests.append(name)
1383 elif f == 0:
1384 passed.append( (name, t) )
1385 else:
1386 failed.append(x)
1387 if verbose:
1388 if notests:
1389 print len(notests), "items had no tests:"
1390 notests.sort()
1391 for thing in notests:
1392 print " ", thing
1393 if passed:
1394 print len(passed), "items passed all tests:"
1395 passed.sort()
1396 for thing, count in passed:
1397 print " %3d tests in %s" % (count, thing)
1398 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001399 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001400 print len(failed), "items had failures:"
1401 failed.sort()
1402 for thing, (f, t) in failed:
1403 print " %3d of %3d in %s" % (f, t, thing)
1404 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001405 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001406 print totalt - totalf, "passed and", totalf, "failed."
1407 if totalf:
1408 print "***Test Failed***", totalf, "failures."
1409 elif verbose:
1410 print "Test passed."
1411 return totalf, totalt
1412
Tim Peters82076ef2004-09-13 00:52:51 +00001413 #/////////////////////////////////////////////////////////////////
1414 # Backward compatibility cruft to maintain doctest.master.
1415 #/////////////////////////////////////////////////////////////////
1416 def merge(self, other):
1417 d = self._name2ft
1418 for name, (f, t) in other._name2ft.items():
1419 if name in d:
1420 print "*** DocTestRunner.merge: '" + name + "' in both" \
1421 " testers; summing outcomes."
1422 f2, t2 = d[name]
1423 f = f + f2
1424 t = t + t2
1425 d[name] = f, t
1426
Edward Loper34fcb142004-08-09 02:45:41 +00001427class OutputChecker:
1428 """
1429 A class used to check the whether the actual output from a doctest
1430 example matches the expected output. `OutputChecker` defines two
1431 methods: `check_output`, which compares a given pair of outputs,
1432 and returns true if they match; and `output_difference`, which
1433 returns a string describing the differences between two outputs.
1434 """
1435 def check_output(self, want, got, optionflags):
1436 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001437 Return True iff the actual output from an example (`got`)
1438 matches the expected output (`want`). These strings are
1439 always considered to match if they are identical; but
1440 depending on what option flags the test runner is using,
1441 several non-exact match types are also possible. See the
1442 documentation for `TestRunner` for more information about
1443 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001444 """
1445 # Handle the common case first, for efficiency:
1446 # if they're string-identical, always return true.
1447 if got == want:
1448 return True
1449
1450 # The values True and False replaced 1 and 0 as the return
1451 # value for boolean comparisons in Python 2.3.
1452 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1453 if (got,want) == ("True\n", "1\n"):
1454 return True
1455 if (got,want) == ("False\n", "0\n"):
1456 return True
1457
1458 # <BLANKLINE> can be used as a special sequence to signify a
1459 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1460 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1461 # Replace <BLANKLINE> in want with a blank line.
1462 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1463 '', want)
1464 # If a line in got contains only spaces, then remove the
1465 # spaces.
1466 got = re.sub('(?m)^\s*?$', '', got)
1467 if got == want:
1468 return True
1469
1470 # This flag causes doctest to ignore any differences in the
1471 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001472 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001473 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001474 got = ' '.join(got.split())
1475 want = ' '.join(want.split())
1476 if got == want:
1477 return True
1478
1479 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001480 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001481 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001482 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001483 return True
1484
1485 # We didn't find any match; return false.
1486 return False
1487
Tim Petersc6cbab02004-08-22 19:43:28 +00001488 # Should we do a fancy diff?
1489 def _do_a_fancy_diff(self, want, got, optionflags):
1490 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001491 if not optionflags & (REPORT_UDIFF |
1492 REPORT_CDIFF |
1493 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001494 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001495
Tim Petersc6cbab02004-08-22 19:43:28 +00001496 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001497 # too hard ... or maybe not. In two real-life failures Tim saw,
1498 # a diff was a major help anyway, so this is commented out.
1499 # [todo] _ellipsis_match() knows which pieces do and don't match,
1500 # and could be the basis for a kick-ass diff in this case.
1501 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1502 ## return False
1503
Tim Petersc6cbab02004-08-22 19:43:28 +00001504 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001505 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001506 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001507 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001508
Tim Petersc6cbab02004-08-22 19:43:28 +00001509 # The other diff types need at least a few lines to be helpful.
1510 return want.count('\n') > 2 and got.count('\n') > 2
1511
Edward Loperca9111e2004-08-26 03:00:24 +00001512 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001513 """
1514 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001515 expected output for a given example (`example`) and the actual
1516 output (`got`). `optionflags` is the set of option flags used
1517 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001518 """
Edward Loperca9111e2004-08-26 03:00:24 +00001519 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001520 # If <BLANKLINE>s are being used, then replace blank lines
1521 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001522 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001523 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001524
Tim Peters5b799c12004-08-26 05:21:59 +00001525 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001526 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001527 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001528 want_lines = want.splitlines(True) # True == keep line ends
1529 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001530 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001531 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001532 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1533 diff = list(diff)[2:] # strip the diff header
1534 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001535 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001536 diff = difflib.context_diff(want_lines, got_lines, n=2)
1537 diff = list(diff)[2:] # strip the diff header
1538 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001539 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001540 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1541 diff = list(engine.compare(want_lines, got_lines))
1542 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001543 else:
1544 assert 0, 'Bad diff option'
1545 # Remove trailing whitespace on diff output.
1546 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001547 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001548
1549 # If we're not using diff, then simply list the expected
1550 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001551 if want and got:
1552 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1553 elif want:
1554 return 'Expected:\n%sGot nothing\n' % _indent(want)
1555 elif got:
1556 return 'Expected nothing\nGot:\n%s' % _indent(got)
1557 else:
1558 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001559
Tim Peters19397e52004-08-06 22:02:59 +00001560class DocTestFailure(Exception):
1561 """A DocTest example has failed in debugging mode.
1562
1563 The exception instance has variables:
1564
1565 - test: the DocTest object being run
1566
Neal Norwitz8bd1c0d2006-09-03 20:01:05 +00001567 - example: the Example object that failed
Tim Peters19397e52004-08-06 22:02:59 +00001568
1569 - got: the actual output
1570 """
1571 def __init__(self, test, example, got):
1572 self.test = test
1573 self.example = example
1574 self.got = got
1575
1576 def __str__(self):
1577 return str(self.test)
1578
1579class UnexpectedException(Exception):
1580 """A DocTest example has encountered an unexpected exception
1581
1582 The exception instance has variables:
1583
1584 - test: the DocTest object being run
1585
Neal Norwitz8bd1c0d2006-09-03 20:01:05 +00001586 - example: the Example object that failed
Tim Peters19397e52004-08-06 22:02:59 +00001587
1588 - exc_info: the exception info
1589 """
1590 def __init__(self, test, example, exc_info):
1591 self.test = test
1592 self.example = example
1593 self.exc_info = exc_info
1594
1595 def __str__(self):
1596 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001597
Tim Peters19397e52004-08-06 22:02:59 +00001598class DebugRunner(DocTestRunner):
1599 r"""Run doc tests but raise an exception as soon as there is a failure.
1600
1601 If an unexpected exception occurs, an UnexpectedException is raised.
1602 It contains the test, the example, and the original exception:
1603
1604 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001605 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1606 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001607 >>> try:
1608 ... runner.run(test)
1609 ... except UnexpectedException, failure:
1610 ... pass
1611
1612 >>> failure.test is test
1613 True
1614
1615 >>> failure.example.want
1616 '42\n'
1617
1618 >>> exc_info = failure.exc_info
1619 >>> raise exc_info[0], exc_info[1], exc_info[2]
1620 Traceback (most recent call last):
1621 ...
1622 KeyError
1623
1624 We wrap the original exception to give the calling application
1625 access to the test and example information.
1626
1627 If the output doesn't match, then a DocTestFailure is raised:
1628
Edward Lopera1ef6112004-08-09 16:14:41 +00001629 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001630 ... >>> x = 1
1631 ... >>> x
1632 ... 2
1633 ... ''', {}, 'foo', 'foo.py', 0)
1634
1635 >>> try:
1636 ... runner.run(test)
1637 ... except DocTestFailure, failure:
1638 ... pass
1639
1640 DocTestFailure objects provide access to the test:
1641
1642 >>> failure.test is test
1643 True
1644
1645 As well as to the example:
1646
1647 >>> failure.example.want
1648 '2\n'
1649
1650 and the actual output:
1651
1652 >>> failure.got
1653 '1\n'
1654
1655 If a failure or error occurs, the globals are left intact:
1656
1657 >>> del test.globs['__builtins__']
1658 >>> test.globs
1659 {'x': 1}
1660
Edward Lopera1ef6112004-08-09 16:14:41 +00001661 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001662 ... >>> x = 2
1663 ... >>> raise KeyError
1664 ... ''', {}, 'foo', 'foo.py', 0)
1665
1666 >>> runner.run(test)
1667 Traceback (most recent call last):
1668 ...
1669 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001670
Tim Peters19397e52004-08-06 22:02:59 +00001671 >>> del test.globs['__builtins__']
1672 >>> test.globs
1673 {'x': 2}
1674
1675 But the globals are cleared if there is no error:
1676
Edward Lopera1ef6112004-08-09 16:14:41 +00001677 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001678 ... >>> x = 2
1679 ... ''', {}, 'foo', 'foo.py', 0)
1680
1681 >>> runner.run(test)
1682 (0, 1)
1683
1684 >>> test.globs
1685 {}
1686
1687 """
1688
1689 def run(self, test, compileflags=None, out=None, clear_globs=True):
1690 r = DocTestRunner.run(self, test, compileflags, out, False)
1691 if clear_globs:
1692 test.globs.clear()
1693 return r
1694
1695 def report_unexpected_exception(self, out, test, example, exc_info):
1696 raise UnexpectedException(test, example, exc_info)
1697
1698 def report_failure(self, out, test, example, got):
1699 raise DocTestFailure(test, example, got)
1700
Tim Peters8485b562004-08-04 18:46:34 +00001701######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001702## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001703######################################################################
1704# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001705
Tim Peters82076ef2004-09-13 00:52:51 +00001706# For backward compatibility, a global instance of a DocTestRunner
1707# class, updated by testmod.
1708master = None
1709
Tim Petersbf0400a2006-06-05 01:43:03 +00001710def testmod(m=None, name=None, globs=None, verbose=None,
Tim Peters19397e52004-08-06 22:02:59 +00001711 report=True, optionflags=0, extraglobs=None,
Tim Peters958cc892004-09-13 14:53:28 +00001712 raise_on_error=False, exclude_empty=False):
Tim Petersbf0400a2006-06-05 01:43:03 +00001713 """m=None, name=None, globs=None, verbose=None, report=True,
1714 optionflags=0, extraglobs=None, raise_on_error=False,
Tim Peters958cc892004-09-13 14:53:28 +00001715 exclude_empty=False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001716
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001717 Test examples in docstrings in functions and classes reachable
1718 from module m (or the current module if m is not supplied), starting
Tim Petersbf0400a2006-06-05 01:43:03 +00001719 with m.__doc__.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001720
1721 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001722 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001723 function and class docstrings are tested even if the name is private;
1724 strings are tested directly, as if they were docstrings.
1725
1726 Return (#failures, #tests).
1727
1728 See doctest.__doc__ for an overview.
1729
1730 Optional keyword arg "name" gives the name of the module; by default
1731 use m.__name__.
1732
1733 Optional keyword arg "globs" gives a dict to be used as the globals
1734 when executing examples; by default, use m.__dict__. A copy of this
1735 dict is actually used for each docstring, so that each docstring's
1736 examples start with a clean slate.
1737
Tim Peters8485b562004-08-04 18:46:34 +00001738 Optional keyword arg "extraglobs" gives a dictionary that should be
1739 merged into the globals that are used to execute examples. By
1740 default, no extra globals are used. This is new in 2.4.
1741
Tim Peters8a7d2d52001-01-16 07:10:57 +00001742 Optional keyword arg "verbose" prints lots of stuff if true, prints
1743 only failures if false; by default, it's true iff "-v" is in sys.argv.
1744
Tim Peters8a7d2d52001-01-16 07:10:57 +00001745 Optional keyword arg "report" prints a summary at the end when true,
1746 else prints nothing at the end. In verbose mode, the summary is
1747 detailed, else very brief (in fact, empty if all tests passed).
1748
Tim Peters6ebe61f2003-06-27 20:48:05 +00001749 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001750 and defaults to 0. This is new in 2.3. Possible values (see the
1751 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001752
1753 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001754 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001755 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001756 ELLIPSIS
Tim Peters711bf302006-04-25 03:31:36 +00001757 SKIP
Edward Loper052d0cd2004-09-19 17:19:33 +00001758 IGNORE_EXCEPTION_DETAIL
Edward Loper71f55af2004-08-26 01:41:51 +00001759 REPORT_UDIFF
1760 REPORT_CDIFF
1761 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001762 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001763
1764 Optional keyword arg "raise_on_error" raises an exception on the
1765 first unexpected exception or failure. This allows failures to be
1766 post-mortem debugged.
1767
Tim Peters8a7d2d52001-01-16 07:10:57 +00001768 Advanced tomfoolery: testmod runs methods of a local instance of
1769 class doctest.Tester, then merges the results into (or creates)
1770 global Tester instance doctest.master. Methods of doctest.master
1771 can be called directly too, if you want to do something unusual.
1772 Passing report=0 to testmod is especially useful then, to delay
1773 displaying a summary. Invoke doctest.master.summarize(verbose)
1774 when you're done fiddling.
1775 """
Tim Peters82076ef2004-09-13 00:52:51 +00001776 global master
1777
Tim Peters8485b562004-08-04 18:46:34 +00001778 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001779 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001780 # DWA - m will still be None if this wasn't invoked from the command
1781 # line, in which case the following TypeError is about as good an error
1782 # as we should expect
1783 m = sys.modules.get('__main__')
1784
Tim Peters8485b562004-08-04 18:46:34 +00001785 # Check that we were actually given a module.
1786 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001787 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001788
1789 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001790 if name is None:
1791 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001792
1793 # Find, parse, and run all tests in the given module.
Tim Petersbf0400a2006-06-05 01:43:03 +00001794 finder = DocTestFinder(exclude_empty=exclude_empty)
Tim Peters19397e52004-08-06 22:02:59 +00001795
1796 if raise_on_error:
1797 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1798 else:
1799 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1800
Tim Peters8485b562004-08-04 18:46:34 +00001801 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1802 runner.run(test)
1803
Tim Peters8a7d2d52001-01-16 07:10:57 +00001804 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001805 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001806
Tim Peters82076ef2004-09-13 00:52:51 +00001807 if master is None:
1808 master = runner
1809 else:
1810 master.merge(runner)
1811
Tim Peters8485b562004-08-04 18:46:34 +00001812 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001813
Edward Loper052d0cd2004-09-19 17:19:33 +00001814def testfile(filename, module_relative=True, name=None, package=None,
1815 globs=None, verbose=None, report=True, optionflags=0,
George Yoshidaf3c65de2006-05-28 16:39:09 +00001816 extraglobs=None, raise_on_error=False, parser=DocTestParser(),
1817 encoding=None):
Edward Loper052d0cd2004-09-19 17:19:33 +00001818 """
1819 Test examples in the given file. Return (#failures, #tests).
1820
1821 Optional keyword arg "module_relative" specifies how filenames
1822 should be interpreted:
1823
1824 - If "module_relative" is True (the default), then "filename"
1825 specifies a module-relative path. By default, this path is
1826 relative to the calling module's directory; but if the
1827 "package" argument is specified, then it is relative to that
1828 package. To ensure os-independence, "filename" should use
1829 "/" characters to separate path segments, and should not
1830 be an absolute path (i.e., it may not begin with "/").
1831
1832 - If "module_relative" is False, then "filename" specifies an
1833 os-specific path. The path may be absolute or relative (to
1834 the current working directory).
1835
Edward Lopera2fc7ec2004-09-21 03:24:24 +00001836 Optional keyword arg "name" gives the name of the test; by default
1837 use the file's basename.
Edward Loper052d0cd2004-09-19 17:19:33 +00001838
1839 Optional keyword argument "package" is a Python package or the
1840 name of a Python package whose directory should be used as the
1841 base directory for a module relative filename. If no package is
1842 specified, then the calling module's directory is used as the base
1843 directory for module relative filenames. It is an error to
1844 specify "package" if "module_relative" is False.
1845
1846 Optional keyword arg "globs" gives a dict to be used as the globals
1847 when executing examples; by default, use {}. A copy of this dict
1848 is actually used for each docstring, so that each docstring's
1849 examples start with a clean slate.
1850
1851 Optional keyword arg "extraglobs" gives a dictionary that should be
1852 merged into the globals that are used to execute examples. By
1853 default, no extra globals are used.
1854
1855 Optional keyword arg "verbose" prints lots of stuff if true, prints
1856 only failures if false; by default, it's true iff "-v" is in sys.argv.
1857
1858 Optional keyword arg "report" prints a summary at the end when true,
1859 else prints nothing at the end. In verbose mode, the summary is
1860 detailed, else very brief (in fact, empty if all tests passed).
1861
1862 Optional keyword arg "optionflags" or's together module constants,
1863 and defaults to 0. Possible values (see the docs for details):
1864
1865 DONT_ACCEPT_TRUE_FOR_1
1866 DONT_ACCEPT_BLANKLINE
1867 NORMALIZE_WHITESPACE
1868 ELLIPSIS
Tim Peters711bf302006-04-25 03:31:36 +00001869 SKIP
Edward Loper052d0cd2004-09-19 17:19:33 +00001870 IGNORE_EXCEPTION_DETAIL
1871 REPORT_UDIFF
1872 REPORT_CDIFF
1873 REPORT_NDIFF
1874 REPORT_ONLY_FIRST_FAILURE
1875
1876 Optional keyword arg "raise_on_error" raises an exception on the
1877 first unexpected exception or failure. This allows failures to be
1878 post-mortem debugged.
1879
Edward Loper498a1862004-09-27 03:42:58 +00001880 Optional keyword arg "parser" specifies a DocTestParser (or
1881 subclass) that should be used to extract tests from the files.
1882
George Yoshidaf3c65de2006-05-28 16:39:09 +00001883 Optional keyword arg "encoding" specifies an encoding that should
1884 be used to convert the file to unicode.
Tim Peters27c70592006-05-30 02:26:46 +00001885
Edward Loper052d0cd2004-09-19 17:19:33 +00001886 Advanced tomfoolery: testmod runs methods of a local instance of
1887 class doctest.Tester, then merges the results into (or creates)
1888 global Tester instance doctest.master. Methods of doctest.master
1889 can be called directly too, if you want to do something unusual.
1890 Passing report=0 to testmod is especially useful then, to delay
1891 displaying a summary. Invoke doctest.master.summarize(verbose)
1892 when you're done fiddling.
1893 """
1894 global master
1895
1896 if package and not module_relative:
1897 raise ValueError("Package may only be specified for module-"
1898 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00001899
Edward Loper052d0cd2004-09-19 17:19:33 +00001900 # Relativize the path
Phillip J. Eby47032112006-04-11 01:07:43 +00001901 text, filename = _load_testfile(filename, package, module_relative)
Edward Loper052d0cd2004-09-19 17:19:33 +00001902
1903 # If no name was given, then use the file's name.
1904 if name is None:
Edward Lopera2fc7ec2004-09-21 03:24:24 +00001905 name = os.path.basename(filename)
Edward Loper052d0cd2004-09-19 17:19:33 +00001906
1907 # Assemble the globals.
1908 if globs is None:
1909 globs = {}
1910 else:
1911 globs = globs.copy()
1912 if extraglobs is not None:
1913 globs.update(extraglobs)
1914
1915 if raise_on_error:
1916 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1917 else:
1918 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1919
George Yoshidaf3c65de2006-05-28 16:39:09 +00001920 if encoding is not None:
1921 text = text.decode(encoding)
1922
Edward Loper052d0cd2004-09-19 17:19:33 +00001923 # Read the file, convert it to a test, and run it.
Phillip J. Eby47032112006-04-11 01:07:43 +00001924 test = parser.get_doctest(text, globs, name, filename, 0)
Edward Loper052d0cd2004-09-19 17:19:33 +00001925 runner.run(test)
1926
1927 if report:
1928 runner.summarize()
1929
1930 if master is None:
1931 master = runner
1932 else:
1933 master.merge(runner)
1934
1935 return runner.failures, runner.tries
1936
Tim Peters8485b562004-08-04 18:46:34 +00001937def run_docstring_examples(f, globs, verbose=False, name="NoName",
1938 compileflags=None, optionflags=0):
1939 """
1940 Test examples in the given object's docstring (`f`), using `globs`
1941 as globals. Optional argument `name` is used in failure messages.
1942 If the optional argument `verbose` is true, then generate output
1943 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001944
Tim Peters8485b562004-08-04 18:46:34 +00001945 `compileflags` gives the set of flags that should be used by the
1946 Python compiler when running the examples. If not specified, then
1947 it will default to the set of future-import flags that apply to
1948 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001949
Tim Peters8485b562004-08-04 18:46:34 +00001950 Optional keyword arg `optionflags` specifies options for the
1951 testing and output. See the documentation for `testmod` for more
1952 information.
1953 """
1954 # Find, parse, and run all tests in the given module.
1955 finder = DocTestFinder(verbose=verbose, recurse=False)
1956 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1957 for test in finder.find(f, name, globs=globs):
1958 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001959
Tim Peters8485b562004-08-04 18:46:34 +00001960######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001961## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001962######################################################################
1963# This is provided only for backwards compatibility. It's not
1964# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001965
Tim Peters8485b562004-08-04 18:46:34 +00001966class Tester:
Tim Petersbf0400a2006-06-05 01:43:03 +00001967 def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001968
1969 warnings.warn("class Tester is deprecated; "
1970 "use class doctest.DocTestRunner instead",
1971 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001972 if mod is None and globs is None:
1973 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00001974 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00001975 raise TypeError("Tester.__init__: mod must be a module; %r" %
1976 (mod,))
1977 if globs is None:
1978 globs = mod.__dict__
1979 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001980
Tim Peters8485b562004-08-04 18:46:34 +00001981 self.verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +00001982 self.optionflags = optionflags
Tim Petersbf0400a2006-06-05 01:43:03 +00001983 self.testfinder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00001984 self.testrunner = DocTestRunner(verbose=verbose,
1985 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001986
Tim Peters8485b562004-08-04 18:46:34 +00001987 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001988 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001989 if self.verbose:
1990 print "Running string", name
1991 (f,t) = self.testrunner.run(test)
1992 if self.verbose:
1993 print f, "of", t, "examples failed in string", name
1994 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001995
Tim Petersf3f57472004-08-08 06:11:48 +00001996 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001997 f = t = 0
1998 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001999 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00002000 for test in tests:
2001 (f2, t2) = self.testrunner.run(test)
2002 (f,t) = (f+f2, t+t2)
2003 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002004
Tim Peters8485b562004-08-04 18:46:34 +00002005 def rundict(self, d, name, module=None):
2006 import new
2007 m = new.module(name)
2008 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002009 if module is None:
2010 module = False
2011 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002012
Tim Peters8485b562004-08-04 18:46:34 +00002013 def run__test__(self, d, name):
2014 import new
2015 m = new.module(name)
2016 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002017 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002018
Tim Peters8485b562004-08-04 18:46:34 +00002019 def summarize(self, verbose=None):
2020 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002021
Tim Peters8485b562004-08-04 18:46:34 +00002022 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002023 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002024
Tim Peters8485b562004-08-04 18:46:34 +00002025######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002026## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002027######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002028
Jim Fultonf54bad42004-08-28 14:57:56 +00002029_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002030
Jim Fultonf54bad42004-08-28 14:57:56 +00002031def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002032 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002033
2034 The old flag is returned so that a runner could restore the old
2035 value if it wished to:
2036
Tim Petersb7e99b62005-03-28 23:50:54 +00002037 >>> import doctest
2038 >>> old = doctest._unittest_reportflags
2039 >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
Jim Fultonf54bad42004-08-28 14:57:56 +00002040 ... REPORT_ONLY_FIRST_FAILURE) == old
2041 True
2042
Jim Fultonf54bad42004-08-28 14:57:56 +00002043 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2044 ... REPORT_ONLY_FIRST_FAILURE)
2045 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002046
Jim Fultonf54bad42004-08-28 14:57:56 +00002047 Only reporting flags can be set:
2048
Tim Petersb7e99b62005-03-28 23:50:54 +00002049 >>> doctest.set_unittest_reportflags(ELLIPSIS)
Jim Fultonf54bad42004-08-28 14:57:56 +00002050 Traceback (most recent call last):
2051 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002052 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002053
Tim Petersb7e99b62005-03-28 23:50:54 +00002054 >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
Jim Fultonf54bad42004-08-28 14:57:56 +00002055 ... REPORT_ONLY_FIRST_FAILURE)
2056 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002057 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002058 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002059
2060 if (flags & REPORTING_FLAGS) != flags:
2061 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002062 old = _unittest_reportflags
2063 _unittest_reportflags = flags
2064 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002065
Jim Fultonf54bad42004-08-28 14:57:56 +00002066
Tim Peters19397e52004-08-06 22:02:59 +00002067class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002068
Edward Loper34fcb142004-08-09 02:45:41 +00002069 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2070 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002071
Jim Fultona643b652004-07-14 19:06:50 +00002072 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002073 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002074 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002075 self._dt_test = test
2076 self._dt_setUp = setUp
2077 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002078
Jim Fultona643b652004-07-14 19:06:50 +00002079 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002080 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002081
Tim Peters19397e52004-08-06 22:02:59 +00002082 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002083 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002084
2085 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002086 test = self._dt_test
2087
Tim Peters19397e52004-08-06 22:02:59 +00002088 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002089 self._dt_tearDown(test)
2090
2091 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002092
2093 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002094 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002095 old = sys.stdout
2096 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002097 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002098
Tim Peters38330fe2004-08-30 16:19:24 +00002099 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002100 # The option flags don't include any reporting flags,
2101 # so add the default reporting flags
2102 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002103
Jim Fultonf54bad42004-08-28 14:57:56 +00002104 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002105 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002106
Jim Fultona643b652004-07-14 19:06:50 +00002107 try:
Tim Peters19397e52004-08-06 22:02:59 +00002108 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002109 failures, tries = runner.run(
2110 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002111 finally:
2112 sys.stdout = old
2113
2114 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002115 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002116
Tim Peters19397e52004-08-06 22:02:59 +00002117 def format_failure(self, err):
2118 test = self._dt_test
2119 if test.lineno is None:
2120 lineno = 'unknown line number'
2121 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002122 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002123 lname = '.'.join(test.name.split('.')[-1:])
2124 return ('Failed doctest test for %s\n'
2125 ' File "%s", line %s, in %s\n\n%s'
2126 % (test.name, test.filename, lineno, lname, err)
2127 )
2128
2129 def debug(self):
2130 r"""Run the test case without results and without catching exceptions
2131
2132 The unit test framework includes a debug method on test cases
2133 and test suites to support post-mortem debugging. The test code
2134 is run in such a way that errors are not caught. This way a
2135 caller can catch the errors and initiate post-mortem debugging.
2136
2137 The DocTestCase provides a debug method that raises
2138 UnexpectedException errors if there is an unexepcted
2139 exception:
2140
Edward Lopera1ef6112004-08-09 16:14:41 +00002141 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002142 ... {}, 'foo', 'foo.py', 0)
2143 >>> case = DocTestCase(test)
2144 >>> try:
2145 ... case.debug()
2146 ... except UnexpectedException, failure:
2147 ... pass
2148
2149 The UnexpectedException contains the test, the example, and
2150 the original exception:
2151
2152 >>> failure.test is test
2153 True
2154
2155 >>> failure.example.want
2156 '42\n'
2157
2158 >>> exc_info = failure.exc_info
2159 >>> raise exc_info[0], exc_info[1], exc_info[2]
2160 Traceback (most recent call last):
2161 ...
2162 KeyError
2163
2164 If the output doesn't match, then a DocTestFailure is raised:
2165
Edward Lopera1ef6112004-08-09 16:14:41 +00002166 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002167 ... >>> x = 1
2168 ... >>> x
2169 ... 2
2170 ... ''', {}, 'foo', 'foo.py', 0)
2171 >>> case = DocTestCase(test)
2172
2173 >>> try:
2174 ... case.debug()
2175 ... except DocTestFailure, failure:
2176 ... pass
2177
2178 DocTestFailure objects provide access to the test:
2179
2180 >>> failure.test is test
2181 True
2182
2183 As well as to the example:
2184
2185 >>> failure.example.want
2186 '2\n'
2187
2188 and the actual output:
2189
2190 >>> failure.got
2191 '1\n'
2192
2193 """
2194
Jim Fultonf54bad42004-08-28 14:57:56 +00002195 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002196 runner = DebugRunner(optionflags=self._dt_optionflags,
2197 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002198 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002199 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002200
2201 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002202 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002203
2204 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002205 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002206 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2207
2208 __str__ = __repr__
2209
2210 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002211 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002212
Jim Fultonf54bad42004-08-28 14:57:56 +00002213def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2214 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002215 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002216 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002217
Tim Peters19397e52004-08-06 22:02:59 +00002218 This converts each documentation string in a module that
2219 contains doctest tests to a unittest test case. If any of the
2220 tests in a doc string fail, then the test case fails. An exception
2221 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002222 (sometimes approximate) line number.
2223
Tim Peters19397e52004-08-06 22:02:59 +00002224 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002225 can be either a module or a module name.
2226
2227 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002228
2229 A number of options may be provided as keyword arguments:
2230
Jim Fultonf54bad42004-08-28 14:57:56 +00002231 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002232 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002233 tests in each file. The setUp function will be passed a DocTest
2234 object. The setUp function can access the test globals as the
2235 globs attribute of the test passed.
2236
2237 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002238 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002239 tests in each file. The tearDown function will be passed a DocTest
2240 object. The tearDown function can access the test globals as the
2241 globs attribute of the test passed.
2242
2243 globs
2244 A dictionary containing initial global variables for the tests.
2245
2246 optionflags
2247 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002248 """
Jim Fultona643b652004-07-14 19:06:50 +00002249
Tim Peters8485b562004-08-04 18:46:34 +00002250 if test_finder is None:
2251 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002252
Tim Peters19397e52004-08-06 22:02:59 +00002253 module = _normalize_module(module)
2254 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2255 if globs is None:
2256 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002257 if not tests:
2258 # Why do we want to do this? Because it reveals a bug that might
2259 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002260 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002261
2262 tests.sort()
2263 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002264 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002265 if len(test.examples) == 0:
2266 continue
Tim Peters8485b562004-08-04 18:46:34 +00002267 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002268 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002269 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002270 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002271 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002272 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002273
2274 return suite
2275
2276class DocFileCase(DocTestCase):
2277
2278 def id(self):
2279 return '_'.join(self._dt_test.name.split('.'))
2280
2281 def __repr__(self):
2282 return self._dt_test.filename
2283 __str__ = __repr__
2284
2285 def format_failure(self, err):
2286 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2287 % (self._dt_test.name, self._dt_test.filename, err)
2288 )
2289
Edward Loper052d0cd2004-09-19 17:19:33 +00002290def DocFileTest(path, module_relative=True, package=None,
George Yoshidaf3c65de2006-05-28 16:39:09 +00002291 globs=None, parser=DocTestParser(),
2292 encoding=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002293 if globs is None:
2294 globs = {}
Fred Drake7c404a42004-12-21 23:46:34 +00002295 else:
2296 globs = globs.copy()
Tim Peters19397e52004-08-06 22:02:59 +00002297
Edward Loper052d0cd2004-09-19 17:19:33 +00002298 if package and not module_relative:
2299 raise ValueError("Package may only be specified for module-"
2300 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00002301
Edward Loper052d0cd2004-09-19 17:19:33 +00002302 # Relativize the path.
Phillip J. Eby47032112006-04-11 01:07:43 +00002303 doc, path = _load_testfile(path, package, module_relative)
2304
Fred Drake7c404a42004-12-21 23:46:34 +00002305 if "__file__" not in globs:
2306 globs["__file__"] = path
Tim Peters19397e52004-08-06 22:02:59 +00002307
Edward Loper052d0cd2004-09-19 17:19:33 +00002308 # Find the file and read it.
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002309 name = os.path.basename(path)
Tim Peters27c70592006-05-30 02:26:46 +00002310
George Yoshidaf3c65de2006-05-28 16:39:09 +00002311 # If an encoding is specified, use it to convert the file to unicode
2312 if encoding is not None:
2313 doc = doc.decode(encoding)
Edward Loper052d0cd2004-09-19 17:19:33 +00002314
2315 # Convert it to a test, and wrap it in a DocFileCase.
Edward Loper498a1862004-09-27 03:42:58 +00002316 test = parser.get_doctest(doc, globs, name, path, 0)
Jim Fultonf54bad42004-08-28 14:57:56 +00002317 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002318
2319def DocFileSuite(*paths, **kw):
Edward Loper052d0cd2004-09-19 17:19:33 +00002320 """A unittest suite for one or more doctest files.
Tim Petersbab3e992004-09-20 19:52:34 +00002321
Edward Loper052d0cd2004-09-19 17:19:33 +00002322 The path to each doctest file is given as a string; the
2323 interpretation of that string depends on the keyword argument
2324 "module_relative".
Tim Peters19397e52004-08-06 22:02:59 +00002325
2326 A number of options may be provided as keyword arguments:
2327
Edward Loper052d0cd2004-09-19 17:19:33 +00002328 module_relative
2329 If "module_relative" is True, then the given file paths are
2330 interpreted as os-independent module-relative paths. By
2331 default, these paths are relative to the calling module's
2332 directory; but if the "package" argument is specified, then
2333 they are relative to that package. To ensure os-independence,
2334 "filename" should use "/" characters to separate path
2335 segments, and may not be an absolute path (i.e., it may not
2336 begin with "/").
Tim Petersbab3e992004-09-20 19:52:34 +00002337
Edward Loper052d0cd2004-09-19 17:19:33 +00002338 If "module_relative" is False, then the given file paths are
2339 interpreted as os-specific paths. These paths may be absolute
2340 or relative (to the current working directory).
2341
Tim Peters19397e52004-08-06 22:02:59 +00002342 package
Edward Loper052d0cd2004-09-19 17:19:33 +00002343 A Python package or the name of a Python package whose directory
2344 should be used as the base directory for module relative paths.
2345 If "package" is not specified, then the calling module's
2346 directory is used as the base directory for module relative
2347 filenames. It is an error to specify "package" if
2348 "module_relative" is False.
Tim Peters19397e52004-08-06 22:02:59 +00002349
2350 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002351 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002352 tests in each file. The setUp function will be passed a DocTest
2353 object. The setUp function can access the test globals as the
2354 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002355
2356 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002357 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002358 tests in each file. The tearDown function will be passed a DocTest
2359 object. The tearDown function can access the test globals as the
2360 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002361
2362 globs
2363 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002364
2365 optionflags
Edward Loper498a1862004-09-27 03:42:58 +00002366 A set of doctest option flags expressed as an integer.
2367
2368 parser
2369 A DocTestParser (or subclass) that should be used to extract
2370 tests from the files.
Tim Peters27c70592006-05-30 02:26:46 +00002371
George Yoshidaf3c65de2006-05-28 16:39:09 +00002372 encoding
2373 An encoding that will be used to convert the files to unicode.
Tim Peters19397e52004-08-06 22:02:59 +00002374 """
2375 suite = unittest.TestSuite()
2376
2377 # We do this here so that _normalize_module is called at the right
2378 # level. If it were called in DocFileTest, then this function
2379 # would be the caller and we might guess the package incorrectly.
Edward Loper052d0cd2004-09-19 17:19:33 +00002380 if kw.get('module_relative', True):
2381 kw['package'] = _normalize_module(kw.get('package'))
Tim Peters19397e52004-08-06 22:02:59 +00002382
2383 for path in paths:
2384 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002385
Tim Petersdb3756d2003-06-29 05:30:48 +00002386 return suite
2387
Tim Peters8485b562004-08-04 18:46:34 +00002388######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002389## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002390######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002391
Tim Peters19397e52004-08-06 22:02:59 +00002392def script_from_examples(s):
2393 r"""Extract script from text with examples.
2394
2395 Converts text with examples to a Python script. Example input is
2396 converted to regular code. Example output and all other words
2397 are converted to comments:
2398
2399 >>> text = '''
2400 ... Here are examples of simple math.
2401 ...
2402 ... Python has super accurate integer addition
2403 ...
2404 ... >>> 2 + 2
2405 ... 5
2406 ...
2407 ... And very friendly error messages:
2408 ...
2409 ... >>> 1/0
2410 ... To Infinity
2411 ... And
2412 ... Beyond
2413 ...
2414 ... You can use logic if you want:
2415 ...
2416 ... >>> if 0:
2417 ... ... blah
2418 ... ... blah
2419 ... ...
2420 ...
2421 ... Ho hum
2422 ... '''
2423
2424 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002425 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002426 #
Edward Lopera5db6002004-08-12 02:41:30 +00002427 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002428 #
2429 2 + 2
2430 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002431 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002432 #
Edward Lopera5db6002004-08-12 02:41:30 +00002433 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002434 #
2435 1/0
2436 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002437 ## To Infinity
2438 ## And
2439 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002440 #
Edward Lopera5db6002004-08-12 02:41:30 +00002441 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002442 #
2443 if 0:
2444 blah
2445 blah
Tim Peters19397e52004-08-06 22:02:59 +00002446 #
Edward Lopera5db6002004-08-12 02:41:30 +00002447 # Ho hum
Georg Brandlecf93c72005-06-26 23:09:51 +00002448 <BLANKLINE>
Tim Peters19397e52004-08-06 22:02:59 +00002449 """
Edward Loper00f8da72004-08-26 18:05:07 +00002450 output = []
2451 for piece in DocTestParser().parse(s):
2452 if isinstance(piece, Example):
2453 # Add the example's source code (strip trailing NL)
2454 output.append(piece.source[:-1])
2455 # Add the expected output:
2456 want = piece.want
2457 if want:
2458 output.append('# Expected:')
2459 output += ['## '+l for l in want.split('\n')[:-1]]
2460 else:
2461 # Add non-example text.
2462 output += [_comment_line(l)
2463 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002464
Edward Loper00f8da72004-08-26 18:05:07 +00002465 # Trim junk on both ends.
2466 while output and output[-1] == '#':
2467 output.pop()
2468 while output and output[0] == '#':
2469 output.pop(0)
2470 # Combine the output, and return it.
Georg Brandl1f149642005-06-26 22:22:31 +00002471 # Add a courtesy newline to prevent exec from choking (see bug #1172785)
2472 return '\n'.join(output) + '\n'
Tim Petersdb3756d2003-06-29 05:30:48 +00002473
2474def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002475 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002476
2477 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002478 test to be debugged and the name (within the module) of the object
2479 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002480 """
Tim Peters8485b562004-08-04 18:46:34 +00002481 module = _normalize_module(module)
2482 tests = DocTestFinder().find(module)
2483 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002484 if not test:
2485 raise ValueError(name, "not found in tests")
2486 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002487 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002488 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002489
Jim Fultona643b652004-07-14 19:06:50 +00002490def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002491 """Debug a single doctest docstring, in argument `src`'"""
2492 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002493 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002494
Jim Fultona643b652004-07-14 19:06:50 +00002495def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002496 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002497 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002498
Tim Petersb6a04d62004-08-23 21:37:56 +00002499 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2500 # docs say, a file so created cannot be opened by name a second time
2501 # on modern Windows boxes, and execfile() needs to open it.
2502 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002503 f = open(srcfilename, 'w')
2504 f.write(src)
2505 f.close()
2506
Tim Petersb6a04d62004-08-23 21:37:56 +00002507 try:
2508 if globs:
2509 globs = globs.copy()
2510 else:
2511 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002512
Tim Petersb6a04d62004-08-23 21:37:56 +00002513 if pm:
2514 try:
2515 execfile(srcfilename, globs, globs)
2516 except:
2517 print sys.exc_info()[1]
2518 pdb.post_mortem(sys.exc_info()[2])
2519 else:
2520 # Note that %r is vital here. '%s' instead can, e.g., cause
2521 # backslashes to get treated as metacharacters on Windows.
2522 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2523
2524 finally:
2525 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002526
Jim Fultona643b652004-07-14 19:06:50 +00002527def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002528 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002529
2530 Provide the module (or dotted name of the module) containing the
2531 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002532 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002533 """
Tim Peters8485b562004-08-04 18:46:34 +00002534 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002535 testsrc = testsource(module, name)
2536 debug_script(testsrc, pm, module.__dict__)
2537
Tim Peters8485b562004-08-04 18:46:34 +00002538######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002539## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002540######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002541class _TestClass:
2542 """
2543 A pointless class, for sanity-checking of docstring testing.
2544
2545 Methods:
2546 square()
2547 get()
2548
2549 >>> _TestClass(13).get() + _TestClass(-12).get()
2550 1
2551 >>> hex(_TestClass(13).square().get())
2552 '0xa9'
2553 """
2554
2555 def __init__(self, val):
2556 """val -> _TestClass object with associated value val.
2557
2558 >>> t = _TestClass(123)
2559 >>> print t.get()
2560 123
2561 """
2562
2563 self.val = val
2564
2565 def square(self):
2566 """square() -> square TestClass's associated value
2567
2568 >>> _TestClass(13).square().get()
2569 169
2570 """
2571
2572 self.val = self.val ** 2
2573 return self
2574
2575 def get(self):
2576 """get() -> return TestClass's associated value.
2577
2578 >>> x = _TestClass(-42)
2579 >>> print x.get()
2580 -42
2581 """
2582
2583 return self.val
2584
2585__test__ = {"_TestClass": _TestClass,
2586 "string": r"""
2587 Example of a string object, searched as-is.
2588 >>> x = 1; y = 2
2589 >>> x + y, x * y
2590 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002591 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002592
Tim Peters6ebe61f2003-06-27 20:48:05 +00002593 "bool-int equivalence": r"""
2594 In 2.2, boolean expressions displayed
2595 0 or 1. By default, we still accept
2596 them. This can be disabled by passing
2597 DONT_ACCEPT_TRUE_FOR_1 to the new
2598 optionflags argument.
2599 >>> 4 == 4
2600 1
2601 >>> 4 == 4
2602 True
2603 >>> 4 > 4
2604 0
2605 >>> 4 > 4
2606 False
2607 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002608
Tim Peters8485b562004-08-04 18:46:34 +00002609 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002610 Blank lines can be marked with <BLANKLINE>:
2611 >>> print 'foo\n\nbar\n'
2612 foo
2613 <BLANKLINE>
2614 bar
2615 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002616 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002617
2618 "ellipsis": r"""
2619 If the ellipsis flag is used, then '...' can be used to
2620 elide substrings in the desired output:
2621 >>> print range(1000) #doctest: +ELLIPSIS
2622 [0, 1, 2, ..., 999]
2623 """,
2624
2625 "whitespace normalization": r"""
2626 If the whitespace normalization flag is used, then
2627 differences in whitespace are ignored.
2628 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2629 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2630 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2631 27, 28, 29]
2632 """,
2633 }
Tim Peters8485b562004-08-04 18:46:34 +00002634
Tim Peters8a7d2d52001-01-16 07:10:57 +00002635def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002636 r = unittest.TextTestRunner()
2637 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002638
2639if __name__ == "__main__":
2640 _test()