blob: d120a0130615c2911c4b301df8000e9b741d1dff [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',
Thomas Wouters477c8d52006-05-27 19:21:47 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +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):
Thomas Wouters477c8d52006-05-27 19:21:47 +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')
Thomas Wouters477c8d52006-05-27 19:21:47 +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 |
Thomas Wouters477c8d52006-05-27 19:21:47 +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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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'):
212 return package.__loader__.get_data(filename), filename
213 return open(filename).read(), filename
214
Edward Loperaacf0832004-08-26 01:19:50 +0000215def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000216 """
Edward Loperaacf0832004-08-26 01:19:50 +0000217 Add the given number of space characters to the beginning every
218 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000219 """
Edward Loperaacf0832004-08-26 01:19:50 +0000220 # This regexp matches the start of non-blank lines:
221 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000222
Edward Loper8e4a34b2004-08-12 02:34:27 +0000223def _exception_traceback(exc_info):
224 """
225 Return a string containing a traceback message for the given
226 exc_info tuple (as returned by sys.exc_info()).
227 """
228 # Get a traceback message.
229 excout = StringIO()
230 exc_type, exc_val, exc_tb = exc_info
231 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
232 return excout.getvalue()
233
Tim Peters8485b562004-08-04 18:46:34 +0000234# Override some StringIO methods.
235class _SpoofOut(StringIO):
236 def getvalue(self):
237 result = StringIO.getvalue(self)
238 # If anything at all was written, make sure there's a trailing
239 # newline. There's no way for the expected output to indicate
240 # that a trailing newline is missing.
241 if result and not result.endswith("\n"):
242 result += "\n"
243 # Prevent softspace from screwing up the next test case, in
244 # case they used print with a trailing comma in an example.
245 if hasattr(self, "softspace"):
246 del self.softspace
247 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000248
Tim Peters8485b562004-08-04 18:46:34 +0000249 def truncate(self, size=None):
250 StringIO.truncate(self, size)
251 if hasattr(self, "softspace"):
252 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000253
Tim Peters26b3ebb2004-08-19 08:10:08 +0000254# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000255def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000256 """
257 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000258 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000259 False
260 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000261 if ELLIPSIS_MARKER not in want:
262 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000263
Tim Peters26b3ebb2004-08-19 08:10:08 +0000264 # Find "the real" strings.
265 ws = want.split(ELLIPSIS_MARKER)
266 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000267
Tim Petersdc5de3b2004-08-19 14:06:20 +0000268 # Deal with exact matches possibly needed at one or both ends.
269 startpos, endpos = 0, len(got)
270 w = ws[0]
271 if w: # starts with exact match
272 if got.startswith(w):
273 startpos = len(w)
274 del ws[0]
275 else:
276 return False
277 w = ws[-1]
278 if w: # ends with exact match
279 if got.endswith(w):
280 endpos -= len(w)
281 del ws[-1]
282 else:
283 return False
284
285 if startpos > endpos:
286 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000287 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000288 return False
289
290 # For the rest, we only need to find the leftmost non-overlapping
291 # match for each piece. If there's no overall match that way alone,
292 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000293 for w in ws:
294 # w may be '' at times, if there are consecutive ellipses, or
295 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000296 # Search for an empty string succeeds, and doesn't change startpos.
297 startpos = got.find(w, startpos, endpos)
298 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000299 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000300 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000301
Tim Petersdc5de3b2004-08-19 14:06:20 +0000302 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000303
Edward Loper00f8da72004-08-26 18:05:07 +0000304def _comment_line(line):
305 "Return a commented form of the given line"
306 line = line.rstrip()
307 if line:
308 return '# '+line
309 else:
310 return '#'
311
Edward Loper2de91ba2004-08-27 02:07:46 +0000312class _OutputRedirectingPdb(pdb.Pdb):
313 """
314 A specialized version of the python debugger that redirects stdout
315 to a given stream when interacting with the user. Stdout is *not*
316 redirected when traced code is executed.
317 """
318 def __init__(self, out):
319 self.__out = out
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320 pdb.Pdb.__init__(self, stdout=out)
Edward Loper2de91ba2004-08-27 02:07:46 +0000321
322 def trace_dispatch(self, *args):
323 # Redirect stdout to the given stream.
324 save_stdout = sys.stdout
325 sys.stdout = self.__out
326 # Call Pdb's trace dispatch method.
Tim Petersd7bbbbc2004-11-08 22:30:28 +0000327 try:
328 return pdb.Pdb.trace_dispatch(self, *args)
329 finally:
Tim Petersd7bbbbc2004-11-08 22:30:28 +0000330 sys.stdout = save_stdout
Edward Loper2de91ba2004-08-27 02:07:46 +0000331
Edward Lopera2fc7ec2004-09-21 03:24:24 +0000332# [XX] Normalize with respect to os.path.pardir?
Edward Loper052d0cd2004-09-19 17:19:33 +0000333def _module_relative_path(module, path):
334 if not inspect.ismodule(module):
335 raise TypeError, 'Expected a module: %r' % module
336 if path.startswith('/'):
337 raise ValueError, 'Module-relative files may not have absolute paths'
338
339 # Find the base directory for the path.
340 if hasattr(module, '__file__'):
341 # A normal module/package
342 basedir = os.path.split(module.__file__)[0]
343 elif module.__name__ == '__main__':
344 # An interactive session.
345 if len(sys.argv)>0 and sys.argv[0] != '':
346 basedir = os.path.split(sys.argv[0])[0]
347 else:
348 basedir = os.curdir
349 else:
350 # A module w/o __file__ (this includes builtins)
351 raise ValueError("Can't resolve paths relative to the module " +
352 module + " (it has no __file__)")
353
354 # Combine the base directory and the path.
355 return os.path.join(basedir, *(path.split('/')))
356
Tim Peters8485b562004-08-04 18:46:34 +0000357######################################################################
358## 2. Example & DocTest
359######################################################################
360## - An "example" is a <source, want> pair, where "source" is a
361## fragment of source code, and "want" is the expected output for
362## "source." The Example class also includes information about
363## where the example was extracted from.
364##
Edward Lopera1ef6112004-08-09 16:14:41 +0000365## - A "doctest" is a collection of examples, typically extracted from
366## a string (such as an object's docstring). The DocTest class also
367## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000368
Tim Peters8485b562004-08-04 18:46:34 +0000369class Example:
370 """
371 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000372 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000373
Edward Loper74bca7a2004-08-12 02:27:44 +0000374 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000375 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000376
Edward Loper74bca7a2004-08-12 02:27:44 +0000377 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000378 from stdout, or a traceback in case of exception). `want` ends
379 with a newline unless it's empty, in which case it's an empty
380 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000381
Edward Lopera6b68322004-08-26 00:05:43 +0000382 - exc_msg: The exception message generated by the example, if
383 the example is expected to generate an exception; or `None` if
384 it is not expected to generate an exception. This exception
385 message is compared against the return value of
386 `traceback.format_exception_only()`. `exc_msg` ends with a
387 newline unless it's `None`. The constructor adds a newline
388 if needed.
389
Edward Loper74bca7a2004-08-12 02:27:44 +0000390 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000391 this Example where the Example begins. This line number is
392 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000393
394 - indent: The example's indentation in the DocTest string.
395 I.e., the number of space characters that preceed the
396 example's first prompt.
397
398 - options: A dictionary mapping from option flags to True or
399 False, which is used to override default options for this
400 example. Any option flags not contained in this dictionary
401 are left at their default value (as specified by the
402 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000403 """
Edward Lopera6b68322004-08-26 00:05:43 +0000404 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
405 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000406 # Normalize inputs.
407 if not source.endswith('\n'):
408 source += '\n'
409 if want and not want.endswith('\n'):
410 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000411 if exc_msg is not None and not exc_msg.endswith('\n'):
412 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000413 # Store properties.
414 self.source = source
415 self.want = want
416 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000417 self.indent = indent
418 if options is None: options = {}
419 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000420 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000421
Tim Peters8485b562004-08-04 18:46:34 +0000422class DocTest:
423 """
424 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000425 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000426
Tim Peters8485b562004-08-04 18:46:34 +0000427 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000428
Tim Peters8485b562004-08-04 18:46:34 +0000429 - globs: The namespace (aka globals) that the examples should
430 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000431
Tim Peters8485b562004-08-04 18:46:34 +0000432 - name: A name identifying the DocTest (typically, the name of
433 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000434
Tim Peters8485b562004-08-04 18:46:34 +0000435 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000436 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000437
Tim Peters8485b562004-08-04 18:46:34 +0000438 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000439 begins, or `None` if the line number is unavailable. This
440 line number is zero-based, with respect to the beginning of
441 the file.
442
443 - docstring: The string that the examples were extracted from,
444 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000445 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000446 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000447 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000448 Create a new DocTest containing the given examples. The
449 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000450 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000451 assert not isinstance(examples, basestring), \
452 "DocTest no longer accepts str; use DocTestParser instead"
453 self.examples = examples
454 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000455 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000456 self.name = name
457 self.filename = filename
458 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000459
460 def __repr__(self):
461 if len(self.examples) == 0:
462 examples = 'no examples'
463 elif len(self.examples) == 1:
464 examples = '1 example'
465 else:
466 examples = '%d examples' % len(self.examples)
467 return ('<DocTest %s from %s:%s (%s)>' %
468 (self.name, self.filename, self.lineno, examples))
469
470
471 # This lets us sort tests by name:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000472 def __lt__(self, other):
Tim Peters8485b562004-08-04 18:46:34 +0000473 if not isinstance(other, DocTest):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000474 return NotImplemented
475 return ((self.name, self.filename, self.lineno, id(self))
476 <
477 (other.name, other.filename, other.lineno, id(other)))
Tim Peters8485b562004-08-04 18:46:34 +0000478
479######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000480## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000481######################################################################
482
Edward Lopera1ef6112004-08-09 16:14:41 +0000483class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000484 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000485 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000486 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000487 # This regular expression is used to find doctest examples in a
488 # string. It defines three groups: `source` is the source code
489 # (including leading indentation and prompts); `indent` is the
490 # indentation of the first (PS1) line of the source code; and
491 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000492 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000493 # Source consists of a PS1 line followed by zero or more PS2 lines.
494 (?P<source>
495 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
496 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
497 \n?
498 # Want consists of any non-blank lines that do not start with PS1.
499 (?P<want> (?:(?![ ]*$) # Not a blank line
500 (?![ ]*>>>) # Not a line starting with PS1
501 .*$\n? # But any other line
502 )*)
503 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000504
Edward Lopera6b68322004-08-26 00:05:43 +0000505 # A regular expression for handling `want` strings that contain
506 # expected exceptions. It divides `want` into three pieces:
507 # - the traceback header line (`hdr`)
508 # - the traceback stack (`stack`)
509 # - the exception message (`msg`), as generated by
510 # traceback.format_exception_only()
511 # `msg` may have multiple lines. We assume/require that the
512 # exception message is the first non-indented line starting with a word
513 # character following the traceback header line.
514 _EXCEPTION_RE = re.compile(r"""
515 # Grab the traceback header. Different versions of Python have
516 # said different things on the first traceback line.
517 ^(?P<hdr> Traceback\ \(
518 (?: most\ recent\ call\ last
519 | innermost\ last
520 ) \) :
521 )
522 \s* $ # toss trailing whitespace on the header.
523 (?P<stack> .*?) # don't blink: absorb stuff until...
524 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
525 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
526
Tim Peters7ea48dd2004-08-13 01:52:59 +0000527 # A callable returning a true value iff its argument is a blank line
528 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000529 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000530
Edward Loper00f8da72004-08-26 18:05:07 +0000531 def parse(self, string, name='<string>'):
532 """
533 Divide the given string into examples and intervening text,
534 and return them as a list of alternating Examples and strings.
535 Line numbers for the Examples are 0-based. The optional
536 argument `name` is a name identifying this string, and is only
537 used for error messages.
538 """
539 string = string.expandtabs()
540 # If all lines begin with the same indentation, then strip it.
541 min_indent = self._min_indent(string)
542 if min_indent > 0:
543 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
544
545 output = []
546 charno, lineno = 0, 0
547 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000548 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000549 # Add the pre-example text to `output`.
550 output.append(string[charno:m.start()])
551 # Update lineno (lines before this example)
552 lineno += string.count('\n', charno, m.start())
553 # Extract info from the regexp match.
554 (source, options, want, exc_msg) = \
555 self._parse_example(m, name, lineno)
556 # Create an Example, and add it to the list.
557 if not self._IS_BLANK_OR_COMMENT(source):
558 output.append( Example(source, want, exc_msg,
559 lineno=lineno,
560 indent=min_indent+len(m.group('indent')),
561 options=options) )
562 # Update lineno (lines inside this example)
563 lineno += string.count('\n', m.start(), m.end())
564 # Update charno.
565 charno = m.end()
566 # Add any remaining post-example text to `output`.
567 output.append(string[charno:])
568 return output
569
Edward Lopera1ef6112004-08-09 16:14:41 +0000570 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000571 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000572 Extract all doctest examples from the given string, and
573 collect them into a `DocTest` object.
574
575 `globs`, `name`, `filename`, and `lineno` are attributes for
576 the new `DocTest` object. See the documentation for `DocTest`
577 for more information.
578 """
579 return DocTest(self.get_examples(string, name), globs,
580 name, filename, lineno, string)
581
582 def get_examples(self, string, name='<string>'):
583 """
584 Extract all doctest examples from the given string, and return
585 them as a list of `Example` objects. Line numbers are
586 0-based, because it's most common in doctests that nothing
587 interesting appears on the same line as opening triple-quote,
588 and so the first interesting line is called \"line 1\" then.
589
590 The optional argument `name` is a name identifying this
591 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000592 """
Edward Loper00f8da72004-08-26 18:05:07 +0000593 return [x for x in self.parse(string, name)
594 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000595
Edward Loper74bca7a2004-08-12 02:27:44 +0000596 def _parse_example(self, m, name, lineno):
597 """
598 Given a regular expression match from `_EXAMPLE_RE` (`m`),
599 return a pair `(source, want)`, where `source` is the matched
600 example's source code (with prompts and indentation stripped);
601 and `want` is the example's expected output (with indentation
602 stripped).
603
604 `name` is the string's name, and `lineno` is the line number
605 where the example starts; both are used for error messages.
606 """
Edward Loper7c748462004-08-09 02:06:06 +0000607 # Get the example's indentation level.
608 indent = len(m.group('indent'))
609
610 # Divide source into lines; check that they're properly
611 # indented; and then strip their indentation & prompts.
612 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000613 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000614 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000615 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000616
Tim Petersc5049152004-08-22 17:34:58 +0000617 # Divide want into lines; check that it's properly indented; and
618 # then strip the indentation. Spaces before the last newline should
619 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000620 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000621 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000622 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
623 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000624 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000625 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000626 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000627
Edward Lopera6b68322004-08-26 00:05:43 +0000628 # If `want` contains a traceback message, then extract it.
629 m = self._EXCEPTION_RE.match(want)
630 if m:
631 exc_msg = m.group('msg')
632 else:
633 exc_msg = None
634
Edward Loper00f8da72004-08-26 18:05:07 +0000635 # Extract options from the source.
636 options = self._find_options(source, name, lineno)
637
638 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000639
Edward Loper74bca7a2004-08-12 02:27:44 +0000640 # This regular expression looks for option directives in the
641 # source code of an example. Option directives are comments
642 # starting with "doctest:". Warning: this may give false
643 # positives for string-literals that contain the string
644 # "#doctest:". Eliminating these false positives would require
645 # actually parsing the string; but we limit them by ignoring any
646 # line containing "#doctest:" that is *followed* by a quote mark.
647 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
648 re.MULTILINE)
649
650 def _find_options(self, source, name, lineno):
651 """
652 Return a dictionary containing option overrides extracted from
653 option directives in the given source string.
654
655 `name` is the string's name, and `lineno` is the line number
656 where the example starts; both are used for error messages.
657 """
658 options = {}
659 # (note: with the current regexp, this will match at most once:)
660 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
661 option_strings = m.group(1).replace(',', ' ').split()
662 for option in option_strings:
663 if (option[0] not in '+-' or
664 option[1:] not in OPTIONFLAGS_BY_NAME):
665 raise ValueError('line %r of the doctest for %s '
666 'has an invalid option: %r' %
667 (lineno+1, name, option))
668 flag = OPTIONFLAGS_BY_NAME[option[1:]]
669 options[flag] = (option[0] == '+')
670 if options and self._IS_BLANK_OR_COMMENT(source):
671 raise ValueError('line %r of the doctest for %s has an option '
672 'directive on a line with no example: %r' %
673 (lineno, name, source))
674 return options
675
Edward Lopera5db6002004-08-12 02:41:30 +0000676 # This regular expression finds the indentation of every non-blank
677 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000678 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000679
680 def _min_indent(self, s):
681 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000682 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
683 if len(indents) > 0:
684 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000685 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000686 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000687
Edward Lopera1ef6112004-08-09 16:14:41 +0000688 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000689 """
690 Given the lines of a source string (including prompts and
691 leading indentation), check to make sure that every prompt is
692 followed by a space character. If any line is not followed by
693 a space character, then raise ValueError.
694 """
Edward Loper7c748462004-08-09 02:06:06 +0000695 for i, line in enumerate(lines):
696 if len(line) >= indent+4 and line[indent+3] != ' ':
697 raise ValueError('line %r of the docstring for %s '
698 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000699 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000700 line[indent:indent+3], line))
701
Edward Lopera1ef6112004-08-09 16:14:41 +0000702 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000703 """
704 Check that every line in the given list starts with the given
705 prefix; if any line does not, then raise a ValueError.
706 """
Edward Loper7c748462004-08-09 02:06:06 +0000707 for i, line in enumerate(lines):
708 if line and not line.startswith(prefix):
709 raise ValueError('line %r of the docstring for %s has '
710 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000711 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000712
713
714######################################################################
715## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000716######################################################################
717
718class DocTestFinder:
719 """
720 A class used to extract the DocTests that are relevant to a given
721 object, from its docstring and the docstrings of its contained
722 objects. Doctests can currently be extracted from the following
723 object types: modules, functions, classes, methods, staticmethods,
724 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000725 """
726
Edward Lopera1ef6112004-08-09 16:14:41 +0000727 def __init__(self, verbose=False, parser=DocTestParser(),
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000728 recurse=True, exclude_empty=True):
Tim Peters8485b562004-08-04 18:46:34 +0000729 """
730 Create a new doctest finder.
731
Edward Lopera1ef6112004-08-09 16:14:41 +0000732 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000733 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000734 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000735 signature for this factory function should match the signature
736 of the DocTest constructor.
737
Tim Peters8485b562004-08-04 18:46:34 +0000738 If the optional argument `recurse` is false, then `find` will
739 only examine the given object, and not any contained objects.
Edward Loper32ddbf72004-09-13 05:47:24 +0000740
Tim Peters958cc892004-09-13 14:53:28 +0000741 If the optional argument `exclude_empty` is false, then `find`
742 will include tests for objects with empty docstrings.
Tim Peters8485b562004-08-04 18:46:34 +0000743 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000744 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000745 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000746 self._recurse = recurse
Edward Loper32ddbf72004-09-13 05:47:24 +0000747 self._exclude_empty = exclude_empty
Tim Peters8485b562004-08-04 18:46:34 +0000748
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000749 def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000750 """
751 Return a list of the DocTests that are defined by the given
752 object's docstring, or by any of its contained objects'
753 docstrings.
754
755 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000756 the given object. If the module is not specified or is None, then
757 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000758 correct module. The object's module is used:
759
760 - As a default namespace, if `globs` is not specified.
761 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000762 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000763 - To find the name of the file containing the object.
764 - To help find the line number of the object within its
765 file.
766
Tim Petersf3f57472004-08-08 06:11:48 +0000767 Contained objects whose module does not match `module` are ignored.
768
769 If `module` is False, no attempt to find the module will be made.
770 This is obscure, of use mostly in tests: if `module` is False, or
771 is None but cannot be found automatically, then all objects are
772 considered to belong to the (non-existent) module, so all contained
773 objects will (recursively) be searched for doctests.
774
Tim Peters8485b562004-08-04 18:46:34 +0000775 The globals for each DocTest is formed by combining `globs`
776 and `extraglobs` (bindings in `extraglobs` override bindings
777 in `globs`). A new copy of the globals dictionary is created
778 for each DocTest. If `globs` is not specified, then it
779 defaults to the module's `__dict__`, if specified, or {}
780 otherwise. If `extraglobs` is not specified, then it defaults
781 to {}.
782
Tim Peters8485b562004-08-04 18:46:34 +0000783 """
784 # If name was not specified, then extract it from the object.
785 if name is None:
786 name = getattr(obj, '__name__', None)
787 if name is None:
788 raise ValueError("DocTestFinder.find: name must be given "
789 "when obj.__name__ doesn't exist: %r" %
790 (type(obj),))
791
792 # Find the module that contains the given object (if obj is
793 # a module, then module=obj.). Note: this may fail, in which
794 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000795 if module is False:
796 module = None
797 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000798 module = inspect.getmodule(obj)
799
800 # Read the module's source code. This is used by
801 # DocTestFinder._find_lineno to find the line number for a
802 # given object's docstring.
803 try:
804 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
805 source_lines = linecache.getlines(file)
806 if not source_lines:
807 source_lines = None
808 except TypeError:
809 source_lines = None
810
811 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000812 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000813 if module is None:
814 globs = {}
815 else:
816 globs = module.__dict__.copy()
817 else:
818 globs = globs.copy()
819 if extraglobs is not None:
820 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000821
Tim Peters8485b562004-08-04 18:46:34 +0000822 # Recursively expore `obj`, extracting DocTests.
823 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000824 self._find(tests, obj, name, module, source_lines, globs, {})
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000825 # Sort the tests by alpha order of names, for consistency in
826 # verbose-mode output. This was a feature of doctest in Pythons
827 # <= 2.3 that got lost by accident in 2.4. It was repaired in
828 # 2.4.4 and 2.5.
829 tests.sort()
Tim Peters8485b562004-08-04 18:46:34 +0000830 return tests
831
Tim Peters8485b562004-08-04 18:46:34 +0000832 def _from_module(self, module, object):
833 """
834 Return true if the given object is defined in the given
835 module.
836 """
837 if module is None:
838 return True
839 elif inspect.isfunction(object):
840 return module.__dict__ is object.func_globals
841 elif inspect.isclass(object):
842 return module.__name__ == object.__module__
843 elif inspect.getmodule(object) is not None:
844 return module is inspect.getmodule(object)
845 elif hasattr(object, '__module__'):
846 return module.__name__ == object.__module__
847 elif isinstance(object, property):
848 return True # [XX] no way not be sure.
849 else:
850 raise ValueError("object must be a class or function")
851
Tim Petersf3f57472004-08-08 06:11:48 +0000852 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000853 """
854 Find tests for the given object and any contained objects, and
855 add them to `tests`.
856 """
857 if self._verbose:
858 print 'Finding tests in %s' % name
859
860 # If we've already processed this object, then ignore it.
861 if id(obj) in seen:
862 return
863 seen[id(obj)] = 1
864
865 # Find a test for this object, and add it to the list of tests.
866 test = self._get_test(obj, name, module, globs, source_lines)
867 if test is not None:
868 tests.append(test)
869
870 # Look for tests in a module's contained objects.
871 if inspect.ismodule(obj) and self._recurse:
872 for valname, val in obj.__dict__.items():
Tim Peters8485b562004-08-04 18:46:34 +0000873 valname = '%s.%s' % (name, valname)
874 # Recurse to functions & classes.
875 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000876 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000877 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000878 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000879
880 # Look for tests in a module's __test__ dictionary.
881 if inspect.ismodule(obj) and self._recurse:
882 for valname, val in getattr(obj, '__test__', {}).items():
883 if not isinstance(valname, basestring):
884 raise ValueError("DocTestFinder.find: __test__ keys "
885 "must be strings: %r" %
886 (type(valname),))
887 if not (inspect.isfunction(val) or inspect.isclass(val) or
888 inspect.ismethod(val) or inspect.ismodule(val) or
889 isinstance(val, basestring)):
890 raise ValueError("DocTestFinder.find: __test__ values "
891 "must be strings, functions, methods, "
892 "classes, or modules: %r" %
893 (type(val),))
Tim Petersc5684782004-09-13 01:07:12 +0000894 valname = '%s.__test__.%s' % (name, valname)
Tim Peters8485b562004-08-04 18:46:34 +0000895 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000896 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000897
898 # Look for tests in a class's contained objects.
899 if inspect.isclass(obj) and self._recurse:
900 for valname, val in obj.__dict__.items():
Tim Peters8485b562004-08-04 18:46:34 +0000901 # Special handling for staticmethod/classmethod.
902 if isinstance(val, staticmethod):
903 val = getattr(obj, valname)
904 if isinstance(val, classmethod):
905 val = getattr(obj, valname).im_func
906
907 # Recurse to methods, properties, and nested classes.
908 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000909 isinstance(val, property)) and
910 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000911 valname = '%s.%s' % (name, valname)
912 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000913 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000914
915 def _get_test(self, obj, name, module, globs, source_lines):
916 """
917 Return a DocTest for the given object, if it defines a docstring;
918 otherwise, return None.
919 """
920 # Extract the object's docstring. If it doesn't have one,
921 # then return None (no test for this object).
922 if isinstance(obj, basestring):
923 docstring = obj
924 else:
925 try:
926 if obj.__doc__ is None:
Edward Loper32ddbf72004-09-13 05:47:24 +0000927 docstring = ''
928 else:
Jim Fulton7d428782004-10-13 14:15:32 +0000929 docstring = obj.__doc__
930 if not isinstance(docstring, basestring):
931 docstring = str(docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000932 except (TypeError, AttributeError):
Edward Loper32ddbf72004-09-13 05:47:24 +0000933 docstring = ''
Tim Peters8485b562004-08-04 18:46:34 +0000934
935 # Find the docstring's location in the file.
936 lineno = self._find_lineno(obj, source_lines)
937
Edward Loper32ddbf72004-09-13 05:47:24 +0000938 # Don't bother if the docstring is empty.
939 if self._exclude_empty and not docstring:
940 return None
941
Tim Peters8485b562004-08-04 18:46:34 +0000942 # Return a DocTest for this object.
943 if module is None:
944 filename = None
945 else:
946 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +0000947 if filename[-4:] in (".pyc", ".pyo"):
948 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +0000949 return self._parser.get_doctest(docstring, globs, name,
950 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000951
952 def _find_lineno(self, obj, source_lines):
953 """
954 Return a line number of the given object's docstring. Note:
955 this method assumes that the object has a docstring.
956 """
957 lineno = None
958
959 # Find the line number for modules.
960 if inspect.ismodule(obj):
961 lineno = 0
962
963 # Find the line number for classes.
964 # Note: this could be fooled if a class is defined multiple
965 # times in a single file.
966 if inspect.isclass(obj):
967 if source_lines is None:
968 return None
969 pat = re.compile(r'^\s*class\s*%s\b' %
970 getattr(obj, '__name__', '-'))
971 for i, line in enumerate(source_lines):
972 if pat.match(line):
973 lineno = i
974 break
975
976 # Find the line number for functions & methods.
977 if inspect.ismethod(obj): obj = obj.im_func
978 if inspect.isfunction(obj): obj = obj.func_code
979 if inspect.istraceback(obj): obj = obj.tb_frame
980 if inspect.isframe(obj): obj = obj.f_code
981 if inspect.iscode(obj):
982 lineno = getattr(obj, 'co_firstlineno', None)-1
983
984 # Find the line number where the docstring starts. Assume
985 # that it's the first line that begins with a quote mark.
986 # Note: this could be fooled by a multiline function
987 # signature, where a continuation line begins with a quote
988 # mark.
989 if lineno is not None:
990 if source_lines is None:
991 return lineno+1
992 pat = re.compile('(^|.*:)\s*\w*("|\')')
993 for lineno in range(lineno, len(source_lines)):
994 if pat.match(source_lines[lineno]):
995 return lineno
996
997 # We couldn't find the line number.
998 return None
999
1000######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001001## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001002######################################################################
1003
Tim Peters8485b562004-08-04 18:46:34 +00001004class DocTestRunner:
1005 """
1006 A class used to run DocTest test cases, and accumulate statistics.
1007 The `run` method is used to process a single DocTest case. It
1008 returns a tuple `(f, t)`, where `t` is the number of test cases
1009 tried, and `f` is the number of test cases that failed.
1010
1011 >>> tests = DocTestFinder().find(_TestClass)
1012 >>> runner = DocTestRunner(verbose=False)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001013 >>> tests.sort(key = lambda test: test.name)
Tim Peters8485b562004-08-04 18:46:34 +00001014 >>> for test in tests:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001015 ... print test.name, '->', runner.run(test)
1016 _TestClass -> (0, 2)
1017 _TestClass.__init__ -> (0, 2)
1018 _TestClass.get -> (0, 2)
1019 _TestClass.square -> (0, 1)
Tim Peters8485b562004-08-04 18:46:34 +00001020
1021 The `summarize` method prints a summary of all the test cases that
1022 have been run by the runner, and returns an aggregated `(f, t)`
1023 tuple:
1024
1025 >>> runner.summarize(verbose=1)
1026 4 items passed all tests:
1027 2 tests in _TestClass
1028 2 tests in _TestClass.__init__
1029 2 tests in _TestClass.get
1030 1 tests in _TestClass.square
1031 7 tests in 4 items.
1032 7 passed and 0 failed.
1033 Test passed.
1034 (0, 7)
1035
1036 The aggregated number of tried examples and failed examples is
1037 also available via the `tries` and `failures` attributes:
1038
1039 >>> runner.tries
1040 7
1041 >>> runner.failures
1042 0
1043
1044 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001045 by an `OutputChecker`. This comparison may be customized with a
1046 number of option flags; see the documentation for `testmod` for
1047 more information. If the option flags are insufficient, then the
1048 comparison may also be customized by passing a subclass of
1049 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001050
1051 The test runner's display output can be controlled in two ways.
1052 First, an output function (`out) can be passed to
1053 `TestRunner.run`; this function will be called with strings that
1054 should be displayed. It defaults to `sys.stdout.write`. If
1055 capturing the output is not sufficient, then the display output
1056 can be also customized by subclassing DocTestRunner, and
1057 overriding the methods `report_start`, `report_success`,
1058 `report_unexpected_exception`, and `report_failure`.
1059 """
1060 # This divider string is used to separate failure messages, and to
1061 # separate sections of the summary.
1062 DIVIDER = "*" * 70
1063
Edward Loper34fcb142004-08-09 02:45:41 +00001064 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001065 """
1066 Create a new test runner.
1067
Edward Loper34fcb142004-08-09 02:45:41 +00001068 Optional keyword arg `checker` is the `OutputChecker` that
1069 should be used to compare the expected outputs and actual
1070 outputs of doctest examples.
1071
Tim Peters8485b562004-08-04 18:46:34 +00001072 Optional keyword arg 'verbose' prints lots of stuff if true,
1073 only failures if false; by default, it's true iff '-v' is in
1074 sys.argv.
1075
1076 Optional argument `optionflags` can be used to control how the
1077 test runner compares expected output to actual output, and how
1078 it displays failures. See the documentation for `testmod` for
1079 more information.
1080 """
Edward Loper34fcb142004-08-09 02:45:41 +00001081 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001082 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001083 verbose = '-v' in sys.argv
1084 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001085 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001086 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001087
Tim Peters8485b562004-08-04 18:46:34 +00001088 # Keep track of the examples we've run.
1089 self.tries = 0
1090 self.failures = 0
1091 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001092
Tim Peters8485b562004-08-04 18:46:34 +00001093 # Create a fake output target for capturing doctest output.
1094 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001095
Tim Peters8485b562004-08-04 18:46:34 +00001096 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001097 # Reporting methods
1098 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001099
Tim Peters8485b562004-08-04 18:46:34 +00001100 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001101 """
Tim Peters8485b562004-08-04 18:46:34 +00001102 Report that the test runner is about to process the given
1103 example. (Only displays a message if verbose=True)
1104 """
1105 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001106 if example.want:
1107 out('Trying:\n' + _indent(example.source) +
1108 'Expecting:\n' + _indent(example.want))
1109 else:
1110 out('Trying:\n' + _indent(example.source) +
1111 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001112
Tim Peters8485b562004-08-04 18:46:34 +00001113 def report_success(self, out, test, example, got):
1114 """
1115 Report that the given example ran successfully. (Only
1116 displays a message if verbose=True)
1117 """
1118 if self._verbose:
1119 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001120
Tim Peters8485b562004-08-04 18:46:34 +00001121 def report_failure(self, out, test, example, got):
1122 """
1123 Report that the given example failed.
1124 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001125 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001126 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001127
Tim Peters8485b562004-08-04 18:46:34 +00001128 def report_unexpected_exception(self, out, test, example, exc_info):
1129 """
1130 Report that the given example raised an unexpected exception.
1131 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001132 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001133 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001134
Edward Loper8e4a34b2004-08-12 02:34:27 +00001135 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001136 out = [self.DIVIDER]
1137 if test.filename:
1138 if test.lineno is not None and example.lineno is not None:
1139 lineno = test.lineno + example.lineno + 1
1140 else:
1141 lineno = '?'
1142 out.append('File "%s", line %s, in %s' %
1143 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001144 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001145 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1146 out.append('Failed example:')
1147 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001148 out.append(_indent(source))
1149 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001150
Tim Peters8485b562004-08-04 18:46:34 +00001151 #/////////////////////////////////////////////////////////////////
1152 # DocTest Running
1153 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001154
Tim Peters8485b562004-08-04 18:46:34 +00001155 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001156 """
Tim Peters8485b562004-08-04 18:46:34 +00001157 Run the examples in `test`. Write the outcome of each example
1158 with one of the `DocTestRunner.report_*` methods, using the
1159 writer function `out`. `compileflags` is the set of compiler
1160 flags that should be used to execute examples. Return a tuple
1161 `(f, t)`, where `t` is the number of examples tried, and `f`
1162 is the number of examples that failed. The examples are run
1163 in the namespace `test.globs`.
1164 """
1165 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001166 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001167
1168 # Save the option flags (since option directives can be used
1169 # to modify them).
1170 original_optionflags = self.optionflags
1171
Tim Peters1fbf9c52004-09-04 17:21:02 +00001172 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1173
1174 check = self._checker.check_output
1175
Tim Peters8485b562004-08-04 18:46:34 +00001176 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001177 for examplenum, example in enumerate(test.examples):
1178
Edward Lopera89f88d2004-08-26 02:45:51 +00001179 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1180 # reporting after the first failure.
1181 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1182 failures > 0)
1183
Edward Loper74bca7a2004-08-12 02:27:44 +00001184 # Merge in the example's options.
1185 self.optionflags = original_optionflags
1186 if example.options:
1187 for (optionflag, val) in example.options.items():
1188 if val:
1189 self.optionflags |= optionflag
1190 else:
1191 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001192
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193 # If 'SKIP' is set, then skip this example.
1194 if self.optionflags & SKIP:
1195 continue
1196
Tim Peters8485b562004-08-04 18:46:34 +00001197 # Record that we started this example.
1198 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001199 if not quiet:
1200 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001201
Edward Loper2de91ba2004-08-27 02:07:46 +00001202 # Use a special filename for compile(), so we can retrieve
1203 # the source code during interactive debugging (see
1204 # __patched_linecache_getlines).
1205 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1206
Tim Peters8485b562004-08-04 18:46:34 +00001207 # Run the example in the given context (globs), and record
1208 # any exception that gets raised. (But don't intercept
1209 # keyboard interrupts.)
1210 try:
Tim Peters208ca702004-08-09 04:12:36 +00001211 # Don't blink! This is where the user's code gets run.
Georg Brandl7cae87c2006-09-06 06:51:57 +00001212 exec(compile(example.source, filename, "single",
1213 compileflags, 1), test.globs)
Edward Loper2de91ba2004-08-27 02:07:46 +00001214 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001215 exception = None
1216 except KeyboardInterrupt:
1217 raise
1218 except:
1219 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001220 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001221
Tim Peters208ca702004-08-09 04:12:36 +00001222 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001223 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001224 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001225
1226 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001227 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001228 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001229 if check(example.want, got, self.optionflags):
1230 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001231
Tim Peters1fbf9c52004-09-04 17:21:02 +00001232 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001233 else:
1234 exc_info = sys.exc_info()
1235 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001236 if not quiet:
1237 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001238
Tim Peters1fbf9c52004-09-04 17:21:02 +00001239 # If `example.exc_msg` is None, then we weren't expecting
1240 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001241 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001242 outcome = BOOM
1243
1244 # We expected an exception: see whether it matches.
1245 elif check(example.exc_msg, exc_msg, self.optionflags):
1246 outcome = SUCCESS
1247
1248 # Another chance if they didn't care about the detail.
1249 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1250 m1 = re.match(r'[^:]*:', example.exc_msg)
1251 m2 = re.match(r'[^:]*:', exc_msg)
1252 if m1 and m2 and check(m1.group(0), m2.group(0),
1253 self.optionflags):
1254 outcome = SUCCESS
1255
1256 # Report the outcome.
1257 if outcome is SUCCESS:
1258 if not quiet:
1259 self.report_success(out, test, example, got)
1260 elif outcome is FAILURE:
1261 if not quiet:
1262 self.report_failure(out, test, example, got)
1263 failures += 1
1264 elif outcome is BOOM:
1265 if not quiet:
1266 self.report_unexpected_exception(out, test, example,
1267 exc_info)
1268 failures += 1
1269 else:
1270 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001271
1272 # Restore the option flags (in case they were modified)
1273 self.optionflags = original_optionflags
1274
1275 # Record and return the number of failures and tries.
1276 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001277 return failures, tries
1278
Tim Peters8485b562004-08-04 18:46:34 +00001279 def __record_outcome(self, test, f, t):
1280 """
1281 Record the fact that the given DocTest (`test`) generated `f`
1282 failures out of `t` tried examples.
1283 """
1284 f2, t2 = self._name2ft.get(test.name, (0,0))
1285 self._name2ft[test.name] = (f+f2, t+t2)
1286 self.failures += f
1287 self.tries += t
1288
Edward Loper2de91ba2004-08-27 02:07:46 +00001289 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1290 r'(?P<name>[\w\.]+)'
1291 r'\[(?P<examplenum>\d+)\]>$')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001292 def __patched_linecache_getlines(self, filename, module_globals=None):
Edward Loper2de91ba2004-08-27 02:07:46 +00001293 m = self.__LINECACHE_FILENAME_RE.match(filename)
1294 if m and m.group('name') == self.test.name:
1295 example = self.test.examples[int(m.group('examplenum'))]
1296 return example.source.splitlines(True)
1297 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298 return self.save_linecache_getlines(filename, module_globals)
Edward Loper2de91ba2004-08-27 02:07:46 +00001299
Tim Peters8485b562004-08-04 18:46:34 +00001300 def run(self, test, compileflags=None, out=None, clear_globs=True):
1301 """
1302 Run the examples in `test`, and display the results using the
1303 writer function `out`.
1304
1305 The examples are run in the namespace `test.globs`. If
1306 `clear_globs` is true (the default), then this namespace will
1307 be cleared after the test runs, to help with garbage
1308 collection. If you would like to examine the namespace after
1309 the test completes, then use `clear_globs=False`.
1310
1311 `compileflags` gives the set of flags that should be used by
1312 the Python compiler when running the examples. If not
1313 specified, then it will default to the set of future-import
1314 flags that apply to `globs`.
1315
1316 The output of each example is checked using
1317 `DocTestRunner.check_output`, and the results are formatted by
1318 the `DocTestRunner.report_*` methods.
1319 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001320 self.test = test
1321
Tim Peters8485b562004-08-04 18:46:34 +00001322 if compileflags is None:
1323 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001324
Tim Peters6c542b72004-08-09 16:43:36 +00001325 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001326 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001327 out = save_stdout.write
1328 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001329
Edward Loper2de91ba2004-08-27 02:07:46 +00001330 # Patch pdb.set_trace to restore sys.stdout during interactive
1331 # debugging (so it's not still redirected to self._fakeout).
1332 # Note that the interactive output will go to *our*
1333 # save_stdout, even if that's not the real sys.stdout; this
1334 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001335 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001336 self.debugger = _OutputRedirectingPdb(save_stdout)
1337 self.debugger.reset()
1338 pdb.set_trace = self.debugger.set_trace
1339
1340 # Patch linecache.getlines, so we can see the example's source
1341 # when we're inside the debugger.
1342 self.save_linecache_getlines = linecache.getlines
1343 linecache.getlines = self.__patched_linecache_getlines
1344
Tim Peters8485b562004-08-04 18:46:34 +00001345 try:
Tim Peters8485b562004-08-04 18:46:34 +00001346 return self.__run(test, compileflags, out)
1347 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001348 sys.stdout = save_stdout
1349 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001350 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001351 if clear_globs:
1352 test.globs.clear()
1353
1354 #/////////////////////////////////////////////////////////////////
1355 # Summarization
1356 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001357 def summarize(self, verbose=None):
1358 """
Tim Peters8485b562004-08-04 18:46:34 +00001359 Print a summary of all the test cases that have been run by
1360 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1361 the total number of failed examples, and `t` is the total
1362 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001363
Tim Peters8485b562004-08-04 18:46:34 +00001364 The optional `verbose` argument controls how detailed the
1365 summary is. If the verbosity is not specified, then the
1366 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001367 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001368 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001369 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001370 notests = []
1371 passed = []
1372 failed = []
1373 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001374 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001375 name, (f, t) = x
1376 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001377 totalt += t
1378 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001379 if t == 0:
1380 notests.append(name)
1381 elif f == 0:
1382 passed.append( (name, t) )
1383 else:
1384 failed.append(x)
1385 if verbose:
1386 if notests:
1387 print len(notests), "items had no tests:"
1388 notests.sort()
1389 for thing in notests:
1390 print " ", thing
1391 if passed:
1392 print len(passed), "items passed all tests:"
1393 passed.sort()
1394 for thing, count in passed:
1395 print " %3d tests in %s" % (count, thing)
1396 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001397 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001398 print len(failed), "items had failures:"
1399 failed.sort()
1400 for thing, (f, t) in failed:
1401 print " %3d of %3d in %s" % (f, t, thing)
1402 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001403 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001404 print totalt - totalf, "passed and", totalf, "failed."
1405 if totalf:
1406 print "***Test Failed***", totalf, "failures."
1407 elif verbose:
1408 print "Test passed."
1409 return totalf, totalt
1410
Tim Peters82076ef2004-09-13 00:52:51 +00001411 #/////////////////////////////////////////////////////////////////
1412 # Backward compatibility cruft to maintain doctest.master.
1413 #/////////////////////////////////////////////////////////////////
1414 def merge(self, other):
1415 d = self._name2ft
1416 for name, (f, t) in other._name2ft.items():
1417 if name in d:
1418 print "*** DocTestRunner.merge: '" + name + "' in both" \
1419 " testers; summing outcomes."
1420 f2, t2 = d[name]
1421 f = f + f2
1422 t = t + t2
1423 d[name] = f, t
1424
Edward Loper34fcb142004-08-09 02:45:41 +00001425class OutputChecker:
1426 """
1427 A class used to check the whether the actual output from a doctest
1428 example matches the expected output. `OutputChecker` defines two
1429 methods: `check_output`, which compares a given pair of outputs,
1430 and returns true if they match; and `output_difference`, which
1431 returns a string describing the differences between two outputs.
1432 """
1433 def check_output(self, want, got, optionflags):
1434 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001435 Return True iff the actual output from an example (`got`)
1436 matches the expected output (`want`). These strings are
1437 always considered to match if they are identical; but
1438 depending on what option flags the test runner is using,
1439 several non-exact match types are also possible. See the
1440 documentation for `TestRunner` for more information about
1441 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001442 """
1443 # Handle the common case first, for efficiency:
1444 # if they're string-identical, always return true.
1445 if got == want:
1446 return True
1447
1448 # The values True and False replaced 1 and 0 as the return
1449 # value for boolean comparisons in Python 2.3.
1450 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1451 if (got,want) == ("True\n", "1\n"):
1452 return True
1453 if (got,want) == ("False\n", "0\n"):
1454 return True
1455
1456 # <BLANKLINE> can be used as a special sequence to signify a
1457 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1458 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1459 # Replace <BLANKLINE> in want with a blank line.
1460 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1461 '', want)
1462 # If a line in got contains only spaces, then remove the
1463 # spaces.
1464 got = re.sub('(?m)^\s*?$', '', got)
1465 if got == want:
1466 return True
1467
1468 # This flag causes doctest to ignore any differences in the
1469 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001470 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001471 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001472 got = ' '.join(got.split())
1473 want = ' '.join(want.split())
1474 if got == want:
1475 return True
1476
1477 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001478 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001479 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001480 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001481 return True
1482
1483 # We didn't find any match; return false.
1484 return False
1485
Tim Petersc6cbab02004-08-22 19:43:28 +00001486 # Should we do a fancy diff?
1487 def _do_a_fancy_diff(self, want, got, optionflags):
1488 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001489 if not optionflags & (REPORT_UDIFF |
1490 REPORT_CDIFF |
1491 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001492 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001493
Tim Petersc6cbab02004-08-22 19:43:28 +00001494 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001495 # too hard ... or maybe not. In two real-life failures Tim saw,
1496 # a diff was a major help anyway, so this is commented out.
1497 # [todo] _ellipsis_match() knows which pieces do and don't match,
1498 # and could be the basis for a kick-ass diff in this case.
1499 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1500 ## return False
1501
Tim Petersc6cbab02004-08-22 19:43:28 +00001502 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001503 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001504 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001505 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001506
Tim Petersc6cbab02004-08-22 19:43:28 +00001507 # The other diff types need at least a few lines to be helpful.
1508 return want.count('\n') > 2 and got.count('\n') > 2
1509
Edward Loperca9111e2004-08-26 03:00:24 +00001510 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001511 """
1512 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001513 expected output for a given example (`example`) and the actual
1514 output (`got`). `optionflags` is the set of option flags used
1515 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001516 """
Edward Loperca9111e2004-08-26 03:00:24 +00001517 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001518 # If <BLANKLINE>s are being used, then replace blank lines
1519 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001520 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001521 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001522
Tim Peters5b799c12004-08-26 05:21:59 +00001523 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001524 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001525 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001526 want_lines = want.splitlines(True) # True == keep line ends
1527 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001528 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001529 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001530 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1531 diff = list(diff)[2:] # strip the diff header
1532 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001533 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001534 diff = difflib.context_diff(want_lines, got_lines, n=2)
1535 diff = list(diff)[2:] # strip the diff header
1536 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001537 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001538 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1539 diff = list(engine.compare(want_lines, got_lines))
1540 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001541 else:
1542 assert 0, 'Bad diff option'
1543 # Remove trailing whitespace on diff output.
1544 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001545 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001546
1547 # If we're not using diff, then simply list the expected
1548 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001549 if want and got:
1550 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1551 elif want:
1552 return 'Expected:\n%sGot nothing\n' % _indent(want)
1553 elif got:
1554 return 'Expected nothing\nGot:\n%s' % _indent(got)
1555 else:
1556 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001557
Tim Peters19397e52004-08-06 22:02:59 +00001558class DocTestFailure(Exception):
1559 """A DocTest example has failed in debugging mode.
1560
1561 The exception instance has variables:
1562
1563 - test: the DocTest object being run
1564
Neal Norwitzc082cb72006-08-29 05:40:08 +00001565 - example: the Example object that failed
Tim Peters19397e52004-08-06 22:02:59 +00001566
1567 - got: the actual output
1568 """
1569 def __init__(self, test, example, got):
1570 self.test = test
1571 self.example = example
1572 self.got = got
1573
1574 def __str__(self):
1575 return str(self.test)
1576
1577class UnexpectedException(Exception):
1578 """A DocTest example has encountered an unexpected exception
1579
1580 The exception instance has variables:
1581
1582 - test: the DocTest object being run
1583
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00001584 - example: the Example object that failed
Tim Peters19397e52004-08-06 22:02:59 +00001585
1586 - exc_info: the exception info
1587 """
1588 def __init__(self, test, example, exc_info):
1589 self.test = test
1590 self.example = example
1591 self.exc_info = exc_info
1592
1593 def __str__(self):
1594 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001595
Tim Peters19397e52004-08-06 22:02:59 +00001596class DebugRunner(DocTestRunner):
1597 r"""Run doc tests but raise an exception as soon as there is a failure.
1598
1599 If an unexpected exception occurs, an UnexpectedException is raised.
1600 It contains the test, the example, and the original exception:
1601
1602 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001603 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1604 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001605 >>> try:
1606 ... runner.run(test)
Guido van Rossumb940e112007-01-10 16:19:56 +00001607 ... except UnexpectedException as f:
1608 ... failure = f
Tim Peters19397e52004-08-06 22:02:59 +00001609
1610 >>> failure.test is test
1611 True
1612
1613 >>> failure.example.want
1614 '42\n'
1615
1616 >>> exc_info = failure.exc_info
1617 >>> raise exc_info[0], exc_info[1], exc_info[2]
1618 Traceback (most recent call last):
1619 ...
1620 KeyError
1621
1622 We wrap the original exception to give the calling application
1623 access to the test and example information.
1624
1625 If the output doesn't match, then a DocTestFailure is raised:
1626
Edward Lopera1ef6112004-08-09 16:14:41 +00001627 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001628 ... >>> x = 1
1629 ... >>> x
1630 ... 2
1631 ... ''', {}, 'foo', 'foo.py', 0)
1632
1633 >>> try:
1634 ... runner.run(test)
Guido van Rossumb940e112007-01-10 16:19:56 +00001635 ... except DocTestFailure as f:
1636 ... failure = f
Tim Peters19397e52004-08-06 22:02:59 +00001637
1638 DocTestFailure objects provide access to the test:
1639
1640 >>> failure.test is test
1641 True
1642
1643 As well as to the example:
1644
1645 >>> failure.example.want
1646 '2\n'
1647
1648 and the actual output:
1649
1650 >>> failure.got
1651 '1\n'
1652
1653 If a failure or error occurs, the globals are left intact:
1654
1655 >>> del test.globs['__builtins__']
1656 >>> test.globs
1657 {'x': 1}
1658
Edward Lopera1ef6112004-08-09 16:14:41 +00001659 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001660 ... >>> x = 2
1661 ... >>> raise KeyError
1662 ... ''', {}, 'foo', 'foo.py', 0)
1663
1664 >>> runner.run(test)
1665 Traceback (most recent call last):
1666 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00001667 doctest.UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001668
Tim Peters19397e52004-08-06 22:02:59 +00001669 >>> del test.globs['__builtins__']
1670 >>> test.globs
1671 {'x': 2}
1672
1673 But the globals are cleared if there is no error:
1674
Edward Lopera1ef6112004-08-09 16:14:41 +00001675 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001676 ... >>> x = 2
1677 ... ''', {}, 'foo', 'foo.py', 0)
1678
1679 >>> runner.run(test)
1680 (0, 1)
1681
1682 >>> test.globs
1683 {}
1684
1685 """
1686
1687 def run(self, test, compileflags=None, out=None, clear_globs=True):
1688 r = DocTestRunner.run(self, test, compileflags, out, False)
1689 if clear_globs:
1690 test.globs.clear()
1691 return r
1692
1693 def report_unexpected_exception(self, out, test, example, exc_info):
1694 raise UnexpectedException(test, example, exc_info)
1695
1696 def report_failure(self, out, test, example, got):
1697 raise DocTestFailure(test, example, got)
1698
Tim Peters8485b562004-08-04 18:46:34 +00001699######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001700## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001701######################################################################
1702# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001703
Tim Peters82076ef2004-09-13 00:52:51 +00001704# For backward compatibility, a global instance of a DocTestRunner
1705# class, updated by testmod.
1706master = None
1707
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001708def testmod(m=None, name=None, globs=None, verbose=None,
Tim Peters19397e52004-08-06 22:02:59 +00001709 report=True, optionflags=0, extraglobs=None,
Tim Peters958cc892004-09-13 14:53:28 +00001710 raise_on_error=False, exclude_empty=False):
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001711 """m=None, name=None, globs=None, verbose=None, report=True,
1712 optionflags=0, extraglobs=None, raise_on_error=False,
Tim Peters958cc892004-09-13 14:53:28 +00001713 exclude_empty=False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001714
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001715 Test examples in docstrings in functions and classes reachable
1716 from module m (or the current module if m is not supplied), starting
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001717 with m.__doc__.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001718
1719 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001720 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001721 function and class docstrings are tested even if the name is private;
1722 strings are tested directly, as if they were docstrings.
1723
1724 Return (#failures, #tests).
1725
1726 See doctest.__doc__ for an overview.
1727
1728 Optional keyword arg "name" gives the name of the module; by default
1729 use m.__name__.
1730
1731 Optional keyword arg "globs" gives a dict to be used as the globals
1732 when executing examples; by default, use m.__dict__. A copy of this
1733 dict is actually used for each docstring, so that each docstring's
1734 examples start with a clean slate.
1735
Tim Peters8485b562004-08-04 18:46:34 +00001736 Optional keyword arg "extraglobs" gives a dictionary that should be
1737 merged into the globals that are used to execute examples. By
1738 default, no extra globals are used. This is new in 2.4.
1739
Tim Peters8a7d2d52001-01-16 07:10:57 +00001740 Optional keyword arg "verbose" prints lots of stuff if true, prints
1741 only failures if false; by default, it's true iff "-v" is in sys.argv.
1742
Tim Peters8a7d2d52001-01-16 07:10:57 +00001743 Optional keyword arg "report" prints a summary at the end when true,
1744 else prints nothing at the end. In verbose mode, the summary is
1745 detailed, else very brief (in fact, empty if all tests passed).
1746
Tim Peters6ebe61f2003-06-27 20:48:05 +00001747 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001748 and defaults to 0. This is new in 2.3. Possible values (see the
1749 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001750
1751 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001752 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001753 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001754 ELLIPSIS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001755 SKIP
Edward Loper052d0cd2004-09-19 17:19:33 +00001756 IGNORE_EXCEPTION_DETAIL
Edward Loper71f55af2004-08-26 01:41:51 +00001757 REPORT_UDIFF
1758 REPORT_CDIFF
1759 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001760 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001761
1762 Optional keyword arg "raise_on_error" raises an exception on the
1763 first unexpected exception or failure. This allows failures to be
1764 post-mortem debugged.
1765
Tim Peters8a7d2d52001-01-16 07:10:57 +00001766 Advanced tomfoolery: testmod runs methods of a local instance of
1767 class doctest.Tester, then merges the results into (or creates)
1768 global Tester instance doctest.master. Methods of doctest.master
1769 can be called directly too, if you want to do something unusual.
1770 Passing report=0 to testmod is especially useful then, to delay
1771 displaying a summary. Invoke doctest.master.summarize(verbose)
1772 when you're done fiddling.
1773 """
Tim Peters82076ef2004-09-13 00:52:51 +00001774 global master
1775
Tim Peters8485b562004-08-04 18:46:34 +00001776 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001777 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001778 # DWA - m will still be None if this wasn't invoked from the command
1779 # line, in which case the following TypeError is about as good an error
1780 # as we should expect
1781 m = sys.modules.get('__main__')
1782
Tim Peters8485b562004-08-04 18:46:34 +00001783 # Check that we were actually given a module.
1784 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001785 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001786
1787 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001788 if name is None:
1789 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001790
1791 # Find, parse, and run all tests in the given module.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001792 finder = DocTestFinder(exclude_empty=exclude_empty)
Tim Peters19397e52004-08-06 22:02:59 +00001793
1794 if raise_on_error:
1795 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1796 else:
1797 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1798
Tim Peters8485b562004-08-04 18:46:34 +00001799 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1800 runner.run(test)
1801
Tim Peters8a7d2d52001-01-16 07:10:57 +00001802 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001803 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001804
Tim Peters82076ef2004-09-13 00:52:51 +00001805 if master is None:
1806 master = runner
1807 else:
1808 master.merge(runner)
1809
Tim Peters8485b562004-08-04 18:46:34 +00001810 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001811
Edward Loper052d0cd2004-09-19 17:19:33 +00001812def testfile(filename, module_relative=True, name=None, package=None,
1813 globs=None, verbose=None, report=True, optionflags=0,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001814 extraglobs=None, raise_on_error=False, parser=DocTestParser(),
1815 encoding=None):
Edward Loper052d0cd2004-09-19 17:19:33 +00001816 """
1817 Test examples in the given file. Return (#failures, #tests).
1818
1819 Optional keyword arg "module_relative" specifies how filenames
1820 should be interpreted:
1821
1822 - If "module_relative" is True (the default), then "filename"
1823 specifies a module-relative path. By default, this path is
1824 relative to the calling module's directory; but if the
1825 "package" argument is specified, then it is relative to that
1826 package. To ensure os-independence, "filename" should use
1827 "/" characters to separate path segments, and should not
1828 be an absolute path (i.e., it may not begin with "/").
1829
1830 - If "module_relative" is False, then "filename" specifies an
1831 os-specific path. The path may be absolute or relative (to
1832 the current working directory).
1833
Edward Lopera2fc7ec2004-09-21 03:24:24 +00001834 Optional keyword arg "name" gives the name of the test; by default
1835 use the file's basename.
Edward Loper052d0cd2004-09-19 17:19:33 +00001836
1837 Optional keyword argument "package" is a Python package or the
1838 name of a Python package whose directory should be used as the
1839 base directory for a module relative filename. If no package is
1840 specified, then the calling module's directory is used as the base
1841 directory for module relative filenames. It is an error to
1842 specify "package" if "module_relative" is False.
1843
1844 Optional keyword arg "globs" gives a dict to be used as the globals
1845 when executing examples; by default, use {}. A copy of this dict
1846 is actually used for each docstring, so that each docstring's
1847 examples start with a clean slate.
1848
1849 Optional keyword arg "extraglobs" gives a dictionary that should be
1850 merged into the globals that are used to execute examples. By
1851 default, no extra globals are used.
1852
1853 Optional keyword arg "verbose" prints lots of stuff if true, prints
1854 only failures if false; by default, it's true iff "-v" is in sys.argv.
1855
1856 Optional keyword arg "report" prints a summary at the end when true,
1857 else prints nothing at the end. In verbose mode, the summary is
1858 detailed, else very brief (in fact, empty if all tests passed).
1859
1860 Optional keyword arg "optionflags" or's together module constants,
1861 and defaults to 0. Possible values (see the docs for details):
1862
1863 DONT_ACCEPT_TRUE_FOR_1
1864 DONT_ACCEPT_BLANKLINE
1865 NORMALIZE_WHITESPACE
1866 ELLIPSIS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001867 SKIP
Edward Loper052d0cd2004-09-19 17:19:33 +00001868 IGNORE_EXCEPTION_DETAIL
1869 REPORT_UDIFF
1870 REPORT_CDIFF
1871 REPORT_NDIFF
1872 REPORT_ONLY_FIRST_FAILURE
1873
1874 Optional keyword arg "raise_on_error" raises an exception on the
1875 first unexpected exception or failure. This allows failures to be
1876 post-mortem debugged.
1877
Edward Loper498a1862004-09-27 03:42:58 +00001878 Optional keyword arg "parser" specifies a DocTestParser (or
1879 subclass) that should be used to extract tests from the files.
1880
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001881 Optional keyword arg "encoding" specifies an encoding that should
1882 be used to convert the file to unicode.
1883
Edward Loper052d0cd2004-09-19 17:19:33 +00001884 Advanced tomfoolery: testmod runs methods of a local instance of
1885 class doctest.Tester, then merges the results into (or creates)
1886 global Tester instance doctest.master. Methods of doctest.master
1887 can be called directly too, if you want to do something unusual.
1888 Passing report=0 to testmod is especially useful then, to delay
1889 displaying a summary. Invoke doctest.master.summarize(verbose)
1890 when you're done fiddling.
1891 """
1892 global master
1893
1894 if package and not module_relative:
1895 raise ValueError("Package may only be specified for module-"
1896 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00001897
Edward Loper052d0cd2004-09-19 17:19:33 +00001898 # Relativize the path
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001899 text, filename = _load_testfile(filename, package, module_relative)
Edward Loper052d0cd2004-09-19 17:19:33 +00001900
1901 # If no name was given, then use the file's name.
1902 if name is None:
Edward Lopera2fc7ec2004-09-21 03:24:24 +00001903 name = os.path.basename(filename)
Edward Loper052d0cd2004-09-19 17:19:33 +00001904
1905 # Assemble the globals.
1906 if globs is None:
1907 globs = {}
1908 else:
1909 globs = globs.copy()
1910 if extraglobs is not None:
1911 globs.update(extraglobs)
1912
1913 if raise_on_error:
1914 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1915 else:
1916 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1917
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001918 if encoding is not None:
1919 text = text.decode(encoding)
1920
Edward Loper052d0cd2004-09-19 17:19:33 +00001921 # Read the file, convert it to a test, and run it.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001922 test = parser.get_doctest(text, globs, name, filename, 0)
Edward Loper052d0cd2004-09-19 17:19:33 +00001923 runner.run(test)
1924
1925 if report:
1926 runner.summarize()
1927
1928 if master is None:
1929 master = runner
1930 else:
1931 master.merge(runner)
1932
1933 return runner.failures, runner.tries
1934
Tim Peters8485b562004-08-04 18:46:34 +00001935def run_docstring_examples(f, globs, verbose=False, name="NoName",
1936 compileflags=None, optionflags=0):
1937 """
1938 Test examples in the given object's docstring (`f`), using `globs`
1939 as globals. Optional argument `name` is used in failure messages.
1940 If the optional argument `verbose` is true, then generate output
1941 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001942
Tim Peters8485b562004-08-04 18:46:34 +00001943 `compileflags` gives the set of flags that should be used by the
1944 Python compiler when running the examples. If not specified, then
1945 it will default to the set of future-import flags that apply to
1946 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001947
Tim Peters8485b562004-08-04 18:46:34 +00001948 Optional keyword arg `optionflags` specifies options for the
1949 testing and output. See the documentation for `testmod` for more
1950 information.
1951 """
1952 # Find, parse, and run all tests in the given module.
1953 finder = DocTestFinder(verbose=verbose, recurse=False)
1954 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1955 for test in finder.find(f, name, globs=globs):
1956 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001957
Tim Peters8485b562004-08-04 18:46:34 +00001958######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001959## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001960######################################################################
1961# This is provided only for backwards compatibility. It's not
1962# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001963
Tim Peters8485b562004-08-04 18:46:34 +00001964class Tester:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001965 def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001966
1967 warnings.warn("class Tester is deprecated; "
1968 "use class doctest.DocTestRunner instead",
1969 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001970 if mod is None and globs is None:
1971 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00001972 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00001973 raise TypeError("Tester.__init__: mod must be a module; %r" %
1974 (mod,))
1975 if globs is None:
1976 globs = mod.__dict__
1977 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001978
Tim Peters8485b562004-08-04 18:46:34 +00001979 self.verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +00001980 self.optionflags = optionflags
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001981 self.testfinder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00001982 self.testrunner = DocTestRunner(verbose=verbose,
1983 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001984
Tim Peters8485b562004-08-04 18:46:34 +00001985 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001986 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001987 if self.verbose:
1988 print "Running string", name
1989 (f,t) = self.testrunner.run(test)
1990 if self.verbose:
1991 print f, "of", t, "examples failed in string", name
1992 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001993
Tim Petersf3f57472004-08-08 06:11:48 +00001994 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001995 f = t = 0
1996 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001997 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001998 for test in tests:
1999 (f2, t2) = self.testrunner.run(test)
2000 (f,t) = (f+f2, t+t2)
2001 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002002
Tim Peters8485b562004-08-04 18:46:34 +00002003 def rundict(self, d, name, module=None):
2004 import new
2005 m = new.module(name)
2006 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002007 if module is None:
2008 module = False
2009 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002010
Tim Peters8485b562004-08-04 18:46:34 +00002011 def run__test__(self, d, name):
2012 import new
2013 m = new.module(name)
2014 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002015 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002016
Tim Peters8485b562004-08-04 18:46:34 +00002017 def summarize(self, verbose=None):
2018 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002019
Tim Peters8485b562004-08-04 18:46:34 +00002020 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002021 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002022
Tim Peters8485b562004-08-04 18:46:34 +00002023######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002024## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002025######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002026
Jim Fultonf54bad42004-08-28 14:57:56 +00002027_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002028
Jim Fultonf54bad42004-08-28 14:57:56 +00002029def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002030 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002031
2032 The old flag is returned so that a runner could restore the old
2033 value if it wished to:
2034
Tim Petersb7e99b62005-03-28 23:50:54 +00002035 >>> import doctest
2036 >>> old = doctest._unittest_reportflags
2037 >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
Jim Fultonf54bad42004-08-28 14:57:56 +00002038 ... REPORT_ONLY_FIRST_FAILURE) == old
2039 True
2040
Jim Fultonf54bad42004-08-28 14:57:56 +00002041 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2042 ... REPORT_ONLY_FIRST_FAILURE)
2043 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002044
Jim Fultonf54bad42004-08-28 14:57:56 +00002045 Only reporting flags can be set:
2046
Tim Petersb7e99b62005-03-28 23:50:54 +00002047 >>> doctest.set_unittest_reportflags(ELLIPSIS)
Jim Fultonf54bad42004-08-28 14:57:56 +00002048 Traceback (most recent call last):
2049 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002050 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002051
Tim Petersb7e99b62005-03-28 23:50:54 +00002052 >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
Jim Fultonf54bad42004-08-28 14:57:56 +00002053 ... REPORT_ONLY_FIRST_FAILURE)
2054 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002055 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002056 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002057
2058 if (flags & REPORTING_FLAGS) != flags:
2059 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002060 old = _unittest_reportflags
2061 _unittest_reportflags = flags
2062 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002063
Jim Fultonf54bad42004-08-28 14:57:56 +00002064
Tim Peters19397e52004-08-06 22:02:59 +00002065class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002066
Edward Loper34fcb142004-08-09 02:45:41 +00002067 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2068 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002069
Jim Fultona643b652004-07-14 19:06:50 +00002070 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002071 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002072 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002073 self._dt_test = test
2074 self._dt_setUp = setUp
2075 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002076
Jim Fultona643b652004-07-14 19:06:50 +00002077 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002078 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002079
Tim Peters19397e52004-08-06 22:02:59 +00002080 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002081 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002082
2083 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002084 test = self._dt_test
2085
Tim Peters19397e52004-08-06 22:02:59 +00002086 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002087 self._dt_tearDown(test)
2088
2089 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002090
2091 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002092 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002093 old = sys.stdout
2094 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002095 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002096
Tim Peters38330fe2004-08-30 16:19:24 +00002097 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002098 # The option flags don't include any reporting flags,
2099 # so add the default reporting flags
2100 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002101
Jim Fultonf54bad42004-08-28 14:57:56 +00002102 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002103 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002104
Jim Fultona643b652004-07-14 19:06:50 +00002105 try:
Tim Peters19397e52004-08-06 22:02:59 +00002106 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002107 failures, tries = runner.run(
2108 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002109 finally:
2110 sys.stdout = old
2111
2112 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002113 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002114
Tim Peters19397e52004-08-06 22:02:59 +00002115 def format_failure(self, err):
2116 test = self._dt_test
2117 if test.lineno is None:
2118 lineno = 'unknown line number'
2119 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002120 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002121 lname = '.'.join(test.name.split('.')[-1:])
2122 return ('Failed doctest test for %s\n'
2123 ' File "%s", line %s, in %s\n\n%s'
2124 % (test.name, test.filename, lineno, lname, err)
2125 )
2126
2127 def debug(self):
2128 r"""Run the test case without results and without catching exceptions
2129
2130 The unit test framework includes a debug method on test cases
2131 and test suites to support post-mortem debugging. The test code
2132 is run in such a way that errors are not caught. This way a
2133 caller can catch the errors and initiate post-mortem debugging.
2134
2135 The DocTestCase provides a debug method that raises
2136 UnexpectedException errors if there is an unexepcted
2137 exception:
2138
Edward Lopera1ef6112004-08-09 16:14:41 +00002139 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002140 ... {}, 'foo', 'foo.py', 0)
2141 >>> case = DocTestCase(test)
2142 >>> try:
2143 ... case.debug()
Guido van Rossumb940e112007-01-10 16:19:56 +00002144 ... except UnexpectedException as f:
2145 ... failure = f
Tim Peters19397e52004-08-06 22:02:59 +00002146
2147 The UnexpectedException contains the test, the example, and
2148 the original exception:
2149
2150 >>> failure.test is test
2151 True
2152
2153 >>> failure.example.want
2154 '42\n'
2155
2156 >>> exc_info = failure.exc_info
2157 >>> raise exc_info[0], exc_info[1], exc_info[2]
2158 Traceback (most recent call last):
2159 ...
2160 KeyError
2161
2162 If the output doesn't match, then a DocTestFailure is raised:
2163
Edward Lopera1ef6112004-08-09 16:14:41 +00002164 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002165 ... >>> x = 1
2166 ... >>> x
2167 ... 2
2168 ... ''', {}, 'foo', 'foo.py', 0)
2169 >>> case = DocTestCase(test)
2170
2171 >>> try:
2172 ... case.debug()
Guido van Rossumb940e112007-01-10 16:19:56 +00002173 ... except DocTestFailure as f:
2174 ... failure = f
Tim Peters19397e52004-08-06 22:02:59 +00002175
2176 DocTestFailure objects provide access to the test:
2177
2178 >>> failure.test is test
2179 True
2180
2181 As well as to the example:
2182
2183 >>> failure.example.want
2184 '2\n'
2185
2186 and the actual output:
2187
2188 >>> failure.got
2189 '1\n'
2190
2191 """
2192
Jim Fultonf54bad42004-08-28 14:57:56 +00002193 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002194 runner = DebugRunner(optionflags=self._dt_optionflags,
2195 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002196 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002197 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002198
2199 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002200 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002201
2202 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002203 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002204 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2205
2206 __str__ = __repr__
2207
2208 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002209 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002210
Jim Fultonf54bad42004-08-28 14:57:56 +00002211def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2212 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002213 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002214 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002215
Tim Peters19397e52004-08-06 22:02:59 +00002216 This converts each documentation string in a module that
2217 contains doctest tests to a unittest test case. If any of the
2218 tests in a doc string fail, then the test case fails. An exception
2219 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002220 (sometimes approximate) line number.
2221
Tim Peters19397e52004-08-06 22:02:59 +00002222 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002223 can be either a module or a module name.
2224
2225 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002226
2227 A number of options may be provided as keyword arguments:
2228
Jim Fultonf54bad42004-08-28 14:57:56 +00002229 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002230 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002231 tests in each file. The setUp function will be passed a DocTest
2232 object. The setUp function can access the test globals as the
2233 globs attribute of the test passed.
2234
2235 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002236 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002237 tests in each file. The tearDown function will be passed a DocTest
2238 object. The tearDown function can access the test globals as the
2239 globs attribute of the test passed.
2240
2241 globs
2242 A dictionary containing initial global variables for the tests.
2243
2244 optionflags
2245 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002246 """
Jim Fultona643b652004-07-14 19:06:50 +00002247
Tim Peters8485b562004-08-04 18:46:34 +00002248 if test_finder is None:
2249 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002250
Tim Peters19397e52004-08-06 22:02:59 +00002251 module = _normalize_module(module)
2252 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2253 if globs is None:
2254 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002255 if not tests:
2256 # Why do we want to do this? Because it reveals a bug that might
2257 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002258 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002259
2260 tests.sort()
2261 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002262 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002263 if len(test.examples) == 0:
2264 continue
Tim Peters8485b562004-08-04 18:46:34 +00002265 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002266 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002267 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002268 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002269 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002270 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002271
2272 return suite
2273
2274class DocFileCase(DocTestCase):
2275
2276 def id(self):
2277 return '_'.join(self._dt_test.name.split('.'))
2278
2279 def __repr__(self):
2280 return self._dt_test.filename
2281 __str__ = __repr__
2282
2283 def format_failure(self, err):
2284 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2285 % (self._dt_test.name, self._dt_test.filename, err)
2286 )
2287
Edward Loper052d0cd2004-09-19 17:19:33 +00002288def DocFileTest(path, module_relative=True, package=None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002289 globs=None, parser=DocTestParser(),
2290 encoding=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002291 if globs is None:
2292 globs = {}
Fred Drake7c404a42004-12-21 23:46:34 +00002293 else:
2294 globs = globs.copy()
Tim Peters19397e52004-08-06 22:02:59 +00002295
Edward Loper052d0cd2004-09-19 17:19:33 +00002296 if package and not module_relative:
2297 raise ValueError("Package may only be specified for module-"
2298 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00002299
Edward Loper052d0cd2004-09-19 17:19:33 +00002300 # Relativize the path.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002301 doc, path = _load_testfile(path, package, module_relative)
2302
Fred Drake7c404a42004-12-21 23:46:34 +00002303 if "__file__" not in globs:
2304 globs["__file__"] = path
Tim Peters19397e52004-08-06 22:02:59 +00002305
Edward Loper052d0cd2004-09-19 17:19:33 +00002306 # Find the file and read it.
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002307 name = os.path.basename(path)
Edward Loper052d0cd2004-09-19 17:19:33 +00002308
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002309 # If an encoding is specified, use it to convert the file to unicode
2310 if encoding is not None:
2311 doc = doc.decode(encoding)
2312
Edward Loper052d0cd2004-09-19 17:19:33 +00002313 # Convert it to a test, and wrap it in a DocFileCase.
Edward Loper498a1862004-09-27 03:42:58 +00002314 test = parser.get_doctest(doc, globs, name, path, 0)
Jim Fultonf54bad42004-08-28 14:57:56 +00002315 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002316
2317def DocFileSuite(*paths, **kw):
Edward Loper052d0cd2004-09-19 17:19:33 +00002318 """A unittest suite for one or more doctest files.
Tim Petersbab3e992004-09-20 19:52:34 +00002319
Edward Loper052d0cd2004-09-19 17:19:33 +00002320 The path to each doctest file is given as a string; the
2321 interpretation of that string depends on the keyword argument
2322 "module_relative".
Tim Peters19397e52004-08-06 22:02:59 +00002323
2324 A number of options may be provided as keyword arguments:
2325
Edward Loper052d0cd2004-09-19 17:19:33 +00002326 module_relative
2327 If "module_relative" is True, then the given file paths are
2328 interpreted as os-independent module-relative paths. By
2329 default, these paths are relative to the calling module's
2330 directory; but if the "package" argument is specified, then
2331 they are relative to that package. To ensure os-independence,
2332 "filename" should use "/" characters to separate path
2333 segments, and may not be an absolute path (i.e., it may not
2334 begin with "/").
Tim Petersbab3e992004-09-20 19:52:34 +00002335
Edward Loper052d0cd2004-09-19 17:19:33 +00002336 If "module_relative" is False, then the given file paths are
2337 interpreted as os-specific paths. These paths may be absolute
2338 or relative (to the current working directory).
2339
Tim Peters19397e52004-08-06 22:02:59 +00002340 package
Edward Loper052d0cd2004-09-19 17:19:33 +00002341 A Python package or the name of a Python package whose directory
2342 should be used as the base directory for module relative paths.
2343 If "package" is not specified, then the calling module's
2344 directory is used as the base directory for module relative
2345 filenames. It is an error to specify "package" if
2346 "module_relative" is False.
Tim Peters19397e52004-08-06 22:02:59 +00002347
2348 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002349 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002350 tests in each file. The setUp function will be passed a DocTest
2351 object. The setUp function can access the test globals as the
2352 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002353
2354 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002355 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002356 tests in each file. The tearDown function will be passed a DocTest
2357 object. The tearDown function can access the test globals as the
2358 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002359
2360 globs
2361 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002362
2363 optionflags
Edward Loper498a1862004-09-27 03:42:58 +00002364 A set of doctest option flags expressed as an integer.
2365
2366 parser
2367 A DocTestParser (or subclass) that should be used to extract
2368 tests from the files.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002369
2370 encoding
2371 An encoding that will be used to convert the files to unicode.
Tim Peters19397e52004-08-06 22:02:59 +00002372 """
2373 suite = unittest.TestSuite()
2374
2375 # We do this here so that _normalize_module is called at the right
2376 # level. If it were called in DocFileTest, then this function
2377 # would be the caller and we might guess the package incorrectly.
Edward Loper052d0cd2004-09-19 17:19:33 +00002378 if kw.get('module_relative', True):
2379 kw['package'] = _normalize_module(kw.get('package'))
Tim Peters19397e52004-08-06 22:02:59 +00002380
2381 for path in paths:
2382 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002383
Tim Petersdb3756d2003-06-29 05:30:48 +00002384 return suite
2385
Tim Peters8485b562004-08-04 18:46:34 +00002386######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002387## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002388######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002389
Tim Peters19397e52004-08-06 22:02:59 +00002390def script_from_examples(s):
2391 r"""Extract script from text with examples.
2392
2393 Converts text with examples to a Python script. Example input is
2394 converted to regular code. Example output and all other words
2395 are converted to comments:
2396
2397 >>> text = '''
2398 ... Here are examples of simple math.
2399 ...
2400 ... Python has super accurate integer addition
2401 ...
2402 ... >>> 2 + 2
2403 ... 5
2404 ...
2405 ... And very friendly error messages:
2406 ...
2407 ... >>> 1/0
2408 ... To Infinity
2409 ... And
2410 ... Beyond
2411 ...
2412 ... You can use logic if you want:
2413 ...
2414 ... >>> if 0:
2415 ... ... blah
2416 ... ... blah
2417 ... ...
2418 ...
2419 ... Ho hum
2420 ... '''
2421
2422 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002423 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002424 #
Edward Lopera5db6002004-08-12 02:41:30 +00002425 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002426 #
2427 2 + 2
2428 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002429 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002430 #
Edward Lopera5db6002004-08-12 02:41:30 +00002431 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002432 #
2433 1/0
2434 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002435 ## To Infinity
2436 ## And
2437 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002438 #
Edward Lopera5db6002004-08-12 02:41:30 +00002439 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002440 #
2441 if 0:
2442 blah
2443 blah
Tim Peters19397e52004-08-06 22:02:59 +00002444 #
Edward Lopera5db6002004-08-12 02:41:30 +00002445 # Ho hum
Georg Brandlecf93c72005-06-26 23:09:51 +00002446 <BLANKLINE>
Tim Peters19397e52004-08-06 22:02:59 +00002447 """
Edward Loper00f8da72004-08-26 18:05:07 +00002448 output = []
2449 for piece in DocTestParser().parse(s):
2450 if isinstance(piece, Example):
2451 # Add the example's source code (strip trailing NL)
2452 output.append(piece.source[:-1])
2453 # Add the expected output:
2454 want = piece.want
2455 if want:
2456 output.append('# Expected:')
2457 output += ['## '+l for l in want.split('\n')[:-1]]
2458 else:
2459 # Add non-example text.
2460 output += [_comment_line(l)
2461 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002462
Edward Loper00f8da72004-08-26 18:05:07 +00002463 # Trim junk on both ends.
2464 while output and output[-1] == '#':
2465 output.pop()
2466 while output and output[0] == '#':
2467 output.pop(0)
2468 # Combine the output, and return it.
Georg Brandl1f149642005-06-26 22:22:31 +00002469 # Add a courtesy newline to prevent exec from choking (see bug #1172785)
2470 return '\n'.join(output) + '\n'
Tim Petersdb3756d2003-06-29 05:30:48 +00002471
2472def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002473 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002474
2475 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002476 test to be debugged and the name (within the module) of the object
2477 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002478 """
Tim Peters8485b562004-08-04 18:46:34 +00002479 module = _normalize_module(module)
2480 tests = DocTestFinder().find(module)
2481 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002482 if not test:
2483 raise ValueError(name, "not found in tests")
2484 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002485 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002486 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002487
Jim Fultona643b652004-07-14 19:06:50 +00002488def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002489 """Debug a single doctest docstring, in argument `src`'"""
2490 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002491 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002492
Jim Fultona643b652004-07-14 19:06:50 +00002493def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002494 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002495 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002496
Tim Petersb6a04d62004-08-23 21:37:56 +00002497 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2498 # docs say, a file so created cannot be opened by name a second time
2499 # on modern Windows boxes, and execfile() needs to open it.
2500 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002501 f = open(srcfilename, 'w')
2502 f.write(src)
2503 f.close()
2504
Tim Petersb6a04d62004-08-23 21:37:56 +00002505 try:
2506 if globs:
2507 globs = globs.copy()
2508 else:
2509 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002510
Tim Petersb6a04d62004-08-23 21:37:56 +00002511 if pm:
2512 try:
2513 execfile(srcfilename, globs, globs)
2514 except:
2515 print sys.exc_info()[1]
2516 pdb.post_mortem(sys.exc_info()[2])
2517 else:
2518 # Note that %r is vital here. '%s' instead can, e.g., cause
2519 # backslashes to get treated as metacharacters on Windows.
2520 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2521
2522 finally:
2523 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002524
Jim Fultona643b652004-07-14 19:06:50 +00002525def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002526 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002527
2528 Provide the module (or dotted name of the module) containing the
2529 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002530 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002531 """
Tim Peters8485b562004-08-04 18:46:34 +00002532 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002533 testsrc = testsource(module, name)
2534 debug_script(testsrc, pm, module.__dict__)
2535
Tim Peters8485b562004-08-04 18:46:34 +00002536######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002537## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002538######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002539class _TestClass:
2540 """
2541 A pointless class, for sanity-checking of docstring testing.
2542
2543 Methods:
2544 square()
2545 get()
2546
2547 >>> _TestClass(13).get() + _TestClass(-12).get()
2548 1
2549 >>> hex(_TestClass(13).square().get())
2550 '0xa9'
2551 """
2552
2553 def __init__(self, val):
2554 """val -> _TestClass object with associated value val.
2555
2556 >>> t = _TestClass(123)
2557 >>> print t.get()
2558 123
2559 """
2560
2561 self.val = val
2562
2563 def square(self):
2564 """square() -> square TestClass's associated value
2565
2566 >>> _TestClass(13).square().get()
2567 169
2568 """
2569
2570 self.val = self.val ** 2
2571 return self
2572
2573 def get(self):
2574 """get() -> return TestClass's associated value.
2575
2576 >>> x = _TestClass(-42)
2577 >>> print x.get()
2578 -42
2579 """
2580
2581 return self.val
2582
2583__test__ = {"_TestClass": _TestClass,
2584 "string": r"""
2585 Example of a string object, searched as-is.
2586 >>> x = 1; y = 2
2587 >>> x + y, x * y
2588 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002589 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002590
Tim Peters6ebe61f2003-06-27 20:48:05 +00002591 "bool-int equivalence": r"""
2592 In 2.2, boolean expressions displayed
2593 0 or 1. By default, we still accept
2594 them. This can be disabled by passing
2595 DONT_ACCEPT_TRUE_FOR_1 to the new
2596 optionflags argument.
2597 >>> 4 == 4
2598 1
2599 >>> 4 == 4
2600 True
2601 >>> 4 > 4
2602 0
2603 >>> 4 > 4
2604 False
2605 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002606
Tim Peters8485b562004-08-04 18:46:34 +00002607 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002608 Blank lines can be marked with <BLANKLINE>:
2609 >>> print 'foo\n\nbar\n'
2610 foo
2611 <BLANKLINE>
2612 bar
2613 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002614 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002615
2616 "ellipsis": r"""
2617 If the ellipsis flag is used, then '...' can be used to
2618 elide substrings in the desired output:
2619 >>> print range(1000) #doctest: +ELLIPSIS
2620 [0, 1, 2, ..., 999]
2621 """,
2622
2623 "whitespace normalization": r"""
2624 If the whitespace normalization flag is used, then
2625 differences in whitespace are ignored.
2626 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2627 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2628 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2629 27, 28, 29]
2630 """,
2631 }
Tim Peters8485b562004-08-04 18:46:34 +00002632
Tim Peters8a7d2d52001-01-16 07:10:57 +00002633def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002634 r = unittest.TextTestRunner()
2635 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002636
2637if __name__ == "__main__":
2638 _test()