blob: 67907a52c4f99921852f613483d155927bb2cc18 [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
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +0000173 # 0, Option Flags
174 'register_optionflag',
175 'DONT_ACCEPT_TRUE_FOR_1',
176 'DONT_ACCEPT_BLANKLINE',
177 'NORMALIZE_WHITESPACE',
178 'ELLIPSIS',
Edward Loper71f55af2004-08-26 01:41:51 +0000179 'REPORT_UDIFF',
180 'REPORT_CDIFF',
181 'REPORT_NDIFF',
Jim Fultonf54bad42004-08-28 14:57:56 +0000182 'REPORT_ONLY_FIRST_FAILURE',
Edward Loperb7503ff2004-08-19 19:19:03 +0000183 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000184 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000185 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000186 'Example',
187 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000188 # 3. Doctest Parser
189 'DocTestParser',
190 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000191 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000192 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000193 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000194 'OutputChecker',
195 'DocTestFailure',
196 'UnexpectedException',
197 'DebugRunner',
198 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000199 'testmod',
200 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000201 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000202 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000203 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000204 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000205 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000206 'DocFileCase',
207 'DocFileTest',
208 'DocFileSuite',
209 # 9. Debugging Support
210 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000211 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000212 'debug_src',
213 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000214 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000215]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000216
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000217import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000218
Tim Peters19397e52004-08-06 22:02:59 +0000219import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000220import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000221import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000222from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000223
Tim Petersdd50cb72004-08-23 22:42:55 +0000224# Don't whine about the deprecated is_private function in this
225# module's tests.
226warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
227 __name__, 0)
228
Jim Fulton356fd192004-08-09 11:34:47 +0000229real_pdb_set_trace = pdb.set_trace
230
Tim Peters19397e52004-08-06 22:02:59 +0000231# There are 4 basic classes:
232# - Example: a <source, want> pair, plus an intra-docstring line number.
233# - DocTest: a collection of examples, parsed from a docstring, plus
234# info about where the docstring came from (name, filename, lineno).
235# - DocTestFinder: extracts DocTests from a given object's docstring and
236# its contained objects' docstrings.
237# - DocTestRunner: runs DocTest cases, and accumulates statistics.
238#
239# So the basic picture is:
240#
241# list of:
242# +------+ +---------+ +-------+
243# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
244# +------+ +---------+ +-------+
245# | Example |
246# | ... |
247# | Example |
248# +---------+
249
Edward Loperac20f572004-08-12 02:02:24 +0000250# Option constants.
251OPTIONFLAGS_BY_NAME = {}
252def register_optionflag(name):
253 flag = 1 << len(OPTIONFLAGS_BY_NAME)
254 OPTIONFLAGS_BY_NAME[name] = flag
255 return flag
256
257DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
258DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
259NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
260ELLIPSIS = register_optionflag('ELLIPSIS')
Edward Loper71f55af2004-08-26 01:41:51 +0000261REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
262REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
263REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000264REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000265
266# Special string markers for use in `want` strings:
267BLANKLINE_MARKER = '<BLANKLINE>'
268ELLIPSIS_MARKER = '...'
269
Tim Peters8485b562004-08-04 18:46:34 +0000270######################################################################
271## Table of Contents
272######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000273# 1. Utility Functions
274# 2. Example & DocTest -- store test cases
275# 3. DocTest Parser -- extracts examples from strings
276# 4. DocTest Finder -- extracts test cases from objects
277# 5. DocTest Runner -- runs test cases
278# 6. Test Functions -- convenient wrappers for testing
279# 7. Tester Class -- for backwards compatibility
280# 8. Unittest Support
281# 9. Debugging Support
282# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000283
Tim Peters8485b562004-08-04 18:46:34 +0000284######################################################################
285## 1. Utility Functions
286######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000287
288def is_private(prefix, base):
289 """prefix, base -> true iff name prefix + "." + base is "private".
290
291 Prefix may be an empty string, and base does not contain a period.
292 Prefix is ignored (although functions you write conforming to this
293 protocol may make use of it).
294 Return true iff base begins with an (at least one) underscore, but
295 does not both begin and end with (at least) two underscores.
296
297 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000298 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000300 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000301 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000302 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000303 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000304 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000305 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000306 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000307 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000308 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000309 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000310 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000311 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000312 warnings.warn("is_private is deprecated; it wasn't useful; "
313 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000314 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000315 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
316
Tim Peters8485b562004-08-04 18:46:34 +0000317def _extract_future_flags(globs):
318 """
319 Return the compiler-flags associated with the future features that
320 have been imported into the given namespace (globs).
321 """
322 flags = 0
323 for fname in __future__.all_feature_names:
324 feature = globs.get(fname, None)
325 if feature is getattr(__future__, fname):
326 flags |= feature.compiler_flag
327 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000328
Tim Peters8485b562004-08-04 18:46:34 +0000329def _normalize_module(module, depth=2):
330 """
331 Return the module specified by `module`. In particular:
332 - If `module` is a module, then return module.
333 - If `module` is a string, then import and return the
334 module with that name.
335 - If `module` is None, then return the calling module.
336 The calling module is assumed to be the module of
337 the stack frame at the given depth in the call stack.
338 """
339 if inspect.ismodule(module):
340 return module
341 elif isinstance(module, (str, unicode)):
342 return __import__(module, globals(), locals(), ["*"])
343 elif module is None:
344 return sys.modules[sys._getframe(depth).f_globals['__name__']]
345 else:
346 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000347
Edward Loperaacf0832004-08-26 01:19:50 +0000348def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000349 """
Edward Loperaacf0832004-08-26 01:19:50 +0000350 Add the given number of space characters to the beginning every
351 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000352 """
Edward Loperaacf0832004-08-26 01:19:50 +0000353 # This regexp matches the start of non-blank lines:
354 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000355
Edward Loper8e4a34b2004-08-12 02:34:27 +0000356def _exception_traceback(exc_info):
357 """
358 Return a string containing a traceback message for the given
359 exc_info tuple (as returned by sys.exc_info()).
360 """
361 # Get a traceback message.
362 excout = StringIO()
363 exc_type, exc_val, exc_tb = exc_info
364 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
365 return excout.getvalue()
366
Tim Peters8485b562004-08-04 18:46:34 +0000367# Override some StringIO methods.
368class _SpoofOut(StringIO):
369 def getvalue(self):
370 result = StringIO.getvalue(self)
371 # If anything at all was written, make sure there's a trailing
372 # newline. There's no way for the expected output to indicate
373 # that a trailing newline is missing.
374 if result and not result.endswith("\n"):
375 result += "\n"
376 # Prevent softspace from screwing up the next test case, in
377 # case they used print with a trailing comma in an example.
378 if hasattr(self, "softspace"):
379 del self.softspace
380 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000381
Tim Peters8485b562004-08-04 18:46:34 +0000382 def truncate(self, size=None):
383 StringIO.truncate(self, size)
384 if hasattr(self, "softspace"):
385 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000386
Tim Peters26b3ebb2004-08-19 08:10:08 +0000387# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000388def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000389 """
390 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000391 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000392 False
393 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000394 if ELLIPSIS_MARKER not in want:
395 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000396
Tim Peters26b3ebb2004-08-19 08:10:08 +0000397 # Find "the real" strings.
398 ws = want.split(ELLIPSIS_MARKER)
399 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000400
Tim Petersdc5de3b2004-08-19 14:06:20 +0000401 # Deal with exact matches possibly needed at one or both ends.
402 startpos, endpos = 0, len(got)
403 w = ws[0]
404 if w: # starts with exact match
405 if got.startswith(w):
406 startpos = len(w)
407 del ws[0]
408 else:
409 return False
410 w = ws[-1]
411 if w: # ends with exact match
412 if got.endswith(w):
413 endpos -= len(w)
414 del ws[-1]
415 else:
416 return False
417
418 if startpos > endpos:
419 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000420 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000421 return False
422
423 # For the rest, we only need to find the leftmost non-overlapping
424 # match for each piece. If there's no overall match that way alone,
425 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000426 for w in ws:
427 # w may be '' at times, if there are consecutive ellipses, or
428 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000429 # Search for an empty string succeeds, and doesn't change startpos.
430 startpos = got.find(w, startpos, endpos)
431 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000432 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000433 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000434
Tim Petersdc5de3b2004-08-19 14:06:20 +0000435 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000436
Edward Loper00f8da72004-08-26 18:05:07 +0000437def _comment_line(line):
438 "Return a commented form of the given line"
439 line = line.rstrip()
440 if line:
441 return '# '+line
442 else:
443 return '#'
444
Edward Loper2de91ba2004-08-27 02:07:46 +0000445class _OutputRedirectingPdb(pdb.Pdb):
446 """
447 A specialized version of the python debugger that redirects stdout
448 to a given stream when interacting with the user. Stdout is *not*
449 redirected when traced code is executed.
450 """
451 def __init__(self, out):
452 self.__out = out
453 pdb.Pdb.__init__(self)
454
455 def trace_dispatch(self, *args):
456 # Redirect stdout to the given stream.
457 save_stdout = sys.stdout
458 sys.stdout = self.__out
459 # Call Pdb's trace dispatch method.
460 pdb.Pdb.trace_dispatch(self, *args)
461 # Restore stdout.
462 sys.stdout = save_stdout
463
Tim Peters8485b562004-08-04 18:46:34 +0000464######################################################################
465## 2. Example & DocTest
466######################################################################
467## - An "example" is a <source, want> pair, where "source" is a
468## fragment of source code, and "want" is the expected output for
469## "source." The Example class also includes information about
470## where the example was extracted from.
471##
Edward Lopera1ef6112004-08-09 16:14:41 +0000472## - A "doctest" is a collection of examples, typically extracted from
473## a string (such as an object's docstring). The DocTest class also
474## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000475
Tim Peters8485b562004-08-04 18:46:34 +0000476class Example:
477 """
478 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000479 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000480
Edward Loper74bca7a2004-08-12 02:27:44 +0000481 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000482 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000483
Edward Loper74bca7a2004-08-12 02:27:44 +0000484 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000485 from stdout, or a traceback in case of exception). `want` ends
486 with a newline unless it's empty, in which case it's an empty
487 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000488
Edward Lopera6b68322004-08-26 00:05:43 +0000489 - exc_msg: The exception message generated by the example, if
490 the example is expected to generate an exception; or `None` if
491 it is not expected to generate an exception. This exception
492 message is compared against the return value of
493 `traceback.format_exception_only()`. `exc_msg` ends with a
494 newline unless it's `None`. The constructor adds a newline
495 if needed.
496
Edward Loper74bca7a2004-08-12 02:27:44 +0000497 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000498 this Example where the Example begins. This line number is
499 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000500
501 - indent: The example's indentation in the DocTest string.
502 I.e., the number of space characters that preceed the
503 example's first prompt.
504
505 - options: A dictionary mapping from option flags to True or
506 False, which is used to override default options for this
507 example. Any option flags not contained in this dictionary
508 are left at their default value (as specified by the
509 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000510 """
Edward Lopera6b68322004-08-26 00:05:43 +0000511 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
512 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000513 # Normalize inputs.
514 if not source.endswith('\n'):
515 source += '\n'
516 if want and not want.endswith('\n'):
517 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000518 if exc_msg is not None and not exc_msg.endswith('\n'):
519 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000520 # Store properties.
521 self.source = source
522 self.want = want
523 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000524 self.indent = indent
525 if options is None: options = {}
526 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000527 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000528
Tim Peters8485b562004-08-04 18:46:34 +0000529class DocTest:
530 """
531 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000532 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000533
Tim Peters8485b562004-08-04 18:46:34 +0000534 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000535
Tim Peters8485b562004-08-04 18:46:34 +0000536 - globs: The namespace (aka globals) that the examples should
537 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000538
Tim Peters8485b562004-08-04 18:46:34 +0000539 - name: A name identifying the DocTest (typically, the name of
540 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000541
Tim Peters8485b562004-08-04 18:46:34 +0000542 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000543 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000544
Tim Peters8485b562004-08-04 18:46:34 +0000545 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000546 begins, or `None` if the line number is unavailable. This
547 line number is zero-based, with respect to the beginning of
548 the file.
549
550 - docstring: The string that the examples were extracted from,
551 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000552 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000553 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000554 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000555 Create a new DocTest containing the given examples. The
556 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000557 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000558 assert not isinstance(examples, basestring), \
559 "DocTest no longer accepts str; use DocTestParser instead"
560 self.examples = examples
561 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000562 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000563 self.name = name
564 self.filename = filename
565 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000566
567 def __repr__(self):
568 if len(self.examples) == 0:
569 examples = 'no examples'
570 elif len(self.examples) == 1:
571 examples = '1 example'
572 else:
573 examples = '%d examples' % len(self.examples)
574 return ('<DocTest %s from %s:%s (%s)>' %
575 (self.name, self.filename, self.lineno, examples))
576
577
578 # This lets us sort tests by name:
579 def __cmp__(self, other):
580 if not isinstance(other, DocTest):
581 return -1
582 return cmp((self.name, self.filename, self.lineno, id(self)),
583 (other.name, other.filename, other.lineno, id(other)))
584
585######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000586## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000587######################################################################
588
Edward Lopera1ef6112004-08-09 16:14:41 +0000589class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000590 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000591 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000592 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000593 # This regular expression is used to find doctest examples in a
594 # string. It defines three groups: `source` is the source code
595 # (including leading indentation and prompts); `indent` is the
596 # indentation of the first (PS1) line of the source code; and
597 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000598 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000599 # Source consists of a PS1 line followed by zero or more PS2 lines.
600 (?P<source>
601 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
602 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
603 \n?
604 # Want consists of any non-blank lines that do not start with PS1.
605 (?P<want> (?:(?![ ]*$) # Not a blank line
606 (?![ ]*>>>) # Not a line starting with PS1
607 .*$\n? # But any other line
608 )*)
609 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000610
Edward Lopera6b68322004-08-26 00:05:43 +0000611 # A regular expression for handling `want` strings that contain
612 # expected exceptions. It divides `want` into three pieces:
613 # - the traceback header line (`hdr`)
614 # - the traceback stack (`stack`)
615 # - the exception message (`msg`), as generated by
616 # traceback.format_exception_only()
617 # `msg` may have multiple lines. We assume/require that the
618 # exception message is the first non-indented line starting with a word
619 # character following the traceback header line.
620 _EXCEPTION_RE = re.compile(r"""
621 # Grab the traceback header. Different versions of Python have
622 # said different things on the first traceback line.
623 ^(?P<hdr> Traceback\ \(
624 (?: most\ recent\ call\ last
625 | innermost\ last
626 ) \) :
627 )
628 \s* $ # toss trailing whitespace on the header.
629 (?P<stack> .*?) # don't blink: absorb stuff until...
630 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
631 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
632
Tim Peters7ea48dd2004-08-13 01:52:59 +0000633 # A callable returning a true value iff its argument is a blank line
634 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000635 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000636
Edward Loper00f8da72004-08-26 18:05:07 +0000637 def parse(self, string, name='<string>'):
638 """
639 Divide the given string into examples and intervening text,
640 and return them as a list of alternating Examples and strings.
641 Line numbers for the Examples are 0-based. The optional
642 argument `name` is a name identifying this string, and is only
643 used for error messages.
644 """
645 string = string.expandtabs()
646 # If all lines begin with the same indentation, then strip it.
647 min_indent = self._min_indent(string)
648 if min_indent > 0:
649 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
650
651 output = []
652 charno, lineno = 0, 0
653 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000654 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000655 # Add the pre-example text to `output`.
656 output.append(string[charno:m.start()])
657 # Update lineno (lines before this example)
658 lineno += string.count('\n', charno, m.start())
659 # Extract info from the regexp match.
660 (source, options, want, exc_msg) = \
661 self._parse_example(m, name, lineno)
662 # Create an Example, and add it to the list.
663 if not self._IS_BLANK_OR_COMMENT(source):
664 output.append( Example(source, want, exc_msg,
665 lineno=lineno,
666 indent=min_indent+len(m.group('indent')),
667 options=options) )
668 # Update lineno (lines inside this example)
669 lineno += string.count('\n', m.start(), m.end())
670 # Update charno.
671 charno = m.end()
672 # Add any remaining post-example text to `output`.
673 output.append(string[charno:])
674 return output
675
Edward Lopera1ef6112004-08-09 16:14:41 +0000676 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000677 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000678 Extract all doctest examples from the given string, and
679 collect them into a `DocTest` object.
680
681 `globs`, `name`, `filename`, and `lineno` are attributes for
682 the new `DocTest` object. See the documentation for `DocTest`
683 for more information.
684 """
685 return DocTest(self.get_examples(string, name), globs,
686 name, filename, lineno, string)
687
688 def get_examples(self, string, name='<string>'):
689 """
690 Extract all doctest examples from the given string, and return
691 them as a list of `Example` objects. Line numbers are
692 0-based, because it's most common in doctests that nothing
693 interesting appears on the same line as opening triple-quote,
694 and so the first interesting line is called \"line 1\" then.
695
696 The optional argument `name` is a name identifying this
697 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000698 """
Edward Loper00f8da72004-08-26 18:05:07 +0000699 return [x for x in self.parse(string, name)
700 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000701
Edward Loper74bca7a2004-08-12 02:27:44 +0000702 def _parse_example(self, m, name, lineno):
703 """
704 Given a regular expression match from `_EXAMPLE_RE` (`m`),
705 return a pair `(source, want)`, where `source` is the matched
706 example's source code (with prompts and indentation stripped);
707 and `want` is the example's expected output (with indentation
708 stripped).
709
710 `name` is the string's name, and `lineno` is the line number
711 where the example starts; both are used for error messages.
712 """
Edward Loper7c748462004-08-09 02:06:06 +0000713 # Get the example's indentation level.
714 indent = len(m.group('indent'))
715
716 # Divide source into lines; check that they're properly
717 # indented; and then strip their indentation & prompts.
718 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000719 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000720 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000721 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000722
Tim Petersc5049152004-08-22 17:34:58 +0000723 # Divide want into lines; check that it's properly indented; and
724 # then strip the indentation. Spaces before the last newline should
725 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000726 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000727 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000728 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
729 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000730 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000731 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000732 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000733
Edward Lopera6b68322004-08-26 00:05:43 +0000734 # If `want` contains a traceback message, then extract it.
735 m = self._EXCEPTION_RE.match(want)
736 if m:
737 exc_msg = m.group('msg')
738 else:
739 exc_msg = None
740
Edward Loper00f8da72004-08-26 18:05:07 +0000741 # Extract options from the source.
742 options = self._find_options(source, name, lineno)
743
744 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000745
Edward Loper74bca7a2004-08-12 02:27:44 +0000746 # This regular expression looks for option directives in the
747 # source code of an example. Option directives are comments
748 # starting with "doctest:". Warning: this may give false
749 # positives for string-literals that contain the string
750 # "#doctest:". Eliminating these false positives would require
751 # actually parsing the string; but we limit them by ignoring any
752 # line containing "#doctest:" that is *followed* by a quote mark.
753 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
754 re.MULTILINE)
755
756 def _find_options(self, source, name, lineno):
757 """
758 Return a dictionary containing option overrides extracted from
759 option directives in the given source string.
760
761 `name` is the string's name, and `lineno` is the line number
762 where the example starts; both are used for error messages.
763 """
764 options = {}
765 # (note: with the current regexp, this will match at most once:)
766 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
767 option_strings = m.group(1).replace(',', ' ').split()
768 for option in option_strings:
769 if (option[0] not in '+-' or
770 option[1:] not in OPTIONFLAGS_BY_NAME):
771 raise ValueError('line %r of the doctest for %s '
772 'has an invalid option: %r' %
773 (lineno+1, name, option))
774 flag = OPTIONFLAGS_BY_NAME[option[1:]]
775 options[flag] = (option[0] == '+')
776 if options and self._IS_BLANK_OR_COMMENT(source):
777 raise ValueError('line %r of the doctest for %s has an option '
778 'directive on a line with no example: %r' %
779 (lineno, name, source))
780 return options
781
Edward Lopera5db6002004-08-12 02:41:30 +0000782 # This regular expression finds the indentation of every non-blank
783 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000784 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000785
786 def _min_indent(self, s):
787 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000788 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
789 if len(indents) > 0:
790 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000791 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000792 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000793
Edward Lopera1ef6112004-08-09 16:14:41 +0000794 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000795 """
796 Given the lines of a source string (including prompts and
797 leading indentation), check to make sure that every prompt is
798 followed by a space character. If any line is not followed by
799 a space character, then raise ValueError.
800 """
Edward Loper7c748462004-08-09 02:06:06 +0000801 for i, line in enumerate(lines):
802 if len(line) >= indent+4 and line[indent+3] != ' ':
803 raise ValueError('line %r of the docstring for %s '
804 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000805 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000806 line[indent:indent+3], line))
807
Edward Lopera1ef6112004-08-09 16:14:41 +0000808 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000809 """
810 Check that every line in the given list starts with the given
811 prefix; if any line does not, then raise a ValueError.
812 """
Edward Loper7c748462004-08-09 02:06:06 +0000813 for i, line in enumerate(lines):
814 if line and not line.startswith(prefix):
815 raise ValueError('line %r of the docstring for %s has '
816 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000817 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000818
819
820######################################################################
821## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000822######################################################################
823
824class DocTestFinder:
825 """
826 A class used to extract the DocTests that are relevant to a given
827 object, from its docstring and the docstrings of its contained
828 objects. Doctests can currently be extracted from the following
829 object types: modules, functions, classes, methods, staticmethods,
830 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000831 """
832
Edward Lopera1ef6112004-08-09 16:14:41 +0000833 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000834 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000835 """
836 Create a new doctest finder.
837
Edward Lopera1ef6112004-08-09 16:14:41 +0000838 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000839 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000840 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000841 signature for this factory function should match the signature
842 of the DocTest constructor.
843
Tim Peters8485b562004-08-04 18:46:34 +0000844 If the optional argument `recurse` is false, then `find` will
845 only examine the given object, and not any contained objects.
846 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000847 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000848 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000849 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000850 # _namefilter is undocumented, and exists only for temporary backward-
851 # compatibility support of testmod's deprecated isprivate mess.
852 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000853
854 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000855 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000856 """
857 Return a list of the DocTests that are defined by the given
858 object's docstring, or by any of its contained objects'
859 docstrings.
860
861 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000862 the given object. If the module is not specified or is None, then
863 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000864 correct module. The object's module is used:
865
866 - As a default namespace, if `globs` is not specified.
867 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000868 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000869 - To find the name of the file containing the object.
870 - To help find the line number of the object within its
871 file.
872
Tim Petersf3f57472004-08-08 06:11:48 +0000873 Contained objects whose module does not match `module` are ignored.
874
875 If `module` is False, no attempt to find the module will be made.
876 This is obscure, of use mostly in tests: if `module` is False, or
877 is None but cannot be found automatically, then all objects are
878 considered to belong to the (non-existent) module, so all contained
879 objects will (recursively) be searched for doctests.
880
Tim Peters8485b562004-08-04 18:46:34 +0000881 The globals for each DocTest is formed by combining `globs`
882 and `extraglobs` (bindings in `extraglobs` override bindings
883 in `globs`). A new copy of the globals dictionary is created
884 for each DocTest. If `globs` is not specified, then it
885 defaults to the module's `__dict__`, if specified, or {}
886 otherwise. If `extraglobs` is not specified, then it defaults
887 to {}.
888
Tim Peters8485b562004-08-04 18:46:34 +0000889 """
890 # If name was not specified, then extract it from the object.
891 if name is None:
892 name = getattr(obj, '__name__', None)
893 if name is None:
894 raise ValueError("DocTestFinder.find: name must be given "
895 "when obj.__name__ doesn't exist: %r" %
896 (type(obj),))
897
898 # Find the module that contains the given object (if obj is
899 # a module, then module=obj.). Note: this may fail, in which
900 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000901 if module is False:
902 module = None
903 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000904 module = inspect.getmodule(obj)
905
906 # Read the module's source code. This is used by
907 # DocTestFinder._find_lineno to find the line number for a
908 # given object's docstring.
909 try:
910 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
911 source_lines = linecache.getlines(file)
912 if not source_lines:
913 source_lines = None
914 except TypeError:
915 source_lines = None
916
917 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000918 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000919 if module is None:
920 globs = {}
921 else:
922 globs = module.__dict__.copy()
923 else:
924 globs = globs.copy()
925 if extraglobs is not None:
926 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000927
Tim Peters8485b562004-08-04 18:46:34 +0000928 # Recursively expore `obj`, extracting DocTests.
929 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000930 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000931 return tests
932
933 def _filter(self, obj, prefix, base):
934 """
935 Return true if the given object should not be examined.
936 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000937 return (self._namefilter is not None and
938 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000939
940 def _from_module(self, module, object):
941 """
942 Return true if the given object is defined in the given
943 module.
944 """
945 if module is None:
946 return True
947 elif inspect.isfunction(object):
948 return module.__dict__ is object.func_globals
949 elif inspect.isclass(object):
950 return module.__name__ == object.__module__
951 elif inspect.getmodule(object) is not None:
952 return module is inspect.getmodule(object)
953 elif hasattr(object, '__module__'):
954 return module.__name__ == object.__module__
955 elif isinstance(object, property):
956 return True # [XX] no way not be sure.
957 else:
958 raise ValueError("object must be a class or function")
959
Tim Petersf3f57472004-08-08 06:11:48 +0000960 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000961 """
962 Find tests for the given object and any contained objects, and
963 add them to `tests`.
964 """
965 if self._verbose:
966 print 'Finding tests in %s' % name
967
968 # If we've already processed this object, then ignore it.
969 if id(obj) in seen:
970 return
971 seen[id(obj)] = 1
972
973 # Find a test for this object, and add it to the list of tests.
974 test = self._get_test(obj, name, module, globs, source_lines)
975 if test is not None:
976 tests.append(test)
977
978 # Look for tests in a module's contained objects.
979 if inspect.ismodule(obj) and self._recurse:
980 for valname, val in obj.__dict__.items():
981 # Check if this contained object should be ignored.
982 if self._filter(val, name, valname):
983 continue
984 valname = '%s.%s' % (name, valname)
985 # Recurse to functions & classes.
986 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000987 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000988 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000989 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000990
991 # Look for tests in a module's __test__ dictionary.
992 if inspect.ismodule(obj) and self._recurse:
993 for valname, val in getattr(obj, '__test__', {}).items():
994 if not isinstance(valname, basestring):
995 raise ValueError("DocTestFinder.find: __test__ keys "
996 "must be strings: %r" %
997 (type(valname),))
998 if not (inspect.isfunction(val) or inspect.isclass(val) or
999 inspect.ismethod(val) or inspect.ismodule(val) or
1000 isinstance(val, basestring)):
1001 raise ValueError("DocTestFinder.find: __test__ values "
1002 "must be strings, functions, methods, "
1003 "classes, or modules: %r" %
1004 (type(val),))
1005 valname = '%s.%s' % (name, valname)
1006 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001007 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001008
1009 # Look for tests in a class's contained objects.
1010 if inspect.isclass(obj) and self._recurse:
1011 for valname, val in obj.__dict__.items():
1012 # Check if this contained object should be ignored.
1013 if self._filter(val, name, valname):
1014 continue
1015 # Special handling for staticmethod/classmethod.
1016 if isinstance(val, staticmethod):
1017 val = getattr(obj, valname)
1018 if isinstance(val, classmethod):
1019 val = getattr(obj, valname).im_func
1020
1021 # Recurse to methods, properties, and nested classes.
1022 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001023 isinstance(val, property)) and
1024 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001025 valname = '%s.%s' % (name, valname)
1026 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001027 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001028
1029 def _get_test(self, obj, name, module, globs, source_lines):
1030 """
1031 Return a DocTest for the given object, if it defines a docstring;
1032 otherwise, return None.
1033 """
1034 # Extract the object's docstring. If it doesn't have one,
1035 # then return None (no test for this object).
1036 if isinstance(obj, basestring):
1037 docstring = obj
1038 else:
1039 try:
1040 if obj.__doc__ is None:
1041 return None
1042 docstring = str(obj.__doc__)
1043 except (TypeError, AttributeError):
1044 return None
1045
1046 # Don't bother if the docstring is empty.
1047 if not docstring:
1048 return None
1049
1050 # Find the docstring's location in the file.
1051 lineno = self._find_lineno(obj, source_lines)
1052
1053 # Return a DocTest for this object.
1054 if module is None:
1055 filename = None
1056 else:
1057 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001058 if filename[-4:] in (".pyc", ".pyo"):
1059 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001060 return self._parser.get_doctest(docstring, globs, name,
1061 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001062
1063 def _find_lineno(self, obj, source_lines):
1064 """
1065 Return a line number of the given object's docstring. Note:
1066 this method assumes that the object has a docstring.
1067 """
1068 lineno = None
1069
1070 # Find the line number for modules.
1071 if inspect.ismodule(obj):
1072 lineno = 0
1073
1074 # Find the line number for classes.
1075 # Note: this could be fooled if a class is defined multiple
1076 # times in a single file.
1077 if inspect.isclass(obj):
1078 if source_lines is None:
1079 return None
1080 pat = re.compile(r'^\s*class\s*%s\b' %
1081 getattr(obj, '__name__', '-'))
1082 for i, line in enumerate(source_lines):
1083 if pat.match(line):
1084 lineno = i
1085 break
1086
1087 # Find the line number for functions & methods.
1088 if inspect.ismethod(obj): obj = obj.im_func
1089 if inspect.isfunction(obj): obj = obj.func_code
1090 if inspect.istraceback(obj): obj = obj.tb_frame
1091 if inspect.isframe(obj): obj = obj.f_code
1092 if inspect.iscode(obj):
1093 lineno = getattr(obj, 'co_firstlineno', None)-1
1094
1095 # Find the line number where the docstring starts. Assume
1096 # that it's the first line that begins with a quote mark.
1097 # Note: this could be fooled by a multiline function
1098 # signature, where a continuation line begins with a quote
1099 # mark.
1100 if lineno is not None:
1101 if source_lines is None:
1102 return lineno+1
1103 pat = re.compile('(^|.*:)\s*\w*("|\')')
1104 for lineno in range(lineno, len(source_lines)):
1105 if pat.match(source_lines[lineno]):
1106 return lineno
1107
1108 # We couldn't find the line number.
1109 return None
1110
1111######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001112## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001113######################################################################
1114
Tim Peters8485b562004-08-04 18:46:34 +00001115class DocTestRunner:
1116 """
1117 A class used to run DocTest test cases, and accumulate statistics.
1118 The `run` method is used to process a single DocTest case. It
1119 returns a tuple `(f, t)`, where `t` is the number of test cases
1120 tried, and `f` is the number of test cases that failed.
1121
1122 >>> tests = DocTestFinder().find(_TestClass)
1123 >>> runner = DocTestRunner(verbose=False)
1124 >>> for test in tests:
1125 ... print runner.run(test)
1126 (0, 2)
1127 (0, 1)
1128 (0, 2)
1129 (0, 2)
1130
1131 The `summarize` method prints a summary of all the test cases that
1132 have been run by the runner, and returns an aggregated `(f, t)`
1133 tuple:
1134
1135 >>> runner.summarize(verbose=1)
1136 4 items passed all tests:
1137 2 tests in _TestClass
1138 2 tests in _TestClass.__init__
1139 2 tests in _TestClass.get
1140 1 tests in _TestClass.square
1141 7 tests in 4 items.
1142 7 passed and 0 failed.
1143 Test passed.
1144 (0, 7)
1145
1146 The aggregated number of tried examples and failed examples is
1147 also available via the `tries` and `failures` attributes:
1148
1149 >>> runner.tries
1150 7
1151 >>> runner.failures
1152 0
1153
1154 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001155 by an `OutputChecker`. This comparison may be customized with a
1156 number of option flags; see the documentation for `testmod` for
1157 more information. If the option flags are insufficient, then the
1158 comparison may also be customized by passing a subclass of
1159 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001160
1161 The test runner's display output can be controlled in two ways.
1162 First, an output function (`out) can be passed to
1163 `TestRunner.run`; this function will be called with strings that
1164 should be displayed. It defaults to `sys.stdout.write`. If
1165 capturing the output is not sufficient, then the display output
1166 can be also customized by subclassing DocTestRunner, and
1167 overriding the methods `report_start`, `report_success`,
1168 `report_unexpected_exception`, and `report_failure`.
1169 """
1170 # This divider string is used to separate failure messages, and to
1171 # separate sections of the summary.
1172 DIVIDER = "*" * 70
1173
Edward Loper34fcb142004-08-09 02:45:41 +00001174 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001175 """
1176 Create a new test runner.
1177
Edward Loper34fcb142004-08-09 02:45:41 +00001178 Optional keyword arg `checker` is the `OutputChecker` that
1179 should be used to compare the expected outputs and actual
1180 outputs of doctest examples.
1181
Tim Peters8485b562004-08-04 18:46:34 +00001182 Optional keyword arg 'verbose' prints lots of stuff if true,
1183 only failures if false; by default, it's true iff '-v' is in
1184 sys.argv.
1185
1186 Optional argument `optionflags` can be used to control how the
1187 test runner compares expected output to actual output, and how
1188 it displays failures. See the documentation for `testmod` for
1189 more information.
1190 """
Edward Loper34fcb142004-08-09 02:45:41 +00001191 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001192 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001193 verbose = '-v' in sys.argv
1194 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001195 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001196 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001197
Tim Peters8485b562004-08-04 18:46:34 +00001198 # Keep track of the examples we've run.
1199 self.tries = 0
1200 self.failures = 0
1201 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001202
Tim Peters8485b562004-08-04 18:46:34 +00001203 # Create a fake output target for capturing doctest output.
1204 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001205
Tim Peters8485b562004-08-04 18:46:34 +00001206 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001207 # Reporting methods
1208 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001209
Tim Peters8485b562004-08-04 18:46:34 +00001210 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001211 """
Tim Peters8485b562004-08-04 18:46:34 +00001212 Report that the test runner is about to process the given
1213 example. (Only displays a message if verbose=True)
1214 """
1215 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001216 if example.want:
1217 out('Trying:\n' + _indent(example.source) +
1218 'Expecting:\n' + _indent(example.want))
1219 else:
1220 out('Trying:\n' + _indent(example.source) +
1221 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001222
Tim Peters8485b562004-08-04 18:46:34 +00001223 def report_success(self, out, test, example, got):
1224 """
1225 Report that the given example ran successfully. (Only
1226 displays a message if verbose=True)
1227 """
1228 if self._verbose:
1229 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001230
Tim Peters8485b562004-08-04 18:46:34 +00001231 def report_failure(self, out, test, example, got):
1232 """
1233 Report that the given example failed.
1234 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001235 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001236 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001237
Tim Peters8485b562004-08-04 18:46:34 +00001238 def report_unexpected_exception(self, out, test, example, exc_info):
1239 """
1240 Report that the given example raised an unexpected exception.
1241 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001242 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001243 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001244
Edward Loper8e4a34b2004-08-12 02:34:27 +00001245 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001246 out = [self.DIVIDER]
1247 if test.filename:
1248 if test.lineno is not None and example.lineno is not None:
1249 lineno = test.lineno + example.lineno + 1
1250 else:
1251 lineno = '?'
1252 out.append('File "%s", line %s, in %s' %
1253 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001254 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001255 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1256 out.append('Failed example:')
1257 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001258 out.append(_indent(source))
1259 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001260
Tim Peters8485b562004-08-04 18:46:34 +00001261 #/////////////////////////////////////////////////////////////////
1262 # DocTest Running
1263 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001264
Tim Peters8485b562004-08-04 18:46:34 +00001265 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001266 """
Tim Peters8485b562004-08-04 18:46:34 +00001267 Run the examples in `test`. Write the outcome of each example
1268 with one of the `DocTestRunner.report_*` methods, using the
1269 writer function `out`. `compileflags` is the set of compiler
1270 flags that should be used to execute examples. Return a tuple
1271 `(f, t)`, where `t` is the number of examples tried, and `f`
1272 is the number of examples that failed. The examples are run
1273 in the namespace `test.globs`.
1274 """
1275 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001276 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001277
1278 # Save the option flags (since option directives can be used
1279 # to modify them).
1280 original_optionflags = self.optionflags
1281
1282 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001283 for examplenum, example in enumerate(test.examples):
1284
Edward Lopera89f88d2004-08-26 02:45:51 +00001285 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1286 # reporting after the first failure.
1287 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1288 failures > 0)
1289
Edward Loper74bca7a2004-08-12 02:27:44 +00001290 # Merge in the example's options.
1291 self.optionflags = original_optionflags
1292 if example.options:
1293 for (optionflag, val) in example.options.items():
1294 if val:
1295 self.optionflags |= optionflag
1296 else:
1297 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001298
1299 # Record that we started this example.
1300 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001301 if not quiet:
1302 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001303
Edward Loper2de91ba2004-08-27 02:07:46 +00001304 # Use a special filename for compile(), so we can retrieve
1305 # the source code during interactive debugging (see
1306 # __patched_linecache_getlines).
1307 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1308
Tim Peters8485b562004-08-04 18:46:34 +00001309 # Run the example in the given context (globs), and record
1310 # any exception that gets raised. (But don't intercept
1311 # keyboard interrupts.)
1312 try:
Tim Peters208ca702004-08-09 04:12:36 +00001313 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001314 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001315 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001316 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001317 exception = None
1318 except KeyboardInterrupt:
1319 raise
1320 except:
1321 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001322 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001323
Tim Peters208ca702004-08-09 04:12:36 +00001324 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001325 self._fakeout.truncate(0)
1326
1327 # If the example executed without raising any exceptions,
1328 # then verify its output and report its outcome.
1329 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001330 if self._checker.check_output(example.want, got,
1331 self.optionflags):
Edward Lopera89f88d2004-08-26 02:45:51 +00001332 if not quiet:
1333 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001334 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001335 if not quiet:
1336 self.report_failure(out, test, example, got)
Tim Peters8485b562004-08-04 18:46:34 +00001337 failures += 1
1338
1339 # If the example raised an exception, then check if it was
1340 # expected.
1341 else:
1342 exc_info = sys.exc_info()
1343 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1344
Edward Lopera6b68322004-08-26 00:05:43 +00001345 # If `example.exc_msg` is None, then we weren't
1346 # expecting an exception.
1347 if example.exc_msg is None:
Edward Lopera89f88d2004-08-26 02:45:51 +00001348 if not quiet:
1349 self.report_unexpected_exception(out, test, example,
1350 exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001351 failures += 1
Edward Lopera6b68322004-08-26 00:05:43 +00001352 # If `example.exc_msg` matches the actual exception
1353 # message (`exc_msg`), then the example succeeds.
1354 elif (self._checker.check_output(example.exc_msg, exc_msg,
1355 self.optionflags)):
Edward Lopera89f88d2004-08-26 02:45:51 +00001356 if not quiet:
1357 got += _exception_traceback(exc_info)
1358 self.report_success(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001359 # Otherwise, the example fails.
Tim Peters8485b562004-08-04 18:46:34 +00001360 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001361 if not quiet:
1362 got += _exception_traceback(exc_info)
1363 self.report_failure(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001364 failures += 1
Tim Peters8485b562004-08-04 18:46:34 +00001365
1366 # Restore the option flags (in case they were modified)
1367 self.optionflags = original_optionflags
1368
1369 # Record and return the number of failures and tries.
1370 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001371 return failures, tries
1372
Tim Peters8485b562004-08-04 18:46:34 +00001373 def __record_outcome(self, test, f, t):
1374 """
1375 Record the fact that the given DocTest (`test`) generated `f`
1376 failures out of `t` tried examples.
1377 """
1378 f2, t2 = self._name2ft.get(test.name, (0,0))
1379 self._name2ft[test.name] = (f+f2, t+t2)
1380 self.failures += f
1381 self.tries += t
1382
Edward Loper2de91ba2004-08-27 02:07:46 +00001383 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1384 r'(?P<name>[\w\.]+)'
1385 r'\[(?P<examplenum>\d+)\]>$')
1386 def __patched_linecache_getlines(self, filename):
1387 m = self.__LINECACHE_FILENAME_RE.match(filename)
1388 if m and m.group('name') == self.test.name:
1389 example = self.test.examples[int(m.group('examplenum'))]
1390 return example.source.splitlines(True)
1391 else:
1392 return self.save_linecache_getlines(filename)
1393
Tim Peters8485b562004-08-04 18:46:34 +00001394 def run(self, test, compileflags=None, out=None, clear_globs=True):
1395 """
1396 Run the examples in `test`, and display the results using the
1397 writer function `out`.
1398
1399 The examples are run in the namespace `test.globs`. If
1400 `clear_globs` is true (the default), then this namespace will
1401 be cleared after the test runs, to help with garbage
1402 collection. If you would like to examine the namespace after
1403 the test completes, then use `clear_globs=False`.
1404
1405 `compileflags` gives the set of flags that should be used by
1406 the Python compiler when running the examples. If not
1407 specified, then it will default to the set of future-import
1408 flags that apply to `globs`.
1409
1410 The output of each example is checked using
1411 `DocTestRunner.check_output`, and the results are formatted by
1412 the `DocTestRunner.report_*` methods.
1413 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001414 self.test = test
1415
Tim Peters8485b562004-08-04 18:46:34 +00001416 if compileflags is None:
1417 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001418
Tim Peters6c542b72004-08-09 16:43:36 +00001419 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001420 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001421 out = save_stdout.write
1422 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001423
Edward Loper2de91ba2004-08-27 02:07:46 +00001424 # Patch pdb.set_trace to restore sys.stdout during interactive
1425 # debugging (so it's not still redirected to self._fakeout).
1426 # Note that the interactive output will go to *our*
1427 # save_stdout, even if that's not the real sys.stdout; this
1428 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001429 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001430 self.debugger = _OutputRedirectingPdb(save_stdout)
1431 self.debugger.reset()
1432 pdb.set_trace = self.debugger.set_trace
1433
1434 # Patch linecache.getlines, so we can see the example's source
1435 # when we're inside the debugger.
1436 self.save_linecache_getlines = linecache.getlines
1437 linecache.getlines = self.__patched_linecache_getlines
1438
Tim Peters8485b562004-08-04 18:46:34 +00001439 try:
Tim Peters8485b562004-08-04 18:46:34 +00001440 return self.__run(test, compileflags, out)
1441 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001442 sys.stdout = save_stdout
1443 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001444 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001445 if clear_globs:
1446 test.globs.clear()
1447
1448 #/////////////////////////////////////////////////////////////////
1449 # Summarization
1450 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001451 def summarize(self, verbose=None):
1452 """
Tim Peters8485b562004-08-04 18:46:34 +00001453 Print a summary of all the test cases that have been run by
1454 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1455 the total number of failed examples, and `t` is the total
1456 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001457
Tim Peters8485b562004-08-04 18:46:34 +00001458 The optional `verbose` argument controls how detailed the
1459 summary is. If the verbosity is not specified, then the
1460 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001461 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001462 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001463 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001464 notests = []
1465 passed = []
1466 failed = []
1467 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001468 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001469 name, (f, t) = x
1470 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001471 totalt += t
1472 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001473 if t == 0:
1474 notests.append(name)
1475 elif f == 0:
1476 passed.append( (name, t) )
1477 else:
1478 failed.append(x)
1479 if verbose:
1480 if notests:
1481 print len(notests), "items had no tests:"
1482 notests.sort()
1483 for thing in notests:
1484 print " ", thing
1485 if passed:
1486 print len(passed), "items passed all tests:"
1487 passed.sort()
1488 for thing, count in passed:
1489 print " %3d tests in %s" % (count, thing)
1490 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001491 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001492 print len(failed), "items had failures:"
1493 failed.sort()
1494 for thing, (f, t) in failed:
1495 print " %3d of %3d in %s" % (f, t, thing)
1496 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001497 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001498 print totalt - totalf, "passed and", totalf, "failed."
1499 if totalf:
1500 print "***Test Failed***", totalf, "failures."
1501 elif verbose:
1502 print "Test passed."
1503 return totalf, totalt
1504
Edward Loper34fcb142004-08-09 02:45:41 +00001505class OutputChecker:
1506 """
1507 A class used to check the whether the actual output from a doctest
1508 example matches the expected output. `OutputChecker` defines two
1509 methods: `check_output`, which compares a given pair of outputs,
1510 and returns true if they match; and `output_difference`, which
1511 returns a string describing the differences between two outputs.
1512 """
1513 def check_output(self, want, got, optionflags):
1514 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001515 Return True iff the actual output from an example (`got`)
1516 matches the expected output (`want`). These strings are
1517 always considered to match if they are identical; but
1518 depending on what option flags the test runner is using,
1519 several non-exact match types are also possible. See the
1520 documentation for `TestRunner` for more information about
1521 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001522 """
1523 # Handle the common case first, for efficiency:
1524 # if they're string-identical, always return true.
1525 if got == want:
1526 return True
1527
1528 # The values True and False replaced 1 and 0 as the return
1529 # value for boolean comparisons in Python 2.3.
1530 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1531 if (got,want) == ("True\n", "1\n"):
1532 return True
1533 if (got,want) == ("False\n", "0\n"):
1534 return True
1535
1536 # <BLANKLINE> can be used as a special sequence to signify a
1537 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1538 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1539 # Replace <BLANKLINE> in want with a blank line.
1540 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1541 '', want)
1542 # If a line in got contains only spaces, then remove the
1543 # spaces.
1544 got = re.sub('(?m)^\s*?$', '', got)
1545 if got == want:
1546 return True
1547
1548 # This flag causes doctest to ignore any differences in the
1549 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001550 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001551 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001552 got = ' '.join(got.split())
1553 want = ' '.join(want.split())
1554 if got == want:
1555 return True
1556
1557 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001558 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001559 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001560 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001561 return True
1562
1563 # We didn't find any match; return false.
1564 return False
1565
Tim Petersc6cbab02004-08-22 19:43:28 +00001566 # Should we do a fancy diff?
1567 def _do_a_fancy_diff(self, want, got, optionflags):
1568 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001569 if not optionflags & (REPORT_UDIFF |
1570 REPORT_CDIFF |
1571 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001572 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001573
Tim Petersc6cbab02004-08-22 19:43:28 +00001574 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001575 # too hard ... or maybe not. In two real-life failures Tim saw,
1576 # a diff was a major help anyway, so this is commented out.
1577 # [todo] _ellipsis_match() knows which pieces do and don't match,
1578 # and could be the basis for a kick-ass diff in this case.
1579 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1580 ## return False
1581
Tim Petersc6cbab02004-08-22 19:43:28 +00001582 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001583 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001584 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001585 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001586
Tim Petersc6cbab02004-08-22 19:43:28 +00001587 # The other diff types need at least a few lines to be helpful.
1588 return want.count('\n') > 2 and got.count('\n') > 2
1589
Edward Loperca9111e2004-08-26 03:00:24 +00001590 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001591 """
1592 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001593 expected output for a given example (`example`) and the actual
1594 output (`got`). `optionflags` is the set of option flags used
1595 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001596 """
Edward Loperca9111e2004-08-26 03:00:24 +00001597 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001598 # If <BLANKLINE>s are being used, then replace blank lines
1599 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001600 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001601 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001602
Tim Peters5b799c12004-08-26 05:21:59 +00001603 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001604 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001605 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001606 want_lines = want.splitlines(True) # True == keep line ends
1607 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001608 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001609 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001610 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1611 diff = list(diff)[2:] # strip the diff header
1612 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001613 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001614 diff = difflib.context_diff(want_lines, got_lines, n=2)
1615 diff = list(diff)[2:] # strip the diff header
1616 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001617 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001618 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1619 diff = list(engine.compare(want_lines, got_lines))
1620 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001621 else:
1622 assert 0, 'Bad diff option'
1623 # Remove trailing whitespace on diff output.
1624 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001625 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001626
1627 # If we're not using diff, then simply list the expected
1628 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001629 if want and got:
1630 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1631 elif want:
1632 return 'Expected:\n%sGot nothing\n' % _indent(want)
1633 elif got:
1634 return 'Expected nothing\nGot:\n%s' % _indent(got)
1635 else:
1636 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001637
Tim Peters19397e52004-08-06 22:02:59 +00001638class DocTestFailure(Exception):
1639 """A DocTest example has failed in debugging mode.
1640
1641 The exception instance has variables:
1642
1643 - test: the DocTest object being run
1644
1645 - excample: the Example object that failed
1646
1647 - got: the actual output
1648 """
1649 def __init__(self, test, example, got):
1650 self.test = test
1651 self.example = example
1652 self.got = got
1653
1654 def __str__(self):
1655 return str(self.test)
1656
1657class UnexpectedException(Exception):
1658 """A DocTest example has encountered an unexpected exception
1659
1660 The exception instance has variables:
1661
1662 - test: the DocTest object being run
1663
1664 - excample: the Example object that failed
1665
1666 - exc_info: the exception info
1667 """
1668 def __init__(self, test, example, exc_info):
1669 self.test = test
1670 self.example = example
1671 self.exc_info = exc_info
1672
1673 def __str__(self):
1674 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001675
Tim Peters19397e52004-08-06 22:02:59 +00001676class DebugRunner(DocTestRunner):
1677 r"""Run doc tests but raise an exception as soon as there is a failure.
1678
1679 If an unexpected exception occurs, an UnexpectedException is raised.
1680 It contains the test, the example, and the original exception:
1681
1682 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001683 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1684 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001685 >>> try:
1686 ... runner.run(test)
1687 ... except UnexpectedException, failure:
1688 ... pass
1689
1690 >>> failure.test is test
1691 True
1692
1693 >>> failure.example.want
1694 '42\n'
1695
1696 >>> exc_info = failure.exc_info
1697 >>> raise exc_info[0], exc_info[1], exc_info[2]
1698 Traceback (most recent call last):
1699 ...
1700 KeyError
1701
1702 We wrap the original exception to give the calling application
1703 access to the test and example information.
1704
1705 If the output doesn't match, then a DocTestFailure is raised:
1706
Edward Lopera1ef6112004-08-09 16:14:41 +00001707 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001708 ... >>> x = 1
1709 ... >>> x
1710 ... 2
1711 ... ''', {}, 'foo', 'foo.py', 0)
1712
1713 >>> try:
1714 ... runner.run(test)
1715 ... except DocTestFailure, failure:
1716 ... pass
1717
1718 DocTestFailure objects provide access to the test:
1719
1720 >>> failure.test is test
1721 True
1722
1723 As well as to the example:
1724
1725 >>> failure.example.want
1726 '2\n'
1727
1728 and the actual output:
1729
1730 >>> failure.got
1731 '1\n'
1732
1733 If a failure or error occurs, the globals are left intact:
1734
1735 >>> del test.globs['__builtins__']
1736 >>> test.globs
1737 {'x': 1}
1738
Edward Lopera1ef6112004-08-09 16:14:41 +00001739 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001740 ... >>> x = 2
1741 ... >>> raise KeyError
1742 ... ''', {}, 'foo', 'foo.py', 0)
1743
1744 >>> runner.run(test)
1745 Traceback (most recent call last):
1746 ...
1747 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001748
Tim Peters19397e52004-08-06 22:02:59 +00001749 >>> del test.globs['__builtins__']
1750 >>> test.globs
1751 {'x': 2}
1752
1753 But the globals are cleared if there is no error:
1754
Edward Lopera1ef6112004-08-09 16:14:41 +00001755 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001756 ... >>> x = 2
1757 ... ''', {}, 'foo', 'foo.py', 0)
1758
1759 >>> runner.run(test)
1760 (0, 1)
1761
1762 >>> test.globs
1763 {}
1764
1765 """
1766
1767 def run(self, test, compileflags=None, out=None, clear_globs=True):
1768 r = DocTestRunner.run(self, test, compileflags, out, False)
1769 if clear_globs:
1770 test.globs.clear()
1771 return r
1772
1773 def report_unexpected_exception(self, out, test, example, exc_info):
1774 raise UnexpectedException(test, example, exc_info)
1775
1776 def report_failure(self, out, test, example, got):
1777 raise DocTestFailure(test, example, got)
1778
Tim Peters8485b562004-08-04 18:46:34 +00001779######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001780## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001781######################################################################
1782# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001783
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001784def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001785 report=True, optionflags=0, extraglobs=None,
1786 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001787 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001788 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001789
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001790 Test examples in docstrings in functions and classes reachable
1791 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001792 with m.__doc__. Unless isprivate is specified, private names
1793 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001794
1795 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001796 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001797 function and class docstrings are tested even if the name is private;
1798 strings are tested directly, as if they were docstrings.
1799
1800 Return (#failures, #tests).
1801
1802 See doctest.__doc__ for an overview.
1803
1804 Optional keyword arg "name" gives the name of the module; by default
1805 use m.__name__.
1806
1807 Optional keyword arg "globs" gives a dict to be used as the globals
1808 when executing examples; by default, use m.__dict__. A copy of this
1809 dict is actually used for each docstring, so that each docstring's
1810 examples start with a clean slate.
1811
Tim Peters8485b562004-08-04 18:46:34 +00001812 Optional keyword arg "extraglobs" gives a dictionary that should be
1813 merged into the globals that are used to execute examples. By
1814 default, no extra globals are used. This is new in 2.4.
1815
Tim Peters8a7d2d52001-01-16 07:10:57 +00001816 Optional keyword arg "verbose" prints lots of stuff if true, prints
1817 only failures if false; by default, it's true iff "-v" is in sys.argv.
1818
Tim Peters8a7d2d52001-01-16 07:10:57 +00001819 Optional keyword arg "report" prints a summary at the end when true,
1820 else prints nothing at the end. In verbose mode, the summary is
1821 detailed, else very brief (in fact, empty if all tests passed).
1822
Tim Peters6ebe61f2003-06-27 20:48:05 +00001823 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001824 and defaults to 0. This is new in 2.3. Possible values (see the
1825 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001826
1827 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001828 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001829 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001830 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001831 REPORT_UDIFF
1832 REPORT_CDIFF
1833 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001834 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001835
1836 Optional keyword arg "raise_on_error" raises an exception on the
1837 first unexpected exception or failure. This allows failures to be
1838 post-mortem debugged.
1839
Tim Petersf727c6c2004-08-08 01:48:59 +00001840 Deprecated in Python 2.4:
1841 Optional keyword arg "isprivate" specifies a function used to
1842 determine whether a name is private. The default function is
1843 treat all functions as public. Optionally, "isprivate" can be
1844 set to doctest.is_private to skip over functions marked as private
1845 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001846 """
1847
1848 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001849 Advanced tomfoolery: testmod runs methods of a local instance of
1850 class doctest.Tester, then merges the results into (or creates)
1851 global Tester instance doctest.master. Methods of doctest.master
1852 can be called directly too, if you want to do something unusual.
1853 Passing report=0 to testmod is especially useful then, to delay
1854 displaying a summary. Invoke doctest.master.summarize(verbose)
1855 when you're done fiddling.
1856 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001857 if isprivate is not None:
1858 warnings.warn("the isprivate argument is deprecated; "
1859 "examine DocTestFinder.find() lists instead",
1860 DeprecationWarning)
1861
Tim Peters8485b562004-08-04 18:46:34 +00001862 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001863 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001864 # DWA - m will still be None if this wasn't invoked from the command
1865 # line, in which case the following TypeError is about as good an error
1866 # as we should expect
1867 m = sys.modules.get('__main__')
1868
Tim Peters8485b562004-08-04 18:46:34 +00001869 # Check that we were actually given a module.
1870 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001871 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001872
1873 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001874 if name is None:
1875 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001876
1877 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001878 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001879
1880 if raise_on_error:
1881 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1882 else:
1883 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1884
Tim Peters8485b562004-08-04 18:46:34 +00001885 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1886 runner.run(test)
1887
Tim Peters8a7d2d52001-01-16 07:10:57 +00001888 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001889 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001890
Tim Peters8485b562004-08-04 18:46:34 +00001891 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001892
Tim Peters8485b562004-08-04 18:46:34 +00001893def run_docstring_examples(f, globs, verbose=False, name="NoName",
1894 compileflags=None, optionflags=0):
1895 """
1896 Test examples in the given object's docstring (`f`), using `globs`
1897 as globals. Optional argument `name` is used in failure messages.
1898 If the optional argument `verbose` is true, then generate output
1899 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001900
Tim Peters8485b562004-08-04 18:46:34 +00001901 `compileflags` gives the set of flags that should be used by the
1902 Python compiler when running the examples. If not specified, then
1903 it will default to the set of future-import flags that apply to
1904 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001905
Tim Peters8485b562004-08-04 18:46:34 +00001906 Optional keyword arg `optionflags` specifies options for the
1907 testing and output. See the documentation for `testmod` for more
1908 information.
1909 """
1910 # Find, parse, and run all tests in the given module.
1911 finder = DocTestFinder(verbose=verbose, recurse=False)
1912 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1913 for test in finder.find(f, name, globs=globs):
1914 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001915
Tim Peters8485b562004-08-04 18:46:34 +00001916######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001917## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001918######################################################################
1919# This is provided only for backwards compatibility. It's not
1920# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001921
Tim Peters8485b562004-08-04 18:46:34 +00001922class Tester:
1923 def __init__(self, mod=None, globs=None, verbose=None,
1924 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001925
1926 warnings.warn("class Tester is deprecated; "
1927 "use class doctest.DocTestRunner instead",
1928 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001929 if mod is None and globs is None:
1930 raise TypeError("Tester.__init__: must specify mod or globs")
1931 if mod is not None and not _ismodule(mod):
1932 raise TypeError("Tester.__init__: mod must be a module; %r" %
1933 (mod,))
1934 if globs is None:
1935 globs = mod.__dict__
1936 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001937
Tim Peters8485b562004-08-04 18:46:34 +00001938 self.verbose = verbose
1939 self.isprivate = isprivate
1940 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001941 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001942 self.testrunner = DocTestRunner(verbose=verbose,
1943 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001944
Tim Peters8485b562004-08-04 18:46:34 +00001945 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001946 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001947 if self.verbose:
1948 print "Running string", name
1949 (f,t) = self.testrunner.run(test)
1950 if self.verbose:
1951 print f, "of", t, "examples failed in string", name
1952 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001953
Tim Petersf3f57472004-08-08 06:11:48 +00001954 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001955 f = t = 0
1956 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001957 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001958 for test in tests:
1959 (f2, t2) = self.testrunner.run(test)
1960 (f,t) = (f+f2, t+t2)
1961 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001962
Tim Peters8485b562004-08-04 18:46:34 +00001963 def rundict(self, d, name, module=None):
1964 import new
1965 m = new.module(name)
1966 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001967 if module is None:
1968 module = False
1969 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001970
Tim Peters8485b562004-08-04 18:46:34 +00001971 def run__test__(self, d, name):
1972 import new
1973 m = new.module(name)
1974 m.__test__ = d
1975 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001976
Tim Peters8485b562004-08-04 18:46:34 +00001977 def summarize(self, verbose=None):
1978 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001979
Tim Peters8485b562004-08-04 18:46:34 +00001980 def merge(self, other):
1981 d = self.testrunner._name2ft
1982 for name, (f, t) in other.testrunner._name2ft.items():
1983 if name in d:
1984 print "*** Tester.merge: '" + name + "' in both" \
1985 " testers; summing outcomes."
1986 f2, t2 = d[name]
1987 f = f + f2
1988 t = t + t2
1989 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001990
Tim Peters8485b562004-08-04 18:46:34 +00001991######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001992## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001993######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001994
Jim Fultonf54bad42004-08-28 14:57:56 +00001995_unittest_reportflags = 0
1996valid_unittest_reportflags = (
1997 REPORT_CDIFF |
1998 REPORT_UDIFF |
1999 REPORT_NDIFF |
2000 REPORT_ONLY_FIRST_FAILURE
2001 )
2002def set_unittest_reportflags(flags):
2003 """Sets the unit test option flags
2004
2005 The old flag is returned so that a runner could restore the old
2006 value if it wished to:
2007
2008 >>> old = _unittest_reportflags
2009 >>> set_unittest_reportflags(REPORT_NDIFF |
2010 ... REPORT_ONLY_FIRST_FAILURE) == old
2011 True
2012
2013 >>> import doctest
2014 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2015 ... REPORT_ONLY_FIRST_FAILURE)
2016 True
2017
2018 Only reporting flags can be set:
2019
2020 >>> set_unittest_reportflags(ELLIPSIS)
2021 Traceback (most recent call last):
2022 ...
2023 ValueError: ('Invalid flags passed', 8)
2024
2025 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2026 ... REPORT_ONLY_FIRST_FAILURE)
2027 True
2028
2029 """
2030
2031 # extract the valid reporting flags:
2032 rflags = flags & valid_unittest_reportflags
2033
2034 # Now remove these flags from the given flags
2035 nrflags = flags ^ rflags
2036
2037 if nrflags:
2038 raise ValueError("Invalid flags passed", flags)
2039
2040 global _unittest_reportflags
2041 old = _unittest_reportflags
2042 _unittest_reportflags = flags
2043 return old
2044
2045
2046class FakeModule:
2047 """Fake module created by tests
2048 """
2049
2050 def __init__(self, dict, name):
2051 self.__dict__ = dict
2052 self.__name__ = name
2053
Tim Peters19397e52004-08-06 22:02:59 +00002054class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002055
Edward Loper34fcb142004-08-09 02:45:41 +00002056 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2057 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002058
Jim Fultona643b652004-07-14 19:06:50 +00002059 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002060 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002061 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002062 self._dt_test = test
2063 self._dt_setUp = setUp
2064 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002065
Jim Fultona643b652004-07-14 19:06:50 +00002066 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002067 test = self._dt_test
2068
Tim Peters19397e52004-08-06 22:02:59 +00002069 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002070 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002071
2072 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002073 test = self._dt_test
2074
Tim Peters19397e52004-08-06 22:02:59 +00002075 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002076 self._dt_tearDown(test)
2077
2078 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002079
2080 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002081 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002082 old = sys.stdout
2083 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002084 optionflags = self._dt_optionflags
2085
2086 if not (optionflags & valid_unittest_reportflags):
2087 # The option flags don't include any reporting flags,
2088 # so add the default reporting flags
2089 optionflags |= _unittest_reportflags
2090
2091 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002092 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002093
Jim Fultona643b652004-07-14 19:06:50 +00002094 try:
Tim Peters19397e52004-08-06 22:02:59 +00002095 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002096 failures, tries = runner.run(
2097 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002098 finally:
2099 sys.stdout = old
2100
2101 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002102 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002103
Tim Peters19397e52004-08-06 22:02:59 +00002104 def format_failure(self, err):
2105 test = self._dt_test
2106 if test.lineno is None:
2107 lineno = 'unknown line number'
2108 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002109 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002110 lname = '.'.join(test.name.split('.')[-1:])
2111 return ('Failed doctest test for %s\n'
2112 ' File "%s", line %s, in %s\n\n%s'
2113 % (test.name, test.filename, lineno, lname, err)
2114 )
2115
2116 def debug(self):
2117 r"""Run the test case without results and without catching exceptions
2118
2119 The unit test framework includes a debug method on test cases
2120 and test suites to support post-mortem debugging. The test code
2121 is run in such a way that errors are not caught. This way a
2122 caller can catch the errors and initiate post-mortem debugging.
2123
2124 The DocTestCase provides a debug method that raises
2125 UnexpectedException errors if there is an unexepcted
2126 exception:
2127
Edward Lopera1ef6112004-08-09 16:14:41 +00002128 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002129 ... {}, 'foo', 'foo.py', 0)
2130 >>> case = DocTestCase(test)
2131 >>> try:
2132 ... case.debug()
2133 ... except UnexpectedException, failure:
2134 ... pass
2135
2136 The UnexpectedException contains the test, the example, and
2137 the original exception:
2138
2139 >>> failure.test is test
2140 True
2141
2142 >>> failure.example.want
2143 '42\n'
2144
2145 >>> exc_info = failure.exc_info
2146 >>> raise exc_info[0], exc_info[1], exc_info[2]
2147 Traceback (most recent call last):
2148 ...
2149 KeyError
2150
2151 If the output doesn't match, then a DocTestFailure is raised:
2152
Edward Lopera1ef6112004-08-09 16:14:41 +00002153 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002154 ... >>> x = 1
2155 ... >>> x
2156 ... 2
2157 ... ''', {}, 'foo', 'foo.py', 0)
2158 >>> case = DocTestCase(test)
2159
2160 >>> try:
2161 ... case.debug()
2162 ... except DocTestFailure, failure:
2163 ... pass
2164
2165 DocTestFailure objects provide access to the test:
2166
2167 >>> failure.test is test
2168 True
2169
2170 As well as to the example:
2171
2172 >>> failure.example.want
2173 '2\n'
2174
2175 and the actual output:
2176
2177 >>> failure.got
2178 '1\n'
2179
2180 """
2181
Jim Fultonf54bad42004-08-28 14:57:56 +00002182 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002183 runner = DebugRunner(optionflags=self._dt_optionflags,
2184 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002185 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002186 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002187
2188 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002189 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002190
2191 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002192 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002193 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2194
2195 __str__ = __repr__
2196
2197 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002198 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002199
Jim Fultonf54bad42004-08-28 14:57:56 +00002200def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2201 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002202 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002203 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002204
Tim Peters19397e52004-08-06 22:02:59 +00002205 This converts each documentation string in a module that
2206 contains doctest tests to a unittest test case. If any of the
2207 tests in a doc string fail, then the test case fails. An exception
2208 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002209 (sometimes approximate) line number.
2210
Tim Peters19397e52004-08-06 22:02:59 +00002211 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002212 can be either a module or a module name.
2213
2214 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002215
2216 A number of options may be provided as keyword arguments:
2217
2218 package
2219 The name of a Python package. Text-file paths will be
2220 interpreted relative to the directory containing this package.
2221 The package may be supplied as a package object or as a dotted
2222 package name.
2223
2224 setUp
2225 The name of a set-up function. This is called before running the
2226 tests in each file. The setUp function will be passed a DocTest
2227 object. The setUp function can access the test globals as the
2228 globs attribute of the test passed.
2229
2230 tearDown
2231 The name of a tear-down function. This is called after running the
2232 tests in each file. The tearDown function will be passed a DocTest
2233 object. The tearDown function can access the test globals as the
2234 globs attribute of the test passed.
2235
2236 globs
2237 A dictionary containing initial global variables for the tests.
2238
2239 optionflags
2240 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002241 """
Jim Fultona643b652004-07-14 19:06:50 +00002242
Tim Peters8485b562004-08-04 18:46:34 +00002243 if test_finder is None:
2244 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002245
Tim Peters19397e52004-08-06 22:02:59 +00002246 module = _normalize_module(module)
2247 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2248 if globs is None:
2249 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002250 if not tests:
2251 # Why do we want to do this? Because it reveals a bug that might
2252 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002253 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002254
2255 tests.sort()
2256 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002257 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002258 if len(test.examples) == 0:
2259 continue
Tim Peters8485b562004-08-04 18:46:34 +00002260 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002261 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002262 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002263 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002264 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002265 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002266
2267 return suite
2268
2269class DocFileCase(DocTestCase):
2270
2271 def id(self):
2272 return '_'.join(self._dt_test.name.split('.'))
2273
2274 def __repr__(self):
2275 return self._dt_test.filename
2276 __str__ = __repr__
2277
2278 def format_failure(self, err):
2279 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2280 % (self._dt_test.name, self._dt_test.filename, err)
2281 )
2282
Jim Fultonf54bad42004-08-28 14:57:56 +00002283def DocFileTest(path, package=None, globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002284 package = _normalize_module(package)
2285 name = path.split('/')[-1]
2286 dir = os.path.split(package.__file__)[0]
2287 path = os.path.join(dir, *(path.split('/')))
2288 doc = open(path).read()
2289
2290 if globs is None:
2291 globs = {}
2292
Edward Lopera1ef6112004-08-09 16:14:41 +00002293 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002294
Jim Fultonf54bad42004-08-28 14:57:56 +00002295 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002296
2297def DocFileSuite(*paths, **kw):
2298 """Creates a suite of doctest files.
2299
2300 One or more text file paths are given as strings. These should
2301 use "/" characters to separate path segments. Paths are relative
2302 to the directory of the calling module, or relative to the package
2303 passed as a keyword argument.
2304
2305 A number of options may be provided as keyword arguments:
2306
2307 package
2308 The name of a Python package. Text-file paths will be
2309 interpreted relative to the directory containing this package.
2310 The package may be supplied as a package object or as a dotted
2311 package name.
2312
2313 setUp
2314 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002315 tests in each file. The setUp function will be passed a DocTest
2316 object. The setUp function can access the test globals as the
2317 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002318
2319 tearDown
2320 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002321 tests in each file. The tearDown function will be passed a DocTest
2322 object. The tearDown function can access the test globals as the
2323 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002324
2325 globs
2326 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002327
2328 optionflags
2329 A set of doctest option flags expressed as an integer.
2330
Tim Peters19397e52004-08-06 22:02:59 +00002331 """
2332 suite = unittest.TestSuite()
2333
2334 # We do this here so that _normalize_module is called at the right
2335 # level. If it were called in DocFileTest, then this function
2336 # would be the caller and we might guess the package incorrectly.
2337 kw['package'] = _normalize_module(kw.get('package'))
2338
2339 for path in paths:
2340 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002341
Tim Petersdb3756d2003-06-29 05:30:48 +00002342 return suite
2343
Tim Peters8485b562004-08-04 18:46:34 +00002344######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002345## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002346######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002347
Tim Peters19397e52004-08-06 22:02:59 +00002348def script_from_examples(s):
2349 r"""Extract script from text with examples.
2350
2351 Converts text with examples to a Python script. Example input is
2352 converted to regular code. Example output and all other words
2353 are converted to comments:
2354
2355 >>> text = '''
2356 ... Here are examples of simple math.
2357 ...
2358 ... Python has super accurate integer addition
2359 ...
2360 ... >>> 2 + 2
2361 ... 5
2362 ...
2363 ... And very friendly error messages:
2364 ...
2365 ... >>> 1/0
2366 ... To Infinity
2367 ... And
2368 ... Beyond
2369 ...
2370 ... You can use logic if you want:
2371 ...
2372 ... >>> if 0:
2373 ... ... blah
2374 ... ... blah
2375 ... ...
2376 ...
2377 ... Ho hum
2378 ... '''
2379
2380 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002381 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002382 #
Edward Lopera5db6002004-08-12 02:41:30 +00002383 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002384 #
2385 2 + 2
2386 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002387 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002388 #
Edward Lopera5db6002004-08-12 02:41:30 +00002389 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002390 #
2391 1/0
2392 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002393 ## To Infinity
2394 ## And
2395 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002396 #
Edward Lopera5db6002004-08-12 02:41:30 +00002397 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002398 #
2399 if 0:
2400 blah
2401 blah
Tim Peters19397e52004-08-06 22:02:59 +00002402 #
Edward Lopera5db6002004-08-12 02:41:30 +00002403 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002404 """
Edward Loper00f8da72004-08-26 18:05:07 +00002405 output = []
2406 for piece in DocTestParser().parse(s):
2407 if isinstance(piece, Example):
2408 # Add the example's source code (strip trailing NL)
2409 output.append(piece.source[:-1])
2410 # Add the expected output:
2411 want = piece.want
2412 if want:
2413 output.append('# Expected:')
2414 output += ['## '+l for l in want.split('\n')[:-1]]
2415 else:
2416 # Add non-example text.
2417 output += [_comment_line(l)
2418 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002419
Edward Loper00f8da72004-08-26 18:05:07 +00002420 # Trim junk on both ends.
2421 while output and output[-1] == '#':
2422 output.pop()
2423 while output and output[0] == '#':
2424 output.pop(0)
2425 # Combine the output, and return it.
2426 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002427
2428def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002429 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002430
2431 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002432 test to be debugged and the name (within the module) of the object
2433 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002434 """
Tim Peters8485b562004-08-04 18:46:34 +00002435 module = _normalize_module(module)
2436 tests = DocTestFinder().find(module)
2437 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002438 if not test:
2439 raise ValueError(name, "not found in tests")
2440 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002441 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002442 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002443
Jim Fultona643b652004-07-14 19:06:50 +00002444def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002445 """Debug a single doctest docstring, in argument `src`'"""
2446 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002447 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002448
Jim Fultona643b652004-07-14 19:06:50 +00002449def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002450 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002451 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002452
Tim Petersb6a04d62004-08-23 21:37:56 +00002453 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2454 # docs say, a file so created cannot be opened by name a second time
2455 # on modern Windows boxes, and execfile() needs to open it.
2456 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002457 f = open(srcfilename, 'w')
2458 f.write(src)
2459 f.close()
2460
Tim Petersb6a04d62004-08-23 21:37:56 +00002461 try:
2462 if globs:
2463 globs = globs.copy()
2464 else:
2465 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002466
Tim Petersb6a04d62004-08-23 21:37:56 +00002467 if pm:
2468 try:
2469 execfile(srcfilename, globs, globs)
2470 except:
2471 print sys.exc_info()[1]
2472 pdb.post_mortem(sys.exc_info()[2])
2473 else:
2474 # Note that %r is vital here. '%s' instead can, e.g., cause
2475 # backslashes to get treated as metacharacters on Windows.
2476 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2477
2478 finally:
2479 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002480
Jim Fultona643b652004-07-14 19:06:50 +00002481def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002482 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002483
2484 Provide the module (or dotted name of the module) containing the
2485 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002486 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002487 """
Tim Peters8485b562004-08-04 18:46:34 +00002488 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002489 testsrc = testsource(module, name)
2490 debug_script(testsrc, pm, module.__dict__)
2491
Tim Peters8485b562004-08-04 18:46:34 +00002492######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002493## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002494######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002495class _TestClass:
2496 """
2497 A pointless class, for sanity-checking of docstring testing.
2498
2499 Methods:
2500 square()
2501 get()
2502
2503 >>> _TestClass(13).get() + _TestClass(-12).get()
2504 1
2505 >>> hex(_TestClass(13).square().get())
2506 '0xa9'
2507 """
2508
2509 def __init__(self, val):
2510 """val -> _TestClass object with associated value val.
2511
2512 >>> t = _TestClass(123)
2513 >>> print t.get()
2514 123
2515 """
2516
2517 self.val = val
2518
2519 def square(self):
2520 """square() -> square TestClass's associated value
2521
2522 >>> _TestClass(13).square().get()
2523 169
2524 """
2525
2526 self.val = self.val ** 2
2527 return self
2528
2529 def get(self):
2530 """get() -> return TestClass's associated value.
2531
2532 >>> x = _TestClass(-42)
2533 >>> print x.get()
2534 -42
2535 """
2536
2537 return self.val
2538
2539__test__ = {"_TestClass": _TestClass,
2540 "string": r"""
2541 Example of a string object, searched as-is.
2542 >>> x = 1; y = 2
2543 >>> x + y, x * y
2544 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002545 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002546
Tim Peters6ebe61f2003-06-27 20:48:05 +00002547 "bool-int equivalence": r"""
2548 In 2.2, boolean expressions displayed
2549 0 or 1. By default, we still accept
2550 them. This can be disabled by passing
2551 DONT_ACCEPT_TRUE_FOR_1 to the new
2552 optionflags argument.
2553 >>> 4 == 4
2554 1
2555 >>> 4 == 4
2556 True
2557 >>> 4 > 4
2558 0
2559 >>> 4 > 4
2560 False
2561 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002562
Tim Peters8485b562004-08-04 18:46:34 +00002563 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002564 Blank lines can be marked with <BLANKLINE>:
2565 >>> print 'foo\n\nbar\n'
2566 foo
2567 <BLANKLINE>
2568 bar
2569 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002570 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002571
2572 "ellipsis": r"""
2573 If the ellipsis flag is used, then '...' can be used to
2574 elide substrings in the desired output:
2575 >>> print range(1000) #doctest: +ELLIPSIS
2576 [0, 1, 2, ..., 999]
2577 """,
2578
2579 "whitespace normalization": r"""
2580 If the whitespace normalization flag is used, then
2581 differences in whitespace are ignored.
2582 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2583 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2584 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2585 27, 28, 29]
2586 """,
2587 }
Tim Peters8485b562004-08-04 18:46:34 +00002588
Tim Peters8a7d2d52001-01-16 07:10:57 +00002589def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002590 r = unittest.TextTestRunner()
2591 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002592
2593if __name__ == "__main__":
2594 _test()